
    %	&h6                    h   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Zd dlmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZmZmZ ddlmZmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2m3Z3  e*jh                  e5      Z6dZ7e G d de             Z8 G d dejr                        Z: G d dejv                        Z< G d dejv                        Z= G d dejv                        Z>d  Z?dCd!Z@d"ej                  d#eBd$ej                  fd%ZC	 	 	 dDd&ejv                  d'ej                  d(ej                  d)ej                  d*e	ej                     d+eDd,e	eD   d-e	eD   d$e
ej                  ej                  f   fd.ZE G d/ d0ejv                        ZF G d1 d2ejv                        ZGd3ZH e&d4eH       G d5 d6e"             ZId7ZJ e&d8eH       G d9 d:eI             ZK G d; d<eIe      ZL G d= d>ejv                        ZM e&d?eH       G d@ dAeIe             ZNg dBZOy)E    N)Callable)	dataclass)partial)ListOptionalTupleUnion   )ACT2FN)CacheHybridCacheStaticCache)GenerationMixin)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPastModelOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)add_start_docstrings%add_start_docstrings_to_model_forwardcan_return_tupleis_torchdynamo_compilingloggingreplace_return_docstrings)deprecate_kwarg   )	AutoModelAutoModelForCausalLM   )Gemma3ConfigGemma3TextConfigr$   c                      e Zd ZU dZdZeej                     ed<   dZ	eej                     ed<   dZ
eeeej                     ef      ed<   dZeeej                        ed<   dZeeej                        ed<   dZeej                     ed<   y)	Gemma3CausalLMOutputWithPasta  
    Base class for Gemma3 causal language model (or autoregressive) outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.text_config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`torch.FloatTensor`, *optional*):
            A `torch.FloatTensor` of size `(batch_size, sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
    Nlosslogitspast_key_valueshidden_states
attentionsimage_hidden_states)__name__
__module____qualname____doc__r(   r   torchFloatTensor__annotations__r)   r*   r	   r   r   r+   r   r,   r-        /var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/gemma3/modeling_gemma3.pyr'   r'   8   s    < )-D(5$$
%,*.FHU&&'.GKOXeD):):$;U$BCDK8<M8E%"3"345<59Ju001297;%"3"34;r6   r'   c            	       Z     e Zd ZdZd	dedededef fdZdej                  f fdZ	 xZ
S )
Gemma3TextScaledWordEmbeddingz\
    This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
    num_embeddingsembedding_dimpadding_idxembed_scalec                 v    t         |   |||       | j                  dt        j                  |      d       y )Nr=   F
persistent)super__init__register_bufferr2   tensor)selfr:   r;   r<   r=   	__class__s        r7   rB   z&Gemma3TextScaledWordEmbedding.__init__e   s3    D]ELL,ERWXr6   	input_idsc                     t         |   |      | j                  j                  | j                  j
                        z  S N)rA   forwardr=   toweightdtype)rE   rG   rF   s     r7   rJ   z%Gemma3TextScaledWordEmbedding.forwardi   s2    wy)D,<,<,?,?@Q@Q,RRRr6   )      ?)r.   r/   r0   r1   intfloatrB   r2   TensorrJ   __classcell__rF   s   @r7   r9   r9   `   sG    Ys Y3 YS Y_d YS S Sr6   r9   c                   *     e Zd Zdef fdZd Z xZS )	Gemma3MLPconfigc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        y NFbias)rA   rB   rV   hidden_sizeintermediate_sizennLinear	gate_projup_proj	down_projr   hidden_activationact_fnrE   rV   rF   s     r7   rB   zGemma3MLP.__init__n   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV556r6   c                     | j                  | j                  | j                  |            | j                  |      z        }|S rI   )ra   rc   r_   r`   )rE   xra   s      r7   rJ   zGemma3MLP.forwardx   s6    NN4;;t~~a/@#ADLLQRO#ST	r6   )r.   r/   r0   r%   rB   rJ   rR   rS   s   @r7   rU   rU   m   s    7/ 7r6   rU   c                   <     e Zd Zddedef fdZd Zd Zd Z xZ	S )Gemma3RMSNormdimepsc                     t         |           || _        t        j                  t        j                  |            | _        y rI   )rA   rB   rj   r]   	Parameterr2   zerosrL   )rE   ri   rj   rF   s      r7   rB   zGemma3RMSNorm.__init__~   s.    ll5;;s#34r6   c                     |t        j                  |j                  d      j                  dd      | j                  z         z  S )Nr    T)keepdim)r2   rsqrtpowmeanrj   )rE   rf   s     r7   _normzGemma3RMSNorm._norm   s4    5;;quuQx}}R}>IJJJr6   c                     | j                  |j                               }|d| j                  j                         z   z  }|j                  |      S )NrN   )rt   rP   rL   type_as)rE   rf   outputs      r7   rJ   zGemma3RMSNorm.forward   sC    AGGI& 3!2!2!445~~a  r6   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tuplerL   shaperj   rE   s    r7   
extra_reprzGemma3RMSNorm.extra_repr   s'    ))*+6$((<<r6   )gư>)
r.   r/   r0   rO   rP   rB   rt   rJ   r|   rR   rS   s   @r7   rh   rh   }   s&    5C 5e 5
K!=r6   rh   c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )Gemma3RotaryEmbeddingrV   c                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typetypedefaultinv_freqFr?   )rA   rB   hasattrr   getr   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrV   r   rope_init_fnattention_scalingrC   r   original_inv_freq)rE   rV   devicer   rF   s       r7   rB   zGemma3RotaryEmbedding.__init__   s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r6   c                 b   | 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        j                  |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   ro   r#   mpscpuF)device_typeenabledr    ri   rM   )r   rP   expandrz   rK   r   
isinstancer   strr2   autocast	transposecatcosr   sinrM   )
rE   rf   position_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r7   rJ   zGemma3RotaryEmbedding.forward   sV    !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.rI   )
r.   r/   r0   r%   rB   r2   no_gradr   rJ   rR   rS   s   @r7   r~   r~      s4    // /" U]]_<  <r6   r~   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..Nro   r    r   )rz   r2   r   )rf   x1x2s      r7   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r6   c                     |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.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        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   r   unsqueeze_dimq_embedk_embeds           r7   apply_rotary_pos_embr      sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr6   r+   n_repreturnc                     | 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)rz   r   reshape)r+   r   batchnum_key_value_headsslenhead_dims         r7   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr6   modulequerykeyvalueattention_maskdropoutscalingsoftcapc                    || j                   dz  }t        || j                        }	t        || j                        }
t        j                  ||	j                  dd            |z  }|||z  }t        j                  |      }||z  }|#|d d d d d d d |	j                  d   f   }||z   }t        j                  j                  |dt        j                        j                  |j                        }t        j                  j                  ||| j                        }t        j                  ||
      }|j                  dd      j!                         }||fS )	N      r    r
   ro   )ri   rM   )ptrainingr#   )r   r   num_key_value_groupsr2   matmulr   tanhrz   r]   
functionalsoftmaxfloat32rK   rM   r   r   
contiguous)r   r   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                 r7   eager_attention_forwardr      sA    //4'3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL#g-zz,/#g-!$Q1.D
0@0@0D.D%DE#k1 ==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r6   c                       e Zd ZdZdedef fdZ	 	 ddej                  dej                  de	ej                     de	e
   d	e	ej                     d
ee   deej                  e	ej                     e	eej                        f   fdZ xZS )Gemma3Attentionz=Multi-headed attention from 'Attention Is All You Need' paperrV   	layer_idxc                    t         |           t        |dz   |j                  z        | _        || _        || _        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
                  j0                  | _        | j                  r|j2                  nd | _        t5        |j                  |j6                        | _        t5        |j                  |j6                        | _        y )Nr#   r   r   TrY   )ri   rj   )rA   rB   boolsliding_window_pattern
is_slidingrV   r   getattrr[   num_attention_headsr   r   r   query_pre_attn_scalarr   attention_dropout	is_causalr]   r^   attention_biasq_projk_projv_projo_projattn_logit_softcappingsliding_windowrh   rms_norm_epsq_normk_normrE   rV   r   rF   s      r7   rB   zGemma3Attention.__init__  s   	A1N1NNO"
F4F4F&JdJd4de$*$>$>&B\B\$\!33T9!%!>!>ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
 '+kk&H&H#7;f33D#V=P=PQ#V=P=PQr6   r+   position_embeddingsr   past_key_valuecache_positionr   r   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }| j                  |	      }	| j                  |
      }
|\  }}t        |	|
||      \  }	}
|~|||| j                  d}|j                  |
|| j                  |      \  }
}|J| j                  j                  dk(  r1|j                   d   }|
d d d d d |d d f   |d d d d d |d d f   }}
t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j!                  dd	      rt"        j%                  d
       nt&        | j                  j                     }||j)                  |	      } || |	|
||f| j*                  r| j,                  nd| j.                  | j                  d|\  }} |j0                  g |d j3                         }| j5                  |      }||fS )Nro   r#   r    )r   r   r   r   flash_attention_2eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )r   r   r   )rz   r   r   viewr   r   r   r   r   r   r   updater   rV   _attn_implementationr   r   loggerwarning_oncer   rK   r   r   r   r   r   r   )rE   r+   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsseq_lenattention_interfacer   r   s                      r7   rJ   zGemma3Attention.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{{<0[[,
&S#7jRUWZ#[ j% "0"&"5"5	L (6'<'<ZW[WeWegs't$J )dkk.N.NRe.e(..r2+5aHWHa6G+H,WXZ[]e^e]eghWhJiL
(?;;++w6{{//69fjjI\^c>d##L '>dkk>^>^&_#%+..|<N$7
%
 /3mmD**LL..
%
 
%
!\ *k));;;;FFHkk+.L((r6   )NN)r.   r/   r0   r1   r%   rO   rB   r2   rQ   r   r   
LongTensorr   r   ry   rJ   rR   rS   s   @r7   r   r     s    GR/ RC RD +/59@)||@) #\\@) !.	@)
 !@) !!1!12@) -.@) 
u||Xell3XeELL>Q5RR	S@)r6   r   c                   ^    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej                  dej                  dej                  deej                     deej                     d	ee
   d
ee   dee   deej                     dedeej                  eeej                  ej                  f      f   fdZ xZS )Gemma3DecoderLayerrV   r   c                 ,   t         |           || _        |j                  | _        || _        t        ||      | _        t        |      | _        t        | j                  |j                        | _        t        | j                  |j                        | _        t        | j                  |j                        | _        t        | j                  |j                        | _        | j                  j                  | _        |j                   | _        y )N)rV   r   rj   )rA   rB   rV   r[   r   r   	self_attnrU   mlprh   r   input_layernormpost_attention_layernormpre_feedforward_layernormpost_feedforward_layernormr   r   r   s      r7   rB   zGemma3DecoderLayer.__init__h  s    !--"()LV$,T-=-=6CVCVW(5d6F6FFL_L_(`%)6t7G7GVM`M`)a&*78H8HfNaNa*b'..33$33r6   r+   position_embeddings_globalposition_embeddings_localr   r   r   r   	use_cacher   last_cache_positionr   c                 V   | j                   r|t        |	j                  d   | j                        }| j                  j
                  dk(  r|d d | d f   }nt        j                  |j                        j                  }t        j                  t        j                  |t        j                        | j                         }t        j                  |||      }|
