
    ^j                     
   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c m	Z
 ddlmZ ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZmZ dd
lmZ ddlmZmZmZ ddl 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/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8  e-d      e G d de#                    Z9 e-d      e G d de+                    Z: ed       G d dejv                               Z< G d d ejv                        Z=d!ej|                  d"e?d#ej|                  fd$Z@	 	 dbd%ejv                  d&ej|                  d'ej|                  d(ej|                  d)ej|                  dz  d*eAd+eAd,ej|                  dz  fd-ZB G d. d/ejv                        ZC G d0 d1ejv                        ZDe G d2 d3ejv                               ZE G d4 d5ejv                        ZF G d6 d7ejv                        ZG G d8 d9ejv                        ZHd: ZI ed;      	 	 dcd!ej|                  d<ej|                  d=ej                  d>ej                  dz  d?eKdz  f
d@       ZL edA      	 	 dcd!ej|                  d=ej                  d>ej                  dz  d?eKdz  fdB       ZM eeLeMg       G dC dDejv                               ZN G dE dFe!      ZOe- G dG dHe'             ZPe- G dI dJeP             ZQe- G dK dLePe             ZR G dM dNejv                        ZS G dO dPeP      ZT G dQ dRejv                        ZUdSe?d#eVe?   fdTZW	 dddUe?dVe?dWe?dXe?d#ej                  f
dYZY G dZ d[eP      ZZ e-d\       G d] d^eP             Z[ e-d\       G d_ d`ePe             Z\g daZ]y)e    N)Callable)	dataclass   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_experts_implementationuse_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)force_accelerate_hooks)create_causal_maskcreate_recurrent_attention_mask!create_sliding_window_causal_mask)GradientCheckpointingLayer)BaseModelOutputWithPastBaseModelOutputWithPooling)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringcan_return_tupletorch_compilable_check)merge_with_config_defaults)capture_outputs   )InklingAudioConfigInklingConfigInklingTextConfigInklingVisionConfigzL
    Base class for Inkling outputs, with hidden states and attentions.
    custom_introc                   :    e Zd ZU dZdZej                  dz  ed<   y)InklingModelOutputWithPasta  
    image_hidden_states (`torch.FloatTensor`, *optional*):
        A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
        image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
    Nimage_hidden_states)__name__
__module____qualname____doc__r)   torchFloatTensor__annotations__     w/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/inkling/modeling_inkling.pyr(   r(   4   s     59**T18r2   r(   zS
    Base class for Inkling causal language model (or autoregressive) outputs.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
dz  ed<   dZeej                     dz  ed<   dZeej                     dz  ed<   dZej                  dz  ed<   y)	InklingCausalLMOutputWithPasta8  
    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 (`Cache`, *optional*, returned when `use_cache=True` is passed or when `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).

        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.
    image_hidden_states (`torch.FloatTensor`, *optional*):
        A `torch.FloatTensor` of size `(batch_size, num_images, 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
attentionsr)   )r*   r+   r,   r-   r6   r.   r/   r0   r7   r8   r   r9   tupler:   r)   r1   r2   r3   r5   r5   D   s     &*D%

d
")'+FE$+$(OUT\(59M5**+d2926Je''(4/648**T18r2   r5   RMSNormc                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	InklingRMSNormepsreturnNc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z=
        InklingRMSNorm is equivalent to T5LayerNorm
        N)super__init__nn	Parameterr.   onesweightvariance_epsilon)selfhidden_sizer?   	__class__s      r3   rC   zInklingRMSNorm.__init__d   s1     	ll5::k#:; #r2   r9   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor.   float32powmeanrsqrtrH   rG   )rI   r9   input_dtypevariances       r3   forwardzInklingRMSNorm.forwardl   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r2   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r;   rG   shaperH   )rI   s    r3   
extra_reprzInklingRMSNorm.extra_reprs   s*    ))*+6$2G2G1HIIr2   )ư>)
r*   r+   r,   floatrC   r.   TensorrX   r[   __classcell__rK   s   @r3   r>   r>   b   s7    $ $$ $;U\\ ;ell ;Jr2   r>   c                        e Zd ZdZdedef fdZdej                  dej                  dej                  dej                  fd	Z xZ	S )
InklingRelativeLogitsa|  hidden states conditioned relative position bias. `proj` is a trained bank of bias-vs-distance profiles; each token's
    `relative_states` mixes them into one bias value per backward distance
    (`sglang RelLogitsProj` + the FA4 `score_mod`, materialized densely). The bias is zero
    outside `0 <= distance < rel_extent`; causality and padding stay in the attention mask.
    d_rel
rel_extentc                     t         |           || _        t        j                  t        j                  ||            | _        y N)rB   rC   rd   rD   rE   r.   emptyproj)rI   rc   rd   rK   s      r3   rC   zInklingRelativeLogits.__init__~   s0    $LLUJ!?@	r2   relative_statesquery_positionskey_positionsr@   c                 j   || j                   z  j                  dd      }|d d d f   |d d d f   z
  d d d d d d f   } |j                  d| j                  dz
        j                  g |j
                  d d dd }|j                  d|      }|j                  |dk  || j                  k\  z  d      S )Nr    rM   r   rN           )rh   	transposeclamprd   expandrZ   gathermasked_fill)rI   ri   rj   rk   
rel_logitsdistancegather_indexposition_biass           r3   rX   zInklingRelativeLogits.forward   s     &		1<<QB
#AtG,}T1W/EEtTSTVWGWXDx~~a1)<=DDcjFVFVWYXYFZc\^c`bc"))"l;(((Q,8t;V)WY\]]r2   )
r*   r+   r,   r-   intrC   r.   r^   rX   r_   r`   s   @r3   rb   rb   w   s^    Ac As A
^^ ^ ||	^
 
^r2   rb   r9   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)rZ   rp   reshape)r9   rx   batchnum_key_value_headsslenhead_dims         r3   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr2   modulequerykeyvalueattention_maskscalingdropoutrv   c                 &   t        || j                        }	t        || j                        }
t        j                  ||	j	                  dd            |z  }|||z   }|||z   }t
        j                  j                  |dt        j                        j                  |j                        }t
        j                  j                  ||| j                        }t        j                  ||
      }|j	                  dd      j                         }||fS )NrM   r   rN   )dimrP   )ptrainingr    )r   num_key_value_groupsr.   matmulrn   rD   
functionalsoftmaxrR   rQ   rP   r   r   
contiguous)r   r   r   r   r   r   r   rv   kwargs
key_statesvalue_statesattn_weightsattn_outputs                r3   eager_attention_forwardr      s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL #m3!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r2   c                        e 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  f   fdZ xZS )InklingAttentionconfig	layer_idxc                    t         |           || _        || _        |j                  | j                     dk(  | _        | j
                  r|j                  n|j                  | _        | j
                  r|j                  n|j                  | _
        | j
                  r|j                  n|j                  | _        | j                  | j                  z  | _        | j
                  r|j                  nd | _        | j
                  r|j                  n|j                   | _        d| j                  z  | _        |j$                  | _        d| _        t)        j*                  |j,                  | j                  | j                  z  d      | _        t)        j*                  |j,                  | j                  | j                  z  d      | _        t)        j*                  |j,                  | j                  | j                  z  d      | _        t)        j*                  |j,                  | j                  |j4                  z  d      | _        t)        j*                  | j                  | j                  z  |j,                  d      | _        t;        | j                  | j                  z  |j<                  |d      | _        t;        | j                  | j                  z  |j<                  |d      | _         tC        | j                  |jD                  	      | _#        tC        | j                  |jD                  	      | _$        tK        |j4                  | j                         | _&        y )
Nhybrid_sliding      ?TFbiasr   )conv_idxr    r?   )'rB   rC   r   r   layer_types
is_slidingswa_head_dimr~   swa_num_attention_headsnum_attention_heads	num_headsswa_num_key_value_headsr|   r   sliding_window_sizesliding_windowrd   r   attention_dropout	is_causalrD   LinearrJ   q_projk_projv_projrc   r_projo_projInklingShortConvolutionsconv_kernel_sizek_sconvv_sconvr>   rms_norm_epsq_normk_normrb   rel_logits_projrI   r   r   rK   s      r3   rC   zInklingAttention.__init__   sg   " ,,T^^<@PP/3++FOO;???77PVPjPjEI__6#A#AZ`ZtZt $(NNd6N6N$N!<@OOf88QU8<&44VM^M^T]]*!'!9!9ii 2 2DNNT]]4RY^_ii 2 2D4L4Lt}}4\chiii 2 2D4L4Lt}}4\chiii 2 2DNNV\\4QX]^ii >@R@RY^_.$$t}}4f6N6NPYde
 /$$t}}4f6N6NPYde
 %T]]8K8KL$T]]8K8KL4V\\4??Sr2   Nr9   r   	conv_maskr8   r   r@   c                 H   |j                   d d }g |d| j                  }| j                  |      }| j                  | j	                  |      ||      }	| j                  | j                  |      ||      }
