U
    ,-e                     @   s  d Z ddlZddlZddlZddlmZmZmZmZ ddl	Z	ddl
Z	ddl	mZ ddlmZ ddlmZmZmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZmZmZ ddlmZm Z m!Z!m"Z" ddl#m$Z$ e!%e&Z'dZ(dZ)dddgZ*dd Z+G dd dej,Z-G dd dej,Z.G dd dej,Z/G dd dej,Z0G dd deZ1dZ2d Z3ed!e2G d"d# d#e1Z4ed$e2G d%d& d&e1Z5ed'e2G d(d) d)e1Z6dS )*zPyTorch OpenAI ImageGPT model.    N)AnyOptionalTupleUnion)nn)autocast)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentions SequenceClassifierOutputWithPast)PreTrainedModel)Conv1D find_pruneable_heads_and_indicesprune_conv1d_layer)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )ImageGPTConfigzopenai/imagegpt-smallr   zopenai/imagegpt-mediumzopenai/imagegpt-largec                 C   s  zddl }ddl}W n  tk
r4   td  Y nX tj|}td	| |j
|}g }g }|D ]@\}	}
td	|	|
 |j
||	}||	 ||  qjt||D ]$\}	}|	dd }	|	d}	tdd	 |	D s|	d
 dkrtd	d|	 q| }|	d
 dkr*t|d}|	D ]}|d|rP|d|}n|g}|d dksr|d dkrt|d}n|d dkrt|d}n|d dks|d dkrt||d }t|d}n|d dkrt|d}t|d}nt|	dkr8|	d dkr8|d dkr8t||d }t|d}nV|d dkr\t|d}t|d}n2|d d krt|d}t|d}nt||d }t|d!kr.t|d }|| }q.t|	dkr|	d dksP|	d
 dksP|	d
 d ksP|	d
 dkrnTz|j|jkstW n< tk
rN } z| j|j|jf7  _ W 5 d}~X Y nX td"	|	 |	d
 d#krt||j|jj|jddd|jf< q|	d
 d$krt||j|jj|jdd|jd!|j f< q|	d
 d%krt||j|jj|jddd!|j df< qt|	dkrb|	d dkrb|	d! dkrbt||j|j|_q|	d
 dkr~t||_q|	d
 dkrt||jd|j d ddf< q|	d
 d krt||jd
< qt||_q| S )&z0
    Load tf checkpoints in a pytorch model
    r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z(Converting TensorFlow checkpoint from {}z"Loading TF weight {} with shape {}   /c                 s   s   | ]}|d kV  qdS ))Zadam_vZadam_mZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepN ).0nr   r   o/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/imagegpt/modeling_imagegpt.py	<genexpr>V   s   z.load_tf_weights_in_imagegpt.<locals>.<genexpr>)Z_stepzSkipping {})wtettransformerz[A-Za-z]+\d+z(\d+)wgweightbbiaswpewte)q_projk_projv_projc_attnr   r   attnc_projr"   lm_headsos   zInitialize PyTorch weight {}r+   r,   r-   )!reZ
tensorflowImportErrorloggererrorospathabspathinfoformattrainZlist_variablesZload_variableappendsqueezezipsplitanyjoingetattr	fullmatchlenintshapeAssertionErrorargstorchZ
from_numpyreshapen_embdTdata
vocab_size)modelconfigZimagegpt_checkpoint_pathr4   tfZtf_pathZ	init_varsnamesZarraysnamerH   arrayZpointerZm_nameZscope_namesnumer   r   r   load_tf_weights_in_imagegpt5   s    





*