|z
  }t        d|      }|d d d d d d |||z   f   }|}| j                  |      }| j                  j                   r|}n|} | j                  d||||||||	d|\  }}| j!                  |      }||z   }|}| j#                  |      }| j%                  |      }| j'                  |      }||z   }|f}|r||fz  }|S )Nr   r   r   diagonal)r+   r   r   r   r   r   r  r   r5   )r   maxrz   r   rV   r   r2   finforM   mintril	ones_liker   wherer  r  r  r  r  r  )rE   r+   r	  r
  r   r   r   r   r  r   r  r   effective_seq_len	min_dtypesliding_window_maskoffsetresidualr   self_attn_weightsoutputss                       r7   rJ   zGemma3DecoderLayer.forwardv  s    ??~9 #N$8$8$;T=P=P Q {{//3FF!/4E3E3F0F!G "KK(<(<=AA	&+jjOON%**EQUQdQdPd'# "'-@)^!\ -/@@Q!/1a&K\B\9\0\!] ,,]; >>$$";"<+94>> 
,
' 3)%)/)
,
 
,
(( 55mD =0 66}E/77F =0 ")++Gr6   )NNNFFNr   )r.   r/   r0   r%   rO   rB   r2   rQ   r   r   r   r   ry   r3   rJ   rR   rS   s   @r7   r   r   g  s   4/ 4C 4& 2637*.,1$)59#$G||G %*LLG $)<<	G
 !.G u//0G !G $D>G D>G !!1!12G !G 
u  (51B1BEDUDU1U+V"WW	XGr6   r   aK  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

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

    Parameters:
        config ([`Gemma3Config`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zTThe bare Gemma3 Model outputting raw hidden-states without any specific head on top.c                   H    e Zd ZeZdZdZg dZdgZdZ	dZ
dZdZdZdZdZd Zy)Gemma3PreTrainedModellanguage_modelT)r   SiglipVisionEmbeddingsSiglipEncoderLayer#SiglipMultiheadAttentionPoolingHeadr*   c                    t        | j                  d      r| j                  j                  n| j                  j                  j                  }t	        |t
        j                  t
        j                  f      rY|j                  j                  j                  d|       |j                  %|j                  j                  j                          y y t	        |t
        j                        rf|j                  j                  j                  d|       |j                  2|j                  j                  |j                     j                          y y y )Ninitializer_ranger   )rs   std)r   rV   r$  text_configr   r]   r^   Conv2drL   datanormal_rZ   zero_	Embeddingr<   )rE   r   r%  s      r7   _init_weightsz#Gemma3PreTrainedModel._init_weights  s    
 t{{$78 KK))((:: 	 fryy"))45MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r6   N)r.   r/   r0   r$   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_flex_attn_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendr,  r5   r6   r7   r  r    sV    
  L(&*# $5"5!N  $!"&?r6   r  a$  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
zXThe bare Gemma3Text Model outputting raw hidden-states without any specific head on top.c                   J    e Zd ZdZeZdef fdZd Zd Ze	 e
e      	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     d	ee   d
eej"                     dee   dee   dee   deej                     dee   dee   defd              Z ej0                         dej                  dej                  dej                  d	edef
d       Zedej                  dededej6                  dej8                  dej                  defd       Z xZS )Gemma3TextModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Gemma3TextDecoderLayer`]

    Args:
        config: Gemma3TextConfig
    rV   c           	         t         |   |       |j                  | _        |j                  | _        t        |j                  |j                  | j                  | j                  j                  dz        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                         | _        t%        |      | _        d| _        t+        j,                  |      }|j.                  |_        ddi|_        t%        |      | _        | j7                          y c c}w )N      ?)r=   r  rV   Fr   r   )rA   rB   pad_token_idr<   
vocab_sizer9   r[   rV   embed_tokensr]   
ModuleListrangenum_hidden_layersr   layersrh   r   normr~   
rotary_embgradient_checkpointingcopydeepcopyrope_local_base_freq
rope_thetar   rotary_emb_local	post_initr   s      r7   rB   zGemma3TextModel.__init__L  s    !.. ++ :v1143C3CQUQ\Q\QhQhjmQm
 mmDI&JbJbDcdy	2d
 "&"4"4&:M:MN	/v>&+# v&"77*I6 5V D 	 es   "Ec                     | j                   S rI   r@  r{   s    r7   get_input_embeddingsz$Gemma3TextModel.get_input_embeddingsf  s       r6   c                     || _         y rI   rO  rE   r   s     r7   set_input_embeddingsz$Gemma3TextModel.set_input_embeddingsi  s
    !r6   rG   r   r   r*   inputs_embedsr  r   output_hidden_statesr   r  flash_attn_kwargsr   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}|| j                  |      }|rA|?| j                  s3|j                  \  }}}t        | j                   |||j                        }|	F||j                         nd}t        j                  |||j                  d   z   |j                         }	||	j#                  d      }|
9d}
|5|j%                         dk(  r|j                  d	   n|	d	   j'                         }
| j)                  |||	||      }|}| j+                  ||      }| j-                  ||      }|rd
nd }|rd
nd }| j.                  d | j                   j0                   D ]v  }|r||fz  }| j
                  r<| j                  r0| j3                  t5        |j6                  fi ||||||||||	|
      }n ||f||||||||	|
d	|}|d   }|sn||d   fz  }x | j9                  |      }|r||fz  }t;        ||||      S )N:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.F)max_batch_sizemax_cache_lenrM   r   r#   r   r    ro   r5   )	r	  r
  r   r   r   r   r  r   r  )last_hidden_stater*   r+   r,   )rV   r   rU  r  
ValueErrorrG  r   r   r   r@  rz   r   rM   get_seq_lengthr2   aranger   r   ri   item_update_causal_maskrF  rL  rD  rC  _gradient_checkpointing_funcr   __call__rE  r   )rE   rG   r   r   r*   rT  r  r   rU  r   r  rV  
batch_sizer   _past_seen_tokensr   r+   r	  r
  all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                           r7   rJ   zGemma3TextModel.forwardl  s     2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I  --i8M0%2%8%8"J))%#))	O !CRC^==?de"\\  =#6#6q#99$++N )33A6L &"#) 1?0B0B0D0IN((,~^`OaOfOfOh $ ..
 & &*__]L%Q"$($9$9-$V! #7BD0d![[)H4;;+H+HI $	6M#!m%55!**t}} $ A AM22H6GH!.- #%"'! !.!!/I.G#.!-#2&7'#1(;! (! *!,M =#3"55I$	6L 		-0-!11&+++%	
 	
r6   input_tensorc           
      b   | j                   j                  dk(  r|S |j                  |j                  }}|j                  d   }t        |t        t        f      r|j                         }	n ||j                  d   n|j                  d   }	| j                  |||	||||j                  d         }