| j                  |      }| j                  |j                  |            j                  dd      }| j                  |	j                  |            j                  dd      }	|
j                  |      j                  dd      }
|j                   d   }|[|j                  || j                        \  }}|j                  | j                        }|j                  |	|
| j                        \  }	}
n|	j                   d   }d\  }}t!        j"                  ||j$                        |z   }t!        j"                  ||j$                        |z   } |j                  g || j&                  d }| j)                  |||      }| j*                  s| j,                  j.                  |dz   j1                         }d| j,                  j2                  t!        j4                  || j,                  j.                  z  j7                  d            z  z   }|j                  dddd      }|j1                         |z  j9                  |j:                        }|j1                         |z  j9                  |j:                        }t=        j>                  | j,                  j@                  tB              } || ||	|
|f| jD                  sd	n| jF                  | jH                  | jJ                  |d
|\  }} |jL                  g |d jO                         }| jQ                  |      }||fS )NrN   r8   r   r    rM   )r   r   devicer   )minrm   )r   r   r   rv   ))rZ   r~   r   r   r   r   r   r   r   viewrn   r   get_mask_sizesr   get_query_offsetupdater.   aranger   r   r   r   r   log_scaling_n_floorr]   log_scaling_alphalogro   rQ   rP   r   get_interface_attn_implementationr   r   r   r   r   rz   r   r   )rI   r9   r   r   r8   r   input_shapehidden_shapequery_statesr   r   ri   q_length	kv_length	kv_offsetq_offsetkv_positionsq_positionsrv   effective_ntauattention_interfacer   r   s                           r3   rX   zInklingAttention.forward   s]    $))#2.88b8$--8{{=1\\$++m"<oir\s
||DKK$>P_kt|u++m4{{<#4#4\#BCMMaQRS[[!>?II!QO
#((6@@AF%%a(&#2#A#A(DNN#[ Iy&77GH'6'='=j,X\XfXf'g$J"((+I"&Hi||Im6J6JKiWll8M4H4HIHT./..PPT^^PRP,,_k<X 4;;#B#B#N&?113K55		t{{>>>EE#EN9  C ((1aQ'C(..036::<;M;MNL*002S8<<]=P=PQM(?(M(MKK,,.E)
 %8%
  $}}C$2H2HLL..'%
 %
!\ *k));;;;FFHkk+.L((r2   NN)r*   r+   r,   r#   rw   rC   r.   r^   r   r   r   r;   rX   r_   r`   s   @r3   r   r      s    T0 TS TF *.(,A)||A) t+A) <<$&	A)
 A) +,A) 
u||U\\D00	1A)r2   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )
InklingMLPr   c                 $   t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        t        j                  t        j                  d            | _        y )NFr   r    )rB   rC   r   rJ   intermediate_sizerD   r   	gate_projup_proj	down_projr   
hidden_actact_fnrE   r.   rF   global_scalerI   r   rK   s     r3   rC   zInklingMLP.__init__  s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../LLA7r2   r9   r@   c                     | j                  | j                  | j                  |            | j                  |      z        }|| j                  z  S rf   )r   r   r   r   r   rI   r9   s     r3   rX   zInklingMLP.forward)  sE    t{{4>>-3P'QTXT`T`anTo'opt0000r2   )	r*   r+   r,   r#   rC   r.   r^   rX   r_   r`   s   @r3   r   r     s+    	80 	81U\\ 1ell 1r2   r   c                        e Zd ZdZdef fdZdej                  dej                  dej                  dej                  fdZ xZ	S )	InklingExpertsz2Collection of expert weights stored as 3D tensors.r   c                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j                  d| j                  z  | j
                              | _        t        j                  t        j                  | j                  | j
                  | j                              | _        t        |j                     | _        y )NrM   )rB   rC   n_routed_expertsnum_expertsrJ   