F."2*$rY   c                       s<   e Zd Zdee ed fddZeje	dddZ
  ZS )	ImageGPTLayerNormh㈵>)hidden_sizeepsc                    s&   t    || _tt|| _d S N)super__init__r]   r   	ParameterrK   Tensorr&   )selfr\   r]   	__class__r   r   r`      s    
zImageGPTLayerNorm.__init__)tensorreturnc                 C   s:   |t t jt |ddd| j  | jjdd d f  S )Nr!   T)ZaxisZkeepdim.)rK   sqrtmeanZsquarer]   r&   rO   )rc   rf   r   r   r   forward   s     zImageGPTLayerNorm.forward)r[   )__name__
__module____qualname__r   rG   floatr`   rK   rb   tuplerj   __classcell__r   r   rd   r   rZ      s   rZ   c                       s   e Zd Zdee ee d fddZdd Zddd	Zdd
dZ	dd Z
dd Zdejee eej eej eej eej ee ee ed	ddZ  ZS )ImageGPTAttentionFNis_cross_attention	layer_idxc                    sF  t    |j}| jdttj||ftjddd||dd | jdt	ddd |j
| _|j| _| j| j | _| j| _| j| j | jkrtd| j d	| j d
|j| _|| _|j| _|| _|j| _| jrtd| j | j| _t| j| j| _ntd| j | j| _t| j| j| _t|j| _t|j| _t  | _!d S )Nr(   dtyper   F)
persistentZmasked_biasg     z=`embed_dim` must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).r3   r   )"r_   r`   max_position_embeddingsZregister_bufferrK   Ztrilonesboolviewrf   r\   	embed_dimZnum_attention_heads	num_headshead_dim
split_size
ValueErrorscale_attn_weightsrs   scale_attn_by_inverse_layer_idxrt   reorder_and_upcast_attnr   r.   q_attnr0   r   DropoutZ
attn_pdropattn_dropoutresid_pdropresid_dropoutsetpruned_heads)rc   rR   rs   rt   Zmax_positionsrd   r   r   r`      sD    
   zImageGPTAttention.__init__c                 C   s   t |dkrd S t|| j| j| j\}}t||| j |d| j  g}t| j	|dd| _	t| j
|dd| _
| j| j | jt |  | _| jt | | _| j|| _d S )Nr   r3   r   dim)rF   r   r}   r~   r   rK   catr   r   r.   r0   union)rc   headsindexZ
index_attnr   r   r   prune_heads   s     zImageGPTAttention.prune_headsc                 C   s  t ||dd}| jr0|t|dd  }| jrH|t| jd  }| js|d|d }}| j	d d d d || |d |f }	t 
|jj}
t j|
|jd|j}
t |	||
}|d k	r|| }tjdd|}||j}| |}|d k	r|| }t ||}||fS )Nr!         ?r   ru   r   )rK   matmul	transposer   rn   sizer   rt   rs   r(   finforv   minrf   todevicewherer   Softmaxtyper   )rc   querykeyvalueattention_mask	head_maskattn_weightsquery_length
key_lengthcausal_mask
mask_valueattn_outputr   r   r   _attn   s(    &

zImageGPTAttention._attnc              	   C   s  |  \}}}}	|  \}
}
}}
tj|| ||tj|jd}d}| jr\|t| dd  }| jrt|t| jd  }t	ddX |
d||	|dd
d|	| }}tj|| | d	|d
}|
||||}W 5 Q R X | jsT| d| d }}| jd d d d || |d |f }t|jj}tj||jd|j}t|||}|d k	rf|| }tjdd|}|jtjkrtd||j}| |}|d k	r|| }t||}||fS )Nrv   r         ?r!   r   r   F)enabledr   r   )betaalpharu   r   zDError with upcasting, attn_weights does not have dtype torch.float32)r   rK   emptyZfloat32r   r   rn   r   rt   r   rL   r   Zbaddbmmrs   r(   r   rv   r   rf   r   r   r   r   RuntimeErrorr   r   r   )rc   r   r   r   r   r   Zbszr}   Z	q_seq_lenZdk_Z	k_seq_lenr   Zscale_factorqkr   r   r   r   r   r   r   r   _upcast_and_reordered_attn  s:    &&


z,ImageGPTAttention._upcast_and_reordered_attnc                 C   s2   |  dd ||f }|j| }|ddddS )zJ
        Splits hidden_size dim into attn_head_size and num_heads
        Nr!   r   r3   r   r   )r   r{   permuterc   rf   r}   Zattn_head_sizeZ	new_shaper   r   r   _split_headsE  s    
zImageGPTAttention._split_headsc                 C   s8   | dddd }| dd || f }||S )zS
        Merges attn_head_size dim and num_attn_heads dim into hidden_size
        r   r3   r   r   Nr   )r   
contiguousr   r{   r   r   r   r   _merge_headsM  s    zImageGPTAttention._merge_heads	hidden_states
layer_pastr   r   encoder_hidden_statesencoder_attention_mask	use_cacheoutput_attentionsrg   c	                 C   sV  |d k	rDt | dstd| |}	| |j| jdd\}
}|}n| |j| jdd\}	}
}| |	| j| j}	| |
| j| j}
| || j| j}|d k	r|\}}t	j
||
fdd}
t	j
||fdd}|dkr|
|f}nd }| jr| |	|
|||\}}n| |	|
|||\}}| || j| j}| |}| |}||f}|rR||f7 }|S )Nr   zIf class is used as cross attention, the weights `q_attn` have to be defined. Please make sure to instantiate class with `ImageGPTAttention(..., is_cross_attention=True)`.r3   r   r   T)hasattrr   r   r.   rA   r   r   r}   r~   rK   r   r   r   r   r   r0   r   )rc   r   r   r   r   r   r   r   r   r   r   r   Zpast_keyZ
past_valueZpresentr   r   outputsr   r   r   rj   U  s:    





zImageGPTAttention.forward)FN)NN)NN)NNNNNFF)rk   rl   rm   r   rz   rG   r`   r   r   r   r   r   rK   rb   ro   rj   rp   r   r   rd   r   rq      s0   +
&
4       rq   c                       s0   e Zd Z fddZejejdddZ  ZS )ImageGPTMLPc                    sF   t    |j}t||| _t||| _t|j | _t	
|j| _d S r^   )r_   r`   r\   r   c_fcr0   r   Zactivation_functionactr   r   r   dropout)rc   Zintermediate_sizerR   r|   rd   r   r   r`     s    
zImageGPTMLP.__init__)r   rg   c                 C   s,   |  |}| |}| |}| |}|S r^   )r   r   r0   r   )rc   r   r   r   r   rj     s
    



