
    qic                        d 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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 m!Z! ddl"m#Z# ddl$m%Z%  G d de#      Z& G d de!      Z' G d de      Z( G d de       Z)e G d de             Z*e G d de*             Z+ ed       G d  d!e*e             Z,e G d" d#e*             Z- ed$       G d% d&e*             Z.g d'Z/y)(zPyTorch BioGPT model.    N)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCache)GenerationMixin)create_causal_mask))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentions SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)Unpack)TransformersKwargsauto_docstringlogger   )BartAttentionBartDecoderLayerBartScaledWordEmbedding)OPTLearnedPositionalEmbedding   )BioGptConfigc                   `     e Zd Z	 	 ddej                  dedej                  dz  f fdZ xZS ) BioGptLearnedPositionalEmbeddingNattention_maskpast_key_values_lengthposition_idsc                 (    t         |   |||       y)z3`input_ids_shape` is expected to be [bsz x seqlen].N)superforward)selfr   r   r    	__class__s       [/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/biogpt/modular_biogpt.pyr#   z(BioGptLearnedPositionalEmbedding.forward1   s     	(>M    )r   N)__name__
__module____qualname__torch
LongTensorintr#   __classcell__r%   s   @r&   r   r   0   sG     '(04	N((N !$N &&-	N Nr'   r   c                       e Zd Zy)BioGptScaledWordEmbeddingNr(   r)   r*    r'   r&   r1   r1   ;       r'   r1   c                       e Zd Zy)BioGptAttentionNr2   r3   r'   r&   r6   r6   ?   r4   r'   r6   c                   :    e Zd Zddededz  f fdZ	 	 	 	 	 	 ddej                  dej                  dz  dedz  de	dz  d	e	dz  d
ej                  dz  dej                  dz  dee   deej                  eej                  ej                  f   dz  f   fdZ xZS )BioGptDecoderLayerNconfig	layer_idxc           	         t         |   |       |j                  | _        t	        | j                  |j
                  |j                  dd||      | _        |j                  | _	        t        |j                     | _        t        j                  | j                  |j                        | _        t        j                  |j                  | j                        | _        | `| `y )NT)	embed_dim	num_headsdropout
is_decoder	is_causalr9   r:   )r"   __init__hidden_sizer<   r6   num_attention_headsattention_probs_dropout_prob	self_attnhidden_dropout_probr>   r   
hidden_actactivation_fnnnLinearintermediate_sizefc1fc2encoder_attnencoder_attn_layer_norm)r$   r9   r:   r%   s      r&   rA   zBioGptDecoderLayer.__init__D   s     ++(nn0077
 11#F$5$5699T^^V-E-EF99V55t~~F(r'   hidden_statesr   past_key_valuesoutput_attentions	use_cacher    cache_positionkwargsreturnc           
      ^   |}	| j                  |      } | j                  d||||||d|\  }}
t        j                  j	                  || j                  | j
                        }|	|z   }|}	| j                  |      }| j                  |      }| j                  |      }t        j                  j	                  || j                  | j
                        }| j                  |      }t        j                  j	                  || j                  | j
                        }|	|z   }|f}|r||