hidden_dimmoe_intermediate_sizeintermediate_dimrD   rE   r.   rg   gate_up_projr   r   r   r   r   s     r3   rC   zInklingExperts.__init__2  s    !22 ,, & < <LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r2   r9   top_k_indextop_k_weightsr@   c                 f   t        j                  |      }t        j                         5  t         j                  j                  j                  || j                        }|j                  ddd      }t        j                  |j                  d      d      j                         }d d d        D ]  }|d   }|| j                  k(  rt        j                  |         \  }}	||	   }
t        j                  j                  |
| j                  |         j                  dd      \  }}| j                  |      |z  }t        j                  j                  || j                   |         }|||	|d f   z  }|j#                  d|	|j%                  |j&                                |S # 1 sw Y   xY w)N)num_classesrM   r    r   )rN   r   rN   )r.   
zeros_likeno_gradrD   r   one_hotr   permutegreatersumnonzerowherelinearr   chunkr   r   
index_add_rQ   rP   )rI   r9   r   r   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r3   rX   zInklingExperts.forward;  s    $..}=]]_ 	S((--55ktO_O_5`K%--aA6K{8'DaHPPRJ	S
 % 
	nJ#AJT---#(;;{:/F#G Iy))4M}}++M4;L;LZ;XY__`agi_jHD"$(KK$5$:!$&MM$8$89NPTP^P^_iPj$k!$9M)U^`dJd<e$e!**1i9N9Q9QReRkRk9lm
	n #"#	S 	Ss   A=F&&F0)
r*   r+   r,   r-   r#   rC   r.   r^   rX   r_   r`   s   @r3   r   r   .  sN    <00 0#||# \\# ||	#
 
#r2   r   c                   r     e Zd Z fdZdeej                  ej                  ej                  f   fdZ xZS )InklingTopkRouterc                 T   t         |           |j                  | _        |j                  | _        | j                  | j                  z   | _        |j                  | _        |j                  | _        |j                  | _
        t        j                  t        j                  | j
                  |j                              | _        t        j                  t        j                   d            | _        t        j                  t        j                  | j                              | _        y Nr    )rB   rC   r   r   n_shared_expertsn_total_expertsrJ   r   route_scalenum_experts_per_toktop_krD   rE   r.   rg   rG   rF   r   e_score_correction_biasr   s     r3   rC   zInklingTopkRouter.__init__W  s    !22 & 7 7#//$2G2GG ,,!--//
ll5;;t/C/CVEWEW#XYLLA7')||EKK@P@P4Q'R$r2   r@   c                    |j                  d| j                        }t        j                  || j                        }|j                         }|dd | j                   f   }|| j                  z   }t        j                  || j                  dd      d   }|dd | j                   f   }|d| j                   d f   }	t        j                  |j                  d|      |	gd      }
t        j                  |
      }t        j                  |t        j                  |dd      z
        }|| j                   z  | j"                  z  }|d| j                   d f   j%                         }|dd | j                  f   j%                         }||||fS )	NrN   .F)r   sortedr    r   T)r   rO   )rz   r   Fr   rG   sigmoidr  r  r.   topkr  catrq   
logsigmoidexp	logsumexpr  r   r   )rI   r9   flatrouter_logitsscoresrouted_scoresscores_for_choicetopk_indicesrouted_logitsshared_logitstopk_logitstopk_log_probstopk_weightsshared_gammass                 r3   rX   zInklingTopkRouter.forwardd  s   $$R9t{{3 &&(s$<t'<'<&<$<<=)D,H,HHzz"3TZZRPUVWXY%c+Cd.C.C-C+C&CD%cD,A,A+A+C&CDii!5!5b,!G W]_`k2yy%//.VXbf2g!gh#d&6&669J9JJ$S4+@+@*@*B%BCNNP#C4::$56AAClL-GGr2   )	r*   r+   r,   rC   r;   r.   r^   rX   r_   r`   s   @r3   r
  r
  V  s/    SHellELL%,,.V(W Hr2   r
  c                   $     e Zd Z fdZd Z xZS )InklingSharedExpertsc                    t         |           |j                  | _        |j                  }t	        j
                  t        j                  |j                  ||j                              | _	        t	        j
                  t        j                  |j                  ||j                              | _
        t	        j
                  t        j                  |j                  |j                  |            | _        t        |j                     | _        y rf   )rB   rC   r  r   rD   rE   r.   rg   rJ   r   r   r   r   r   r   )rI   r   r   rK   s      r3   rC   zInklingSharedExperts.__init__}  s     & 7 7!77
 ekk&2I2IK[]c]o]o&pq||EKK0G0GIY[a[m[m$noekk&2I2I6K]K]_o&pqV../r2   c                    |j                   }|j                  dd|d         j                  | j                  dd      }|j                  d| j                  d      j	                  dd      }t        j                  || j                  j	                  dd            }t        j                  || j                  j	                  dd            }| j                  |      |z  |z  }t        j                  || j                  j	                  dd            }|j                         j                  d      j                  |j                        }|j                  |      S )Nr    rN   r   rM   r   )rZ   rz   rp   r  rn   r.   bmmr   r   r   r   r]   r   rQ   rP   r   )	rI   r9   gammasr   r  r  	activateddownouts	            r3   rX   zInklingSharedExperts.forward  s   #))%--a[_ELLTMbMbdfhjkD$9$91=GG1Myy(@(@A(FGYY}dll&<&<Q&BCKK%*V3	yyDNN$<$<Q$BCjjl1%(()<)<=xx$$r2   r*   r+   r,   rC   rX   r_   r`   s   @r3   r)  r)  |  s    0%r2   r)  c                   B     e Zd ZdZ fdZdej                  fdZ xZS )
