
    ^js                        d dl Z d dlmZ d dlmZ d dlZd dl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mZmZ dd	lmZ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%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7m8Z8 ddl9m:Z:m;Z; ddl<m=Z=m>Z>  e5j~                  e@      ZA G d dej                        ZC G d dej                        ZD G d dej                        ZEd ZF ed      dLd       ZGdej                  d eId!ej                  fd"ZJ	 	 	 dMd#ej                  d$ej                  d%ej                  d&ej                  d'ej                  dz  d(eKeIz  d)eKdz  d*eKdz  d!eLej                  ej                  f   fd+ZM eeG       G d, d-ej                               ZN eeG       G d. d/ej                               ZO G d0 d1e!      ZP G d2 d3e!      ZQ G d4 d5ej                        ZR G d6 d7ej                        ZSe3 G d8 d9e.             ZTd:ej                  dz  dej                  d;eIdz  d!ej                  fd<ZV G d= d>eT      ZW G d? d@eT      ZXe3 G dA dBeT             ZYe3 G dC dDeT             ZZ G dE dFeTe      Z[e3 G dG dHeT             Z\e3 G dI dJeT             Z]g dKZ^y)N    N)Callable)Optional   )initialization)ACT2FN)CacheDynamicCacheEncoderDecoderCacheStaticCache)GenerationConfigGenerationMixinGenerationMode)use_kernel_func_from_hubuse_kernelized_func)create_bidirectional_mask(create_bidirectional_sliding_window_maskcreate_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)BaseModelOutputWithPastAndCrossAttentionsSeq2SeqLMOutputSeq2SeqModelOutputSequenceClassifierOutputTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )T5GemmaConfigT5GemmaModuleConfigc                   <     e Zd Zddedef fdZd Zd Zd Z xZ	S )T5GemmaRMSNormdimepsc                     t         |           || _        t        j                  t        j                  |            | _        y N)super__init__r0   nn	Parametertorchzerosweight)selfr/   r0   	__class__s      w/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/t5gemma/modeling_t5gemma.pyr4   zT5GemmaRMSNorm.__init__>   s.    ll5;;s#34    c                     |t        j                  |j                  d      j                  dd      | j                  z         z  S )N   T)keepdim)r7   rsqrtpowmeanr0   )r:   xs     r<   _normzT5GemmaRMSNorm._normC   s4    5;;quuQx}}R}>IJJJr=   c                     | j                  |j                               }|d| j                  j                         z   z  }|j                  |      S )N      ?)rF   floatr9   type_as)r:   rE   outputs      r<   forwardzT5GemmaRMSNorm.forwardF   sC    AGGI& 3!2!2!445~~a  r=   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler9   shaper0   r:   s    r<   
extra_reprzT5GemmaRMSNorm.extra_reprM   s'    ))*+6$((<<r=   )gư>)
__name__
__module____qualname__intrI   r4   rF   rL   rQ   __classcell__r;   s   @r<   r.   r.   =   s&    5C 5e 5
K!=r=   r.   c                   $     e Zd Z fdZd Z xZS )
T5GemmaMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        t        j                  |j                        | _        y )NFbias)r3   r4   confighidden_sizeintermediate_sizer5   Linear	gate_projup_proj	down_projr   hidden_activationact_fnDropoutdropout_ratedropoutr:   r]   r;   s     r<   r4   zT5GemmaMLP.__init__R   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV556zz&"5"56r=   c                     | j                  | j                  |            | j                  |      z  }| j                  |      }| j	                  |      }|S r2   )re   ra   rb   rh   rc   )r:   rE   hidden_statesrc   s       r<   rL   zT5GemmaMLP.forward]   sH    DNN1$56aH]3NN=1	r=   )rR   rS   rT   r4   rL   rV   rW   s   @r<   rY   rY   Q   s    	7r=   rY   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )T5GemmaRotaryEmbeddinginv_freqNr]   c                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultrn   F)
persistentoriginal_inv_freq)r3   r4   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr]   rope_parametersrp   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r:   r]   devicerope_init_fnrn   r;   s        r<   r4   zT5GemmaRotaryEmbedding.__init__g   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr=   r|   ztorch.deviceseq_lenreturnztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}d|t	        j
                  d|dt        j                        j                  |t        j                        |z  z  z  }||fS )	a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetahead_dimNrH   r   r?   dtyper|   r   )	rw   getattrr^   num_attention_headsr7   arangeint64torI   )r]   r|   r~   baser/   attention_factorrn   s          r<   rx   z6T5GemmaRotaryEmbedding.compute_default_rope_parametersw   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r=   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r@   r*   mpscpuF)device_typeenabledr?   r/   r   )rn   rI   expandrO   r   r|   
isinstancetypestrr&   	transposer7   catcosry   sinr   )
r:   rE   position_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r<   rL   zT5GemmaRotaryEmbedding.forward   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$r2   NNN)rR   rS   rT   r7   Tensor__annotations__r+   r4   staticmethodr   rU   rN   rI   rx   no_gradr   rL   rV   rW   s   @r<   rm   rm   d   s    llV} V  '++/"*$*(* t* 
~u$	%	* *: U]]_<  <r=   rm   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr@   r?   r   )rO   r7   r   )rE   x1x2s      r<   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r=   rotary_pos_embc                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer   )qkr   r   unsqueeze_dimq_embedk_embeds          r<   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr=   rk   n_repr   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r*   N)rO   r   reshape)rk   r   batchnum_key_value_headsslenr   s         r<   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr=   modulequerykeyvalueattention_maskrh   scalingsoftcapc                 |   || j                   dz  }t        || j                        }	t        || j                        }
t        j                  ||	j                  dd            |z  }|||z  }t        j                  |      }||z  }|||z   }t        j                  j                  |dt        j                        j                  |j                        }t        j                  j                  ||| j                        }t        j                  ||
      }|j                  dd      j                         }||fS )N      r?   r   r@   )r/   r   )ptrainingr*   )r   r   num_key_value_groupsr7   matmulr   tanhr5   