fz  }|S )a\  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            past_key_values (`Cache`): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            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`).
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence. It is used to update the
                cache in the correct position and to infer the complete sequence length.
        )rP   rQ   r   rR   r    rT   ptrainingr3   )self_attn_layer_normrE   rI   
functionalr>   rZ   final_layer_normrL   rH   activation_dropoutrM   )r$   rP   r   rQ   rR   rS   r    rT   rU   residualself_attn_weightsoutputss               r&   r#   zBioGptDecoderLayer.forwardZ   s=   6 !11-@ ,:4>> ,
'+)/%),
 ,
(( --mt||VZVcVc-d =0 !--m</**=9--mt?V?Vaeanan-o/--mt||VZVcVc-d =0 ")++Gr'   N)NNFTNN)r(   r)   r*   r   r-   rA   r+   Tensorr   boolr,   r   r   tupleFloatTensorr#   r.   r/   s   @r&   r8   r8   C   s    )| )d
 )2 /3(,).!%04.2;||; t+; 	;
  $;; $;; &&-; t+; +,; 
u  %(9(95;L;L(L"MPT"TT	U;r'   r8   c                   0    e Zd ZU eed<   dZdZdZdZdZ	dZ
y)BioGptPreTrainedModelr9   biogptTN)r(   r)   r*   r   __annotations__base_model_prefixsupports_gradient_checkpointing_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraphr3   r'   r&   rh   rh      s+     &*#N!r'   rh   c                   (    e Zd Zdef fdZe	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  de	dz  de
dz  d	ej                  dz  d
e
dz  de
dz  de
dz  dej                  dz  dee   deez  fd       Z xZS )BioGptModelr9   c           	         t         |   |       || _        |j                  | _        |j                  | _        |j                  | _        |j                  | _	        |j                  rt        j                  |j                        nd}t        |j                  | j                  | j                  |      | _        t!        |j"                  | j                        | _        t'        j(                  t+        |j,                        D cg c]  }t/        ||       c}      | _        t'        j2                  | j                        | _        d| _        | j9                          y c c}w )Ng      ?)embed_scale)r:   F)r"   rA   r9   	layerdroprF   r>   rB   r<   pad_token_idpadding_idxscale_embeddingmathsqrtr1   
vocab_sizeembed_tokensr   max_position_embeddingsembed_positionsrI   
ModuleListrangenum_hidden_layersr8   layers	LayerNorm
layer_normgradient_checkpointing	post_init)r$   r9   rt   ir%   s       r&   rA   zBioGptModel.__init__   s    ))11++!..7=7M7Mdii 2 23SV5t~~t/?/?[
  @@^@^`d`n`nommV[\b\t\tVu$vQR%7!%L$vw,,t~~6&+# %ws   E"N	input_idsr   inputs_embedsrQ   rS   r    rR   output_hidden_statesreturn_dictrT   rU   rV   c                 <   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	|d u |d uz  rt        d      |$|}|j                  }|j                  d|d         }n-| |j                         d d }|d d d d df   }nt        d      || j                  |      }| j                  r%| j                  r|rt        j                  d       d}|r|t        | j                         }|j                         d d \  }}||j                         nd}|
%t!        j"                  |||z   |j$                        }
|'||z   }t!        j&                  |||j$                        }|}t)        | j                   |||
|	      }||
j+                  d      }| j-                  |||
      }||z   }t.        j0                  j3                  || j2                  | j                        }| j                  r%| j                  r|rt        j                  d       d}|rdnd }|rdnd }d }t5        | j6                        D ]_  \  }}|r||fz  }| j                  r%t!        j8                  g       }|| j:                  k  r? ||f||||||
d|}|d   }|sW||d   fz  }a |r||fz  }| j=                  |      }|	st?        d |||||fD              S tA        |||||      S )NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timezEYou have to specify either decoder_input_ids or decoder_inputs_embedsz[`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`...F)r9   r   device)r9   r   r   rT   rQ   )r    rX   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...r3   )r   rQ   rR   rS   r    rT   r   c              3   $   K   | ]  }|| 
 y wrb   r3   ).0vs     r&   	<genexpr>z&BioGptModel.forward.<locals>.<genexpr>5  s      = s   )last_hidden_staterQ   rP   