|
S )Nr   r#   ro   r   sequence_lengthtarget_lengthrM   r   r   rd  )
rV   r   rM   r   rz   r   r   r   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_position)rE   r   rk  r   r*   r   rM   r   rn  ro  r   s              r7   ra  z#Gemma3TextModel._update_causal_mask  s     ;;++/BB!!$**L,?,?v&,,Q/o['AB+??AM8F8RN004XdXjXjklXmM PP+')#))!, Q 
 r6   rn  ro  rM   r   rd  c                    | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }
|ddddddd|
f   | ddddddf   j                  |j                        z   }|dk(  }|ddddddd|
f   j                  ||	      |ddddddd|
f<   |S )	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.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   
fill_valuerM   r   r#   r  r[  ro   r   )ri   r2   r  r  fulltriur_  r   r   clonerz   rK   r   masked_fill)r   rn  ro  rM   r   r   rd  r   r   r  mask_lengthpadding_masks               r7   rq  zEGemma3TextModel._prepare_4d_causal_attention_mask_with_cache_position  sy   B %.*<*<*>!*C(K* ' E*..I** -0Ye\bK !##jjqA5<<fEH^H^_acdHeeeK%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 r6   )
NNNNNNNNNN)r.   r/   r0   r1   r%   r-  rB   rP  rS  r   r   GEMMA3_INPUTS_DOCSTRINGr   r2   r   rQ   r   r3   r   rO   r   r   r   rJ   r   ra  staticmethodrM   r   rq  rR   rS   s   @r7   r:  r:  >  s   
 $L/ 4!" *+BC 1515371559$(,0/359-1A
