
    ^j]                        d Z ddlmZ ddlZddl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 dd	lmZ dd
lmZ ddlmZmZmZ ddlmZmZ ddlmZ ddlmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(  e"jR                  e*      Z+d Z,d Z-	 	 d/dej\                  dej^                  dej^                  dej^                  dej^                  dz  de0dz  de0dee   fdZ1 G d dej\                        Z2d  Z3 G d! d"ej\                        Z4e  G d# d$e             Z5e  G d% d&e5             Z6 e d'(       G d) d*e5e             Z7 e d+(       G d, d-e5             Z8g d.Z9y)0zPyTorch CTRL model.    )CallableN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)CacheDynamicCache)GenerationMixin)create_causal_mask)BaseModelOutputWithPastCausalLMOutputWithPastSequenceClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)merge_with_config_defaults)capture_outputs   )
CTRLConfigc                 P    dt        j                  dd|dz  z  |z        z  }| |z  S )Nr   i'     )torchpow)posid_model_sizeangle_ratess       q/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/ctrl/modeling_ctrl.py
angle_defnr%   -   s/    eiiQ!V'DEEK    c                    t        t        j                  | t        j                        j	                  |      j                  d      t        j                  |t        j                        j	                  |      j                  d      |      }t        j                  |d d dd df         }t        j                  |d d dd df         }t        j                  ||gd      }|S )N)dtyper   r   r   dim)	r%   r   arangeint64to	unsqueezesincoscat)positionr"   r(   
angle_radssinescosinespos_encodings          r$   positional_encodingr8   2   s    XU[[144U;EEaH\588?II!LJ IIjADqD)*Eii
1add7+,G99eW-26Lr&   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |d      }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )Nr)         r   r   r*   )ptrainingr   )
sizer   matmul	transposer   
functionalsoftmaxr?   rD   
contiguous)
r9   r:   r;   r<   r=   r>   r?   r@   attn_weightsattn_outputs
             r$   eager_attention_forwardrM   B   s     **R.D( <<s}}Q':;gEL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$r&   c                   8     e Zd Zd fd	Z	 	 ddee   fdZ xZS )MultiHeadAttentionc                 ~   t         |           || _        |j                  | _        |j
                  | _        || _        d| _        t        | j                  | j                  z        | _
        | j                  dz  | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        t        j                  | j                  | j                        | _        y )NTrB   )super__init__confign_head	num_headsn_embdr"   	layer_idx	is_causalinthead_dimr>   r   LinearWqWkWvdenseselfrS   rW   	__class__s      r$   rR   zMultiHeadAttention.__init___   s    "MM"D-->?}}d*))D--t/@/@A))D--t/@/@A))D--t/@/@AYYt00$2C2CD
r&   r@   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }| |j                  |
|| j                        \  }
}t        j                  | j                  j                  t              } || |	|
||fd| j                  d|\  }} |j                  g |d j!                         }| j#                  |      }||fS )Nr)   r   r           )r?   r>   )shaperZ   r\   viewrG   r]   r^   updaterW   r   get_interfacerS   _attn_implementationrM   r>   reshaperJ   r_   )ra   vkq
layer_pastr=   r@   input_shapehidden_shapequery_states
key_statesvalue_statesattention_interfacerL   rK   s                  r$   forwardzMultiHeadAttention.forwardp   sT    ggcrl88b8$--8wwqz|4>>q!DWWQZ__\2<<QB
wwqz|4>>q!D!'1'8'8\SWSaSa'b$J(?(M(MKK,,.E)
 %8	%
 LL	%
 	%
!\ *k));;;;FFHjj-L((r&   NNN__name__
__module____qualname__rR   r   r   ru   __classcell__rb   s   @r$   rO   rO   ^   s&    E, #) +,#)r&   rO   c                     t        j                  t        j                  | |      t        j                         t        j                  ||             S rv   )r   
Sequentialr[   ReLU)r"   dffs     r$   point_wise_feed_forward_networkr      s2    ==<5rwwy"))CQ]B^__r&   c                   8     e Zd Zd fd	Z	 	 ddee   fdZ xZS )EncoderLayerc                    t         |           t        ||      | _        t	        |j
                  |j                        | _        t        j                  |j
                  d      | _
        t        j                  |j
                  d      | _        t        j                  |j                        | _        t        j                  |j                        | _        y )NrW   gư>eps)rQ   rR   rO   multi_head_attentionr   rV   r   ffnr   	LayerNorm