attentionscross_attentions)!r9   rR   r   rS   use_return_dict
ValueErrorshapeviewsizer|   r   rZ   r   warning_oncer	   get_seq_lengthr+   aranger   onesr   	unsqueezer~   rI   r\   r>   	enumerater   randru   r   re   r   )r$   r   r   r   rQ   rS   r    rR   r   r   rT   rU   inputinput_shape
batch_size
seq_lengthr   mask_seq_lengthself_attn_cachecausal_mask	positionsrP   all_hidden_statesall_self_attnsall_cross_attentionsidxdecoder_layerdropout_probabilitylayer_outputss                                r&   r#   zBioGptModel.forward   s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B] -t";<stt"E++K!r;r?;I&',,.s3K!!Q(+Edee  --e4M&&4==##q "	 0*$++>O!.!3!3!5cr!:
JETE`!?!?!Afg!"\\&(>(KTaThThN !4zAO"ZZ
OML`L`aN)(;;'))+
 )33A6L((9O^j(k	%	1--mt||VZVcVc-d&&4==##p "	"6BD0d#"+DKK"8 	6C#!m%55!}}&+jjn#&7)	* /"3#)-	 	M *!,M =#3"55/	64  -!116 ':K^]qr  
 9+++%1
 	
r'   )
NNNNNNNNNN)r(   r)   r*   r   rA   r   r+   r,   rf   r   rd   rc   r   r   re   r   r#   r.   r/   s   @r&   rr   rr      s   | *  .23726(,!%04)-,0#'.2D
##d*D
 ))D0D
 ((4/	D

 D
 $;D
 &&-D
  $;D
 #TkD
 D[D
 t+D
 +,D
 
:	:D
 D
r'   rr   zR
    BioGPT Model with a `language modeling` head on top for CLM fine-tuning.
    )custom_introc                   v    e Zd ZddiZ fdZd Zd Ze	 	 	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  d	ej                  dz  d
edz  dej                  dz  dedz  dej                  dz  dedz  dedz  dedz  dej                  dz  deej                  z  dee   deez  fd       Z xZS )BioGptForCausalLMzoutput_projection.weightzbiogpt.embed_tokens.weightc                     t         |   |       t        |      | _        t	        j
                  |j                  |j                  d      | _        | j                          y NF)bias)
r"   rA   rr   ri   rI   rJ   rB   r{   output_projectionr   r$   r9   r%   s     r&   rA   zBioGptForCausalLM.__init__K  sJ     !&)!#6+=+=v?P?PW\!] 	r'   c                     | j                   S rb   r   r$   s    r&   get_output_embeddingsz'BioGptForCausalLM.get_output_embeddingsT  s    %%%r'   c                     || _         y rb   r   )r$   new_embeddingss     r&   set_output_embeddingsz'BioGptForCausalLM.set_output_embeddingsW  s
    !/r'   Nr   r   r   rQ   labelsrS   r    rR   r   r   rT   logits_to_keeprU   rV   c                    |
|
n| j                   j                  }
 | j                  |f|||||||	|
|d	|}|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|* | j                  d||| j                   j                  d|}|
s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                  |j                        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]`
        N)	r   r   rQ   rS   r    rR   r   r   rT   r   )logitsr   r{   r   )lossr   rQ   rP   r   r   r3   )r9   r   ri   
isinstancer-   slicer   loss_functionr{   r   rQ   rP   r   r   )r$   r   r   r   rQ   r   rS   r    rR   r   r   rT   r   rU   ra   rP   slice_indicesr   r   outputs                       r&   r#   zBioGptForCausalLM.forwardZ  s0   . &1%<k$++B]B]$++
)'+%/!5#)
 
  
8B>SV8W~ot4]k''a6I(JK%4%%pVFt{{OeOepiopDY,F)-)9TGf$EvE0#33!//))$55
 	
r'   NNNNNNNNNNNr   )r(   r)   r*   _tied_weights_keysrA   r   r   r   r+   r,   rf   r   rd   rc   r-   r   r   re   r   r#   r.   r/   s   @r&   r   r   C  sM    56RS&0  .23726(,*.!%04)-,0#'.2-.:
##d*:
 ))D0:
 ((4/	:

 :
   4':
 $;:
 &&-:
  $;:
 #Tk:
 D[:
 t+:
 ell*:
 +,:
 
2	2:
 :
r'   r   c                   X    e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dedz  dej                  dz  dej                  dz  d	e	dz  d
ej                  dz  de	dz  de	dz  de	dz  dej                  dz  deez  fd       Z xZS )BioGptForTokenClassificationc                 z   t         |   |       |j                  | _        t        |      | _        t        |d      r|j                  |j                  }n|j                  }t        j                  |      | _
        t        j                  |j                  |j                        | _        | j                          y )Nclassifier_dropout)r"   rA   
num_labelsrr   ri   hasattrr   rF   rI   Dropoutr>   rJ   rB   
classifierr   )r$   r9   r   r%   s      r&   rA   z%BioGptForTokenClassification.__init__  s      ++!&)6/0V5N5N5Z!'!:!:!'!;!;zz"45))F$6$68I8IJr'   Nr   token_type_idsr   rQ   r   r   rS   r    rR   r   r   rT   rV   c                    ||n| j                   j                  }| j                  |||||||	|
||
      }|d   }| j                  |      }| j	                  |      }d}|t               }||j                  d      dk(  }|j                  d| j                        }t        j                  ||j                  d      t        j                  |j                        j                  |            } |||      }n2 ||j                  d| j                        |j                  d            }|s|f|dd z   }||f|z   S |S t        |||j                  |j                        S )  
        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).
        N	rQ   r   r   rS   r    rR   r   r   rT   r   r   r   r   )r   r   rP   r   )r9   r   ri   r>   r   r   r   r   r+   wheretensorignore_indextype_asr   rP   r   )r$   r   r   r   rQ   r   r   rS   r    rR   r   r   rT   rU   transformer_outputsrP   r   r   loss_fctactive_lossactive_logitsactive_labelsr   s                          r&   r#   z$BioGptForTokenClassification.forward  sr   . &1%<k$++B]B]"kk+)'%/!5#) * 
 ,A.]3/')H),11"5: &B @ %R%,,x?T?T2U2]2]^d2e!  }=B @&++b/RY!4QR!88F)-)9TGf$EvE$-;;*55	
 	