E,,-A
 !.A
 u//0	A

 "+.A
   1 12A
 D>A
 $D>A
 'tnA
 !!1!12A
 &c]A
 $$89A
 
!A
 D A
F U]]_   ll  	 
 %      D 777 7 {{	7
 7 7 7 7r6   r:  c                        e Zd ZdgZddiZddgdgfiZeZdZdef fdZ	d	 Z
d
 Zd Zd Zd Zd Ze eddd       ee       eee      	 	 	 	 	 	 	 	 	 	 	 d!deej2                     deej4                     deej2                     dee   deej8                     deej2                     dee   dee   dee   deej2                     deeej4                  f   defd                            Z 	 	 	 	 	 	 	 d" fd 	Z! xZ"S )#Gemma3ForCausalLMzlm_head.weightlm_headcolwise_repr+   r)   r  rV   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y rX   )
rA   rB   r:  modelr?  r]   r^   r[   r  rM  rd   s     r7   rB   zGemma3ForCausalLM.__init__V  sU     $V,
 ++yy!3!3V5F5FUS 	r6   c                 .    | j                   j                  S rI   r  r@  r{   s    r7   rP  z&Gemma3ForCausalLM.get_input_embeddings_  s    zz&&&r6   c                 &    || j                   _        y rI   r  rR  s     r7   rS  z&Gemma3ForCausalLM.set_input_embeddingsb  s    "'

r6   c                     | j                   S rI   r  r{   s    r7   get_output_embeddingsz'Gemma3ForCausalLM.get_output_embeddingse  s    ||r6   c                     || _         y rI   r  rE   new_embeddingss     r7   set_output_embeddingsz'Gemma3ForCausalLM.set_output_embeddingsh  s	    %r6   c                     || _         y rI   r  rE   decoders     r7   set_decoderzGemma3ForCausalLM.set_decoderk  s	    
r6   c                     | j                   S rI   r  r{   s    r7   get_decoderzGemma3ForCausalLM.get_decodern  s    zzr6   num_logits_to_keep4.50logits_to_keepversionnew_nameoutput_typer-  rG   r   r   r*   rT  labelsr  r   rU  r   r   c                 .   | j                   rF| j                  j                  dk7  r-t        j	                  d| j                  j                   d       ||n| j                  j
                  }|	|	n| j                  j                  }	 | j                  d||||||||	|
d	|}|j                  }t        |t              rt        | d      n|}| j                  |dd|ddf         }| j                  j                  G|| j                  j                  z  }t        j                  |      }|| j                  j                  z  }d}| | j                   ||| j"                  fi |}t%        |||j&                  |j(                  |j*                        S )a  
            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]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, Gemma3ForCausalLM

        >>> model = Gemma3ForCausalLM.from_pretrained("google/gemma-2-9b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-9b")

        >>> prompt = "What is your favorite condiment?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "What is your favorite condiment?"
        ```r   zhIt is strongly recommended to train Gemma3 models with the `eager` attention implementation instead of `zp`. Use `eager` with `AutoModelForCausalLM.from_pretrained('<path-to-checkpoint>', attn_implementation='eager')`.N)	rG   r   r   r*   rT  r  r   rU  r   )r(   r)   r*   r+   r,   r5   )r   rV   r   r   r   r   rU  r  r\  r   rO   slicer  final_logit_softcappingr2   r   loss_functionr?  r   r*   r+   r,   )rE   rG   r   r   r*   rT  r  r  r   rU  r   r  loss_kwargsr  r+   slice_indicesr)   r(   s                     r7   rJ   zGemma3ForCausalLM.forwardq  s   f ==T[[==H#{{??@  Aqr 2C1N-TXT_T_TqTq$8$D $++JjJj 	 ,64:: ,
)%+'/!5),
 ,
  118B>SV8W~ot4]kmA}a,?@A;;..:dkkAAAFZZ'FdkkAAAF%4%%ffdooUUD%#33!//))
 	
r6   c	                 4   t        |   |f|||||||d|	}
||j                  d   nd|
d<   ||
j                  dd       }t	        |t
              r|j                  dk(  r| j                  j                  dk(  s|
d   #|
d   j                  \  }}}|
d   j                  }n!|
d	   j                  \  }}|
d	   j                  }| j                  j                  |||j                         | j                  j                  j                  |||
      }||
d<   |
S )N)r*   r   rT  r   r   r  r  ro   r   r  r  r    r   rT  rG   rm  r   )rA   prepare_inputs_for_generationrz   popr   r   ndimrV   r   r   r  rq  rp  r  rL   rM   )rE   rG   r*   r   rT  r   r   r  r  r   model_inputsre  rd  rn  r   rF   s                  r7   r  z/Gemma3ForCausalLM.prepare_inputs_for_generation  sU    w<

+)')%)

 

 KYJdn.B.B2.Fjk*+!  !148A 4##q(KK448KKO,81=o1N1T1T.
OQ%o6==.:;.G.M.M+
O%k299!ZZ]] /-AACll))//-% ^ N .<L)*r6   )NNNNNNNNNNr   )NNNNNTN)#r.   r/   r0   _tied_weights_keys_tp_plan_pp_planr%   r-  r.  rB   rP  rS  r  r  r  r  r   r   r   r|  r   r   _CONFIG_FOR_DOCr   r2   r   rQ   r   r3   r   r	   rO   rJ   r  rR   rS   s   @r7   r  r  O  s   *+=)H_-z:;H#L(/ '(& )6DTU*+BC+AP_` 1515371559-1$(,0/35934Y
E,,-Y
 !.Y
 u//0	Y

 "+.Y
   1 12Y
 ))*Y
 D>Y
 $D>Y
 'tnY
 !!1!12Y
 c5<</0Y
 
 Y
 a D V Y
