
    fTh              
       0   S r SSKrSSKrSSKJrJrJr  SSKrSSKrSSKJ	r	  SSK
JrJrJrJr  SSK
Jr  SSKJrJrJr  SS	KJr  SS
KJr  SSKJrJrJrJrJr  SSKJ r   SSK!J"r"J#r#J$r$  SSK%J&r&  \#" 5       (       a  SSK'J(r(  SSK)J*r*  \$RV                  " \,5      r-S\R\                  S\/S\R`                  S\R\                  4S jr1S\R\                  S\R\                  S\2S\3S\R\                  4
S jr4S\R\                  S\R\                  4S jr5S\R\                  S\R\                  S\R\                  4S jr6 " S S \Rn                  Rp                  5      r9 " S! S"\	Rt                  5      r; " S# S$\	Rt                  5      r< " S% S&\	Rt                  5      r= " S' S(\	Rt                  5      r>\" " S) S*\ 5      5       r?\" " S+ S,\?5      5       r@\"" S-S.9 " S/ S0\?\5      5       rA\"" S1S.9 " S2 S3\?5      5       rB\" " S4 S5\?5      5       rC\" " S6 S7\?5      5       rD/ S8QrEg)9zPyTorch BLOOM model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)auto_docstringis_torch_flex_attn_availablelogging   )BloomConfig)	BlockMask)make_flex_block_causal_maskattention_mask	num_headsdtypereturnc                    U R                   u  p4S[        R                  " [        R                  " U5      5      -  n[        R
                  " SS[        R                  " U5      S-
  * -  * -  U R                  [        R                  S9n[        R                  " SSU-   U R                  [        R                  S9n[        R                  " Xg5      nXQ:w  a  [        R
                  " SS[        R                  " SU-  5      S-
  * -  * -  U R                  [        R                  S9n	[        XQU-
  5      n
[        R                  " SSSU
-  -   SU R                  [        R                  S9n[        R                  " U[        R                  " X5      /SS9nU R                  SS9S-
  U -  SS2SSS24   nUS	   U-  nUR                  X1-  SU5      R                  U5      $ )
aN  
Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it
relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
`softmax(l+a) = softmax(l)`. Based on
https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
TODO @thomasw21 this doesn't work as nicely due to the masking strategy, and so masking varies slightly.

Args:
Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
    attention_mask (`torch.Tensor`):
        Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
    num_heads (`int`):
        number of heads
    dtype (`torch.dtype`, *optional*, default=`torch.bfloat16`):
        dtype of the output tensor
   r   devicer!   r   r   dimN).N)shapemathfloorlog2torchtensorr&   float32arangeint32powmincatcumsumreshapeto)r   r    r!   
batch_size
seq_lengthclosest_power_of_2basepowersslopes
extra_basenum_remaining_headsextra_powersarange_tensoralibis                 `/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/bloom/modeling_bloom.pybuild_alibi_tensorrE   7   s   " ,11Jdjj9)=>><<	tyy!34q899:;NDYDYafananD \\!Q!33N<Q<QY^YdYdeFYYt$F&\\A499Q);%;<q@AABCNLaLainiviv

 ""4BT6TU||Aq1/B+B'BAnNcNckpkvkvwFEIIj$GHaP %+++3a7>I1dTU:VM9-E==/J?BB5II    xresidualprobtrainingc                 8    [         R                  " XUS9nX-   nU$ )z
Dropout add function

Args:
    x (`torch.tensor`):
        input tensor
    residual (`torch.tensor`):
        residual tensor
    prob (`float`):
        dropout probability
    training (`bool`):
        training mode
)prJ   )Fdropout)rG   rH   rI   rJ   outs        rD   dropout_addrP   c   s      ))A
1C
.CJrF   c                 ^    U S-  S[         R                  " SU -  SSU -  U -  -   -  5      -   -  $ )z
Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to
make the model jitable.

Args:
    x (`torch.tensor`):
        input hidden states
      ?      ? e3E?r   Hm?r.   tanh)rG   s    rD   bloom_gelu_forwardrX   v   s8     s7cEJJzA~X\A=M9M'NOOPPrF   gc                     US   n[         R                  " SU-  SSU-  U-  -   -  5      nSU-  SX"-  -
  SSU-  U-  -   -  -  SSU-   -  -   nX0-  $ )a   
gradient of tanh approximation of gelu gradient of actual gelu is: 0.5 * (1. + torch.erf(x * 0.70710678)) +
0.3989423 * x * torch.exp(-0.5 * x * x)

Args:
    g (`torch.tensor`):
        gradient output tensor
    x (`torch.tensor`):
        input tensor
r   rT   r   rU   rR   g6vf?rV   )rY   rG   tanh_outffs       rD   bloom_gelu_backr]      sv     	
!Azz*q.A1q0@,@ABH	qQ,,lQ>NQR>R1RS	TWZ^_bj^jWk	kB6MrF   c                       \ rS rSr\S\R                  S\R                  4S j5       r\S\R                  S\R                  4S j5       rSr	g)	GeLUFunction   inputr"   c                 :    U R                  U5        [        U5      $ N)save_for_backwardrX   )ctxra   s     rD   forwardGeLUFunction.forward   s    e$!%((rF   grad_outputc                 4    U R                   n[        X5      nU$ rc   )saved_tensorsr]   )re   rh   ra   tmps       rD   backwardGeLUFunction.backward   s    !!k1
rF    N)
__name__
__module____qualname____firstlineno__staticmethodr.   Tensorrf   rl   __static_attributes__rn   rF   rD   r_   r_      sT    )ELL )U\\ ) ) 5<< ELL  rF   r_   c                   f   ^  \ rS rSrSrU 4S jrS\R                  S\R                  4S jrSr	U =r
$ )	BloomGelu   a  
BloomBiasGelu wrapper function that make use of the simple function on inference mode to make the model
torchscriptable and use the autograd function in training mode to get the accurate results of the gradients Partly
copied from Megatron-DeepSpeed code and adapted for our needs

See here why autograd functions are not torchscriptable: https://github.com/pytorch/pytorch/issues/22329
c                 "   > [         TU ]  5         g rc   super__init__)self	__class__s    rD   r|   BloomGelu.__init__   s    rF   rG   r"   c                 d    U R                   (       a  [        R                  U5      $ [        U5      $ rc   )rJ   r_   applyrX   )r}   rG   s     rD   rf   BloomGelu.forward   s%    ==%%a((%a((rF   rn   )ro   rp   rq   rr   __doc__r|   r.   rt   rf   ru   __classcell__r~   s   @rD   rw   rw      s-    ) )%,, ) )rF   rw   c                     ^  \ rS rSrSS\S\\   4U 4S jjjrS\R                  S\
\R                  \R                  \R                  4   4S jrS\R                  S\R                  4S	 jr     SS
\R                  S\R                  S\R                  S\R                  S\\   S\\R                     S\S\S\\R                     4S jjrSrU =r$ )BloomAttention   config	layer_idxc                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        UR
                  U l        U R                  U R                  -  U l        U R                  U l        UR                  U l	        U R                  U R                  -  U R                  :w  a&  [        SU R                   SU R                   S35      eS[        R                  " U R                  5      -  U l        SU l        X l        Uc-  [         R#                  SU R$                  R&                   S35        [(        R*                  " U R                  SU R                  -  SS	9U l        [(        R*                  " U R                  U R                  5      U l        [(        R0                  " UR2                  5      U l        g )
NzA`hidden_size` must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).rS   zInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.r   Tbias)r{   r|   pretraining_tpslow_but_exacthidden_sizen_headr    head_dim
split_sizehidden_dropout
ValueErrorr+   sqrtinv_norm_factorbetar   loggerwarning_oncer~   ro   r   Linearquery_key_valuedenseDropoutattention_dropout)r}   r   r   r~   s      rD   r|   BloomAttention.__init__   sx   $33$33!--((DNN:**$33==4>>)T-=-==STXTdTdSe fNN#2'   #TYYt}}%==	" !8!8 9 :, ,  "yy)9)91t?O?O;OVZ[YYt//1A1AB
!#F,D,D!ErF   	fused_qkvr"   c                    UR                   u  p#nUR                  X#U R                  SU R                  5      nUSSSS24   R	                  SS5      nUSSSS24   R	                  SS5      nUSSSS24   R	                  SS5      nXVU4$ )a  
Split the last dimension into (num_heads, head_dim) and reshapes to (bs, heads, len, dim) shape
without making any copies, results share same memory storage as `fused_qkv`

Args:
    fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim]

Returns:
    query: [batch_size, num_heads, seq_length, head_dim]
    key: [batch_size, num_heads, seq_length, head_dim]
    value: [batch_size, num_heads, seq_length, head_dim]
r   .r   Nr   r$   )r*   viewr    r   	transpose)r}   r   r9   r:   three_times_hidden_sizequery_layer	key_layervalue_layers           rD   _reshapeBloomAttention._reshape   s     ;D//7
 7NN:4>>1dmm\	Q	*44Q:c1ai(221a8	Q	*44Q:{22rF   rG   c                    UR                   u  p#nX R                  -  nUR                  XPR                  X0R                  5      nUR	                  SSSS5      nUR                  XSU R                  U R                  -  5      $ )z
Merge heads together over the last dimension

Args:
    x (`torch.tensor`): [batch_size * num_heads, seq_length, head_dim]

Returns:
    torch.tensor: [batch_size, seq_length, num_heads * head_dim]
r   r$   r   r   )r*   r    r   r   permuter7   )r}   rG   batch_size_and_num_headsr:   _r9   s         rD   _merge_headsBloomAttention._merge_heads   so     34''/ a-?
 FF:~~z==I IIaAq! yy$--1OPPrF   hidden_statesrH   rC   r   
layer_past	head_mask	use_cacheoutput_attentionscache_positionc
                 2   UR                   u  pnU R                  U5      nU R                  U5      u  pnUb%  SU	0nUR                  UUU R                  U5      u  nnUR                  XR                  -  SU R                  5      nUR                  XR                  -  SU R                  5      R                  SS5      nUR                  XR                  -  SU R                  5      nUR                  UUU R                  U R                  S9nUR                  XR                  US5      nUb#  US S 2S S 2S S 2S UR                   S   24   nUU-   n[        R                  " US[        R                   S9R#                  UR$                  5      nU R'                  U5      nUb  UU-  nUR                  XR                  -  US5      n[        R(                  " UU5      nU R+                  U5      nU R,                  S:  a  U R.                  (       a  U R0                  U R,                  -  n[        R2                  " U5      n[5        U R,                  5       H|  nU[        R6                  " US S 2S S 2[9        UU-  5      [9        US-   U-  5      24   U R:                  R<                  S S 2[9        UU-  5      [9        US-   U-  5      24   5      -   nM~     OU R;                  U5      n[?        UX R@                  U RB                  5      nUU4nU(       a  UU4-  nU$ )Nr   r)   )batch1batch2r   alpha)r(   r!   r   )"r*   r   r   updater   r7   r    r   r   baddbmmr   r   r   rM   softmaxr.   r0   r8   r!   r   bmmr   r   r   r   
zeros_likerangelinearintr   weightrP   r   rJ   )r}   r   rH   rC   r   r   r   r   r   r   r9   q_lengthr   r   r   r   r   cache_kwargsattention_scoresattn_weightscausal_maskattention_probsattention_probs_reshapedcontext_layerslicesoutput_tensorioutputss                               rD   rf   BloomAttention.forward  s    #0"5"5
a((7	.2mmI.F+!,n=L%/%6%6y+t~~_k%l"I{ "))*~~*Er4==Y%%j>>&A2t}}U__`bdfg	!))*~~*Er4==Y !==&&	 ) 
 (,,ZSUV%(Aq2GIOOB4G2G)GHK'+5L ))LbNQQR]RcRcd 00A -	9O $3#7#7
^^8SU]_a#b  		":KH ))-8 "t':':%%(;(;;F!,,];M4../ -!!QAJ#q1u>N:O(O"OPJJ%%aQZ3A?O;P)P&PQ1 ! 0 !JJ}5M#M8=P=PRVR_R_` *-))GrF   )r   r   r   r   r   r   r   r   r    r   r   r   r   rc   NNFFN)ro   rp   rq   rr   r   r   r   r|   r.   rt   r   r   r   r   bool
LongTensorrf   ru   r   r   s   @rD   r   r      s   F{ Fx} F FB3%,, 35u||UZUaUa9a3b 3(Qell Qu|| Q> '+,0"'59L||L ,,L ||	L
 L UOL ELL)L L  L !!1!12L LrF   r   c                      ^  \ rS rSrS\4U 4S jjrS\R                  S\R                  S\R                  4S jrSr	U =r
$ )	BloomMLPiR  r   c                 :  > [         TU ]  5         UR                  nUR                  U l        UR                  U l        [
        R                  " USU-  5      U l        [        5       U l	        [
        R                  " SU-  U5      U l
        UR                  U l        g )N   )r{   r|   r   r   r   r   r   dense_h_to_4hrw   	gelu_impldense_4h_to_hr   )r}   r   r   r~   s      rD   r|   BloomMLP.__init__S  sz    (($33$33YY{AOD"YYq;D$33rF   r   rH   r"   c                    U R                  U R                  U5      5      nU R                  S:  a  U R                  (       a  [        R
                  " U5      nU R                  R                  R                  S   U R                  -  n[        U R                  5       Hz  nU[        R                  " US S 2S S 2[        XT-  5      [        US-   U-  5      24   U R                  R                  S S 2[        XT-  5      [        US-   U-  5      24   5      -   nM|     OU R                  U5      n[        X2U R                  U R                  5      nU$ )Nr   r)   )r   r   r   r   r.   r   r   r   r*   r   rM   r   r   rP   r   rJ   )r}   r   rH   intermediate_outputr   r   outputs          rD   rf   BloomMLP.forward^  s#   t'9'9-'HI"t':':"'"2"28"<''..44R84;N;NNF4../&9AHH!!QAJ#q1u>N:O(O"OP&&--aQZ3AQWGWCX1X.XY= '# 0 #'"4"4]"C0D<O<OQUQ^Q^_rF   )r   r   r   r   r   r   )ro   rp   rq   rr   r   r|   r.   rt   rf   ru   r   r   s   @rD   r   r   R  s:    	4{ 	4U\\ U\\ ell  rF   r   c                      ^  \ rS rSrSS\S\\   4U 4S jjjr     SS\R                  S\R                  S\R                  S\\
   S	\\R                     S
\S\S\\R                     4S jjrSrU =r$ )
BloomBlockiq  r   r   c                 @  > [         TU ]  5         UR                  n[        X1R                  S9U l        UR                  U l        [        X5      U l	        [        X1R                  S9U l
        [        U5      U l        UR                  U l        UR                  U l        g )Neps)r{   r|   r   r	   layer_norm_epsiloninput_layernormr   r    r   self_attentionpost_attention_layernormr   mlp(apply_residual_connection_post_layernormr   )r}   r   r   r   r~   s       rD   r|   BloomBlock.__init__r  s    (((:S:ST,V?(1+C\C\(]%F#8>8g8g5$33rF   r   rC   r   r   r   r   r   r   c	                 6   U R                  U5      n	U R                  (       a  U	n
OUn
U R                  U	U
UUUUUUUS9	nUS   nUSS  nU R                  U5      n	U R                  (       a  U	n
OUn
U R	                  X5      nU(       a  U4U-   nU$ U4USS  -   nU$ )N)r   r   rC   r   r   r   r   r   r   )r   r   r   r   r   )r}   r   rC   r   r   r   r   r   r   layernorm_outputrH   attn_outputsattention_outputr   r   s                  rD   rf   BloomBlock.forward  s      //> 88'H$H **!)/) + 

 (?qr"889IJ 88'H'H *5i')G  i'!"+-GrF   )r   r   r   r   r    r   r   rc   r   )ro   rp   rq   rr   r   r   r   r|   r.   rt   r   r   r   rf   ru   r   r   s   @rD   r   r   q  s    4{ 4x} 4 4& '+,0"'597||7 ||7 	7
 UO7 ELL)7 7  7 !!1!127 7rF   r   c                   l   ^  \ rS rSr\rSrSrS/rSr	Sr
SrSrU 4S jrS\R                  4S jrS	rU =r$ )
BloomPreTrainedModeli  transformerTr   past_key_valuesc                 &   > [         TU ]  " U0 UD6  g rc   rz   )r}   inputskwargsr~   s      rD   r|   BloomPreTrainedModel.__init__  s    &+F+rF   modulec                    [        U[        R                  5      (       ak  UR                  R                  R                  SU R                  R                  S9  UR                  b%  UR                  R                  R                  5         gg[        U[        R                  5      (       ax  UR                  R                  R                  SU R                  R                  S9  UR                  b2  UR                  R                  UR                     R                  5         gg[        U[        5      (       aJ  UR                  R                  R                  5         UR                  R                  R                  S5        gg)zInitialize the weights.        )meanstdNrS   )
isinstancer   r   r   datanormal_r   initializer_ranger   zero_	Embeddingpadding_idxr	   fill_)r}   r   s     rD   _init_weights"BloomPreTrainedModel._init_weights  s   fbii(( MM&&CT[[5R5R&S{{&  &&( '--MM&&CT[[5R5R&S!!-""6#5#56<<> .	**KK""$MM$$S) +rF   rn   )ro   rp   rq   rr   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_cache_class_supports_static_cache_supports_quantized_cacher|   r   Moduler  ru   r   r   s   @rD   r   r     sN    L%&*#%"3 ! $,*BII * *rF   r   c                     ^  \ rS rSrS\4U 4S jjrS\R                  S\S\R                  S\R                  4S jr
S	 rS
\R                  4S jr\          SS\\R                     S\\\\\\R                  \R                  4   S4   4      S\\R                     S\\R                     S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\\R                  S4   \4   4S jj5       r S S\\R                  S4   S\R                  S\R                  S\S\4
S jjr\S\R                  S\S\S\R                  S\R                  S\4S j5       rSrU =r$ )!
BloomModeli  r   c           
        > [         TU ]  U5        UR                  U l        UR                  U l        [        R                  " UR                  U R                  5      U l	        [        U R                  UR                  S9U l        [        R                  " [        UR                  5       Vs/ s H  n[!        XS9PM     sn5      U l        [        U R                  UR                  S9U l        SU l        U R)                  5         g s  snf )Nr   )r   F)r{   r|   r   	embed_dimr   r    r   r  
vocab_sizeword_embeddingsr	   r   word_embeddings_layernorm
ModuleListr   num_hidden_layersr   hln_fgradient_checkpointing	post_init)r}   r   r   r~   s      rD   r|   BloomModel.__init__  s     ++  "||F,=,=t~~N)24>>vG`G`)a& vOgOgIhiIhA
6 ?Ihij dnn&2K2KL	&+# 	  js   -Dr   r    r!   r"   c                     [        XU5      $ rc   )rE   )r}   r   r    r!   s       rD   rE   BloomModel.build_alibi_tensor  s    !.UCCrF   c                     U R                   $ rc   r  r}   s    rD   get_input_embeddingsBloomModel.get_input_embeddings  s    ###rF   new_embeddingsc                     Xl         g rc   r#  r}   r'  s     rD   set_input_embeddingsBloomModel.set_input_embeddings  s    -rF   	input_idsr   .r   inputs_embedsr   r   output_hidden_statesreturn_dictr   c                 \   UR                  SS5      SLa  [        R                  " S[        5        [	        U5      S:  a  [        SU 35      eUb  UOU R                  R                  nUb  UOU R                  R                  nUb  UOU R                  R                  nU	b  U	OU R                  R                  n	USL USL-  (       a  [        S5      eU R                  (       a/  U R                  (       a  U(       a  [        R                  S5        SnUc  U R                  U5      nSnU(       aP  [!        U["        5      (       d;  S	nUc  [%        5       nO+[$        R&                  " U5      n[        R                  S
5        UR(                  u  pnUb  UR+                  5       OSnUU-   nU
c#  [,        R.                  " UUU-   UR0                  S9n
U R3                  X@R                  R4                  5      nU R7                  U5      nSnU(       a  SOSnU(       a  SOSnUc"  [,        R8                  " UU4UR0                  S9nOUR;                  UR0                  5      nU R=                  X0R>                  UR@                  S9nU RC                  X5XU5      n[E        U RF                  5       H  u  nnU(       a  UU4-   nU R                  (       a8  U R                  (       a'  U RI                  URJ                  UUUUUU   UUU
5	      nOU" UUUUU   UUUU
S9nUS   nU(       a  US   nU(       d  M  UUU(       a  SOS   4-   nM     U RM                  U5      nU(       a  UU4-   nU(       a  UOSnU(       a  URO                  5       nU	(       d  [Q        S UUUU4 5       5      $ [S        UUUUS9$ )h  
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_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 [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
    [`PreTrainedTokenizer.__call__`] for details.

    [What are input IDs?](../glossary#input-ids)
position_idsFz`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore passing `position_ids`.r   Got unexpected arguments: Nz:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...TzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r&   rn   )r!   )r   r   r   r   r   rC   r   r   r$   c              3   .   #    U  H  oc  M  Uv   M     g 7frc   rn   ).0vs     rD   	<genexpr>%BloomModel.forward.<locals>.<genexpr>  s      ^a^s   	)last_hidden_stater   r   
attentions)*popwarningswarnFutureWarninglenr   r   r   r.  r   use_return_dictr  rJ   r   r   r  r   r   r   from_legacy_cacher*   get_seq_lengthr.   r1   r&   get_head_maskn_layerr  onesr8   rE   r    r!   _update_causal_mask	enumerater  _gradient_checkpointing_func__call__r  to_legacy_cachetupler   )r}   r,  r   r   r   r-  r   r   r.  r/  r   deprecated_argumentsreturn_legacy_cacher9   r:   r   past_lengthseq_length_with_pastr   next_decoder_cacheall_self_attentionsall_hidden_statesrC   r   r   blockr   
next_caches                               rD   rf   BloomModel.forward  s   8  ##NE:%GMM+
 #$q(9:N9OPQQ1B1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yl I  00;M $Z??"&&".."."@"@"Q##^ %2$7$7!
:I:Uo446[\)K7!"\\+{Z7OXeXlXlmN &&y++2E2EF	66}E!$5b4"6BD !"ZZ5I(JS`SgSghN+..}/C/CDN''mNaNa'b..>L]
 "$&&)HAu#$58H$H!**t}};;NN!#aL%"
  !.#.'l'&7#1	 $AJM%,QZ"  &9W)QYZ=[<]&]#C *H 		-0 1]4D D+4'$
#335J ):7HJ]^   9+&+*	
 	
rF   r   input_tensorc           	         U R                   R                  S:X  a  Ub  US:H  R                  5       (       a  U$ g U R                   R                  S:X  a,  [        U[        R
                  5      (       a  [        U5      nU$ Ub  UR                  5       OSnUb  UR                  OSnU R                   R                  S:X  a5  U(       d.  U(       d'  [        R                  " UUUU R                  S9(       a  g UR                  nUR                  S   n	U(       a  UR                  5       n
O5[        U[        R
                  5      (       a  UR                  S	   OXi-   S-   n
U R                  UU	U
UUUR                  S   S
9nU R                   R                  S:X  aZ  UbW  UR                   R"                  S;   a=  U(       d6  [        R$                  " U5      R&                  n[        R(                  " X5      nU$ )Nflash_attention_2r   flex_attentionr   Fsdpa)r-  past_key_values_lengthis_trainingr   r)   )sequence_lengthtarget_lengthr!   r   r9   )cudaxpunpu)r   _attn_implementationanyr   r.   rt   r   rD  is_compileabler   _ignore_causal_mask_sdparJ   r!   r*   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr&   typefinfor4   _unmask_unattended)r}   r   rX  r   r   r   past_seen_tokensusing_compilable_cacher!   r_  r`  r   	min_dtypes                rD   rH  BloomModel._update_causal_mask  s    ;;++/BB)~/D.I.I.K.K%%;;++/??.%,,77!<^!L!!
 @O?Z?99;`aCRC^!?!?di ;;++v5>T]n%>>*'7 MM	 ""&,,Q/!+??AM nell;; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[KrF   r_  r`  r9   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n[        R                  " X4XUR
                  S9nUS:w  a  [        R                  " USS9nU[        R                  " X$R
                  S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                  S   n	USS2SS2SS2SU	24   U SS2SSSS24   R                  UR
                  5      -   n
U
S:H  n
USS2SS2SS2SU	24   R                  X5      USS2SS2SS2SU	24'   U$ )	a  
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

Args:
    attention_mask (`torch.Tensor`):
        A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
        `(batch_size, 1, query_length, key_value_length)`.
    sequence_length (`int`):
        The sequence length being processed.
    target_length (`int`):
        The target length: when generating with static cache, the mask should be as long as the static cache,
        to account for the 0 padding, the part of the cache that is not filled yet.
    dtype (`torch.dtype`):
        The dtype to use for the 4D attention mask.
    cache_position (`torch.Tensor`):
        Indices depicting the position of the input sequence tokens in the sequence.
    batch_size (`torch.Tensor`):
        Batch size.
Nr   )
fill_valuer!   r&   r   )diagonalr5  r)   r   )r(   r.   rk  r4   fullr&   triur1   r7   expandcloner*   r8   masked_fill)r   r_  r`  r!   r   r9   r   r   ro  mask_lengthpadding_masks              rD   ri  @BloomModel._prepare_4d_causal_attention_mask_with_cache_position  s}   > %.*<*<*>!*C(K* ' E*..I** 0Y\j\q\qK !##jjqA5<<>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c 6Aq!\k\12 rF   )r  r  r  r  r    r  r  
NNNNNNNNNN)F)ro   rp   rq   rr   r   r|   r.   rt   r   r!   rE   r%  r*  r   r   r   r   r   r   r   r   rf   rH  rs   ri  ru   r   r   s   @rD   r  r    sC   { *D D# DV[VaVa Dfkfrfr D$.5<< .  15ae150448$(,0/3&*59Y
E,,-Y
 "%uU5<<;U5VX[5[/\(\"]^Y
 !.	Y

 E,,-Y
   0 01Y
 D>Y
 $D>Y
 'tnY
 d^Y
 !!1!12Y
 
uU\\3&')RR	SY
 Y
D #(BellK78B llB 	B
 B  BH 444 4 {{	4
 4 4 4rF   r  z
    The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input
    embeddings).
    )custom_introc                     ^  \ rS rSrS/rS\4U 4S jjrS rS\R                  4S jr
     SS jr\           SS	\\R                     S
\\\\\\R                  \R                  4   S4   4      S\\R                     S\\R                     S\\R                     S\\R                     S\\   S\\   S\\   S\\   S\\R                     S\\\R                     \4   4S jj5       rS\\\R                  \R                  4   S4   S\R                  S\\\R                  \R                  4   S4   4S jrSrU =r$ )BloomForCausalLMi  zlm_head.weightr   c                    > [         TU ]  U5        [        U5      U l        [        R
                  " UR                  UR                  SS9U l        U R                  5         g NFr   )
r{   r|   r  r   r   r   r   r  lm_headr  r}   r   r~   s     rD   r|   BloomForCausalLM.__init__  sI     %f-yy!3!3V5F5FUS 	rF   c                     U R                   $ rc   r  r$  s    rD   get_output_embeddings&BloomForCausalLM.get_output_embeddings$  s    ||rF   r'  c                     Xl         g rc   r  r)  s     rD   set_output_embeddings&BloomForCausalLM.set_output_embeddings'  s    %rF   c                    Ub  Ub-  UR                   S   S:X  a  US S 2UR                   S   * S 24   nO\Uc  US   UR                   S   :  a  US S 2UR                   S   * S 24   nO)UR                   S   UR                   S   :w  a	  US S 2U4   nUb"  [        U5      UR                   S   :X  a  US S.nO UR                  [        R                  S9S S.n[        U[        5      (       ae  Ubb  UR                  5       n	UR                   u  pX-
  n[        R                  " XUR                  UR                  S9n[        R                  " X=/SS9nUR                  UUUUS	.5        U$ )
Nr   r   r)   )r-  r,  )memory_format)r,  r-  r%   r'   )r   r   r   r   )r*   rA  rw  r.   contiguous_formatr   r   rh  zerosr&   r!   r5   r   )r}   r,  r   r   r-  r   r   r   model_inputsr`  r9   r:   diffnew_attn_masks                 rD   prepare_inputs_for_generation.BloomForCausalLM.prepare_inputs_for_generation*  s   & &(Y__Q-?1-D -a.2F2Fq2I1I1K.K L)!"%);;%a.*>*>q*A)A)C&CD	#~';';A'>>%a&78	 $^)<@S@STU@V)V-:NL
 *3uG^G^)_rvwL o{338R+??AM%3%9%9"J -D!KK
AVAV^l^r^rsM"YY/N
 	"0#2&"0		
 rF   r,  r   .r   r   r-  labelsr   r   r.  r/  r   r"   c                 j   UR                  SS5      nUR                  SS5      SLa  [        R                  " S[        5        [	        U5      S:  a  [        SU 35      eU
b  U
OU R                  R                  n
U R                  UUUUUUUU	U
US9
nUS   nU R                  U5      nSnUbA  UR                  UR                  5      nU R                  UUU R                  R                  US	9nU
(       d  U4US
S -   nUb  U4U-   $ U$ [        UUUR                  UR                   UR"                  S9$ )a  
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_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 [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
    [`PreTrainedTokenizer.__call__`] for details.

    [What are input IDs?](../glossary#input-ids)
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]`
num_items_in_batchNr2  Fr3  r   r4  )	r   r   r   r-  r   r   r.  r/  r   )r  r  r   losslogitsr   r   r<  )r=  r>  r?  r@  rA  r   r   rB  r   r  r8   r&   loss_functionr  r   r   r   r<  )r}   r,  r   r   r   r-  r  r   r   r.  r/  r   rN  r  transformer_outputsr   	lm_logitsr  r   s                      rD   rf   BloomForCausalLM.forwardh  ss   D 2556JDQ##NE:%GMM+
 #$q(9:N9OPQQ%0%<k$++B]B]"..+)'/!5#) / 
 ,A.LL/	YYy//0F%%;;11#5	 & D \$7$;;F)-)9TGf$EvE0/??-;;*55
 	
rF   pastbeam_idxc           	         ^ U VVs0 s H1  o3  H(  oDR                   UR                  UR                   5      _M*     M3     snnm[        U4S jU 5       5      nU$ s  snnf )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.

Output shares the same memory storage as `past`.
c              3      >#    U  HO  nUS    R                  S TUS    R                     5      US   R                  S TUS    R                     5      4v   MQ     g7f)r   r   N)index_selectr&   )r7  r   device_to_beam_idxs     rD   r9  2BloomForCausalLM._reorder_cache.<locals>.<genexpr>  sf      

 #
 1**1.@AAUAU.VW1**1.@AAUAU.VW #s   AA)r&   r8   rM  )r}   r  r  r   
past_statereordered_pastr  s         @rD   _reorder_cacheBloomForCausalLM._reorder_cache  sn     QU
PT*gqYcx{{:+<+<==gqPT
  

 #
 
 
s   8A)r  r   )NNNNT)NNNNNNNNNNN)ro   rp   rq   rr   _tied_weights_keysr   r|   r  r.   rt   r  r  r   r   r   r   r   r   r   r   rf   r  ru   r   r   s   @rD   r  r    s    ++{ &ELL & <|  15ae15,004)-$(,0/3&*59T
E,,-T
 "%uU5<<;U5VX[5[/\(\"]^T
 !.	T

 ELL)T
  -T
 &T
 D>T
 $D>T
 'tnT
 d^T
 !!1!12T
 
uU\\"$EE	FT
 T
l%ell :;S@AMRM]M]	uU\\5<</0#5	6 rF   r  a  
    The Bloom Model transformer with a sequence classification head on top (linear layer).

    [`BloomForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-1) 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                     ^  \ rS rSrS\4U 4S jjr\          SS\\R                     S\\
\\\\R                  \R                  4   S4   4      S\\R                     S\\R                     S	\\R                     S
\\R                     S\\   S\\   S\\   S\\   S\
\\R                     \4   4S jj5       rSrU =r$ )BloomForSequenceClassificationi  r   c                    > [         TU ]  U5        UR                  U l        [        U5      U l        [
        R                  " UR                  UR                  SS9U l        U R                  5         g r  )
r{   r|   
num_labelsr  r   r   r   r   scorer  r  s     rD   r|   'BloomForSequenceClassification.__init__  sV      ++%f-YYv1163D3D5Q
 	rF   r,  r   .r   r   r-  r  r   r   r.  r/  r"   c                 "   UR                  SS5      SLa  [        R                  " S[        5        [	        U5      S:  a  [        SU 35      eU
b  U
OU R                  R                  n
U R                  UUUUUUUU	U
S9	nUS   nU R                  U5      nUb  UR                  S   nOUR                  S   nU R                  R                  c  US:w  a  [        S	5      eU R                  R                  c  S
nOUb  XR                  R                  :g  R                  UR                  [        R                  5      n[        R                   " UR                  S
   UR                  [        R                  S9nUU-  R#                  S
5      nO.S
n[$        R'                  U R(                  R*                   S35        U[        R                   " XR                  S9U4   nSnUGbg  U R                  R,                  c  U R.                  S:X  a  SU R                  l        OoU R.                  S:  aN  UR0                  [        R2                  :X  d  UR0                  [        R4                  :X  a  SU R                  l        OSU R                  l        U R                  R,                  S:X  aJ  [7        5       nU R.                  S:X  a&  U" UR9                  5       UR9                  5       5      nOeU" UU5      nO[U R                  R,                  S:X  a  [;        5       nU" UU5      nO-U R                  R,                  S:X  a  [=        5       nU" UU5      nU
(       d  U4USS -   nUb  U4U-   $ U$ [?        UUUR@                  URB                  URD                  S9$ )  
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_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 [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
    [`PreTrainedTokenizer.__call__`] for details.

    [What are input IDs?](../glossary#input-ids)
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).
r2  Fr3  r   r4  Nr   r   r   r-  r   r   r.  r/  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.`r5  
regressionsingle_label_classificationmulti_label_classificationr  )#r=  r>  r?  r@  rA  r   r   rB  r   r  r*   pad_token_idr8   r&   r.   r2   r1   argmaxr   r   r~   ro   problem_typer  r!   longr   r
   squeezer   r   r   r   r   r<  )r}   r,  r   r   r   r-  r  r   r   r.  r/  rN  r  r   r  r9   last_non_pad_tokennon_pad_masktoken_indicespooled_logitsr  loss_fctr   s                          rD   rf   &BloomForSequenceClassification.forward  s;   @  ##NE:%GMM+
 #$q(9:N9OPQQ%0%<k$++B]B]"..+)'/!5# / 

 ,A.M* "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||J}}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+-v6))-II,.v6#%(;AB(??F)-)9TGf$EvE/ /??-;;*55
 	
rF   )r  r  r   r|  )ro   rp   rq   rr   r   r|   r   r   r.   r   r   r   r   rt   r   r   rf   ru   r   r   s   @rD   r  r    s;   {   15ae15,004)-$(,0/3&*q
E,,-q
 "%uU5<<;U5VX[5[/\(\"]^q
 !.	q

 ELL)q
  -q
 &q
 D>q
 $D>q
 'tnq
 d^q
 
uU\\"$DD	Eq
 q
rF   r  c                     ^  \ rS rSrS\4U 4S jjr\          SS\\R                     S\\
\\\\R                  \R                  4   S4   4      S\\R                     S\\R                     S	\\R                     S
\\R                     S\\   S\\   S\\   S\\   S\
\\R                     \4   4S jj5       rSrU =r$ )BloomForTokenClassificationid  r   c                   > [         TU ]  U5        UR                  U l        [        U5      U l        [        US5      (       a  UR                  b  UR                  nO-[        US5      (       a  UR                  b  UR                  nOSn[        R                  " U5      U l
        [        R                  " UR                  UR                  5      U l        U R                  5         g )Nclassifier_dropoutr   g?)r{   r|   r  r  r   hasattrr  r   r   r   rN   r   r   
classifierr  )r}   r   r  r~   s      rD   r|   $BloomForTokenClassification.__init__f  s      ++%f-6/00V5N5N5Z!'!:!:V-..63H3H3T!'!6!6!$zz"45))F$6$68I8IJ 	rF   r,  r   .r   r   r-  r  r   r   r.  r/  r"   c                    UR                  SS5      SLa  [        R                  " S[        5        [	        U5      S:  a  [        SU 35      eU
b  U
OU R                  R                  n
U R                  UUUUUUUU	U
S9	nUS   nU R                  U5      nU R                  U5      nSnUbl  UR                  UR                  5      nUR                  u  nn[        5       nU" UR                  UU-  U R                   5      UR                  UU-  5      5      nU
(       d  U4USS -   nUb  U4U-   $ U$ [#        UUUR$                  UR&                  S	9$ )
r  r2  Fr3  r   r4  Nr  r$   )r  r  r   r<  )r=  r>  r?  r@  rA  r   r   rB  r   rN   r  r8   r&   r*   r   r   r  r   r   r<  )r}   r,  r   r   r   r-  r  r   r   r.  r/  rN  r  r   r  r  r9   r:   r  r   s                       rD   rf   #BloomForTokenClassification.forwardw  s}   @  ##NE:%GMM+
 #$q(9:N9OPQQ%0%<k$++B]B]"..+)'/!5# / 

 ,A.]3/YYv}}-F%+\\"J
')HJ3T__Ev{{S]`jSjGkD Y!4QR!88F)-)9TGf$EvE$-;;*55	
 	
rF   )r  rN   r  r   r|  )ro   rp   rq   rr   r   r|   r   r   r.   r   r   r   r   rt   r   r   rf   ru   r   r   s   @rD   r  r  d  s;   { "  15ae15,004)-$(,0/3&*N
E,,-N
 "%uU5<<;U5VX[5[/\(\"]^N
 !.	N

 ELL)N
  -N
 &N
 D>N
 $D>N
 'tnN
 d^N
 
uU\\"$99	:N
 N
rF   r  c                   R  ^  \ rS rSrU 4S jr\          SS\\R                     S\\R                     S\\R                     S\\R                     S\\R                     S\\R                     S	\\R                     S
\\
   S\\
   S\\
   S\\\4   4S jj5       rSrU =r$ )BloomForQuestionAnsweringi  c                    > [         TU ]  U5        [        U5      U l        [        R
                  " UR                  S5      U l        U R                  5         g )Nr$   )	r{   r|   r  r   r   r   r   
qa_outputsr  r  s     rD   r|   "BloomForQuestionAnswering.__init__  sA     %f-))F$6$6: 	rF   r,  r   r2  r   r-  start_positionsend_positionsr   r.  r/  r"   c                    U
b  U
OU R                   R                  n
U R                  UUUUUUU	U
S9nUS   nU R                  U5      nUR	                  SSS9u  pUR                  S5      R                  5       nUR                  S5      R                  5       nSnUb  Ub  [        UR                  5       5      S:  a  UR                  S5      n[        UR                  5       5      S:  a  UR                  S5      nUR                  S5      nUR                  SU5      nUR                  SU5      n[        US9nU" X5      nU" X5      nUU-   S-  nU
(       d  X4USS -   nUb  U4U-   $ U$ [        UUUUR                  UR                  S	9$ )
r1  N)r   r2  r   r-  r   r.  r/  r   r   r)   r'   )ignore_indexr$   )r  start_logits
end_logitsr   r<  )r   rB  r   r  splitr  
contiguousrA  sizeclampr   r   r   r<  )r}   r,  r   r2  r   r-  r  r  r   r.  r/  r   sequence_outputr  r  r  
total_lossignored_indexr  
start_lossend_lossr   s                         rD   rf   !BloomForQuestionAnswering.forward  s   6 &1%<k$++B]B]"")%'/!5# # 	
 "!*1#)<<r<#: #++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EO)//=AM']CH!,@J
:H$x/14J"/'!"+=F/9/EZMF*Q6Q+%!!//))
 	
rF   )r  r   r|  )ro   rp   rq   rr   r|   r   r   r.   r   FloatTensorr   r   r   r   rf   ru   r   r   s   @rD   r  r    s     156:3715596:48,0/3&*I
E,,-I
 !!2!23I
 u//0	I

 E--.I
   1 12I
 "%"2"23I
   0 01I
 $D>I
 'tnI
 d^I
 
u22	3I
 I
rF   r  )r  r  r   r  r  r  )Fr   r+   r>  typingr   r   r   r.   torch.utils.checkpointr   torch.nnr   r   r	   r
   r   rM   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   r   r   modeling_utilsr   utilsr   r   r   configuration_bloomr   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   
get_loggerro   r   rt   r   r!   rE   floatr   rP   rX   r]   autogradFunctionr_   r  rw   r   r   r   r   r  r  r  r  r  __all__rn   rF   rD   <module>r     s[      ) )    L L $ ; ; ) >  . 
 -  !!;J 
		H	%)Ju|| )J )JEKK )J\a\h\h )JX5<< 5<< u PT Y^YeYe &	Q%,, 	Q5<< 	Qu||   $
5>>** 
)		 )&[RYY [|ryy >F FR *? * *< v% v vr	 {+_ {{| |
%9 |
|
~ a
"6 a
 a
H S
 4 S
 S
lrF   