functionalsoftmaxfloat32r   r   rh   r   
contiguous)r   r   r   r   r   rh   r   r   kwargs
key_statesvalue_statesattn_weightsattn_outputs                r<   eager_attention_forwardr      s    //4'3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL#g-zz,/#g-!#n4 ==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r=   c                        e Zd ZdZdedef fdZ	 	 	 ddej                  de	ej                  ej                  f   dz  dej                  dz  d	e
dz  d
ee   de	ej                  ej                  dz  e	ej                     dz  f   fdZ xZS )T5GemmaSelfAttention=Multi-headed attention from 'Attention Is All You Need' paperr]   	layer_idxc                 V   t         |           t        |d      r|j                  |   nd | _        || _        || _        t        |d|j                  |j                  z        | _
        |j                  |j                  z  | _        |j                  dz  | _        | j
                  j                  | _        |j                   | _        t%        j&                  |j                  |j                  | j                  z  |j(                        | _        t%        j&                  |j                  |j                  | j                  z  |j(                        | _        t%        j&                  |j                  |j                  | j                  z  |j(                        | _        t%        j&                  |j                  | j                  z  |j                  |j(                        | _        | j
                  j2                  | _        | j                  dk(  r|j4                  | _        y d | _        y )Nlayer_typesr   r   r[   sliding_attention)r3   r4   hasattrr   
layer_typer]   r   r   r^   r   r   r   r   query_pre_attn_scalarr   attention_dropout
is_decoder	is_causalr5   r`   attention_biasq_projk_projv_projo_projattn_logit_softcappingsliding_windowr:   r]   r   r;   s      r<   r4   zT5GemmaSelfAttention.__init__   s   ;B6=;Y&,,Y7_c"
F4F4F&JdJd4de$*$>$>&B\B\$\!33T9!%!>!>**ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
 '+kk&H&H#7;J]7]f33cgr=   Nrk   position_embeddingsr   past_key_valuesr   r   c                 6   |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
|\  }}t        ||	||      \  }}	| |j                  |	|
| j                        \  }	}
t        j                  | j                  j                  t              } || ||	|
|f| j                  r| j                   nd| j"                  | j$                  | j&                  d|\  }} |j(                  g |d j+                         }| j-                  |      }||fS )Nr@   r*   r?           rh   r   r   r   )rO   r   r   viewr   r   r   r   updater   r   get_interfacer]   _attn_implementationr   r   r   r   r   r   r   r   r   )r:   rk   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   attention_interfacer   r   s                   r<   rL   zT5GemmaSelfAttention.forward  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S#7jRUWZ#[ j&'6'='=j,X\XfXf'g$J(?(M(MKK,,.E)
 %8%
 /3mmD**LL..//%
 %
!\ *k));;;;FFHkk+.L((r=   r   )rR   rS   rT   __doc__r,   rU   r4   r7   r   rN   r   r!   r   rL   rV   rW   s   @r<   r   r      s    Gh2 hs h< IM.2(,()||() #5<<#=>E() t+	()
 () -.() 
u||U\\D0%2E2LL	M()r=   r   c                        e Zd ZdZdedef fdZ	 ddej                  dej                  dz  dej                  dz  d	e	dz  d
e
e   deej                  ej                  dz  eej                     dz  f   fdZ xZS )T5GemmaCrossAttentionr   r]   r   c                    t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        |j                  dz  | _        | j                  j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                         | _        t        j                  |j$                  |j                  | j                  z  |j                         | _        t        j                  |j$                  |j                  | j                  z  |j                         | _        t        j                  |j                  | j                  z  |j
                  |j                         | _        | j                  j,                  | _        |j$                  t/        d      y )Nr   r   Fr[   zBCross-attention needs cross_attention_hidden_size to be specified.)r3   r4   r]   r   r   r^   r   r   r   r   r   r   r   r   r5   r`   r   r   cross_attention_hidden_sizer   r   r   r   
ValueErrorr   s      r<   r4   zT5GemmaCrossAttention.__init__B  s   "
F4F4F&JdJd4de$*$>$>&B\B\$\!33T9!%!>!>ii : :T]] JQWQfQf
 ii..0J0JT]]0Zagavav
 ii..0J0JT]]0Zagavav
 ii&&68J8JQWQfQf
 '+kk&H&H#--5abb 6r=   Nrk   r   encoder_hidden_statesr   r   r   c                    |t        d      |j                  d d }g |d| j                  }| j                  |      j	                  |      j                  dd      }|1|j                  j                  | j                        }	|j                  }