| 7 7r6   r  c                   D     e Zd Zdef fdZdej                  fdZ xZS )Gemma3MultiModalProjectorrV   c                    t         |           t        j                  t	        j
                  |j                  j                  |j                  j                              | _	        t        |j                  j                  |j                  j                        | _        t        |j                  j                  |j                  j                  z        | _        t        |j"                  dz        | _        | j                   | j$                  z  | _        t        j(                  | j&                  | j&                        | _        y )Nr  r<  )kernel_sizestride)rA   rB   r]   rl   r2   rm   vision_configr[   r&  mm_input_projection_weightrh   layer_norm_epsmm_soft_emb_normrO   
image_size
patch_sizepatches_per_imagemm_tokens_per_imagetokens_per_sider  	AvgPool2davg_poolrd   s     r7   rB   z"Gemma3MultiModalProjector.__init__  s    *,,,KK,,88&:L:L:X:XY+
' !.  ,,&2F2F2U2U!
 "%V%9%9%D%DH\H\HgHg%g!h"6#=#=s#BC11T5I5II1A1A$JZJZ[r6   vision_outputsc                    |j                   \  }}}|j                  dd      }|j                  ||| j                  | j                        }|j	                         }| j                  |      }|j                  d      }|j                  dd      }| j                  |      }t        j                  || j                        }|j                  |      S )Nr#   r    )rz   r   r   r  r   r  flattenr  r2   r   r  rv   )	rE   r  rd  re  