InklingMoEz7Gate -> routed experts (+ shared experts), TML flavour.c                     t         |           || _        t        |      | _        t        |      | _        t        |      | _        y rf   )	rB   rC   r   r
  r  r   expertsr)  shared_expertsr   s     r3   rC   zInklingMoE.__init__  s:    %f-	%f-26:r2   r@   c                     |}|j                   }| j                  |      \  }}}}|j                  d|j                   d         } | j                  |||      j                  | }|| j	                  ||      z   }|S )NrN   )r-  )rZ   r  r   r5  r6  )rI   r9   	residualsr   _r&  r!  r'  s           r3   rX   zInklingMoE.forward  s    !	#))7;yy7O4<}%**2}/B/B2/FGT]L,OTTVab%(;(;Im(;(\\r2   )	r*   r+   r,   r-   rC   r.   r^   rX   r_   r`   s   @r3   r3  r3    s    A; r2   r3  c                     |N|j                   d   dkD  r<|j                   d   dkD  r*| j                  }| |dddddf   z  j                  |      } | S )zm
    Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
    Nr    r   )rZ   rP   rQ   )r9   r   rP   s      r3   apply_mask_to_padding_statesr;    sa    
 !n&:&:1&=&AnFZFZ[\F]`aFa##&1d
)CCGGNr2   causal_conv1d_update
conv_staterG   r   
activationc                    | j                   \  }}}|j                   d   }t        j                  || gd      j                  |j                        }	|j                  |	d d d d | d f          t        j                  |	|j                  d      |d|      }
|
d d d d | d f   }
|t        |   |
      }
|
j                  | j                        S )NrN   r   r    r   )paddinggroups)
rZ   r.   r  rQ   rP   copy_r  conv1d	unsqueezer   )r9   r=  rG   r   r>  r9  rJ   seq_len	state_lenhidden_states_newr0  s              r3   r<  r<    s     ,11A{G  $I		:}"=2FII&,,W&q!iZ['89:
(($f&6&6q&94S^
_C
aWHIo
CZ %66-%%&&r2   causal_conv1d_fnc                 8   | j                   \  }}}|j                   d   dz
  }t        j                  | j                  |j                        |j                  d      |||      d d d d d |f   }	|t        |   |	      }	|	j                  | j                        S )NrN   r    )rG   r   r@  rA  )rZ   r  rC  rQ   rP   rD  r   )
r9   rG   r   r>  r   r9  rJ   rE  r@  r0  s
             r3   rH  rH    s     ,11A{Gll2"G
((&" HWHnC Z %66-%%&&r2   c                        e Zd Zdedededef fdZ ed      	 	 ddej                  d	edz  d
ej                  dz  de	e
   fd       Z xZS )r   rJ   conv_kernel_sizer   r   c                     t         |           || _        || _        || _        t        j                  |||||dz
  d      | _        y )Nr    F)in_channelsout_channelskernel_sizerA  r@  r   )rB   rC   r   r   rK  rD   Conv1drC  )rI   rJ   rK  r   r   rK   s        r3   rC   z InklingShortConvolution.__init__  sK    "  0ii#$($q(
r2   rC  Nr9   r8   r   r   c                    |j                   }|j                         }|}t        ||      }|j                  d   }|j	                  dd      }|d uxr& |j                  | j                  | j                        }|r|dk(  r|j                  | j                     j                  sv|j                  | j                     j                  | j                     }	t        ||	| j                  j                  j                  d      | j                  j                        }n|3|j!                  || j                  | j                  | j"                        }t%        || j                  j                  j                  d      | j                  j                  |j'                  d            }|r|d d d d | d f   }|j	                  dd      }||z   j)                  |      }|S )Nr    rM   )	state_idxrK  seq_idx)rS  )rP   )rP   r]   r;  rZ   rn   has_previous_stater   r   layersrecord_pastconv_statesr<  rC  rG   squeezer   update_conv_staterK  rH  getrQ   )
rI   r9   r8   r   r   rV   residualrE  use_precomputed_statesr=  s
             r3   rX   zInklingShortConvolution.forward  s    $))%++- 4]IN%%a(%//15!0!< "
AcAcNNDMMB
 "gl?;Q;QRVR`R`;a;m;m(//?KKDMMZJ0z4;;+=+=+E+Ea+H$++JZJZM * / A A!4>>T]]]a]r]r !B ! -t{{1199!<dkk>N>NX^XbXbclXmM
 & -aWHIo >%//15&155K5Hr2   r   )r*   r+   r,   rw   rC   r   r.   r^   r   r   r   rX   r_   r`   s   @r3   r   r     s    
C 
3 
3 
Z] 
 H% )-)-	*||* * <<$&	*
 +,* &*r2   r   c                        e 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j                  fdZ xZS )InklingDecoderLayerr   r   c                 (   t         |           |j                  | _        t        ||      | _        |j
                  |   dk(  rt        |      | _        nt        |      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        |j                  |   | _        t        |j                  |j                   |d      | _        t        |j                  |j                   |d      | _        y )NsparserM   )r   r   r   )rB   rC   rJ   r   	self_attnmlp_layer_typesr3  mlpr   r>   r   input_layernormpost_attention_layernormr   
layer_typer   rK  
attn_sconv	mlp_sconvr   s      r3   rC   zInklingDecoderLayer.__init__#  s    !--)&)<!!),8!&)DH!&)DH-f.@.@&BUBUV(6v7I7I6K^K^(_% ,,Y71 7 79WX
 1 7 79WX
r2   Nr9   r   r   r8   r   r@   c                    |}| j                  |      } | j                  d||||d|\  }}| j                  |||      }||z   }|}| j                  |      }| j	                  |      }| j                  |||      }||z   }|S )N)r9   r   r   r8   r   r1   )rd  ra  rg  re  rc  rh  )rI   r9   r   r   r8   r   r[  r9  s           r3   rX   zInklingDecoderLayer.forward7  s     !,,];)4>> 
')+	

 
q bkl =0 55mD/}oajk =0r2   )NNN)r*   r+   r,   r#   rw   rC   r.   r^   r   r   r   rX   r_   r`   s   @r3   r^  r^  "  s    
0 
S 
. /3)-(,|| t+ <<$&	
  +, 
r2   r^  c                        e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdgZg dZeedZ ej(                          fd	       Z xZS )
InklingPreTrainedModelmodelTr^  r8   Fzmodel\.mtp\..*)rg  rh  r   r   )r9   r:   c                    t         |   |       | j                  j                         j                  }t        |t              r#t        j                  |j                  d|       y t        |t              r t        j                  |j                         y t        |t              rEt        j                  |j                  d|       t        j                  |j                  d|       y t        |t               rat        j                  |j"                  d|       t        j                  |j                         t        j$                  |j&                         y t        |t(              rgt        j                  |j*                  d|       t        j                  |j,                  d|       t        j                  |j                  d|       y t        |t.              rlt1        | j                  d| j                        }t        j2                  |j4                  t7        j8                  |j:                        |j<                  z         y y )Nrm   )rT   stdaudio_config)rB   _init_weightsr   get_text_configinitializer_range
isinstancerb   initnormal_rh   r   ones_r   r   r   r   r
  rG   zeros_r  r)  r   r   InklingAudioModelEmbeddingsgetattrrB  audio_tokens_offsetsr.   r   