zImageGPTMLP.forward)rk   rl   rm   r`   rK   rb   rj   rp   r   r   rd   r   r     s   r   c                       sd   e Zd Zd fdd	Zd	ejee eej eej eej eej ee ee ed	ddZ	  Z
S )
ImageGPTBlockNc                    s   t    |j}|jd k	r |jnd| }t||jd| _t||d| _t||jd| _	|j
r|t|d|d| _t||jd| _t||| _d S )N   r]   rt   Trr   )r_   r`   r\   Zn_innerrZ   layer_norm_epsilonln_1rq   r/   ln_2add_cross_attentioncrossattentionln_cross_attnr   mlp)rc   rR   rt   r\   Z	inner_dimrd   r   r   r`     s    
zImageGPTBlock.__init__Fr   c	                 C   s   |}	|  |}| j||||||d}
|
d }|
dd  }||	 }|d k	rt| dsbtd|  d|}	| |}| j||||||d}|d }|	| }||dd   }|}	| |}| |}|	| }|f|r|n
|dd   }|S )	N)r   r   r   r   r   r   r   r   z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`)r   r   r   r   r   r3   )r   r/   r   r   r   r   r   r   )rc   r   r   r   r   r   r   r   r   ZresidualZattn_outputsr   r   Zcross_attn_outputsZfeed_forward_hidden_statesr   r   r   rj     sJ    