seq_lengthreshaped_vision_outputspooled_vision_outputsnormed_vision_outputsprojected_vision_outputss	            r7   rJ   z!Gemma3MultiModalProjector.forward  s    $2$8$8!
Az"0":":1a"@"9"A"A
D$:$:D<R<R#
 #:"D"D"F $.E F 5 = =a @ 5 ? ?1 E $ 5 56K L#(<<0EtGfGf#g '//??r6   )	r.   r/   r0   r$   rB   r2   rQ   rJ   rR   rS   s   @r7   r  r  
  s#    \| \ @ell @r6   r  zJThe GEMMA3 model which consists of a vision backbone and a language model.c            #           e Zd Zdef fdZd Zd Zd Zd Zd Z	d Z
	 d!d	efd
Zdej                  dej                  fdZe eddd       ee       eee      	 	 	 	 	 	 	 	 	 	 	 	 	 d"deej0                     deej2                     deej                     deej0                     deeeej2                     ef      deej0                     deej0                     deej2                     deej0                     dee   dee   dee   deeej                  f   deeef   fd                            Z	 	 	 	 	 	 	 	 	 	 d#dZ d  Z! xZ"S )$Gemma3ForConditionalGenerationrV   c                    t         |   |       t        j                  |j                        | _        t        |      | _        |j                  j                  | _	        t        j                  |j                        }|j                  "|j                  D cg c]  }d| 	 c}| _        || _        | j                  j                  | j                  j                  nd| _        | j                          y c c}w )Nr=  zlanguage_model.ro   )rA   rB   r!   from_configr  vision_towerr  multi_modal_projectorr&  r?  r"   r  r  rV   r>  rM  )rE   rV   r  r   rF   s       r7   rB   z'Gemma3ForConditionalGeneration.__init__3  s     %119M9MN%>v%F" ,,77-99ASAST,,8FTFgFg&h'<&hD#,8<8P8P8\DKK44bd	 'is   C:c                 6    | j                   j                         S rI   )r  rP  r{   s    r7   rP  z3Gemma3ForConditionalGeneration.get_input_embeddingsB  s    ""7799r6   c                 :    | j                   j                  |       y rI   )r  rS  rR  s     r7   rS  z3Gemma3ForConditionalGeneration.set_input_embeddingsE  s    007r6   c                 6    | j                   j                         S rI   )r  r  r{   s    r7   r  z4Gemma3ForConditionalGeneration.get_output_embeddingsH  s    ""88::r6   c                 :    | j                   j                  |       y rI   )r  r  r  s     r7   r  z4Gemma3ForConditionalGeneration.set_output_embeddingsK  s    11.Ar6   c                 :    | j                   j                  |       y rI   )r  r  r  s     r7   r  z*Gemma3ForConditionalGeneration.set_decoderN  s    ''0r6   c                 6    | j                   j                         S rI   )r  r  r{   s    r7   r  z*Gemma3ForConditionalGeneration.get_decoderQ      ""..00r6   is_trainingc                    | j                   j                  j                  dk(  r|S ||j                         dk(  r|S t	        |t
              }t        j                  | j                        j                  }|j                  d d \  }	}