r'   )NNNNNNNNNNNN)r(   r)   r*   rA   r   r+   r,   rf   r   rd   rc   re   r   r#   r.   r/   s   @r&   r   r     s6     .22637(,26*.!%04)-,0#'.2@
##d*@
 ((4/@
 ))D0	@

 @
 ((4/@
   4'@
 $;@
 &&-@
  $;@
 #Tk@
 D[@
 t+@
 
&	&@
 @
r'   r   a  
    The BioGpt Model transformer with a sequence classification head on top (linear layer).

    [`BioGptForSequenceClassification`] 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 is required 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                   j    e Zd Zdef fdZe	 	 	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  de	dz  dej                  dz  dej                  dz  d	e
dz  d
ej                  dz  de
dz  de
dz  de
dz  dej                  dz  deej                  z  deez  fd       Zd Zd Z xZS )BioGptForSequenceClassificationr9   c                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y r   )
r"   rA   r   rr   ri   rI   rJ   rB   scorer   r   s     r&   rA   z(BioGptForSequenceClassification.__init__  sS      ++!&)YYv114??O
 	r'   Nr   r   rQ   r   r   rS   r    rR   r   r   rT   r   rV   c                 `   |
|
n| j                   j                  }
| j                  ||||||||	|
|
      }|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }||j                  dd \  }}n|j                  dd \  }}| j                   j                  d}n|Vt        j                  || j                   j                        j                  d      dz
  j                  |j                        }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& ||j1                         |j1                               }n |||      }n| j                   j&                  d
k(  r=t3               } ||j5                  d| j(                        |j5                  d            }n,| j                   j&                  dk(  rt7               } |||      }|
s|f|dd z   }||f|z   S |S t9        |||j:                  |j<                  |j>                        S )r   Nr   r   r   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   rQ   rP   r   ) r9   r   ri   r   r-   r   r   r   rv   r+   nesumtor   r   r   r%   r(   r   problem_typer   dtypelongr   squeezer   r   r   r   rQ   rP   r   )r$   r   r   rQ   r   r   rS   r    rR   r   r   rT   r   rU   r   rP   r   r   r   sequence_lengthpooled_logitsr   r   r   s                           r&   r#   z'BioGptForSequenceClassification.forward  s   . &1%<k$++B]B]"kk+)'%/!5#) * 
 ,A.8B>SV8W~ot4]kM!]A*=>? *3//"1*='J*7*=*=bq*A'J;;##+ O$#(88It{{7O7O#P#T#TUW#X[\#\"`"`aganan"o"$##~~../ 0^ ^
 u||Jv}}M^_{{''/??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#%(;AB(??F)-)9TGf$EvE/ /??-;;*55
 	
r'   c                 .    | j                   j                  S rb   ri   r|   r   s    r&   get_input_embeddingsz4BioGptForSequenceClassification.get_input_embeddingsb  s    {{'''r'   c                 &    || j                   _        y rb   r   )r$   values     r&   set_input_embeddingsz4BioGptForSequenceClassification.set_input_embeddingse  s    #( r'   r   )r(   r)   r*   r   rA   r   r+   r,   rf   r   rd   rc   r-   re   r   r#   r   r   r.   r/   s   @r&   r   r     sF   |   .237(,26*.!%04)-,0#'.2-.[
##d*[
 ))D0[
 	[

 ((4/[
   4'[
 $;[
 &&-[
  $;[
 #Tk[
 D[[
 t+[
 ell*[
 
1	1[
 [
z()r'   r   )r   r   r   rr   rh   )0__doc__ry   r+   torch.nnrI   r   r   r   activationsr   cache_utilsr   r	   
generationr
   masking_utilsr   modeling_outputsr   r   r   r   modeling_utilsr   processing_utilsr   utilsr   r   r   bart.modeling_bartr   r   r   opt.modeling_optr   configuration_biogptr   r   r1   r6   r8   rh   rr   r   r   r   __all__r3   r'   r&   <module>r     sC       A A ! . ) /  . & 
 
 = .N'D N	 7 		m 	R) Rj "O " " [
' [
 [
| 
M
- M

M
` P
#8 P
 P
f l)&; l)l)^r'   