n_mel_binsmel_vocab_size)rI   r   rn  ro  rK   s       r3   rp  z$InklingPreTrainedModel._init_weightsh  s   f%kk))+==f34LL3C8
+JJv**+/LL,,3C@LL))= 12LLSc:JJv**+KK667 45LL))=LLcs;LL))= ;< #4;;LLJJ++\4458S8SS	 =r2   )r*   r+   r,   r"   config_class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"_keys_to_ignore_on_load_unexpected_keep_in_fp32_modules_strictr^  r   _can_record_outputsr.   r   rp  r_   r`   s   @r3   rk  rk  S  s~     L&*#./#4"5 !N""'*;)<&#T ,&
 U]]_ r2   rk  c                        e Zd ZU eed<   def fdZe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e   defd                     Z xZS )InklingTextModelr   c           	      6   t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        d| _        | j'                          y c c}w )Nr   F)rB   rC   pad_token_idpadding_idx
vocab_sizerD   	EmbeddingrJ   embed_tokens
ModuleListrangenum_hidden_layersr^  rU  r>   r   norm
embed_normgradient_checkpointing	post_initr   s      r3   rC   zInklingTextModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEde	 3e
 #6#5#56;N;NO	(););ATATU&+# 	 fs   DN	input_idsr   position_idsr8   inputs_embeds	use_cacher   r@   c                    |d u |d uz  rt        d      | | j                  | j                  |            }|r|t        | j                        }|V||j                         nd}t        j                  |j                  d   |j                        |z   }|j                  d      }t        |x}	t              s3| j                  ||||d}
t        di |
t        di |
t        di |
d}	|}t!        | j"                        D ]8  \  }}| j                  j$                  |   dk(  rd	nd
} ||f|	|   |	d   |d|}: | j'                  |      }t)        ||      S )N:You must specify exactly one of input_ids or inputs_embeds)r   r   r    r   r   r  r   r8   r  full_attentionsliding_attentionlinear_attentionhybridr  r  r  )r   r   r8   )last_hidden_stater8   r1   )
ValueErrorr  r  r	   r   get_seq_lengthr.   r   rZ   r   rD  rs  dictr   r   r   	enumeraterU  r   r  r   )rI   r  r   r  r8   r  r  r   past_seen_tokenscausal_mask_mappingmask_kwargsr9   idecoder_layerattention_types                  r3   rX   zInklingTextModel.forward  s    -t";<YZZ  OOD,=,=i,HIM0*$++>OCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L ?-F++!."0#2 ,K #5"C{"C%F%U%U$C$Rk$R# & )$++ 6 	A}151H1H1Kx1W-]pN)2>B-.@A /	
 M	 		-0&++
 	
r2   )NNNNNN)r*   r+   r,   r#   r0   rC   r   r   r   r.   
LongTensorr^   r   r/   boolr   r   r   rX   r_   r`   s   @r3   r  r    s    0     .2.204(,26!%6
##d*6
 t+6
 &&-	6

 6
 ((4/6
 $;6
 +,6
 
!6
    6
r2   r  c                   P    e Zd ZU i ZddiZddgdgfiZeed<   def 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j                  dz  dedz  deej                  z  dee   defd              Z xZS )InklingForCausalLMlm_headrowwise_split_inputr9   r7   r   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y NFr   )
rB   rC   r  rl  r  rD   r   rJ   r  r  r   s     r3   rC   zInklingForCausalLM.__init__  sU     %f-
 ++yy!3!3V5F5FUS 	r2   Nr  r   r  r8   r  labelsr  logits_to_keepr   r@   c	           
          | j                   d||||||d|	}
|
j                  | j                  j                  z  }t	        |t
              rt        | d      n|}| j                  |dd|ddf         }| j                  j                  }|||j                  d   k  r	|dd|f   }d}|# | j                  d|||j                  d   d|	}t        |||
j                  |
j                  |
j                        S )a  
        Example:

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

        >>> model = InklingForCausalLM.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  r   r  r8   r  r  NrN   .r7   r  r  )r6   r7   r8   r9   r:   r1   )rl  r  r   logits_mup_width_multiplierrs  rw   slicer  unpadded_vocab_sizerZ   loss_functionr5   r8   r9   r:   )rI   r  r   r  r8   r  r  r  r  r   outputsr9   slice_indicesr7   r  r6   s                   r3   rX   zInklingForCausalLM.forward  s&   > $** 
)%+'
 
  11DKK4[4[[8B>SV8W~ot4]kmA}a,?@A"kk==*/BV\\RTEU/UC!5"5!556F%4%%jVFv||\^O_jcijD,#33!//))
 	
r2   )NNNNNNNr   )r*   r+   r,   _tied_weights_keys_tp_plan_pp_planr#   r0   rC   r   r   r.   r  r^   r   r/   r  rw   r   r   r5   rX   r_   r`   s   @r3   r  r    s!    01H_-z:;H0   .2.204(,26*.!%-.9
##d*9
 t+9
 &&-	9

 9
 ((4/9
   4'9
 $;9
 ell*9
 +,9
 
'9
  9
r2   r  c                   $     e Zd Z fdZd Z xZS )rx  c                    t         |           t        j                  |j                  |j
                  z  |j                        | _        | j                  dt        j                  |j                        |j
                  z  d       y )Nrz  F)
persistent)rB   rC   rD   r  num_codebookscodebook_sizerJ   embed_audio_tokensregister_bufferr.   r   r   s     r3   rC   z$InklingAudioModelEmbeddings.__init__%  sn    "$,,0D0DvG[G[0[^d^p^p"q"ELL1E1E$FI]I]$]jo 	 	
r2   c                 f    | j                  || j                  z         }|j                  d      }|S )Nr   r   )r  rz  r   )rI   r  r  s      r3   rX   z#InklingAudioModelEmbeddings.forward,  s6    //	D<U<U0UV%))b)1r2   r1  r`   s   @r3   rx  rx  $  s    
r2   rx  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )InklingAudioModelr   c                 |    t         |   |       t        |      | _        t	        |j
                  d      | _        y )Nr\   r   )rB   rC   rx  r  r>   text_hidden_sizer  r   s     r3   rC   zInklingAudioModel.__init__3  s1     "=f"E"6#:#:E	r2   audio_input_idsr@   c                 `    | j                  |      }| j                  |      }t        ||      S )Nr  pooler_output)r  r  r   )rI   r  r9   s      r3   rX   zInklingAudioModel.forward8  s3    //@		-0)+'
 	