|r|j                         }nUt	        |t              r|j                         }n4t	        |t        j                        r|j                  d   n
|d   |
z   dz   }||j                         dk(  r|S t        j                  |
|f|| j                  |j                        }|
dk7  rt        j                   |d      }|t        j"                  ||j                  	      |j%                  dd      kD  z  }|d d d d d d f   j'                  |	ddd      }||
dk7  r|j)                  d      |j)                  d      k(  }d
||dk(  <   |j)                  d      j+                  |j                  t        j,                        }|j/                         }|d d d d d d d |
f   j1                  |d      |d d d d d d d |
f<   ||j/                         }|j                  d   }|d d d d d d d |f   |d d d d d d f   j+                  |j                        z   }|dk(  }|d d d d d d d |f   j1                  ||      |d d d d d d d |f<   |S )Nr   rs  r    ro   r   r#   rt  r  r[  Fr   r   )rV   r&  r   ri   r   r   r2   r  rM   r  rz   rp  r   rQ   rv  r   rw  r_  r   r   r   rK   r   rx  ry  )rE   r   token_type_idsr*   r   rk  r  using_static_cacher  inputs_lead_dimrn  ro  r   token_type_maskrz  r{  s                   r7   ra  z2Gemma3ForConditionalGeneration._update_causal_maskT  s    ;;""77;NN!!%.*<*<*>!*C "!'EKK

+//	+7+=+=bq+A(+??AM5+??AM nell; $$R(#A&81<  %.*<*<*>!*C!!jjm,$**]k]r]r

 a**[1=Ku||M.:O:OPSaSiSijlnoSppp!$a"23::?ArSUV %/Q*>,66q9^=U=UVW=XXO38ONa/0-77:==k>P>PX]XbXb=cO%++-K5@AqJZ?JZAZ5[5g5g6K1a!1/!112 %%++-K(..r2K 'q!Q'<=qRVX\^_O_@`@c@cdodvdv@wwL'1,L1<Q1l{l=R1S1_1_i2K1a+-. r6   pixel_valuesr   c                 `    | j                  |      j                  }| j                  |      }|S )a  
        Projects the last hidden state from the vision model into language model space.

        Args:
            pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
               The tensors corresponding to the input images.
        Returns:
            image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
        )r  )r  r\  r  )rE   r  r  image_featuress       r7   get_image_featuresz1Gemma3ForConditionalGeneration.get_image_features  s3     ***EWW33NCr6   r  r  r  r  r  rG   r   r   r*   r  r   rT  r  r  r   rU  c                 \	   |du |duz  rt        d      ||n| j                  j                  }||n| j                  j                  }|duxr |	du}|R| j                  j                  | j
                  k\  r/|| j                  j                  k(  }|j                         }d||<   n|}| | j                         |      }|F||j                         nd}t        j                  |||j                  d   z   |j                        }|{| j                  |      }|\| | j                         t        j                  | j                  j                  t        j                  |j                              k(  }nR|| j                  j                  k(  j!                  d      }|j#                  |      j%                  |j                        }t'               sx||   j)                         |j)                         k7  rT|j+                  d      j+                  d      d   }t        d	| d