layernorm1
layernorm2Dropoutresid_pdropdropout1dropout2r`   s      r$   rR   zEncoderLayer.__init__   s    $6v$S!26==&**M,,v}}$?,,v}}$?

6#5#56

6#5#56r&   r@   c                     | j                  |      } | j                  |||f||d|\  }}| j                  |      }||z   }| j                  |      }	| j	                  |	      }
| j                  |
      }
||
z   }	|	S )Nrn   r=   )r   r   r   r   r   r   )ra   xrn   r=   r@   normedrL   _out1out2
ffn_outputs              r$   ru   zEncoderLayer.forward   s     #222
 ")
 
Q mmK0;t$XXd^
]]:.
j r&   rv   rw   rx   r}   s   @r$   r   r      s%    
7 	
 +,r&   r   c                   H     e Zd ZU eed<   dZdZdZdZdZ	e
edZ fdZ xZS )CTRLPreTrainedModelrS   transformerT)hidden_states
attentionsc                     t         |   |       t        |t              rXt	        j
                  |j                  t        |j                  j                  |j                  t        j                               y y rv   )rQ   _init_weights
isinstance	CTRLModelinitcopy_r7   r8   rS   n_positionsr"   r   float)ra   r9   rb   s     r$   r   z!CTRLPreTrainedModel._init_weights   sX    f%fi(JJ##%89R9RTZTgTginitit%u )r&   )ry   rz   r{   r   __annotations__base_model_prefix_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr   rO   _can_record_outputsr   r|   r}   s   @r$   r   r      s>    %N"&%(
 r&   r   c                       e Zd Z fdZd Zd Zeee	 	 	 	 	 	 	 dde	j                  dz  dedz  de	j                  dz  de	j                  dz  d	e	j                  dz  d
e	j                  dz  dedz  dee   defd                     Z xZS )r   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                        | _	        t        j                  |j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        j"                  |j                  |j$                        | _        | j)                  dt+        |j,                  | j                  t.        j0                        d       | j3                          y c c}w )Nr   r   r7   F)
persistent)rQ   rR   rV   r"   n_layer
num_layersr   	Embedding
vocab_sizewr   
embd_pdropr?   
ModuleListranger   hr   layer_norm_epsilon	layernormregister_bufferr8   r   r   r   	post_init)ra   rS   r!   rb   s      r$   rR   zCTRLModel.__init__   s     "MM ..f//?zz&"3"345QWQ_Q_K`aaVq Aabfmm9R9RS/0B0BDDUDUW\WbWbcpu 	 	

 	  bs   ,Ec                     | j                   S rv   r   )ra   s    r$   get_input_embeddingszCTRLModel.get_input_embeddings   s    vvr&   c                     || _         y rv   r   )ra   new_embeddingss     r$   set_input_embeddingszCTRLModel.set_input_embeddings   s	    r&   N	input_idspast_key_valuesr=   token_type_idsposition_idsinputs_embeds	use_cacher@   returnc                 ,   ||n| j                   j                  }||t        d      || j                  |      }n|t        d      |j                  dd }	|j                  d   }
|j
                  }|r|t        | j                         }||j                         nd}|>t        j                  ||	d   |z   t        j                  |      }|j                  d      }|4| j                  |      }|t        j                  | j                        z  }nd}|!|j                  dk  r|j!                  |
d      }t#        | j                   ||||	      }|t        j                  | j                        z  }| j$                  j'                  ||j(                  
      | _        | j$                  |ddf   }||z   |z   }| j+                  |      }| j,                  D ]  } ||f||d|} | j/                  |      }t1        ||r|      S d      S )a  
        Example:

        ```python
        >>> from transformers import AutoTokenizer, CTRLModel
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
        >>> model = CTRLModel.from_pretrained("Salesforce/ctrl")

        >>> # CTRL was trained with control codes as the first token
        >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
        >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()

        >>> outputs = model(**inputs)

        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 5, 1280]
        ```NzDYou cannot specify both input_ids and inputs_embeds at the same timez5You have to specify either input_ids or inputs_embedsr)   r   )rS   )r(   device   )rS   r   r=   r   r   r   r(   r   )last_hidden_stater   )rS   r   
ValueErrorr   re   r   r   get_seq_lengthr   r,   longr/   npsqrtr"   ndimrf   r   r7   r.   r(   r?   r   r   r   )ra   r   r   r=   r   r   r   r   r@   ro   
batch_sizer   past_lengthtoken_type_embedscausal_mask
pos_embedsr   r   s                     r$   ru   zCTRLModel.forward   s=   D "+!6IDKK<Q<Q	 ]%>cdd  FF9-M"TUU#))#2."((+
%%0*$++>O:I:Uo446[\ <<[_{5RZ_ZdZdmstL'11!4L% $~ 6):):!;; !%.*=*=*A+00R@N(;;')+%
 	!2!233 !--00mFYFY0Z&&|Q7
%
25FF]3 	A** 	M	 }5&+/8O
 	