r2   )	r*   r+   r,   r!   rC   r.   r^   rX   r_   r`   s   @r3   r  r  2  s-    F1 F

u|| 
 
r2   r  c            
            e Zd Zdededededef
 fdZdej                  dej                  fd	Zdej                  dej                  fd
Z	 xZ
S )InklingVisionEncoderLayer	input_dim
output_dimt_foldhw_foldadd_normc                     t         |           t        j                  ||d      | _        |rt        |      | _        || _        || _        || _	        y r  )
rB   rC   rD   r   
projectionr>   
layer_normr  r  r  )rI   r  r  r  r  r  rK   s         r3   rC   z"InklingVisionEncoderLayer.__init__B  sF    ))IzF,Z8DO r2   r9   r@   c           
         |j                   \  }}}}}|| j                  z  }|| j                  z  }|| j                  z  }	|j                  ||| j                  || j                  |	| j                  |      }|j	                  dddddddd      }|j                  ||||	| j                  | j                  z  | j                  z  |z        }|S )	z
        Convert a tensor of shape (B, T, H, W, C) to a tensor of shape (B, T // t, H // hw, W //  hw, C * (t * hw**2))
        r   r    r      rM            )rZ   r  r  rz   r   )
rI   r9   BTHWCt_newh_neww_news
             r3   fold_timespace_to_depthz1InklingVisionEncoderLayer.fold_timespace_to_depthK  s     &++1aAT[[ T\\!T\\!%--aUDLLZ_aeamamopq%--aAq!Q1E%--audkkTXT`T`F`cgcocoForsFstr2   c                     | j                   dkD  s| j                  dkD  r| j                  |      }| j                  |      }| j                  r&| j                  |      }t        j                  |      }|S r  )r  r  r  r  r  r  r  gelur   s     r3   rX   z!InklingVisionEncoderLayer.forward[  s_    <<!t{{Q 88GM6== OOM:MFF=1Mr2   )r*   r+   r,   rw   r  rC   r.   r^   r  rX   r_   r`   s   @r3   r  r  A  sb    !# !3 ! !c !]a !U\\ ell  U\\ ell r2   r  numberc                 $   g }| dz  dk(  r|j                  d       | dz  } | dz  dk(  rt        dt        j                  |       dz   d      D ]*  }| |z  dk(  s|j                  |       | |z  } | |z  dk(  r, | dkD  r|j                  |        |S )NrM   r   r   r    )appendr  mathisqrt)r  factorsr   s      r3   prime_factorsr  f  s    G
1*/q1 1*/ 1djj(1,a0 qjAoNN1qLF qjAo
 zvNr2   temporal_patch_size
patch_sizen_layers
n_channelsc           	         t        j                  t        j                  t        |      ddd   |      d      }t        j                  t        j                  t        |       ddd   |      d      }t        j                  |dz  |z  dz        j                         dz  }t        j                  |d   dz  |z  |z        j                         dz  }t        j                  ddd|gg|      }	t        j                  t        j                  |      |||gd      }
t        j                  |t        j                  ||d         t        j                  ||d         |gd      }t        j                  |	|
|gd      }t        j                  |ddddf   d      j                         }||z  | z  |z  }t        j                  dt        j                  t        j                  ||            |dz   |      }t        j                  |j                  d      t        j                  |      j                  d      z
        }||j                   d   k\  rt        j"                  |d      }nDdd	lm}  ||j)                         j+                               \  }}t        j                  ||      }d|d<   |j                   d   dz
  |d<   ||   S )
a  
    Plan out the dimensions for each layer in the HMLP encoder.

    This function determines the progression of dimensions (temporal, height, width, channels)
    for a multi-layer perceptual model that processes image/video patches. It follows these
    principles:
    1. Start with small dimensions and increase to full size
    2. Expand spatial dimensions (height/width) first, then temporal
    3. Increase channel count to avoid information bottlenecks
    4. Round channel dimensions to multiples of 64 for hardware efficiency

    The function computes optimal assignments of scale configurations to layers using either:
    - For n_layers >= len(scales): Individual best matching scales for each layer (allowing duplicates)
    - For n_layers < len(scales): Global optimal assignment via linear_sum_assignment

    The first and last scales are always fixed to ensure the proper input and output dimensions.

    Args:
        temporal_patch_size: Temporal dimension of input patches
        patch_size: Spatial dimension (height/width) of input patches
        n_layers: Number of layers in the encoder
        n_channels: Number of input channels (default: 3 for RGB)

    Returns:
        torch.LongTensor of shape `(n_layers + 1, 4)` where the last dim holds values for (t, h, w, c) grids.
    NrN   r   r   r   rM   @   r    )linear_sum_assignment)r.   cumprodtensorr  ceilrw   stack	ones_like	full_liker  prodr]   linspacer   absrD  rZ   argminscipy.optimizer  cpunumpy)r  r  r  r  r   hth_cht_chbasespatialtemporalscalessize_reductiontotal_elementslog_ideal_scalescost_matrixidxsr  r9  idxs_nps                        r3   plan_out_scalesr  w  s]   : 	ell=#<TrT#B6RXYZAell=1D#Edd#KTZ[abcA::adZ'",-113b8D::aeqj:-126682=D<<!Q:./?Dkk5??1-q!T:BG{{Auq!B%8%//!QrU:SUYZ`abHYYgx0a8FZZq#2#vA6<<>N*,/BBZON~~	599U\\.@A8a<X^ )),66q9EIIn<U<_<_`a<bbcK6<<?"||KQ/8*;??+<+B+B+DE
7||GF3 DG||A"DH$<r2   c                   f     e Zd Zdef fdZdej                  dee   dej                  fdZ	 xZ
S )InklingVisionModelr   c                    t         	|   |       t        |j                  |j                  |j
                  |j                        | _        t        j                         | _
        t        t        | j                  d d | j                  dd              D ]  \  }\  }}|d   |d   z  |d   |d   z  z  |d   |d   z  z  }||j
                  dz
  k(  r|j                  n|d   }|d   |d   z  }|d   |d   z  }| j                  j                  t        |d   |z  |||||j
                  dz
  k7                t!        |j                        | _        | j%                          y )NrN   r    r   rM   r   )r  r  r  r  r  )rB   rC   r  r  r  r  num_channelsr  rD   r  encoder_layersr  zipr  r  r  r>   