|j                  d   |j                  d   z   d      |j%                  |j                  |j,                        }|j/                  ||      }|	[| j0                  |	v rMt2        j5                  d       t        j6                  || j0                  k(  | j                  j8                  |	      }	| j;                  ||||||      } | j<                  d|||||
||||d	|}|j>                  }d}|	O|jA                         }|dddddf   }|	dddf   }||dd|j                  d    df   j%                  |j                        }||j%                  |j                        dk7     jC                         }||j%                  |j                        dk7     jC                         }n |jC                         }|jC                         }tE        jF                         }|jI                  d| j                  jJ                  j
                        }|jI                  d      j%                  |j                        } |||      }tM        |||jN                  |jP                  |jR                  |      S d      S )a
  
            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.text_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.text_config.vocab_size]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, Gemma3ForConditionalGeneration

        >>> model = Gemma3ForConditionalGeneration.from_pretrained("google/gemma-3-4b-it")
        >>> processor = AutoProcessor.from_pretrained("google/gemma-3-4b-it")

        >>> messages = [
        ...     {
        ...         "role": "system",
        ...         "content": [
        ...             {"type": "text", "text": "You are a helpful assistant."}
        ...         ]
        ...     },
        ...     {
        ...         "role": "user", "content": [
        ...             {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"},
        ...             {"type": "text", "text": "Where is the cat standing?"},
        ...         ]
        ...     },
        ... ]

        >>> inputs = processor.apply_chat_template(
        ...     messages,
        ...     tokenizer=True,
        ...     return_dict=True,
        ...     return_tensors="pt",
        ...     add_generation_prompt=True
        ... )
        >>> # Generate
        >>> generate_ids = model.generate(**inputs)
        >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "user\nYou are a helpful assistant.\n\n\n\n\n\nWhere is the cat standing?\nmodel\nBased on the image, the cat is standing in a snowy area, likely outdoors. It appears to"
        ```
        NrX  r   r#   r[  )rM   r   ro   r   zVNumber of images does not match number of special image tokens in the input text. Got z image tokens in the text but z tokens from image embeddings.z`labels` contains `pad_token_id` which will be masked with `config.ignore_index`. You have to mask out `pad_token_id` when preparing `labels`, this behavior will be removed in v.4.46.)	r   r   r*   rT  r  r   rU  r   r  .)r(   r)   r*   r+   r,   r-   r5   )*r]  rV   r   rU  image_token_indexr?  rx  rP  r^  r2   r_  rz   r   r  rD   longr   	expand_asrK   r   numelsumrM   masked_scatterr>  r   r   r  ignore_indexra  r  r)   rP   r   r]   CrossEntropyLossr   r&  r'   r*   r+   r,   )rE   rG   r  r   r   r*   r  r   rT  r  r  r   rU  r  	lm_kwargsr  special_image_maskllm_input_idsrf  r  image_tokens_in_textr   r  r)   r(   shift_logitsshift_labelsshift_attention_maskloss_fctflat_logitsflat_labelss                                  r7   rJ   z&Gemma3ForConditionalGeneration.forward  s   V -t";<YZZ1B1N-TXT_T_TqTq$8$D $++JjJj 	 %D0GV45G  T[[%B%Bdoo%U!*dkk.K.K!K%OO-M01M,-%M 7D557FM!CRC^==?de"\\ "2]5H5H5K"KTaThThN
 #!44\BN %26Qd6O6O6QLL!>!>ejjYfYmYmn7 &" '04;;3P3P&P%[%[\^%_"%7%A%A-%P%S%STaThTh%i"+--@R2S2Y2Y2[_m_s_s_u2u(:'?'?A'?'F'J'Jq'J'QRS'T$ /00N~OcOcdeOfiwi}i}~  jA  PA  OB B44 
 ,..}/C/C]EXEXYN)889K^\M $"3"3v"=x [[d.?.?!?AYAY[abF..NO^]\g
 +>$*=*= +
&%+'/!5))+
 +
 \\^F!#ssA+.L!#qr'?L) (6a,:L:LQ:O9O9Q6Q'R'U'UV\VcVc'd$+,@,C,CFMM,RVW,WXcce+,@,C,CLDWDW,X\],]^iik+668+668**,H&++B0G0G0R0RSK&++B/22<3F3FGKK5D+#33!//))2>2J
 	
 QU
 	
r6   c                      | j                   j                  |f||||||	|
|d|}|d   dk(  r||d<   |d uxr |d u}|d   dk(  r1t        |t              r!||n|}| j	                  ||||||      }||d<   |S )N)r*   rT  r   r   r   r  r  r  r   r  r   )r  r  r   r   ra  )rE   rG   r*   rT  r   r   r  r   r  r  r  r  r   r  r  rk  r   s                    r7   r  z<Gemma3ForConditionalGeneration.prepare_inputs_for_generation[  s      It**HH
+')%)))
 
 !!+7L($D0GV45G!!j+&N,9,E=9L22Q]_jK .9L)*r6   c                 6    | j                   j                         S rI   )r  tie_weightsr{   s    r7   r  z*Gemma3ForConditionalGeneration.tie_weights  r  r6   )F)NNNNNNNNNNNNr   )
NNNNNNNTNN)#r.   r/   r0   r$   rB   rP  rS  r  r  r  r  r   ra  r2   rQ   r  r   r   r   r|  r   r'   r  r   r   r3   r	   r   r   rO   r   rJ   r  r  rR   rS   s   @r7   r  r  .  s-   
| :8;B11 "C CJu||   )6DTU*+BC+GVef 15481537KO595959-1$(,0/334n
E,,-n
 u001n
 !.	n

 u//0n
 "%U->->(?(F"GHn
 !!1!12n
 !!1!12n
   1 12n
 ))*n
 D>n
 $D>n
 'tnn
 c5<</0n
  
u22	3!n
 g D V n
f )V1r6   r  )r  r:  r  r  )Nr#   )r   NN)PrH  collections.abcr   dataclassesr   	functoolsr   typingr   r   r   r	   r2   torch.nnr]   activationsr   cache_utilsr   r   r   
generationr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   r   utils.deprecationr   autor!   r"   configuration_gemma3r$   r%   
get_loggerr.   r   r  r'   r+  r9   ModulerU   rh   r~   r   r   rQ   rO   r   rP   r   r   r   GEMMA3_START_DOCSTRINGr  r|  r:  r  r  r  __all__r5   r6   r7   <module>r     sx  ,  $ !  / /   ! : : ) B \ \ K F &  1 2 @ 
		H	%  $<; $< $<N
SBLL 
S		  =BII =(<BII <D(6	UU\\ 	U# 	U%,, 	U$ ## %II %<< % 
 % <<	 %
 U\\* %  % e_ % e_ % 5<<%& %F`)bii `)FV Vr " Z#?O #?	#?L@ F ^J+ J	JZx- xv!@		 !@H TU1%:O U1	U1p
 nr6   