|	s|j                  d d }g |d| j                  }| j                  |      j	                  |      j                  dd      }| j                  |      j	                  |      j                  dd      }|
j                  ||| j                        \  }}d|j                  | j                  <   nF
j                  | j                     j                  }|
j                  | j                     j                  }t!        j"                  | j$                  j&                  t(              } || ||||f| j*                  r| j,                  nd| j.                  d | j0                  d|\  }} |j2                  g |d j5                         }| j7                  |      }||fS )Nz5Encoder hidden state is required for cross attention.r@   r*   r?   Tr   r   )r   rO   r   r   r   r   
is_updatedgetr   cross_attention_cacher   r   r   layerskeysvaluesr   r   r]   r   r   r   r   r   r   r   r   r   )r:   rk   r   r   r   r   r   r   r   r   curr_past_key_valuesencoder_input_shapeencoder_hidden_shaper   r   r   r   r   s                     r<   rL   zT5GemmaCrossAttention.forward^  s?    !(TUU#))#2.88b8$--8{{=166|DNNqRST&(3377GJ#2#H#H "*"7"="=cr"B#L%8#L"#Ldmm#L %:;@@AUV``abdefJ;;'<=BBCWXbbcdfghL*+?+F+FzS_aeaoao+p(
L=A**4>>:-44T^^DIIJ/66t~~FMML(?(M(MKK,,.E)
 %8%
 /3mmD**LL//%
 %
!\ *k));;;;FFHkk+.L((r=   r2   )rR   rS   rT   r   r,   rU   r4   r7   r   r   r!   r   rN   rL   rV   rW   s   @r<   r   r   >  s    Gc2 cs cB )-3)||3) t+3)  %||d2	3)
 3) -.3) 
u||U\\D0%2E2LL	M3)r=   r   c                        e Zd ZdZdef fdZ	 	 	 ddej                  deej                  ej                  f   dz  dej                  dz  dej                  dz  d	eej                  f   f
d
Z xZS )T5GemmaEncoderLayerzEncoder sub-layer.r   c                 D   t         |           |j                  | _        || _        || _        |j
                  |   | _        t        ||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t#        j$                  |j&                        | _        y N)r]   r   r0   )r3   r4   r^   r]   r   r   attention_typer   	self_attnr.   rms_norm_epspre_self_attn_layernormpost_self_attn_layernormrY   mlppre_feedforward_layernormpost_feedforward_layernormr5   rf   rg   rh   r   s      r<   r4   zT5GemmaEncoderLayer.__init__  s    !--"$00;-
 (6f6H6HfNaNa'b$(6v7I7IvObOb(c%f%)78J8JPVPcPc)d&*89K9KQWQdQd*e'zz&"5"56r=   Nrk   r   r   r   r   c           	      >   |}| j                  |      } | j                  d||||d d|\  }}| j                  |      }|| j                  |      z   }|}| j	                  |      }| j                  |      }| j                  |      }|| j                  |      z   }|S )N)rk   r   r   r   r    )r  r
  r  rh   r  r  r  )r:   rk   r   r   r   r   residual_s           r<   rL   zT5GemmaEncoderLayer.forward  s     !44]C)4>> 
' 3)% 
 
q 55mD 4<<#>> 66}E/77F 4<<#>>r=   r   )rR   rS   rT   r   rU   r4   r7   r   rN   
LongTensorFloatTensorrL   rV   rW   s   @r<   r  r    s    7# 7. IM.204|| #5<<#=>E t+	
 &&- 
u  !	"r=   r  c                   8    e Zd ZdZdef fdZ	 	 	 	 	 	 	 ddej                  deej                  ej                  f   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j                  dz  dej                  fdZ xZS )T5GemmaDecoderLayerz2Decoder sub-layer: an extra cross-attention layer.r   c                     t         |           |j                  | _        || _        || _        |j
                  |   | _        t        ||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t        |      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        t#        j$                  |j&                        | _        t+        ||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        y r  )r3   r4   r^   r]   r   r   r	  r   r
  r.   r  r  r  rY   r  r  r  r5   rf   rg   rh   r   
cross_attnpre_cross_attn_layernormpost_cross_attn_layernormr   s      r<   r4   zT5GemmaDecoderLayer.__init__  s&   !--"$00;-
 (6f6H6HfNaNa'b$(6v7I7IvObOb(c%f%)78J8JPVPcPc)d&*89K9KQWQdQd*e'zz&"5"56/vS(6v7I7IvObOb(c%)78J8JPVPcPc)d&r=   Nrk   r   r   r   r   	use_cacher   encoder_attention_maskr   c	           
         |}
| j                  |      } | j                  d||||||j                  nd |d|	\  }}| j                  |      }|
| j	                  |      z   }|}
| j                  |      } | j                  d|||||d|	\  }}| j                  |      }|
| j	                  |      z   }|}
| j                  |      }| j                  |      }| j                  |      }|
| j	                  |      z   }|S )N)rk   r   r   r   r   r  )rk   r   r   r   r  r  )r  r
  self_attention_cacher  rh   r  r  r  r  r  r  )r:   rk   r   r   r   r   r  r   r  r   r  r  s               r<   rL   zT5GemmaDecoderLayer.forward  s;    !44]C)4>> 
' 3)%DSD_O@@ei
 
q 55mD 4<<#>> 55mD*4?? 
'"71+
 
q 66}E 4<<#>> 66}E/77F 4<<#>>r=   )NNNNFNN)rR   rS   rT   r   rU   r4   r7   r   rN   r  r
   boolr  rL   rV   rW   s   @r<   r  r    s    <e# e4 IM.2046:!&596:,||, #5<<#=>E, t+	,
 &&-, -t3, $;,  %||d2, !&t 3, 
		,r=   r  c                   j     e Zd ZdZd	dededef fdZdej                  dej                  fdZ	 xZ