final_normr  )
rI   r   r  start_scale	end_scaleshuffle_multr  r  r  rK   s
            r3   rC   zInklingVisionModel.__init__  s{    %&&$$	
 !mmo+4SSb9I4;;WXWY?5[+\ 	'A'Y1Q/IaLKPQN4RSW`abWcgrstguWuv  569Q9QTU9U4U00[def[gJlk!n4Gq\[^3F&&))!n|;)#!&":":Q">>	" ))@)@Ar2   pixel_valuesr   r@   c                     |j                   d   }|}| j                  D ]  } ||      } | j                  |      }|j                  |d      }t	        ||      S )Nr   )r9   rN   r  )rZ   r  r  rz   r   )rI   r#  r   num_patchesr9   layers         r3   rX   zInklingVisionModel.forward  sk    "((+$(( 	?E!>M	? 6%--k2>)+'
 	
r2   )r*   r+   r,   r$   rC   r.   r^   r   r   rX   r_   r`   s   @r3   r  r    s;    2 >
ELL 
FCU<V 
[`[g[g 
r2   r  zz
    The Base Inkling model which consists of a vision backbone and a language model without language modeling head.,
    c                       e Zd ZdZdef fdZe ed      dej                  de
e   deez  fd	              Ze ed
      	 ddej                  dej                   dz  deez  fd              Zdej                  dej                  dej                  de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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dz  de
e   deez  fd              Z xZS )InklingModelFr   c                    t         |   |       |j                  j                  | _        t	        |j                        | _        t        |j                        | _        t        |j                        | _        | j                          y rf   )rB   rC   text_configr  r  language_modelr  ro  audio_towerr  vision_configvision_towerr  r   s     r3   rC   zInklingModel.__init__  sf      ,,77.v/A/AB,V-@-@A.v/C/CDr2   zOProjects the last hidden state from the vision model into language model space.r%   r#  r   r@   c                 *     | j                   dd|i|S )Nr#  r1   )r.  rI   r#  r   s      r3   get_image_featureszInklingModel.get_image_features  s    
 !t  ElEfEEr2   zCProjects discretized dMel bin tokens into the language model space.Nr  audio_input_ids_maskc                     |||j                            }n|j                  d|j                  d         }| j                  |      S )a  
        audio_input_ids (`torch.LongTensor` of shape `(num_audios, max_num_frames, n_mel_bins)`):
            Batch of (padded) dMel bin tokens produced by [`InklingProcessor`].
        audio_input_ids_mask (`torch.Tensor` of shape `(num_audios, max_num_frames)`, *optional*):
            Mask marking valid (non-padding) frames. When provided, only valid frames are encoded so that the
            number of returned audio embeddings matches the number of audio placeholder tokens.
        rN   )r  rz   rZ   r,  )rI   r  r2  s      r3   get_audio_featureszInklingModel.get_audio_features  sM      +-.B.G.G.IJO-55b/:O:OPR:STO00r2   r  r  featurestoken_idc                    |Y| | j                         t        j                  |t        j                  |j                              k(  }|j                  d      }n||k(  }|j                         }|j                  d      j                  |      j                  |j                        }t        ||   j                         |j                         k(  d| d|j                  d           |S )z
        Obtains a multimodal placeholder mask from `input_ids` or `inputs_embeds` for the given `token_id`, and checks
        that the placeholder token count matches the length of `features`. If the lengths differ, an error is raised.
        )rP   r   rN   zAMultimodal features and placeholder tokens do not match, tokens: z, features: r   )get_input_embeddingsr.   r  longr   allr   rD  	expand_asrQ   r   numelrZ   )rI   r  r  r5  r6  special_maskn_tokenss          r3   get_placeholder_maskz!InklingModel.get_placeholder_mask  s     (,GD,E,E,GXUZZ@T@TU- L (++B/L$0L##%#--b1;;MJMMmNbNbc,'--/8>>3CCOPXzYefnftftuvfwexy	
 r2   r   r  r8   token_type_idsr  r  	lm_kwargsc           	         |du |	duz  rt        d      |	/| j                  j                   | j                         |            }	|{| j	                  |      j
                  }|j                  |	j                  |	j                        }| j                  ||	|| j                  j                        }|	j                  ||      }	d}||| j                  ||      j                  }|j                  |	j                  |	j                        }| j                  ||	|| j                  j                        }|	j                  ||      }	t!        |x}t"              sA| j                  j%                         |	|||d}t'        di |t)        di |t+        di |d} | j                  d||||	|d|}t-        |j                  |j.                  |j0                  |j2                  |      S d      S )a/  
        audio_input_ids (`torch.LongTensor` of shape `(num_audios, max_num_frames, n_mel_bins)`, *optional*):
            Batch of (padded) discretized dMel bin tokens produced by [`InklingProcessor`].
        audio_input_ids_mask (`torch.Tensor` of shape `(num_audios, max_num_frames)`, *optional*):
            Mask marking valid (non-padding) audio frames in `audio_input_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.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]`.

        Example:

        ```python
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO
        >>> from transformers import AutoProcessor, InklingForConditionalGeneration

        >>> model = InklingForConditionalGeneration.from_pretrained("google/inkling2-3b-mix-224")
        >>> processor = AutoProcessor.from_pretrained("google/inkling2-3b-mix-224")

        >>> prompt = "Where is the cat standing?"
        >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> inputs = processor(images=image, text=prompt,  return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(**inputs,)
        >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Where is the cat standing?\nsnow"
        ```Nr  r  r  )r   r  r8   r  r  )r  r8   r9   r:   r)   r1   )r  r+  r  r8  r1  r  rQ   r   rP   r?  r   image_token_idmasked_scatterr4  r  audio_token_idrs  r  rq  r   r   r   r(   r8   r9   r:   )rI   r  r#  r  r2  r   r  r8   r@  r  r  r  rA  image_featuresspecial_image_maskaudio_featuresspecial_audio_maskr  r  r  s                       r3   rX   zInklingModel.forward*  s!   d -t";<YZZ  //::;V4;T;T;VW`;abM #!44\BPPN+..}/C/C]EXEXYN!%!:!:=.$++:T:T" *889K^\M &!44_FZ[mmN+..}/C/C]EXEXYN!%!:!:=.$++:T:T" *889K^\M ?-F++557!."0#2 ,K #5"C{"C%F%U%U$C$Rk$R# &$%% 
.%+'
 
 *%77#33!//))2>2J
 	

 QU
 	
r2   rf   )NNNNNNNNNNN)r*   r+   r,   accepts_loss_kwargsr"   rC   r   r   r.   r/   r   r   r;   r   r1  r  r^   r4  rw   r?  r   r  r(   rX   r_   r`   s   @r3   r(  r(    s@     }  !rsF!--F9?@R9SF	+	+F t F
 !fg 591))1 $llT11 