zImageGPTBlock.forward)N)NNNNNFF)rk   rl   rm   r`   rK   rb   r   rz   ro   rj   rp   r   r   rd   r   r     s&          r   c                       sF   e Zd ZdZeZeZdZdZ	dZ
 fddZdd Zdd
dZ  ZS )ImageGPTPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    r#   	input_idsTc                    s   t  j|| d S r^   )r_   r`   )rc   inputskwargsrd   r   r   r`     s    z ImageGPTPreTrainedModel.__init__c                 C   s   t |tjtfr>|jjjd| jjd |j	dk	r|j	j
  nXt |tjr~|jjjd| jjd |jdk	r|jj|j 
  nt |tr|jjd | D ]>\}}d|krd|kr|jjd| jjtd| jj  d qdS )zInitialize the weights.g        )ri   ZstdNr   r0   r&   r3   )
isinstancer   Linearr   r&   rO   Znormal_rR   Zinitializer_ranger(   Zzero_	EmbeddingZpadding_idxrZ   Zfill_Znamed_parametersmathrh   n_layer)rc   modulerU   pr   r   r   _init_weights  s    


z%ImageGPTPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S r^   )r   ImageGPTModelgradient_checkpointing)rc   r   r   r   r   r   _set_gradient_checkpointing  s    
z3ImageGPTPreTrainedModel._set_gradient_checkpointing)F)rk   rl   rm   __doc__r   config_classrY   Zload_tf_weightsZbase_model_prefixZmain_input_nameZsupports_gradient_checkpointingr`   r   r   rp   r   r   rd   r   r     s   r   aB  

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`ImageGPTConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
            `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
            sequence tokens in the vocabulary.

            If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
            `input_ids`.

            Indices can be obtained using [`AutoImageProcessor`]. See [`ImageGPTImageProcessor.__call__`] for details.

        past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
            Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
            `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
            their past given to this model should not be passed as `input_ids` as they have already been computed.
        attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.

            If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
            `past_key_values`).
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
zbThe bare ImageGPT Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd Zed fddZdd Zdd Zdd	 Zee	e
eed
deej eeeej   eej eej eej eej eej eej eej ee ee ee ee eeeef dddZ  ZS )r   rR   c                    s   t     j| _t j| j| _t j| j| _	t
 j| _t fddt jD | _t| j jd| _d| _d | _d| _|   d S )Nc                    s   g | ]}t  |d qS )r   )r   )r   ir   r   r   
<listcomp>r  s     z*ImageGPTModel.__init__.<locals>.<listcomp>r   F)r_   r`   r\   r|   r   r   rP   r*   rx   r)   r   Z
embd_pdropdropZ
ModuleListrangeZnum_hidden_layershrZ   r   ln_fmodel_parallel
device_mapr   	post_initrc   rR   rd   r   r   r`   i  s     zImageGPTModel.__init__c                 C   s   | j S r^   r*   rc   r   r   r   get_input_embeddings|  s    z"ImageGPTModel.get_input_embeddingsc                 C   s
   || _ d S r^   r   rc   Znew_embeddingsr   r   r   set_input_embeddings  s    z"ImageGPTModel.set_input_embeddingsc                 C   s(   |  D ]\}}| j| j| qdS )zv
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
        N)itemsr   r/   r   )rc   Zheads_to_prunelayerr   r   r   r   _prune_heads  s    zImageGPTModel._prune_headsoutput_typer   N)r   past_key_valuesr   token_type_idsposition_idsr   inputs_embedsr   r   r   r   output_hidden_statesreturn_dictr   rg   c           %         sD  d|kr.t dt |dk	r$td|d}dk	r:n| jj|dk	rN|n| jj}dk	rbn| jj|dk	rv|n| jj	}|dk	r|dk	rtdnd|dk	r| 
|| | }|d|d }|jd }n,|dk	r| dd }|jd }ntd|dk	r|jn|j}|dk	r,|d|d }|dk	rF|d|d }|dkrjd}tdgt| j }n|d d d	}|dkrtj||d | tj|d
}|dd|d }|dk	r|dkrtd||d}|ddddddf }|j| jd}d| t| jj }| jjrj|dk	rj| \}}}||f}|	dkr^tj||d}	| |	}	nd}	| || jj}|dkr| |}|  |}||  |dk	r| |} |  | !  | df }| j"r| j#rrt$%d drdnd}rdnd}r.| jjr.dnd}|r<dnd}t&t'| j|D ]\}\}} | j(rtj)* j | dk	rt fdd| D } |dk	r| j}t+|tj,r| j}|r| f }| j"r| j#rfdd}!tj-j..|!| d||| ||	}"n| | ||| ||	d}"|"d  dkrR||"d f }r||"rfdnd f }| jjr||"rdnd f }| j(rP| j/0 D ]B\}#}$||$d krdt1|# | j2kr dt1|#d   qqP| 3   j|  |r| f }|s2tdd  ||||fD S t4 ||||dS )aR  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, ImageGPTModel
        >>> from PIL import Image
        >>> import requests

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> image_processor = AutoImageProcessor.from_pretrained("openai/imagegpt-small")
        >>> model = ImageGPTModel.from_pretrained("openai/imagegpt-small")

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> last_hidden_states = outputs.last_hidden_state
        ```pixel_valueskThe `pixel_values` argument is deprecated and will be removed in a future version, use `input_ids` instead.N_You cannot pass both `pixel_values` and `input_ids`. Please make sure to only pass `input_ids`.zDYou cannot specify both input_ids and inputs_embeds at the same timer!   r   z5You have to specify either input_ids or inputs_embedsr   r   z$batch_size has to be defined and > 0ru   r   )r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   c                 3   s   | ]}|  jV  qd S r^   )r   r   r   Z