>B
 	
r&   )NNNNNNN)ry   rz   r{   rR   r   r   r   r   r   r   
LongTensorr
   FloatTensorboolr   r   r   ru   r|   r}   s   @r$   r   r      s    &    .2(,37260426!%\
##d*\
 \
 ))D0	\

 ((4/\
 &&-\
 ((4/\
 $;\
 +,\
 
!\
    \
r&   r   z
    The CTRL Model transformer with a language modeling head on top (linear layer with weights tied to the input
    embeddings).
    )custom_introc                   X    e Zd ZddiZ fdZee	 	 	 	 	 	 	 	 	 ddej                  dz  de	dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  dedz  deej                  z  dee   defd              Z	 d fd	Z xZS )CTRLLMHeadModelzlm_head.weightztransformer.w.weightc                     t         |   |       t        |      | _        t	        j
                  |j                  |j                  d      | _        | j                          y )NTbias)
rQ   rR   r   r   r   r[   rV   r   lm_headr   ra   rS   rb   s     r$   rR   zCTRLLMHeadModel.__init__]  sG     $V,yy0A0AM 	r&   Nr   r   r=   r   r   r   labelsr   logits_to_keepr@   r   c
           
      l    | j                   |f||||||d|
}|d   }t        |	t              rt        |	 d      n|	}| j	                  |dd|ddf         }d}|* | j
                  ||fd| j                  j                  i|
}t        |||j                  |j                  |j                        S )ag  
        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]`

        Example:

        ```python
        >>> import torch
        >>> from transformers import AutoTokenizer, CTRLLMHeadModel

        >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
        >>> model = CTRLLMHeadModel.from_pretrained("Salesforce/ctrl")

        >>> # CTRL was trained with control codes as the first token
        >>> inputs = tokenizer("Wikipedia The llama is", return_tensors="pt")
        >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()

        >>> sequence_ids = model.generate(inputs["input_ids"])
        >>> sequences = tokenizer.batch_decode(sequence_ids)
        >>> sequences
        ['Wikipedia The llama is a member of the family Bovidae. It is native to the Andes of Peru,']

        >>> outputs = model(**inputs, labels=inputs["input_ids"])
        >>> round(outputs.loss.item(), 2)
        9.21

        >>> list(outputs.logits.shape)
        [1, 5, 246534]
        ```r   r=   r   r   r   r   r   Nr   )losslogitsr   r   r   )r   r   rY   slicer   loss_functionrS   r   r   r   r   r   )ra   r   r   r=   r   r   r   r   r   r   r@   transformer_outputsr   slice_indicesr   r   s                   r$   ru   zCTRLLMHeadModel.forwarde  s    \ /d..	
+))%'	
 	
 ,A.8B>SV8W~ot4]kmA}a,?@A%4%%  ;;11 	D &/??-;;*55
 	
r&   c                 T    t        |   |f|||d|}|j                  dd        |S )N)r   r   is_first_iterationr   )rQ   prepare_inputs_for_generationpop)ra   r   r   r   r   r@   model_inputsrb   s          r$   r   z-CTRLLMHeadModel.prepare_inputs_for_generation  sH    
 w<
+1	

 
 	)40r&   )	NNNNNNNNr   )NNF)ry   rz   r{   _tied_weights_keysrR   r   r   r   r   r
   r   r   rY   Tensorr   r   r   ru   r   r|   r}   s   @r$   r   r   T  s3    +,BC  .2(,37260426*.!%-.K
##d*K
 K
 ))D0	K

 ((4/K
 &&-K
 ((4/K
   4'K
 $;K
 ell*K
 +,K
 
 K
  K
\ SX r&   r   a  
    The CTRL Model transformer with a sequence classification head on top (linear layer).
    [`CTRLForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last
    token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in
    each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
    guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last
    value in each row of the batch).
    c                   "    e Zd Z fdZee	 	 	 	 	 	 	 	 ddej                  dz  dedz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
e
dz  dee   defd              Z xZS )CTRLForSequenceClassificationc                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y )NFr   )
rQ   rR   
num_labelsr   r   r   r[   rV   
classifierr   r   s     r$   rR   z&CTRLForSequenceClassification.__init__  sR      ++$V,))FMM4??O 	r&   Nr   r   r=   r   r   r   r   r   r@   r   c	           
      ^    | j                   |f||||||d|	}