+	+	1 h 1$## (( ##	
 6  .2153748.204(,2626*.!%h
##d*h
 ''$.h
 ))D0	h

 $llT1h
 t+h
 &&-h
 h
 ((4/h
 ((4/h
   4'h
 $;h
 ./h
 
+	+h
  h
r2   r(  c                       e Zd Zi ZddiZdZdef fdZede	j                  dee   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d	z  de	j                  d	z  de	j                   d	z  de	j                  d	z  de	j                  d	z  ded	z  dee	j                   z  dee   deez  fd              Z	 	 	 	 	 	 	 	 	 	 	 d fd	Z xZS )InklingForConditionalGenerationr  r  Fr   c                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y r  )rB   rC   r(  rl  rD   r   r*  rJ   r  r  r  r   s     r3   rC   z(InklingForConditionalGeneration.__init__  sU     !&)
 yy!3!3!?!?ASASA^A^ejkr2   r#  r   c                 <     | j                   j                  |fi |S rf   )rl  r1  r0  s      r3   r1  z2InklingForConditionalGeneration.get_image_features  s    ,tzz,,\DVDDr2   Nr  r   r  r8   r  r2  r  r  r  r  r@   c                 6    | j                   d|||||||||
|	d
|}|d   | j                  j                  j                  z  }t	        |t
              rt        | d      n|}| j                  |dd|ddf         }| j                  j                  j                  }|||j                  d   k  r	|dd|f   }d}|	# | j                  d||	|j                  d   d|}t        |||j                  |j                  |j                  |j                        S )	a	  
        audio_input_ids (`torch.LongTensor` of shape `(num_audios, max_num_frames, n_mel_bins)`, *optional*):
            Batch of (padded) discretized dMel bin tokens produced by [`InklingProcessor`].
        audio_input_ids_mask (`torch.Tensor` of shape `(num_audios, max_num_frames)`, *optional*):
            Mask marking valid (non-padding) audio frames in `audio_input_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.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]`.

        Example:

        ```python
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO
        >>> from transformers import AutoProcessor, InklingForConditionalGeneration

        >>> model = InklingForConditionalGeneration.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,
        ...     tokenize=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"
        ```
        )
r  r#  r  r2  r   r  r8   r  r  r  r   NrN   .r  )r6   r7   r8   r9   r:   r)   r1   )rl  r   r*  r  rs  rw   r  r  r  rZ   r  r5   r8   r9   r:   r)   )rI   r  r#  r   r  r8   r  r2  r  r  r  r  r   r  r9   r  r7   r  r6   s                      r3   rX   z'InklingForConditionalGeneration.forward  sF   D $** 
%+!5)%+'
 
  
T[[%<%<%X%XX8B>SV8W~ot4]kmA}a,?@A"kk55II*/BV\\RTEU/UC!5"5!556F%4%%jVFv||\^O_jcijD,#33!//)) ' ; ;
 	
r2   c                 ^    t        |   |f|||||	|
|d|}|s|	s||d<   ||d<   ||d<   |S )N)r8   r  r   r  r  r  is_first_iterationr#  r  r2  )rB   prepare_inputs_for_generation)rI   r  r8   r  r  r#  r   r  r2  r  r  r  rQ  r   model_inputsrK   s                  r3   rR  z=InklingForConditionalGeneration.prepare_inputs_for_generation  sh    " w<

+')%)1

 

 Y+7L(.=L*+3GL/0r2   )NNNNNNNNNNr   )NNNNNNNTNNF)r*   r+   r,   r  r  rJ  r"   rC   r   r.   r/   r   r   r1  r   r  r^   r   r  rw   r;   r5   rX   rR  r_   r`   s   @r3   rL  rL    s    01H  }  Eu/@/@ EFSeLf E E  .215.204(,374826*.!%-.a
##d*a
 ''$.a
 t+	a

 &&-a
 a
 ))D0a
 $llT1a
 ((4/a
   4'a
 $;a
 ell*a
 +,a
 
.	.a
  a
L ! " "r2   rL  )rk  r  r  r  r  r(  rL  )rm   Nr   )r  )^r  collections.abcr   dataclassesr   r.   torch.nnrD   torch.nn.functionalr   r   r   rt  activationsr   cache_utilsr   r	   
generationr
   integrationsr   r   r   r   integrations.accelerater   masking_utilsr   r   r   modeling_layersr   modeling_outputsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.genericr   utils.output_capturingr   configuration_inklingr!   r"   r#   r$   r(   r5   Moduler>   rb   r^   rw   r   r]   r   r   r   r   r
  r)  r3  r;  rE   strr<  rH  r   r^  rk  r  r  rx  r  r  listr  r  r  r  r(  rL  __all__r1   r2   r3   <module>rk     sV  ,  $ !     & ! . )  > s s 9 S F & n n 7 5 l l 
 9!8 9 9 
 9K 9 90 Y'JRYY J (J(^BII ^4	UU\\ 	U# 	U%,, 	U& )-%II%<<% 
% <<	%
 LL4'% % % <<$&%8a)ryy a)H1 1" $#RYY $# $#N#H		 #HL%299 %8 (	 01
 !%!'<<'' LL' ,,
	'
 d
' 2'& ,- !%!	'<<'LL' ,,
' d
	' .', *,<=>;bii ; ?;|.4 .b ._ . .b L
- L
 L
^ K
/ K
 K
\")) 
. 
"		 "J# $s) $ W\;;*-;9<;JM;
;|+
/ +
\ 
l
) l

l
^ 
[&<o [
[|r2   