past_state)r   r   r   r    +  s     z(ImageGPTModel.forward.<locals>.<genexpr>c                    s    fdd}|S )Nc                     s    | f S r^   r   )r   )r   r   r   r   r   custom_forward7  s    zLImageGPTModel.forward.<locals>.create_custom_forward.<locals>.custom_forwardr   )r   r  )r   r   )r   r   create_custom_forward6  s    z4ImageGPTModel.forward.<locals>.create_custom_forward)r   r   r   r   r   r   r   Tr   r3   r   zcuda:c                 s   s   | ]}|d k	r|V  qd S r^   r   )r   vr   r   r   r    i  s   )Zlast_hidden_stater   r   
attentionscross_attentions)5warningswarnFutureWarningr   poprR   r   r   r   use_return_dictZ%warn_if_padding_and_no_attention_maskr   r{   rH   r   ro   rF   r   rK   Zarangelong	unsqueezer   rv   r   r   r   ry   Zinvert_attention_maskZget_head_maskr   r*   r)   r   r   Ztrainingr6   Zwarning_once	enumerater@   r   cudaZ
set_devicer   rb   utils
checkpointr   r   strZlast_devicer   r   )%rc   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Zinput_shapeZ
batch_sizer   Zpast_lengthZencoder_batch_sizeZencoder_sequence_lengthr   Zencoder_hidden_shapeZposition_embedsZtoken_type_embedsZoutput_shapeZpresentsZall_self_attentionsZall_cross_attentionsZall_hidden_statesr   blockr   r  r   r   r  r   )r   r   r   r   rj     s   -




















"