S )
T5GemmaClassificationHeadz-Head for sentence-level classification tasks.r^   
num_labelsclassifier_dropout_ratec                     t         |           t        j                  |      | _        t        j
                  ||      | _        y )N)r   )r3   r4   r5   rf   rh   r`   out_proj)r:   r^   r$  r%  r;   s       r<   r4   z"T5GemmaClassificationHead.__init__  s1    zz$;<		+z:r=   rk   r   c                 J    | j                  |      }| j                  |      }|S r2   )rh   r'  )r:   rk   s     r<   rL   z!T5GemmaClassificationHead.forward  s$    ]3m4r=   )r   )rR   rS   rT   r   rU   rI   r4   r7   r   rL   rV   rW   s   @r<   r#  r#    s<    7;C ;S ;SX ;
U\\ ell r=   r#  c                   j     e Zd ZdZd	dededef fdZdej                  dej                  fdZ	 xZ
S )
T5GemmaLMHeadz.Head for language modeling (generation) tasks.r^   
vocab_sizer\   c                 \    t         |           t        j                  |||      | _        y )Nr[   )r3   r4   r5   r`   r'  )r:   r^   r+  r\   r;   s       r<   r4   zT5GemmaLMHead.__init__"  s"    		+zEr=   rk   r   c                 (    | j                  |      }|S r2   )r'  )r:   rk   logitss      r<   rL   zT5GemmaLMHead.forward&  s    }-r=   )F)rR   rS   rT   r   rU   r!  r4   r7   r   rL   rV   rW   s   @r<   r*  r*    s?    8FC FS F FU\\ ell r=   r*  c                        e Zd ZU eed<   dZdZddgZdgZdZ	dZ
dZdZdZdZ ej                           fd       Zd	 Z xZS )
T5GemmaPreTrainedModelr]   modelTr  r  r   Nc                 4   t         |   |       | j                  j                  }t	        |t
              r|j                  j                  j                  d   dz  }t        j                  |j                  j                  d||z         t        |j                  d      rA|j                  j                  *t        j                  |j                  j                         y y y t	        |t              rm| j                  j                  sV|j                  j                  j                  d   dz  }t        j                  |j                  j                  d||z         y y d|j                   j"                  v r t        j                  |j                         y y )Nr   r   r   )rD   stdr\   RMSNorm)r3   _init_weightsr]   initializer_ranger   r#  r'  r9   rO   initnormal_r   r\   zeros_r*  tie_word_embeddingsr;   rR   )r:   r   r3  scaler;   s       r<   r5  z$T5GemmaPreTrainedModel._init_weights;  s)    	f%kk++f78OO**003t;ELL//csU{Kv/FOO4H4H4TFOO001 5U/.;;22..44Q74?V__33#3;O 3 &**333KK& 4r=   c                 `   | j                   j                  j                  }| j                   j                  j                  }|t	        d      |j                  |j                        }|dddf   j                         |dddf<   ||d<   |t	        d      |j                  |dk(  |       |S )	z
        Shifts input_ids to the right, prepends the decoder_start_token_id, and handles
        pad_token_id replacement for labels that were -100.
        This is a common preparation step for decoder inputs in sequence-to-sequence models.
        Nz:self.model.config.decoder.bos_token_id has to be defined. .r@   r*   ).r   z9self.model.config.decoder.pad_token_id has to be defined.i)	r]   decoderbos_token_idpad_token_idr   	new_zerosrO   r{   masked_fill_)r:   	input_idsdecoder_start_token_idr?  shifted_input_idss        r<   _shift_rightz#T5GemmaPreTrainedModel._shift_rightM  s     "&!4!4!A!A{{**77!)YZZ &//	@%.sCRCx%8%>%>%@#qr'"$:&!XYY 	&&'8D'@,O  r=   )rR   rS   rT   r+   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backend_can_record_outputsr7   r   r5  rE  rV   rW   s   @r<   r0  r0  +  sl    &*#.0EF#4"5N!"&U]]_' '"!r=   r0  	token_idsr?  c                    | <|t        d      | |k7  j                  |j                  t        j                        }|S t        j
                  |j                  d   |j                  d   f|j                  t        j                        }|S )z%Construct the default attention mask.z3`pad_token_id` is required for padding information.r   r*   r   )r   r   r|   r7   longonesrO   )rP  rk   r?  r   s       r<   make_default_2d_attention_maskrT  h  s     RSS#|3778L8LejjY
    #]%8%8%;<]EYEYafakak
 r=   c                        e Zd ZeedZ fdZee	 	 	 	 dde	j                  dz  de	j                  dz  de	j                  dz  de	j                  dz  dee   d	eez  fd
              Z xZS )T5GemmaEncoder)
attentionsrk   c           	      T   t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        |j                  |j                        | _        d| _        t        j                  t        |j                        D cg c]  }t!        ||       c}      | _        t        j$                  |j&                        | _        t+        |      | _        | j/                          y c c}w Nr  Fr]   )r3   r4   r?  padding_idxr+  r5   	Embeddingr^   embed_tokensr.   r  normgradient_checkpointing
ModuleListrangenum_hidden_layersr  r   rf   rg   rh   rm   
rotary_emb	post_initr   s      r<   r4   zT5GemmaEncoder.__init__       !.. ++LL):):F<N<NPTP`P`a"6#5#56;N;NO	&+#mmEJ6KcKcEde	 3e
 zz&"5"560? 	 f    D%NrB  r   r   inputs_embedsr   r   c                    |d u |d uz  rt        d      |j                  dd        || j                  |      }|?t        j                  |j
                  d   |j                        }|j                  d      }|!t        ||| j                  j                        }t        |x}t              s'| j                  ||d}t        di |t        di |d}|}t        j                  | j                  j                   dz  |j"                  	      }	||	z  }| j%                  |      }| j'                  ||      }
t)        | j*                  d | j                  j,                         D ]+  \  }} |||
|| j                  j.                  |      |fi |}- | j1                  |      }| j%                  |      }t3        |
      S )N:You must specify exactly one of input_ids or inputs_embedsr   r*   r|   r   )r]   rg  r   full_attentionr         ?r   )last_hidden_stater  )r   popr]  r7   r   rO   r|   r   rT  r]   r?  r   dictr   r   tensorr^   r   rh   rc  	enumerater   rb  r   r^  r   )r:   rB  r   r   rg  r   self_attn_mask_mappingmask_kwargsrk   