|
d   }| j                  |      }||j                  dd \  }}n|j                  dd \  }}| j                  j                  |dk7  rt        d      | j                  j                  d}n||| j                  j                  k7  j                  |j                  t        j                        }t        j                  |j                  d   |j                  t        j                        }||z  j                  d      }n.d}t        j                  | j                  j                   d	       |t        j                  ||j                  
      |f   }d}|| j                  j                   | j"                  dk(  rd| j                  _        nl| j"                  dkD  rL|j$                  t        j&                  k(  s|j$                  t        j(                  k(  rd| j                  _        nd| j                  _        | j                  j                   dk(  rIt+               }| j"                  dk(  r& ||j-                         |j-                               }n |||      }n| j                  j                   dk(  r=t/               } ||j1                  d| j"                        |j1                  d            }n,| j                  j                   dk(  rt3               } |||      }t5        |||
j6                  |
j8                        S )a  
        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).

        Example of single-label classification:

        ```python
        >>> import torch
        >>> from transformers import AutoTokenizer, CTRLForSequenceClassification

        >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
        >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl")

        >>> # CTRL was trained with control codes as the first token
        >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
        >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()

        >>> with torch.no_grad():
        ...     logits = model(**inputs).logits

        >>> predicted_class_id = logits.argmax().item()
        >>> model.config.id2label[predicted_class_id]
        'LABEL_0'
        ```

        ```python
        >>> import torch

        >>> torch.manual_seed(42)  # doctest: +IGNORE_RESULT
        >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
        >>> num_labels = len(model.config.id2label)
        >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)

        >>> labels = torch.tensor(1)
        >>> loss = model(**inputs, labels=labels).loss
        >>> round(loss.item(), 2)
        0.93
        ```

        Example of multi-label classification:

        ```python
        >>> import torch
        >>> from transformers import AutoTokenizer, CTRLForSequenceClassification

        >>> tokenizer = AutoTokenizer.from_pretrained("Salesforce/ctrl")
        >>> model = CTRLForSequenceClassification.from_pretrained(
        ...     "Salesforce/ctrl", problem_type="multi_label_classification"
        ... )

        >>> # CTRL was trained with control codes as the first token
        >>> inputs = tokenizer("Opinion My dog is cute", return_tensors="pt")
        >>> assert inputs["input_ids"][0, 0].item() in tokenizer.control_codes.values()

        >>> with torch.no_grad():
        ...     logits = model(**inputs).logits

        >>> predicted_class_id = logits.argmax().item()
        >>> model.config.id2label[predicted_class_id]
        'LABEL_0'
        ```

        ```python
        >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
        >>> num_labels = len(model.config.id2label)
        >>> model = CTRLForSequenceClassification.from_pretrained("Salesforce/ctrl", num_labels=num_labels)

        >>> num_labels = len(model.config.id2label)
        >>> labels = torch.nn.functional.one_hot(torch.tensor([predicted_class_id]), num_classes=num_labels).to(
        ...     torch.float
        ... )
        >>> loss = model(**inputs, labels=labels).loss
        >>> loss.backward()  # doctest: +IGNORE_RESULT
        ```r   r   Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r)   r   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`)r   
regressionsingle_label_classificationmulti_label_classification)r   r   r   r   )r   r   re   rS   pad_token_idr   r.   r   r   int32r,   argmaxloggerwarning_oncerb   ry   problem_typer   r(   r   rY   r   squeezer   rf   r   r   r   r   )ra   r   r   r=   r   r   r   r   r   r@   r   r   r   r   sequence_lengthlast_non_pad_tokennon_pad_masktoken_indicespooled_logitsr   loss_fcts                        r$   ru   z%CTRLForSequenceClassification.forward  s   v /d..	
+))%'	
 	
 ,A./ *3//"1*='J*7*=*=bq*A'J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||Jv}}MOaab{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#M$9$9$;V^^=MND#M6:D))-JJ+- 2 22t GUWY))-II,.v6' -;;*55	
 	
r&   )NNNNNNNN)ry   rz   r{   rR   r   r   r   r   r
   r   r   r   r   r   ru   r|   r}   s   @r$   r   r     s      .2(,37260426*.!%Y
##d*Y
 Y
 ))D0	Y

 ((4/Y
 &&-Y
 ((4/Y
   4'Y
 $;Y
 +,Y
 
"Y
  Y
r&   r   )r   r   r   r   )Nrd   ):__doc__collections.abcr   numpyr   r   r   torch.nnr   r   r    r	   r   cache_utilsr
   r   
generationr   masking_utilsr   modeling_outputsr   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   utils.output_capturingr   configuration_ctrlr   
get_loggerry   r  r%   r8   Moduler   r   rM   rO   r   r   r   r   r   r   __all__ r&   r$   <module>r      s    $    A A & . ) / i i F &  8 5 * 
		H	%
, !%II%<<% 
% <<	%
 LL4'% T\% % '(%85) 5)p`%299 %P /  ( y
# y
 y
x j)? jjZ 
e
$7 e

e
P cr&   