zImageGPTModel.forward)NNNNNNNNNNNNN)rk   rl   rm   r   r`   r   r   r   r   IMAGEGPT_INPUTS_DOCSTRINGr   r   _CONFIG_FOR_DOCr   rK   rb   r   rz   r   r   rj   rp   r   r   rd   r   r   d  sH   
             
r   z
    The ImageGPT Model transformer with a language modeling head on top (linear layer with weights tied to the input
    embeddings).
    c                       s  e Zd ZdgZed fddZdd Zdd Zdej	e
e d
ddZeeeeedde
ej	 e
eeej	   e
ej	 e
ej	 e
ej	 e
ej	 e
ej	 e
ej	 e
ej	 e
ej	 e
e e
e e
e e
e eeeef dddZeeeej	  ej	eeej	  dddZ  ZS )ImageGPTForCausalImageModelingzlm_head.weightr   c                    sH   t  | t|| _tj|j|jd dd| _d| _	d | _
|   d S )Nr   Fr(   )r_   r`   r   r#   r   r   rM   rP   r1   r   r   r   r   rd   r   r   r`     s    
z'ImageGPTForCausalImageModeling.__init__c                 C   s   | j S r^   r1   r   r   r   r   get_output_embeddings  s    z4ImageGPTForCausalImageModeling.get_output_embeddingsc                 C   s
   || _ d S r^   r  r   r   r   r   set_output_embeddings  s    z4ImageGPTForCausalImageModeling.set_output_embeddingsN)r   r   c                 K   s   | dd }|rD|d d df d}|d k	rD|d d df d}| dd }| dd }|d k	r|d kr| dd }||dkd |r|d d df d}nd }||| d|||dS )	Nr   r!   r   r   r   r   r   )r   r   r   r   r   r   )getr  r  ZcumsumZmasked_fill_)rc   r   r   r   r   r   r   r   r   r   prepare_inputs_for_generation  s(    z<ImageGPTForCausalImageModeling.prepare_inputs_for_generationr   )r   r   r   r   r   r   r   r   r   labelsr   r   r   r   r   rg   c                 K   s"  d|kr.t dt |dk	r$td|d}|dk	r:|n| jj}| j|||||||||	||||d}|d }| |}d}|
dk	r|dddddf 	 }|
dd	df 	 }t
 }||d|d|d}|s|f|d	d  }|dk	r|f| S |S t|||j|j|j|jd
S )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, ImageGPTForCausalImageModeling
        >>> import torch
        >>> import matplotlib.pyplot as plt
        >>> import numpy as np

        >>> image_processor = AutoImageProcessor.from_pretrained("openai/imagegpt-small")
        >>> model = ImageGPTForCausalImageModeling.from_pretrained("openai/imagegpt-small")
        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        >>> model.to(device)  # doctest: +IGNORE_RESULT

        >>> # unconditional generation of 8 images
        >>> batch_size = 4
        >>> context = torch.full((batch_size, 1), model.config.vocab_size - 1)  # initialize with SOS token
        >>> context = context.to(device)
        >>> output = model.generate(
        ...     input_ids=context, max_length=model.config.n_positions + 1, temperature=1.0, do_sample=True, top_k=40
        ... )

        >>> clusters = image_processor.clusters
        >>> height = image_processor.size["height"]
        >>> width = image_processor.size["width"]

        >>> samples = output[:, 1:].cpu().detach().numpy()
        >>> samples_img = [
        ...     np.reshape(np.rint(127.5 * (clusters[s] + 1.0)), [height, width, 3]).astype(np.uint8) for s in samples
        ... ]  # convert color cluster tokens back to pixels
        >>> f, axes = plt.subplots(1, batch_size, dpi=300)

        >>> for img, ax in zip(samples_img, axes):  # doctest: +IGNORE_RESULT
        ...     ax.axis("off")
        ...     ax.imshow(img)
        ```r   r   Nr   )r   r   r   r   r   r   r   r   r   r   r   r   r   .r!   r   )losslogitsr   r   r  r  )r  r  r	  r   r
  rR   r  r#   r1   r   r	   r{   r   r   r   r   r  r  )rc   r   r   r   r   r   r   r   r   r   r  r   r   r   r   r   transformer_outputsr   Z	lm_logitsr  Zshift_logitsZshift_labelsloss_fctoutputr   r   r   rj     sZ    @

z&ImageGPTForCausalImageModeling.forward)r   beam_idxrg   c                    s   t  fdd| D S )a  
        This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
        [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
        beam_idx at every generation step.
        c                 3   s$   | ]}t  fd d|D V  qdS )c                 3   s"   | ]}| d  |jV  qdS )r   N)Zindex_selectr   r   r  r#  r   r   r    2  s     zJImageGPTForCausalImageModeling._reorder_cache.<locals>.<genexpr>.<genexpr>Nro   )r   r   r$  r   r   r    1  s   z@ImageGPTForCausalImageModeling._reorder_cache.<locals>.<genexpr>r%  )r   r#  r   r$  r   _reorder_cache(  s    	z-ImageGPTForCausalImageModeling._reorder_cache)N)NNNNNNNNNNNNNN)rk   rl   rm   Z_tied_weights_keysr   r`   r  r  rK   rb   r   rz   r  r   r  r   r   r  r   r   r   rj   staticmethodr&  rp   r   r   rd   r   r  x  sX   
              