normalizerr   ilayer_modules                r<   rL   zT5GemmaEncoder.forward  s    -t";<YZZ 	

$d+  --i8M <<(;(;A(>}G[G[\L'11!4L!;I}VZVaVaVnVnoNNB0DI++!."0K #<"Jk"J%M%\P[%\&"
 &\\$++"9"93">mFYFYZ
%
2]3"oom\J(5Tt{{7T7T)UV 	OA|(#&t{{'>'>q'AB	
 M	 		-0]3+
 	
r=   NNNN)rR   rS   rT   r   r  rO  r4   r'   r)   r7   r  r   r  r!   r"   rN   r   rL   rV   rW   s   @r<   rV  rV  y  s    *,
$   .2.204266
##d*6
 t+6
 &&-	6

 ((4/6
 +,6
 
	 6
   6
r=   rV  c                   T    e Zd Z eed       eed      edZ fdZe	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j                  dz  dee   deez  fd              Z xZS )T5GemmaDecoderr*   )index)rW  cross_attentionsrk   c           	      T   t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        |j                  |j                        | _        d| _        t        j                  t        |j                        D cg c]  }t!        ||       c}      | _        t        j$                  |j&                        | _        t+        |      | _        | j/                          y c c}w rY  )r3   r4   r?  r[  r+  r5   r\  r^   r]  r.   r  r^  r_  r`  ra  rb  r  r   rf   rg   rh   rm   rc  rd  r   s      r<   r4   zT5GemmaDecoder.__init__  re  rf  NrB  r   r   r   rg  r  r   r  r   r   c	                    |d u |d uz  rt        d      |t        d      || j                  |      }| j                  s,|r*|(t        t	        | j
                        t	                     }|V||j                         nd}
t        j                  |j                  d   |j                        |
z   }|j                  d      }|#|!t        ||| j
                  j                        }t        |x}t              s7| j
                  ||||j                   nd |d}t#        di |t%        di |d}t        |x}t              sd	t'        | j
                  |||
      i}|}t        j(                  | j
                  j*                  dz  |j,                        }||z  }| j/                  |      }| j1                  ||      }t3        | j4                  d | j
                  j6                         D ]2  \  }} ||||| j
                  j8                  |      |||||d	   fi |	}4 | j;                  |      }| j/                  |      }t=        ||      S )Nri  z0`encoder_hidden_states` must be given in decoderrZ  r   r*   rj  )r]   rg  r   r   r   rk  rl  )r]   rg  r   r   rm  r   )rn  r   r  )r   r]  r   r
   r	   r]   get_seq_lengthr7   r   rO   r|   r   rT  r?  r   rp  r   r   r   r   rq  r^   r   rh   rc  rr  r   rb  r   r^  r   )r:   rB  r   r   r   rg  r  r   r  r   past_seen_tokensrs  rt  cross_attn_mask_mappingrk   ru  r   rv  rw  s                      r<   rL   zT5GemmaDecoder.forward  su    -t";<YZZ (OPP  --i8M}}/F 2,dkk2RT`TbcOCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L!o&=;I}VZVaVaVnVnoNNB0DI++!."0KZKf?#G#Glp ,K #5"C{"C%F%U%U&"
 5KK1TR ";;;"/#9*?	#'# &\\$++"9"93">mFYFYZ
%
2]3"oom\J(5Tt{{7T7T)UV 	OA|(#&t{{'>'>q'AB%'(89
 
M	 		-0]38++
 	
r=   )NNNNNNNN)rR   rS   rT   r(   r   r   r  rO  r4   r'   r)   r7   r  r   r
   r  r!  r!   r"   rN   r   rL   rV   rW   s   @r<   rz  rz    s   $%9C*+@J,$   .2.2046:26!%596:P
##d*P
 t+P
 &&-	P

 -t3P
 ((4/P
 $;P
  %||d2P
 !&t 3P
 +,P
 
:	:P
   P
r=   rz  c                       e Zd Zdef fdZd Zd Zee	 	 	 	 	 	 	 	 	 	 	 d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	j                  dz  dedz  de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 )T5GemmaModelr]   c                     t         |   |       |j                  st        d      t	        |j
                        | _        t        |j                        | _        | j                          y )NzVT5GemmaModel only support encoder-decoder modeling. Use `T5GemmaEncoderModel` instead.)	r3   r4   is_encoder_decoderr   rV  encoderrz  r=  rd  ri   s     r<   r4   zT5GemmaModel.__init__<  sO     ((uvv%fnn5%fnn5r=   c                 6    | j                   j                         S r2   r  get_input_embeddingsrP   s    r<   r  z!T5GemmaModel.get_input_embeddingsG      ||0022r=   c                 8    | j                   j                  |      S r2   r  set_input_embeddingsr:   new_embeddingss     r<   r  z!T5GemmaModel.set_input_embeddingsJ      ||00@@r=   NrB  r   r   decoder_input_idsdecoder_attention_maskdecoder_position_idsencoder_outputsr   rg  decoder_inputs_embedsr  r   r   c                    | | j                   d||||	d|}|j                  } | j                  d||||
||||d|}t        |j                  |j                  |j                  dd      r|j                  n|j                  f|j                  |j                  |j                  |j                  |j                        S )aX  
        decoder_position_ids (`torch.LongTensor` of shape `(batch_size, decoder_sequence_length)`, *optional*):
            Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range `[0,
            config.decoder.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
        rB  r   r   rg  )rB  r   r   rg  r   r   r  r  output_hidden_statesF)rn  r   decoder_hidden_statesdecoder_attentionsr|  encoder_last_hidden_stater   encoder_attentionsr  )	r  rn  r=  r   r   r   rk   rW  r|  )r:   rB  r   r   r  r  r  r  r   rg  r  r  r   r   decoder_outputss                  r<   rL   zT5GemmaModel.forwardM  s    , "*dll #-)+	
 O !0 A A&$,, 

'1-/+"7#1

 

 "-??+;;zz0%8 #2"?"?!335.99,==&5&G&G"1"?"?.99
 	
r=   )NNNNNNNNNNN)rR   rS   rT   r+   r4   r  r  r$   r#   r7   r  r  
BoolTensorr   r
   r   r!  r!   r"   r   rL   rV   rW   s   @r<   r  r  :  sA   	} 	3A  .2370459:>8<266:-159!%6
##d*6
 ))D06
 &&-	6

 !++d26
 !& 0 04 76
 $..56
 )4/6
 -t36
 ||d*6
  %||d26
 $;6
 +,6
 
6
  6
r=   r  c                        e Zd Zdef fdZd Zd Zee	 	 	 	 dde	j                  dz  de	j                  dz  de	j                  dz  d	e	j                  dz  d
ee   defd              Z xZS )T5GemmaEncoderModelr]   c                     t         |   |       |j                  rt        d      t	        |j
                        | _        | j                          y )NzQT5GemmaEncoderModel only supports encoder-only model. Use `T5GemmaModel` instead.)r3   r4   r  r   rV  r  rd  ri   s     r<   r4   zT5GemmaEncoderModel.__init__  s?     $$pqq%fnn5r=   c                 6    | j                   j                         S r2   r  rP   s    r<   r  z(T5GemmaEncoderModel.get_input_embeddings  r  r=   c                 8    | j                   j                  |      S r2   r  r  s     r<   r  z(T5GemmaEncoderModel.set_input_embeddings  r  r=   NrB  r   r   rg  r   r   c                 4     | j                   d||||d|}|S )Nr  r  )r  )r:   rB  r   r   rg  r   r  s          r<   rL   zT5GemmaEncoderModel.forward  s7     '$,, 
)%'	

 
 r=   rx  )rR   rS   rT   r+   r4   r  r  r$   r#   r7   r  r  r   r!   r"   r   rL   rV   rW   s   @r<   r  r    s    } 3A  .23704-1##d* ))D0 &&-	
 ||d* +, 
  r=   r  c            "       D    e Zd ZddiZddiZddgdgfiZdef fdZd	 Zd
 Z	e
e	 	 	 	 	 	 	 	 	 	 	 	 	 d#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j                  dz  dedz  de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ej                     ez  fd              Zdej(                  fdZdededed ed!edef fd"Z xZS )$T5GemmaForConditionalGenerationzlm_head.out_proj.weightz!model.decoder.embed_tokens.weightzlm_head.out_projcolwise_gather_outputrk   r.  r]   c                    d|_         t        | 	  |       t        |      | _        |j
                  j                  | _        t        |j
                  j                  | j                        | _	        d| _
        | j                          y )NTForMaskedLM)r  r3   r4   r  r1  r=  r+  r*  r^   lm_head	loss_typerd  ri   s     r<   r4   z(T5GemmaForConditionalGeneration.__init__  sb    $(! !&)
 ..33$V^^%?%?Q&r=   c                 *   || j                   _        | j                  j                  rl|j                  | j
                  j                  j                  _        |j                  j                  d   | j
                  j                  j                  _	        y y )Nr   )
r  r'  r]   r:  r9   r1  r=  r]  rO   num_embeddingsr  s     r<   set_output_embeddingsz5T5GemmaForConditionalGeneration.set_output_embeddings  sj     . ;;**5C5J5JDJJ++2=K=R=R=X=XYZ=[DJJ++: +r=   c                 .    | j                   j                  S r2   )r  r'  rP   s    r<   get_output_embeddingsz5T5GemmaForConditionalGeneration.get_output_embeddings  s    ||$$$r=   NrB  r   r   r  r  r  r  r   rg  r  labelsr  logits_to_keepr   r   c                    |||
| j                  |      } | j                  d|||||||||	|
|d|}|j                  }t        |t              rt        | d      n|}| j                  |dd|ddf         }| j                         j                  }|j                  3||j                  z  }t        j                  |      }||j                  z  }d}| | j                  ||| j                  fi |}t        |||j                  |j                   |j"                  |j$                  |j&                  |j(                  |j*                  	      S )a  
        decoder_position_ids (`torch.LongTensor` of shape `(batch_size, decoder_sequence_length)`, *optional*):
            Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range `[0,
            config.decoder.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
        N)rB  r   r   r  r  r  r  r   rg  r  r  )	lossr.  r   r  r  r|  r  r   r  r  )rE  r1  rn  r   rU   slicer  get_decoderr]   final_logit_softcappingr7   r   loss_functionr+  r   r   r  r  r|  r  r   r  )r:   rB  r   r   r  r  r  r  r   rg  r  r  r  r  r   r  rk   slice_indicesr.  decoder_configr  s                        r<   rL   z'T5GemmaForConditionalGeneration.forward  ss   : "3";@U@] $ 1 1& 9.8djj /
)%/#9!5++'"7/
 /
 (998B>SV8W~ot4]kmA}a,?@A))+2211=nDDDFZZ'FnDDDF%4%%ffdooPPD+;;"1"G"G.AA,==&5&O&O"1"G"G.AA

 
	