w r  z
    The ImageGPT Model transformer with an image classification head on top (linear layer).
    [`ImageGPTForImageClassification`] average-pools the hidden states in order to do the classification.
    c                       s   e Zd Zed fddZeeeee	dd	e
ej e
eeej   e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e e
e eeeef dddZ  ZS )
ImageGPTForImageClassificationr   c                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S )NFr  )
r_   r`   
num_labelsr   r#   r   r   rM   scorer   r   rd   r   r   r`   ?  s
    
z'ImageGPTForImageClassification.__init__r   N)r   r   r   r   r   r   r   r  r   r   r   r   r   rg   c                 K   s  d|kr.t dt |dk	r$td|d}|dk	r:|n| jj}| j||||||||	|
||d}|d }|jdd}| 	|}d}|dk	rp| jj
dkr| jdkrd	| j_
n4| jdkr|jtjks|jtjkrd
| j_
nd| j_
| jj
d	kr"t }| jdkr|| | }n
|||}nN| jj
d
krRt }||d| j|d}n| jj
dkrpt }|||}|s|f|dd  }|dk	r|f| S |S t|||j|j|jdS )a7  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, ImageGPTForImageClassification
        >>> from PIL import Image
        >>> import requests

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> image_processor = AutoImageProcessor.from_pretrained("openai/imagegpt-small")
        >>> model = ImageGPTForImageClassification.from_pretrained("openai/imagegpt-small")

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> logits = outputs.logits
        ```r   r   Nr   )
r   r   r   r   r   r   r   r   r   r   r   r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr!   )r  r  r   r   r  )r  r  r	  r   r
  rR   r  r#   ri   r*  Zproblem_typer)  rv   rK   r  rG   r
   r?   r	   r{   r   r   r   r   r  )rc   r   r   r   r   r   r   r   r  r   r   r   r   r   r   r   Zpooled_hidden_statesr  r  r!  r"  r   r   r   rj   H  sp    ,




"

z&ImageGPTForImageClassification.forward)NNNNNNNNNNNN)rk   rl   rm   r   r`   r   r  r   r   r  r   rK   rb   r   rz   r   r   rj   rp   r   r   rd   r   r(  7  s>   	
            
r(  )7r   r   r8   r  typingr   r   r   r   rK   Ztorch.utils.checkpointr   Ztorch.cuda.ampr   Ztorch.nnr   r	   r
   Zactivationsr   Zmodeling_outputsr   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   r  r   r   r   r   Zconfiguration_imagegptr   Z
get_loggerrk   r6   Z_CHECKPOINT_FOR_DOCr  Z&IMAGEGPT_PRETRAINED_MODEL_ARCHIVE_LISTrY   ModulerZ   rq   r   r   r   ZIMAGEGPT_START_DOCSTRINGr  r   r  r(  r   r   r   r   <module>   sb   
l \K.?   9