r=   c                 $    | j                  |      S r2   )rE  )r:   r  s     r<   %prepare_decoder_input_ids_from_labelszET5GemmaForConditionalGeneration.prepare_decoder_input_ids_from_labels  s      ((r=   generation_configmodel_kwargsgeneration_mode
batch_sizemax_cache_lengthc           	         t         |   |||||       |j                  du ry|j                  }|d}nd|j                  v }t	        j
                  | j                  j                  d            }d|_        dg|j                  z  |_
        ||d}	|j                  d      }
|
t        |
t              st        d	      t        |
j                         d
kD  r|
j                   j                  d
      ryt#        |
j$                        }|t&        k(  r|d   d
   j(                  d   |	d<    |di |	|
_        n=t        t+        di | j                  j                  d      |dt+                     |d<   t-        | d      r=| j.                  0t        | j.                  t              st        d      |d   | _        yyy)a7  Override cache preparation to force full attention on the cross-attention cache.

        The decoder config may declare sliding-window layers, but cross-attention must always use full attention.
        The default `_prepare_cache_for_generation` would otherwise build a sliding cross-attention cache.
        FN	offloadedT)r=  rl  )r]   
offloadingr   z`The `past_key_values` in `model_kwargs` must be of type `EncoderDecoderCache` for T5Gemma model.r   r  r*   max_cache_len_cachezKThe internal cache must be of type `EncoderDecoderCache` for T5Gemma model.r  )r3   _prepare_cache_for_generationr  cache_implementationcopydeepcopyr]   get_text_configr   rb  r   r   r   r
   r   lenr   r   r   r   rO   r	   r   r  )r:   r  r  r  r  r  r  offload_cachecross_attn_configcross_attn_cache_kwargsr   cross_attn_clsr;   s               r<   r  z=T5GemmaForConditionalGeneration._prepare_cache_for_generation  s    	-	
 &&%/0EE'!M'+<+Q+QQM !MM$++*E*Ed*E*ST+/()9(:=N=`=`(`% ('#

 '**+<=&o/BC v 
 ?--.27Q7Q7U7UVW7X!/"G"GHN,;GHY;Z[\;];c;cde;f'84B4]E\4]O1 /B "&++"="=d"="K&3 /L*+ 4"t{{'>dkk+>? !noo&'89DK	 (?"r=   )NNNNNNNNNNNNr   ) rR   rS   rT   _tied_weights_keys_tp_plan_pp_planr+   r4   r  r  r$   r#   r7   r  r  r  r   r
   r!  rU   r   r!   r"   rN   r   rL   r  r   rp  r   r  rV   rW   s   @r<   r  r    s   35XY"$;<H"o%6
$CDH	} 	\%  .2370459:>8<266:26:>*.!%-.G
##d*G
 ))D0G
 &&-	G

 !++d2G
 !& 0 04 7G
 $..5G
 )4/G
 -t3G
 ((4/G
  %0047G
   4'G
 $;G
 ell*G
 +,G
  
u  	!O	3!G
  G
R)ELL )I:+I: I: (	I:
 I: I: 
I: I:r=   r  c                       e Zd Zddededz  f fdZd Zd Zee		 	 	 	 	 	 	 	 	 	 d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
j                  dz  dedz  de
j                  dz  de
j                  dz  de
j                  dz  dee   defd              Z xZS ) T5GemmaForSequenceClassificationNr]   r  c                    |||_         t        | 	  |       |j                  | _        |j                   rt	        |      | _        nt        |      | _        |j                  j                  }|j                   r|j                  j                  }t        |dd      }t        || j                  |      | _        | j                          y)z
        is_encoder_decoder (`Optional`, *optional*):
            Whether use encoder_decoder for sequence classification. When set to False, only encoder is used.
        Nr%  皙?r  r3   r4   r$  r  r1  r  r  r^   r=  r   r#  scorerd  r:   r]   r  r^   classifier_dropoutr;   s        r<   r4   z)T5GemmaForSequenceClassification.__init__e  s    
 )(:F%  ++$$%f-DJ,V4DJnn00$$ ..44K$V-FL.{DOOM_`
r=   c                 6    | j                   j                         S r2   r1  r  rP   s    r<   r  z5T5GemmaForSequenceClassification.get_input_embeddings|      zz..00r=   c                 :    | j                   j                  |       y r2   r1  r  r:   r   s     r<   r  z5T5GemmaForSequenceClassification.set_input_embeddings      

''.r=   rB  r   r   r  r  r  r  rg  r  r  r   r   c                    | j                   j                  r'|%|#t        d| j                  j                   d      | j                   j                  r"| |	|t        d      | j                  |      }| j                   j                  rB | j                  |f||||||||	dd	|}|j                  }|j                  }|j                  }n; | j                  |f|||d|}|j                  }|j                  }|j                  }| j                  |      }||j                  d   }n|j                  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      }| j                   j                  r[|d	z  }t%        j,                  ||j                  d   d	z
        }n.d}t.        j1                  | j                  j                   d       |t%        j(                  ||j"                        |f   }d}|
| j3                  ||
|| j                         }t5        ||||      S )  
        decoder_position_ids (`torch.LongTensor` of shape `(batch_size, decoder_sequence_length)`, *optional*):
            Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the range `[0,
            config.decoder.n_positions - 1]`. [What are position IDs?](../glossary#position-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).
        N8Passing input embeddings is currently not supported for  in encoder-decoder mode.If no `decoder_input_ids` or `decoder_inputs_embeds` are passed, `input_ids` cannot be `None`. Please pass either `input_ids` or `decoder_input_ids` or `decoder_inputs_embeds`.F	r   r   r  r  r  r  rg  r  r  r   r   rg  r   r*   z=Cannot handle batch sizes > 1 if no padding token is defined.r@   r   )maxz will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rj  )r.  r  pooled_logitsr]   r  r.  rk   rW  )r]   r  NotImplementedErrorr;   rR   r   rE  r1  rn  r  r  rk   rW  r  rO   r?  r   r|   r7   int32r   argmaxclamploggerwarning_oncer  r   )r:   rB  r   r   r  r  r  r  rg  r  r  r   outputsrn  rk   rW  r.  r  last_non_pad_tokennon_pad_masktoken_indicesr  r  s                          r<   rL   z(T5GemmaForSequenceClassification.forward  s   2 ;;))y/@]E^%J4>>KbKbJcc|} 
 ;;))/@/HMbMj  U 
 !% 1 1) <;;))*4$**+-)"3'=%9 /+&;+ +G !( 9 9#99M 33J'1tzz(-)+	(
 (G !( 9 9#11M ++J-. "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J{{--"a'"%*[[1CIZI`I`acIdghIh%i"!#>>**+ ,Z Z
 u||Jv}}MOaab%%VFR_hlhshs%tD' '!	
 	
r=   r2   
NNNNNNNNNN)rR   rS   rT   r+   r!  r4   r  r  r$   r#   r7   r  r   r   r  r!   r"   r   rL   rV   rW   s   @r<   r  r  c  sN   } $+ .1/  .2.204596:8<2626:>*.i
##d*i
 t+i
 &&-	i

 !++d2i
 !&t 3i
 $..5i
 )4/i
 ((4/i
  %0047i
   4'i
 +,i
 
"i
  i
r=   r  c                       e Zd Zddededz  f fdZd Zd Zee		 	 	 	 	 	 	 	 	 	 d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
j                  dz  dedz  de
j                  dz  de
j                  dz  de
j                  dz  dee   defd              Z xZS )T5GemmaForTokenClassificationNr]   r  c                    |||_         t        | 	  |       |j                  | _        |j                   rt	        |      | _        nt        |      | _        |j                  j                  }|j                   r|j                  j                  }t        |dd      }t        || j                  |      | _        | j                          y)z
        is_encoder_decoder (`Optional`, *optional*):
            Whether use encoder_decoder for token classification. When set to False, only encoder is used.
        Nr%  r  r  r  s        r<   r4   z&T5GemmaForTokenClassification.__init__  s    
 )(:F%  ++$$%f-DJ,V4DJnn00$$ ..44K$V-FL.{DOOM_`
r=   c                 6    | j                   j                         S r2   r  rP   s    r<   r  z2T5GemmaForTokenClassification.get_input_embeddings
  r  r=   c                 :    | j                   j                  |       y r2   r  r  s     r<   r  z2T5GemmaForTokenClassification.set_input_embeddings  r  r=   rB  r   r   r  r  r  r  rg  r  r  r   r   c                    | j                   j                  r'|%|#t        d| j                  j                   d      | j                   j                  r"| |	|t        d      | j                  |      }| j                   j                  rB | j                  |f||||||||	dd	|}|j                  }|j                  }|j                  }n; | j                  |f|||d|}|j                  }|j                  }|j                  }| j                  |      }d}|
| j                  ||
| j                         }t        ||||      S )	r  Nr  r  r  Fr  r  r  )r]   r  r  r;   rR   r   rE  r1  rn  r  r  rk   rW  r  r  r   )r:   rB  r   r   r  r  r  r  rg  r  r  r   r  rn  rk   rW  r.  r  s                     r<   rL   z%T5GemmaForTokenClassification.forward  s   4 ;;))y/@]E^%J4>>KbKbJcc|}  ;;))/@/HMbMj  U 
 !% 1 1) <;;))*4$**+-)"3'=%9 /+&;+ +G !( 9 9#99M 33J'1tzz(-)+	(
 (G !( 9 9#11M ++J-.%%ffdkkBD$'!	
 	
r=   r2   r  )rR   rS   rT   r+   r!  r4   r  r  r$   r#   r7   r  r   r   r  r!   r"   r   rL   rV   rW   s   @r<   r  r    sN   } $+ 01/  .2.204596:8<2626:>*.N
##d*N
 t+N
 &&-	N

 !++d2N
 !&t 3N
 $..5N
 )4/N
 ((4/N
  %0047N
   4'N
 +,N
 
N
  N
r=   r  )r  r  r  r0  r  r  )r*   )r   NN)_r  collections.abcr   typingr   r7   torch.nnr5    r   r7  activationsr   cache_utilsr   r	   r
   r   
generationr   r   r   integrationsr   r   masking_utilsr   r   r   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   r    processing_utilsr!   utilsr"   r#   r$   r%   utils.genericr&   r'   utils.output_capturingr(   r)   configuration_t5gemmar+   r,   
get_loggerrR   r  Moduler.   rY   rm   r   r   r   rU   r   rI   rN   r   r   r   r  r  r#  r*  r0  r  rT  rV  rz  r  r  r  r  r  __all__r  r=   r<   <module>r     s-  *  $    & ! P P K K I  C 9  L F & R R G E E 
		H	%=RYY =( &><RYY ><B( *+ ,2	UU\\ 	U# 	U%,, 	U$   %II%<<% 
% <<	%
 LL4'% S[% T\% T\% 5<<%&%D )*F)299 F) +F)R )*R)BII R) +R)j14 1hF4 FR		 	BII 	 9!_ 9! 9!x$&<< * \\	"P
+ P
fk
+ k
\ J
) J
 J
Z !0 ! !Hs:&<o s:l I
'= I
 I
X o
$: o
 o
dr=   