
    g9:                       d Z ddlZddlmZmZmZmZmZmZ ddl	Z	ddl
mc mZ ddl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 dd
lmZ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$m%Z%m&Z&m'Z' ddl(m)Z)  e%            rddl*m+Z+  e'            rddl,m-Z-m.Z. ddl/m0Z0 nd\  Z0Z.Z- e$            r	ddl1m2Z2m3Z3 nd\  Z3Z2 e4e0e.e2e3e-f          Z5 e!j6        e7          Z8dZ9	 	 	 dBdee	j:        ee	j:                 df         dee;         dee	j:                 dee	j:        e;f         fdZ< G d dej=                  Z>de	j:        d e;de	j:        fd!Z? G d" d#e          Z@ G d$ d%ej=                  ZA G d& d'eA          ZB G d( d)eA          ZCeAeBeCd*ZD G d+ d,ej=                  ZE G d- d.ej=                  ZF G d/ d0ej=                  ZG G d1 d2ej=                  ZH G d3 d4ej=                  ZId5ZJ ed6eJ           G d7 d8e                      ZKd9ZLeHeId:ZM ed6eJ           G d; d<eK                      ZN G d= d>eKe          ZO ed?eJ           G d@ dAeK                      ZPdS )CzPyTorch Jamba model.    N)AnyDictListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)MoeCausalLMOutputWithPastMoeModelOutputWithPast SequenceClassifierOutputWithPast)PreTrainedModel)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings)is_causal_conv1d_availableis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10is_mamba_ssm_available   )JambaConfig)_flash_attention_forward)mamba_inner_fnselective_scan_fn)selective_state_update)NNN)causal_conv1d_fncausal_conv1d_updateNNr      router_logitsnum_expertsattention_maskreturnc                    | t          | t                    sdS t          | t                    r/| d         j        t          j        fd| D             d          }t          j        j                            |d          }t          j        ||d          \  }}t          j        j        	                    ||          }|@t          j
        |                                d          }	t          j
        |d          }
n.|j        \  }}|j        d         ||z  z  }|dddddddf                             |||||f                              d||                                        }t          j        |                                |z  d          t          j        |d          z  }	|ddddddf                             ||||f                              d|                                        }t          j        ||z  d          t          j        |d          z  }
t          j        |	|
                    d          z            }||z  S )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

    See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
    function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
    experts is too unbalanced.

    Args:
        router_logits:
            Logits from the `router`, should be a tuple of model.config.num_hidden_layers tensors of
            shape [batch_size X sequence_length, num_experts].
        num_experts:
            Number of experts
        top_k:
            The number of experts to route per-token, can be also interpreted as the `top-k` routing
            parameter.
        attention_mask (`torch.Tensor`, *optional*):
            The attention_mask used in forward function
            shape [batch_size X sequence_length] if not None.

    Returns:
        The auxiliary loss.
    Nr   c                 :    g | ]}|                               S  )to).0layer_routercompute_devices     d/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/jamba/modeling_jamba.py
<listcomp>z,load_balancing_loss_func.<locals>.<listcomp>v   s%    OOO\__^,,OOO    dim)
isinstancetupledevicetorchcatr	   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshaper-   sum	unsqueeze)r&   r'   top_kr(   concatenated_router_logitsrouting_weights_selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersexpert_attention_mask router_per_expert_attention_maskoverall_lossr0   s                    @r1   load_balancing_loss_funcrU   S   s   : J}e$D$Dq-'' 
&q)0%*YOOOOOOOUV&
 &
 &
" h)112LRT1UUO*_eDDDA(%--.>LLK!J{'8'8':':BBB "'O!C!C!C&4&:#
O6<Q?JQ`D`a 4AAAtT12V&
OUKXYYWR,,R	 	 "Ik&7&7&9&9<Q&QWXYYY\a\e!q]
 ]
 ]
 
 4AAAt+,V&
O[QRRWR%%R	 	) "'?=]+]cd!e!e!ehmhq,!i
 i
 i
 "
 9.1G1Q1QRS1T1TTUUL+%%r3   c                   ,     e Zd Zd fd	Zd Zd Z xZS )JambaRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z;
        JambaRMSNorm is equivalent to T5LayerNorm
        N)super__init__r	   	Parameterr:   onesweightvariance_epsilon)selfhidden_sizeeps	__class__s      r1   r[   zJambaRMSNorm.__init__   sD     	l5:k#:#:;; #r3   c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )Nr%   r6   T)keepdim)	dtyper-   r:   float32powr@   rsqrtr_   r^   )r`   hidden_statesinput_dtypevariances       r1   forwardzJambaRMSNorm.forward   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r3   c                 H    t          | j        j                   d| j         S )Nz, eps=)r8   r^   rB   r_   r`   s    r1   
extra_reprzJambaRMSNorm.extra_repr   s&    )**II$2GIIIr3   )rX   )__name__
__module____qualname__r[   rm   rp   __classcell__rc   s   @r1   rW   rW      sb        $ $ $ $ $ $; ; ;J J J J J J Jr3   rW   rj   n_repc                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||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)rB   rC   rD   )rj   rv   batchnum_key_value_headsslenhead_dims         r1   	repeat_kvr|      s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr3   c                   r    e Zd ZdZej        df fd	Z	 ddej        dej        dede	e
eef                  deej        ej        f         f
d	Zd
ej        fdZdde	e         defdZdeeej                 eej                 f         fdZedde	eeej                                   ddfd            Z xZS ) HybridMambaAttentionDynamicCachea  
    A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
    (which has a constant shape regardless of seq_len).

    This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
    and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
    For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
    while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
    For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
    while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
    and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
    Nc           
      F   t                                                       || _        |j        | _        d| _        |j        |j        z  }|j        }|j        }g | _	        g | _
        g | _        t          |j                  D ]}| j        |         dk    rQ| xj	        t          j        |||          gz  c_	        | xj
        t          j        |||          gz  c_
        d| xj	        t          j        g gz            gz  c_	        | xj
        t          j        g gz            gz  c_
        | j                            |           шfdt          |j                  D             | _        fdt          |j                  D             | _        d S )NFmambar9   rf   r9   c                 D    g | ]}t          j        g gz             S r   r:   tensorr.   rJ   rO   r9   s     r1   r2   z=HybridMambaAttentionDynamicCache.__init__.<locals>.<listcomp>   s/    rrrQ%,tj'8HHHrrrr3   c                 D    g | ]}t          j        g gz             S r   r   r   s     r1   r2   z=HybridMambaAttentionDynamicCache.__init__.<locals>.<listcomp>   s/    tttqEL"
):6JJJtttr3   )rZ   r[   rf   layers_block_typehas_previous_statemamba_expandra   mamba_d_statemamba_d_convconv_states
ssm_statestransformer_layersrangerQ   r:   zerosr   append	key_cachevalue_cache)
r`   configrO   rf   r9   intermediate_sizessm_state_sizeconv_kernel_sizeirc   s
     ` `    r1   r[   z)HybridMambaAttentionDynamicCache.__init__   s   
!'!9"'"/&2DD-!."$v/00 	2 	2A%a(G33  K
,=?OX^fklll%    K
,=~V\dijjj$    U\2$2CF%S%S%S$TT  EL"
1B6$R$R$R#SS'..q1111rrrrrRWX^XpRqRqrrrtttttTYZ`ZrTsTstttr3   
key_statesvalue_states	layer_idxcache_kwargsr)   c                 D   | j         |         j        d         dk    r|| j         |<   || j        |<   nVt          j        | j         |         |gd          | j         |<   t          j        | j        |         |gd          | j        |<   | j         |         | j        |         fS )Nr6   r   r%   r4   )r   rB   r   r:   r;   )r`   r   r   r   r   s        r1   updatez'HybridMambaAttentionDynamicCache.update   s     >)$*2.!33(2DN9%*6DY''(-	4>)3Lj2Y_`(a(a(aDN9%*/)T5Ei5PR^4_ef*g*g*gDY'~i($*:9*EEEr3   beam_idxc                    t          t          | j                            D ];}| j        |         j        }| j        |                             d|                    |                    | j        |<   | j        |         j        }| j        |                             d|                    |                    | j        |<   | j        |         j        }| j        |                             d|                    |                    | j        |<   | j        |         j        }| j        |                             d|                    |                    | j        |<   =dS )zDReorders the cache for beam search, given the selected beam indices.r   N)	r   lenr   r9   index_selectr-   r   r   r   )r`   r   r   r9   s       r1   reorder_cachez.HybridMambaAttentionDynamicCache.reorder_cache  sE   s4>2233 		i 		iI^I.5F(,y(A(N(NqRZR]R]^dReRe(f(fDN9%%i07F*.*:9*E*R*RSTV^VaVabhViVi*j*jDY'%i07F*.*:9*E*R*RSTV^VaVabhViVi*j*jDY'_Y/6F)-)C)P)PQRT\T_T_`fTgTg)h)hDOI&&		i 		ir3   r   c                     || j         vr| j         d         n|}t          | j                  |k    rdS | j        |         j        d         S )zYReturns the sequence length of the cached states. A layer index can be optionally passed.r   )r   r   r   rB   )r`   r   s     r1   get_seq_lengthz/HybridMambaAttentionDynamicCache.get_seq_length  sS     3<4CZ2Z2ZD+A..`i	t~)++1~i(.r22r3   c                      t          d          NzIHybridMambaAttentionDynamicCache does not have a legacy cache equivalent.NotImplementedErrorro   s    r1   to_legacy_cachez0HybridMambaAttentionDynamicCache.to_legacy_cache  s    !"mnnnr3   past_key_valuesr   c                      t          d          r   r   )clsr   s     r1   from_legacy_cachez2HybridMambaAttentionDynamicCache.from_legacy_cache  s    !"mnnnr3   N)r   )rq   rr   rs   __doc__r:   float16r[   Tensorintr   r   strr   r   r   
LongTensorr   r   r   classmethodFloatTensorr   rt   ru   s   @r1   r~   r~      s         27t u u u u u u@ 26F FLF lF 	F
 tCH~.F 
u|U\)	*F F F F"ie&6 i i i i3 3 3c 3 3 3 3ouU\':E%,<O'O!P o o o o o ouUEV?W9X0Y oes o o o [o o o o or3   r~   c                       e Zd ZdZddedee         f fdZ	 	 	 	 	 	 ddej	        deej	                 d	eej
                 d
ee         dededeej
                 deej	        eej	                 eeej	                          f         fdZ xZS )JambaAttentionz
    Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
    and "Generating Long Sequences with Sparse Transformers".
    Nr   r   c                 V   t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _
        | j        | j
        z  | _        |j        | _        | j
        | j        z  | _        d| _        |j        | _        | j        | j
        z  | j        k    r t!          d| j         d| 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        z  | j        d          | _        d S )	NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).Fbias)rZ   r[   r   r   loggerwarning_oncerc   rq   ra   num_attention_heads	num_headsr{   ry   num_key_value_groups	is_causalattention_dropout
ValueErrorr	   Linearq_projk_projv_projo_proj)r`   r   r   rc   s      r1   r[   zJambaAttention.__init__'  s   ",!8 , , ,   "-3(DN:#)#= $(Nd6N$N!!'!9MDN*t/???8RVRb 8 8%)^8 8 8   i 0$.4=2PW\]]]i 0$2JT]2Zafgggi 0$2JT]2Zafgggi >@PW\]]]r3   Frj   r(   position_idspast_key_valueoutput_attentions	use_cachecache_positionr)   c                    |                                 \  }}	}
|                     |          }|                     |          }|                     |          }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }|                    ||	| j        | j                                      dd          }||	                    ||| j
                  \  }}t          || j                  }t          || j                  }t          j        ||                    dd                    t          j        | j                  z  }|$|d d d d d d d |j        d         f         }||z   }t$          j                            |dt          j                                      |j                  }t$          j                            || j        | j                  }t          j        ||          }|                                 || j        |	| j        fk    r5t7          d|| j        |	| j        f d	|                                            |                    dd                                          }|                    ||	| j                  }|                     |          }|sd }|||fS )
Nr   r%   r
   r   r6   r5   rf   )ptrainingz `attn_output` should be of size z	, but is ) sizer   r   r   viewr   r{   	transposery   r   r   r|   r   r:   matmulmathsqrtrB   r	   r<   r=   rg   r-   rf   dropoutr   r   r   
contiguousrD   ra   r   )r`   rj   r(   r   r   r   r   r   bszq_lenrJ   query_statesr   r   attn_weightscausal_maskattn_outputs                    r1   rm   zJambaAttention.forwardD  s    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm%'5'<'<ZW[We'f'f$J z4+DEE
 t/HII|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T=S^b^k,lll<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!))#ud6FGGkk+..  	 LL.88r3   r   NNNFFN)rq   rr   rs   r   r   r   r   r[   r:   r   r   r~   boolr   rm   rt   ru   s   @r1   r   r   !  s#        
^ ^{ ^x} ^ ^ ^ ^ ^ ^@ 2637EI"'5949 49|49 !.49 u/0	49
 !!AB49  49 49 !!1249 
u|Xel3XeEL>Q5RR	S49 49 49 49 49 49 49 49r3   r   c                        e Zd ZdZ fdZ	 	 	 	 	 	 ddej        deej                 deej                 dee	         d	e
d
e
deej                 fdZ xZS )JambaFlashAttention2aF  
    Jamba flash attention module. This module inherits from `JambaAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                 b     t                      j        |i | t                       | _        d S r   )rZ   r[   r   _flash_attn_uses_top_left_mask)r`   argskwargsrc   s      r1   r[   zJambaFlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r3   NFrj   r(   r   r   r   r   r   c                 z   |                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                  }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }||	                    ||| j
                  \  }}t          || j                  }t          || j                  }| j        sdn| j        }|j        }|t           j        k    rt!          j                    rt!          j                    }n3t)          | j        d          r| j        j        }n| j        j        j        }t0                              d| d           |                    |          }|                    |          }|                    |          }|                    dd          }|                    dd          }t7          |||||
|t9          | j        dd           | j        | j        	  	        }|                    |	|
| j                   !                                }| "                    |          }|sd }|||fS )	Nr   r%           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .sliding_window)r   r   r   use_top_left_mask)#r   r   r   r   r   r   r{   ry   r   r   r   r|   r   r   r   rf   r:   rg   is_autocast_enabledget_autocast_gpu_dtypehasattrr   r   r^   r   r   r-   r   getattrr   r   rD   ra   r   r   )r`   rj   r(   r   r   r   r   r   r   r   r   rJ   r   r   r   dropout_raterk   target_dtyper   r   s                       r1   rm   zJambaFlashAttention2.forward  s    &**,,UA{{=11[[//
{{=11
 $((eT^T]SS__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm%'5'<'<ZW[We'f'f$J z4+DEE
 t/HII"&-KssT5K
 #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L  ))!Q//
#--a33. "4;0@$GGn"A

 

 

 "))#ud6FGGRRTTkk+..  	 LL.88r3   r   )rq   rr   rs   r   r[   r:   r   r   r   r~   r   rm   rt   ru   s   @r1   r   r   |  s         X X X X X 2637EI"'59M9 M9|M9 !.M9 u/0	M9
 !!ABM9  M9 M9 !!12M9 M9 M9 M9 M9 M9 M9 M9r3   r   c                        e Zd ZdZ	 	 	 	 	 	 ddej        deej                 deej                 dee         de	d	e	d
eej                 de
ej        eej                 ee
ej                          f         f fdZ xZS )JambaSdpaAttentionz
    Jamba attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `JambaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFrj   r(   r   r   r   r   r   r)   c                 F   |rAt                               d           t                                          ||||||          S |                                \  }}	}
|                     |          }|                     |          }|                     |          }|                    ||	| j	        | j
                                      dd          }|                    ||	| j        | j
                                      dd          }|                    ||	| j        | j
                                      dd          }||                    ||| j                  \  }}t          || j                  }t          || j                  }|}||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }| j        r
||	dk    rdnd}t,          j        j                            ||||| j        r| j        nd	|
          }|                    dd                                          }|                    ||	| j                  }|                     |          }|d |fS )Na  JambaModel is using JambaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)rj   r(   r   r   r   r   r   r%   r   cudaTFr   )	attn_mask	dropout_pr   )r   r   rZ   rm   r   r   r   r   r   r   r{   r   ry   r   r   r|   r   rB   r9   typer   r   r:   r	   r<   scaled_dot_product_attentionr   r   ra   r   )r`   rj   r(   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   rc   s                    r1   rm   zJambaSdpaAttention.forward  s     	[   77??+-)-"3# #    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm%'5'<'<ZW[We'f'f$Jz4+DEE
 t/HII$%%aaaAAA/E1A"1E/E&EFK #v--.2L'2244L#..00J'2244L
 !N[{/BuqyyDDV[	h)FF!04Fd,,3 G 
 
 "++Aq11<<>>!&&sE43CDDkk+..D.00r3   r   )rq   rr   rs   r   r:   r   r   r   r~   r   r   rm   rt   ru   s   @r1   r   r     s         2637EI"'59G1 G1|G1 !.G1 u/0	G1
 !!ABG1  G1 G1 !!12G1 
u|Xel3XeEL>Q5RR	SG1 G1 G1 G1 G1 G1 G1 G1 G1 G1r3   r   )eagerflash_attention_2sdpac                        e Zd ZdZdef fdZ	 	 ddej        dede	ej
                 fdZddede	ej
                 fd	Z	 	 ddede	ej
                 fd
Z xZS )JambaMambaMixeru  
    Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
    A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
    ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
    and is why Mamba is called **selective** state spaces)
    r   c           	         t                                                       || _        || _        |j        | _        |j        | _        |j        | _        |j	        |j        z  | _
        |j        | _        |j        | _        |j        | _        t#          j        | j
        | j
        | j        | j        | j
        | j        dz
            | _        |j        | _        t,          |j                 | _        |j        | _        t#          j        | j        | j
        dz  | j                  | _        t#          j        | j
        | j        | j        dz  z   d          | _        t#          j        | j        | j
        d          | _        t=          j        d| j        dz             d d d f         }|                     | j
        d          !                                }t#          j"        t=          j#        |                    | _$        t#          j"        t=          j%        | j
                            | _&        t#          j        | j
        | j        | j                  | _'        tQ          | j        |j)                  | _*        tQ          | j        |j)                  | _+        tQ          | j        |j)                  | _,        tZ          st\          /                    d	           d S d S )
Nr   )in_channelsout_channelsr   kernel_sizegroupspaddingr%   r   FTr6   rb   ap  The fast path is not available because on of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)` is None. To install follow https://github.com/state-spaces/mamba/#installation and https://github.com/Dao-AILab/causal-conv1d. If you want to use the naive implementation, set `use_mamba_kernels=False` in the model config)0rZ   r[   r   r   ra   r   r   r   r   r   r   mamba_dt_ranktime_step_rankmamba_conv_biasuse_conv_biasmamba_proj_biasuse_biasr	   Conv1dconv1d
hidden_act
activationr   actuse_mamba_kernelsuse_fast_kernelsr   in_projx_projdt_projr:   arangerC   r   r\   logA_logr]   Dout_projrW   rms_norm_epsdt_layernormb_layernormc_layernormis_fast_path_availabler   r   )r`   r   r   Arc   s       r1   r[   zJambaMambaMixer.__init__?  s   "!-$2 & 3!'!4v7I!I$2#3.i./#-))A-
 
 
 !+&+, & 8 y!143IA3MTXTabbbi 68KdNadeNe8elqrrry!4d6LSWXXX LD/!344T111W=HHT+R00;;==\%)A,,//
ej)?@@AA	$"8$:JQUQ^___()<&BUVVV'(;ATUUU'(;ATUUU% 	^    	 	r3   Nrj   cache_paramsr(   c                 	   |j         \  }}}|d uoR|j        oK|dk    oE|j        | j                 j         d         |j        | j                 j         d         cxk    o|k    nc }|                     |                              dd          }|                    dd          \  }}	|||                    d          z  }| j	        j
                            | j	        j
                            d          | j	        j
                            d                    }
|r[t          |                    d          |j        | j                 |
| j	        j        | j                  }|                    d          }n~|Zt"          j                            || j        |j         d         z
  df          }|j        | j                                     |           t-          ||
| j	        j        | j                  }|||                    d          z  }|                     |                    dd                    }t1          j        || j        | j        | j        gd          \  }}}|                     |          }|                     |          }|                     |          }| j        j        j         }t1          j!                    5  t1          j"        | j        j        j                   | j        j        _         d d d            n# 1 swxY w Y   |                     |                              dd          }t1          j!                    5  || j        j        _         d d d            n# 1 swxY w Y   t1          j#        | j$        %                                           }||%                                nd }|rhtM          |j        | j                 |d         |d         ||d d df         |d d df         | j'        |	d         |d	
  
                            d          }ntQ          ||||                    dd          |                    dd          | j'        %                                |	|dd

  
        \  }}|'|%|j        | j                                     |           | )                    |                    dd                    }|S )Nr   r   r%   r4   r6   )r  ).r   T)dt_softplus)delta_softplusreturn_last_state)*rB   r   r   r   r   r  r   chunkrF   r  r^   r   r   r#   squeezer   r  r	   r<   padr   copy_r"   r  r:   splitr  r   r"  r#  r$  r  datano_grad
zeros_likeexpr  rA   r!   r  r    r   )r`   rj   r'  r(   rO   seq_lenrJ   use_precomputed_statesprojected_statesgateconv_weightsr   ssm_parameters	time_stepBCtime_proj_biasdiscrete_time_stepr&  scan_outputs	ssm_statecontextualized_statess                         r1   cuda_kernels_forwardz$JambaMambaMixer.cuda_kernels_forwards  sX    "/!4
GQ$ /1 (8>qA&t~6<Q?      	 	  <<66@@AFF /44QA4>>t%)N,D,DQ,G,GGM {)..t{/A/F/Fq/I/I4;K]KbKbcdKeKeff! 	x0%%b))(8  M *33B77MM' m//@UXeXklnXo@oqr?stt(8>>{KKK,]L$+JZgkgvwwwM%)N,D,DQ,G,GGM ]%<%<Q%B%BCC+T0$2EtGZ[ac
 
 
	1a %%i00	QQ */]__ 	N 	N%*%5dl6G6L%M%MDL"	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N 	N!\\)44>>q!DD]__ 	4 	4%3DL"	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 Ytz''))***3A3M--///SW! 	I1'7f%"6*!!!Q$!!!Q$V    imm L '8"Aq!!Aq!!#"&' ' '#L) $)A'7==iHHH !%l.D.DQ.J.J K K$$s$   3LLLM,,M03M0c           	      f   |j         \  }}}|j        }|                     |                              dd          }|                    dd          \  }	}
||	|                    d          z  }	t          |t                    }|r|j        | j	                 j         d         |k    r| j
        r%|j        | j	                                                 }n|j        | j	                 }|                    |	j                  }|j        r|dk    r|j        | j	                 j         d         |k    r|j        | j	                 }t!          j        |dd          }|	d d d d df         |d d d d df<   ||j        | j	        <   t!          j        || j        j        d d dd d f         z  d          }	| j        r|	| j        j        z  }	|                     |	                              |                              d          }	nt0          j                            |	| j        |	j         d         z
  df          }||j        | j	        <   |                     |                     |	          dd |f                   }	n[t!          j        || j        | j        f|	j        |          }|                     |                     |	          dd |f                   }	||	|                    d          z  }	|                     |	                    dd                    }t!          j         || j!        | j        | j        gd          \  }}}| "                    |          }| #                    |          }| $                    |          }| %                    |          }t0          j        &                    |                              dd          }t!          j'        | j(        )                                           }t!          j'        |d d d d d d f         |d d d d d d d f         z            }|d d d d d d d f         |d d d d d d d f         )                                z  }||	d d d d d d d f         )                                z  }g }tU          |          D ]}|d d d d |d d f         |z  |d d d d |d d f         z   }t!          j+        |                    |          |d d |d d f                             d                    }|,                    |d d d d df                    t!          j-        |d          }||	| j.        d d d d f         z  z   }||                     |
          z  }|r||j        | j	        <   | /                    |                    dd                    }|S )	Nr   r%   r4   r   r6   )shiftsdims.r   )0rB   rf   r  r   r,  rF   r7   r~   r   r   r   cloner-   r9   r   r   r:   rollrE   r  r^   r  r   r  r	   r<   r.  r   r   r   r   r  r0  r  r"  r#  r$  r  softplusr4  r  rA   r   r   r   stackr  r   )r`   input_statesr'  r(   rO   r5  rJ   rf   r7  rj   r8  r   rA  
conv_stater:  r;  r<  r=  r?  r&  
discrete_A
discrete_BdeltaB_ur@  r   scan_outputrB  s                              r1   slow_forwardzJambaMambaMixer.slow_forward  s   !-!3
GQ"<<55??1EE.44QA4>>t%)N,D,DQ,G,GGM|-MNN	 	P0@FqIZWW} D(3DNCIIKK		(3DNC	!]%9::I. T7a<< ,T^<B1ESS)5dnE
"Z
2BGGG
'4QQQ1W'=
111aaa8$;E(8 %	*t{7I!!!QPQPQPQ'7R*RXZ [ [ [% 6!T[%55M $ 7 7 : :5 A A K KB O O]..!*]-@-DDaH 
 <F(8 $])C)CC'M)R S ST3T5HI$+5  I !HHT[[%?%?XgX%NOOM%)N,D,DQ,G,GGM ]%<%<Q%B%BCC+T0$2EtGZ[ac
 
 
	1a %%i00	QQ!\\)44]334FGGQQRSUVWW Ytz''))***Yqqqq$!125G111aaaQU5VVWW
'111aaa6111dAAAqqq=9I9O9O9Q9QQ
aaaAAAtm < B B D DDw 	6 	6A"111aaaAAA:.:XaaaAqqqj=QQI,y||E':':AaaaAAAgJ<P<PQS<T<TUUKAAAqqq!G 45555k,B777!]TVD!!!TM5J%JK"TXXd^^3 	@6?L#DN3 !%k.C.CAq.I.I J J$$r3   c                     | j         rEt          rd| j        j        j        j        vrt          d          |                     |||          S |                     |||          S )Nr   zsFast Mamba kernels are not available. Make sure to they are installed and that the mamba module is on a CUDA device)	r  r%  r  r^   r9   r   r   rC  rQ  )r`   rj   r'  r(   s       r1   rm   zJambaMambaMixer.forward3  sw       	Z) V4;;M;T;Y-Y-Y  J   ,,]L.YYY  nMMMr3   r$   )rq   rr   rs   r   r   r[   r:   r   r~   r   r   rC  rQ  rm   rt   ru   s   @r1   r  r  7  s)        2{ 2 2 2 2 2 2n :>59	h% h%|h% 7h% !!12	h% h% h% h%VR% R%7W R%pxy~  zJ  qK R% R% R% R%p :>59	N N 7N !!12	N N N N N N N Nr3   r  c                   $     e Zd Z fdZd Z xZS )JambaMLPc                    t                                                       |j        | _        |j        | _        t	          j        | j        | j        d          | _        t	          j        | j        | j        d          | _        t	          j        | j        | j        d          | _        t          |j
                 | _        d S NFr   )rZ   r[   ra   r   r	   r   	gate_projup_proj	down_projr   r  act_fnr`   r   rc   s     r1   r[   zJambaMLP.__init__D  s    !-!'!94#3T5KRWXXXy!143IPUVVV4#94;KRWXXXV./r3   c                     |                      |                     |                     |                    |                     |          z            S r   )rY  rZ  rW  rX  )r`   hidden_states     r1   rm   zJambaMLP.forwardM  s>    ~~dkk$..*F*FGG$,,WcJdJddeeer3   )rq   rr   rs   r[   rm   rt   ru   s   @r1   rT  rT  C  sN        0 0 0 0 0f f f f f f fr3   rT  c                   f     e Zd ZdZdef fdZdej        deej        ej        f         fdZ	 xZ
S )JambaSparseMoeBlocka  
    This implementation is
    strictly equivalent to standard MoE with full capacity (no
    dropped tokens). It's faster since it formulates MoE operations
    in terms of block-sparse operations to accomodate imbalanced
    assignments of tokens to experts, whereas standard MoE either
    (1) drop tokens at the cost of reduced performance or (2) set
    capacity factor to number of experts and thus waste computation
    and memory on padding.
    r   c                 d   t                                                       j        | _        j        | _        j        | _        j        | _        t          j
        | j        | j        d          | _        t          j        fdt          | j                  D                       | _        d S )NFr   c                 .    g | ]}t                    S r,   )rT  )r.   rJ   r   s     r1   r2   z0JambaSparseMoeBlock.__init__.<locals>.<listcomp>f  s!    %X%X%X1hv&6&6%X%X%Xr3   )rZ   r[   ra   
hidden_dimr   ffn_dimr'   num_experts_per_tokrG   r	   r   router
ModuleListr   expertsr[  s    `r1   r[   zJambaSparseMoeBlock.__init__^  s     ,/!-/
i1ANNN}%X%X%X%XdFV@W@W%X%X%XYYr3   rj   r)   c                    |j         \  }}}|                    d|          }|                     |          }t          j        |dt
          j                  }t          j        || j        d          \  }}|	                    |j
                  }t          j        ||z  |f|j
        |j                  }t
          j        j                            || j                                      ddd          }	t%          | j                  D ]}
| j        |
         }t          j        |	|
                   \  }}|j         d         dk    r>|d	|f                             d|          } ||          |||d	f         z  }|                    d||	                    |j
                             |                    |||          }||fS )
 r6   r   r   r4   )rf   r9   )num_classesr%   r   N)rB   r   re  Fr=   r:   rA   r>   rG   r-   rf   r   r9   r	   r<   r?   r'   permuter   rg  whererD   
index_add_)r`   rj   rO   rP   rb  r&   rI   rK   final_hidden_statesrL   
expert_idxexpert_layeridxtop_xcurrent_statecurrent_hidden_statess                   r1   rm   zJambaSparseMoeBlock.forwardh  s   2?2E/
OZ%**2z::M22)MqLLL,1J
XZ,[,[,[))),,]-@AA#k/):6m>QZgZn
 
 
 h)112BPTP`1aaiijkmnpqrr   011 	d 	dJ<
3L[%<==JC{1~""
 *$+6>>r:NNM$0L$?$?/RWY\^bRbBc$c!  **1e5J5M5MmNa5b5bcccc199*oWabb"M11r3   )rq   rr   rs   r   r   r[   r:   r   r   rm   rt   ru   s   @r1   r_  r_  R  s        	 	Z{ Z Z Z Z Z Z&2U\ &2eEL%,<V6W &2 &2 &2 &2 &2 &2 &2 &2r3   r_  c                   *    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej        deej                 deej	                 d	ee
         d
ee         dee         dee         deej	                 deej        eeej        ej        f                  f         fdZ xZS )JambaAttentionDecoderLayerr   r   c                 j   t                                                       |j        |         }t          |j                 ||          | _        |dk    rt          nt          } ||          | _        t          |j
        |j                  | _        t          |j
        |j                  | _        d S )Nr   r  )rZ   r[   layers_num_expertsJAMBA_ATTENTION_CLASSES_attn_implementation	self_attnr_  rT  feed_forwardrW   ra   r!  input_layernormpre_ff_layernormr`   r   r   r'   ffn_layer_classrc   s        r1   r[   z#JambaAttentionDecoderLayer.__init__  s    /	:01LMfV_``1<q--h+OF33+F,>FDWXXX ,V-?VEX Y Y Yr3   NFrj   r(   r   r   r   output_router_logitsr   r   r)   c	           	      T   |}	|                      |          }|                     |||||||          \  }}
}|	|z   }|}	|                     |          }|                     |          }t	          |t
                    r|\  }}n|d}}|	|z   }|f}|r||
fz  }|r||fz  }|r||fz  }|S )  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_value (`HybridMambaAttentionDynamicCache`, *optional*): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_router_logits (`bool`, *optional*):
                Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
                should not be returned during inference.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence.
        )rj   r(   r   r   r   r   r   N)r~  r|  r  r}  r7   r8   )r`   rj   r(   r   r   r   r  r   r   residualself_attn_weightspresent_key_value
ff_outputsr&   outputss                  r1   rm   z"JambaAttentionDecoderLayer.forward  s   < !,,];;>Bnn')%)/) ?M ?
 ?
;(*; !=0 !--m<<&&}55
j%(( 	<+5(M==+5t=M =0 " 	,)++G 	,)++G 	(''Gr3   NNNFFFNrq   rr   rs   r   r   r[   r:   r   r   r   r~   r   r   r   rm   rt   ru   s   @r1   rw  rw    s:       Z{ Zs Z Z Z Z Z Z 2637EI,1/4$)59D D|D !.D u/0	D
 !!ABD $D>D 'tnD D>D !!12D 
u (51BEDU1U+V"WW	XD D D D D D D Dr3   rw  c                   *    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej        deej                 deej	                 d	ee
         d
ee         dee         dee         deej	                 deej        eeej        ej        f                  f         fdZ xZS )JambaMambaDecoderLayerr   r   c                 V   t                                                       |j        |         }t          ||          | _        |dk    rt
          nt          } ||          | _        t          |j	        |j
                  | _        t          |j	        |j
                  | _        d S )N)r   r   r   r  )rZ   r[   ry  r  r   r_  rT  r}  rW   ra   r!  r~  r  r  s        r1   r[   zJambaMambaDecoderLayer.__init__  s    /	:$FiHHH
1<q--h+OF33+F,>FDWXXX ,V-?VEX Y Y Yr3   NFrj   r(   r   r   r   r  r   r   r)   c	                 H   |}	|                      |          }|                     |||          }d}
|	|z   }|}	|                     |          }|                     |          }t	          |t
                    r|\  }}n|d}}|	|z   }|f}|r||
fz  }|r||fz  }|r||fz  }|S )r  )rj   r'  r(   N)r~  r   r  r}  r7   r8   )r`   rj   r(   r   r   r   r  r   r   r  r  r  r&   r  s                 r1   rm   zJambaMambaDecoderLayer.forward  s    < !,,];;

'') # 
 

 ! !=0 !--m<<&&}55
j%(( 	<+5(M==+5t=M =0 " 	,)++G 	)((G 	(''Gr3   r  r  ru   s   @r1   r  r    s:       Z{ Zs Z Z Z Z Z Z 2637EI,1/4$)59A A|A !.A u/0	A
 !!ABA $D>A 'tnA D>A !!12A 
u (51BEDU1U+V"WW	XA A A A A A A Ar3   r  aJ  
    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 ([`JambaConfig`]):
            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.
zSThe bare Jamba Model outputting raw hidden-states without any specific head on top.c                   <    e Zd ZeZdZdZddgZdZdZ	dZ
dZdZd ZdS )JambaPreTrainedModelmodelTrw  r  r   c                    | j         j        }t          |t          j        t          j        f          rJ|j        j                            d|           |j	         |j	        j        
                                 d S d S t          |t          j                  rS|j        j                            d|           |j        -|j        j        |j                 
                                 d S d S d S )Nr   )r@   std)r   initializer_ranger7   r	   r   r  r^   r1  normal_r   zero_	Embeddingpadding_idx)r`   moduler  s      r1   _init_weightsz"JambaPreTrainedModel._init_weightsR  s    k+fry")455 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r3   N)rq   rr   rs   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_is_statefulr  r,   r3   r1   r  r  C  s^        
 L&*#57OP"3!N L	? 	? 	? 	? 	?r3   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 (`HybridMambaAttentionDynamicCache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            A HybridMambaAttentionDynamicCache object containing pre-computed hidden-states (keys and values in the
            self-attention blocks and convolution and ssm states in the mamba blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
            Key and value cache tensors have shape `(batch_size, num_heads, seq_len, head_dim)`.
            Convolution and ssm states tensors have shape `(batch_size, d_inner, d_conv)` and
            `(batch_size, d_inner, d_state)` respectively.
            See the `HybridMambaAttentionDynamicCache` class for more details.

            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.
        output_router_logits (`bool`, *optional*):
            Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
            should not be returned during inference.
        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.
)	attentionr   c                   l    e Zd ZdZdef fdZd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 	 dd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         dee         dee
j                 deeef         fd            Zd Zd Z xZS )
JambaModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`JambaDecoderLayer`]

    Args:
        config: JambaConfig
    r   c                 0   t                                          |           |j        | _        |j        | _        t          j        |j        |j        | j                  | _        g }t          |j
                  D ]:}t          |j        |                  }|                     |||                     ;t          j        |          | _        |j        | _        t#          |j        |j                  | _        d| _        |                                  d S )N)r   r  F)rZ   r[   pad_token_idr  
vocab_sizer	   r  ra   embed_tokensr   rQ   ALL_DECODER_LAYER_TYPESr   r   rf  layersr{  rW   r!  final_layernormgradient_checkpointing	post_init)r`   r   decoder_layersr   layer_classrc   s        r1   r[   zJambaModel.__init__  s       !. +L):F<NPTP`aav/00 	D 	DA1&2J12MNK!!++f"B"B"BCCCCmN33$*$?!+F,>FDWXXX&+#r3   c                     | j         S r   r  ro   s    r1   get_input_embeddingszJambaModel.get_input_embeddings  s      r3   c                     || _         d S r   r  r`   values     r1   set_input_embeddingszJambaModel.set_input_embeddings  s    !r3   N	input_idsr(   r   r   inputs_embedsr   r   output_hidden_statesr  return_dictr   r)   c                    ||n| j         j        }|	|	n| j         j        }	||n| j         j        }||n| j         j        }|
|
n| j         j        }
|d u |d uz  rt          d          | j        r%| j        r|rt          
                    d           d}||                     |          }|}|r|t          
                    d           |&t          j        |j        d         |j                  }||                    d          }|                     |||          }|                     ||          }|rdnd }|rdnd }|	rdnd }| j        D ]}t)          |t*                    r|n|}|r||fz  }| j        r*| j        r#|                     |j        ||||||	||	  	        }n |||||||	||	          }|d         }|r|d         ||d         fz  }|	r|d
         ||d
         fz  }|                     |          }|r||fz  }|r|j        sd|_        |sd n|}|
st5          d |||||fD                       S t7          |||||          S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzJamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was provided, so no cache will be returned.r   r   r   r,   )r(   r   r   r   r  r   r   r6   Tc              3      K   | ]}||V  	d S r   r,   )r.   vs     r1   	<genexpr>z%JambaModel.forward.<locals>.<genexpr>>  s0        =  === r3   )last_hidden_stater   rj   
attentionsr&   )r   r   r  r  r   use_return_dictr   r  r   r   r   r  r:   r  rB   r9   rF   _update_causal_mask_update_mamba_maskr  r7   r  _gradient_checkpointing_func__call__r  r   r8   r   )r`   r  r(   r   r   r  r   r   r  r  r  r   rj   r   
mamba_maskall_hidden_statesall_self_attnsall_router_logitsdecoder_layer
layer_masklayer_outputs
next_caches                         r1   rm   zJambaModel.forward  s    2C1N--TXT_Tq$8$D  $+Jj 	 %9$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	4= 	Y 	j   I  --i88M% 	0:  
 !"\-*=a*@I]^^^N)33A66L..~}n]],,^^LL
"6@BBD0:d"6@BBD![ )	> )	>M'1-AW'X'Xi^iJ# 6!m%55!* t}  $ A A!*! #%("
! 
! !.!#-!-#2&7)='#1	! 	! 	! *!,M  : #/"}Q'7&99N# > $0%-*;)==%,,];;   	2-!11 	6?#E 	615O.!*?TT
 	  '5FXij     
 &+&+%+
 
 
 	
r3   c                    | j         j        dk    r
|d|v r|S d S |j        |j        }}t	          j        |          j        }|j        d         }|d         dz   }t	          j        ||f|||          }	|dk    rt	          j	        |	d          }	|	t	          j
        ||          |                    dd          k    z  }	|	d d d d d d f                             |j        d         ddd          }	||	                                }	|                                d	k    rw|j        d         }
|	d
d |
f                             d          |d d d d d d f                             d          z  }|	d
d |
f                             ||          |	d
d |
f<   | j         j        dk    r'|%|j        j        dk    rt%          j        |	|          }	|	S )Nr  r   r   r6   )
fill_valuerf   r9   )diagonalr   r   r%   .r  r   )r   r{  rf   r9   r:   finfominrB   fulltriur  rD   rC   rG  r5   eqmasked_fillr   r   _unmask_unattended)r`   r(   input_tensorr   rf   r9   	min_dtyperP   target_lengthr   mask_lengthpadding_masks               r1   r  zJambaModel._update_causal_maskK  s   ;+/BBB)c^.C.C%%4$*L,?vK&&*	&,Q/&r*Q.j/=!Ai_dmsttta*[1===Ku|M&AAANDZDZ[]_`DaDaaa!$aaa"23::<;Ma;PRSUWY[\\%%++--K!!##q((,226*3+<=@@EEWXWXWXZ^`dfgfgfgWgHhHkHkloHpHpp1<S,;,=N1O1[1[\hjs1t1tC+-. K,66*%*f44
 1CKQZ[[Kr3   c                 Z    |}|d         dk    s|t          j        |dk              rd}|S )zv
        No need for zeroing states when
            1. Cached forward
            2. Attending to all inputs
        r   Nr   )r:   all)r`   r(   r   r  s       r1   r  zJambaModel._update_mamba_maskn  s>     $
!q  ^%?EIn`aNaDbDb%?Jr3   )NNNNNNNNNNN)rq   rr   rs   r   r   r[   r  r  r   JAMBA_INPUTS_DOCSTRINGr:   r   r   r   r~   r   r   r   r   r   rm   r  r  rt   ru   s   @r1   r  r    s        {      &! ! !" " " +*+ABB '+1537FJ59$(,0/3/3&*59z
 z
#z
 !.z
 u/0	z

 ""BCz
   12z
 D>z
 $D>z
 'tnz
 'tnz
 d^z
 !!12z
 
u,,	-z
 z
 z
 CBz
x! ! !F	 	 	 	 	 	 	r3   r  c            !           e Zd ZdgZdef fdZd Zd Zd Zd Z	d Z
d	 Z ee           eee
          	 	 	 	 	 	 	 	 	 	 	 	 	 ddej        deej                 deej                 dee         deej                 deej                 dee         dee         dee         dee         dee         deej                 deeedf                  deeef         fd                        Z	 	 	 	 	 	 	 ddZ xZS ) JambaForCausalLMzlm_head.weightr   c                 F   t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        |j	        | _	        |j
        | _
        |j        | _        |                                  d S rV  )rZ   r[   r  r  r  r	   r   ra   lm_headrouter_aux_loss_coefr'   rd  r  r[  s     r1   r[   zJambaForCausalLM.__init__~  s       ''
 +y!3V5FUSSS$*$?!!-#)#= r3   c                     | j         j        S r   r  r  ro   s    r1   r  z%JambaForCausalLM.get_input_embeddings      z&&r3   c                     || j         _        d S r   r  r  s     r1   r  z%JambaForCausalLM.set_input_embeddings      "'
r3   c                     | j         S r   r  ro   s    r1   get_output_embeddingsz&JambaForCausalLM.get_output_embeddings  s
    |r3   c                     || _         d S r   r  )r`   new_embeddingss     r1   set_output_embeddingsz&JambaForCausalLM.set_output_embeddings  s    %r3   c                     || _         d S r   r  )r`   decoders     r1   set_decoderzJambaForCausalLM.set_decoder  s    


r3   c                     | j         S r   r  ro   s    r1   get_decoderzJambaForCausalLM.get_decoder  s
    zr3   )output_typer  Nr  r(   r   r   r  labelsr   r   r  r  r  r   num_logits_to_keepr)   c                    ||n| j         j        }|
|
n| j         j        }
|	|	n| j         j        }	||n| j         j        }|                     ||||||||	|
||          }|d         }||                     |          }n#|                     |d| dddf                   }d}| | j        ||| j        fi |}d}|
rRt          |r|j
        n|d         | j        | j        |          }|%|| j        |                    |j                  z  z  }|s |f|dd         z   }|
r|f|z   }||f|z   n|S t!          ||||j        |j        |j        |j
                  S )a  
        Args:
            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]`.

            num_logits_to_keep (`int` or `None`, *optional*):
                Calculate logits for the last `num_logits_to_keep` tokens. If `None`, calculate logits for all
                `input_ids`. 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.

        Returns:

        Example:

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

        >>> model = JambaForCausalLM.from_pretrained("ai21labs/Jamba-v0.1")
        >>> tokenizer = AutoTokenizer.from_pretrained("ai21labs/Jamba-v0.1")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> 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]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)r  r(   r   r   r  r   r   r  r  r   r  r   .r6   r   )lossaux_losslogitsr   rj   r  r&   )r   r   r  r  r  r  r  loss_functionr  rU   r&   r'   rd  r  r-   r9   r   r   rj   r  )r`   r  r(   r   r   r  r  r   r   r  r  r  r   r  loss_kwargsr  rj   r  r  r  outputs                        r1   rm   zJambaForCausalLM.forward  s   f 2C1N--TXT_Tq$8$D  $+Jj 	
 %9$D  $+Jj 	 &1%<kk$+B] **)%+'/!5!5)#  
 
  
%\\-00FF\\-6H5H5I5I1110L"MNNF%4%ffdoUUUUD 	M/)4E%%'"+ (	 H !1HKK4L4LLL 	DY,F# ."v-'+'7D7V##VC(#3!/)!/
 
 
 	
r3   FTc	           
      L   |d u }
|
sF||d d |j         d          d f         }nV|j         d         |j         d         k    r|d d |f         }n-t          | j        |j         d         | j        | j                  }|b|`|                                                    d          dz
  }|                    |dk    d           |
s|d d |j         d          d f         }||
rd|i}nd|                                i}|	                    |||||| j        j
        |d           |S )Nr   r   r   r6   r  r  )r   r   r   r(   r  r  r   )rB   r~   r   rf   r9   longcumsummasked_fill_r   r   r  )r`   r  r   r(   r  r  r   r   r   r   empty_past_kvmodel_inputss               r1   prepare_inputs_for_generationz.JambaForCausalLM.prepare_inputs_for_generation  s    (4/
  	(%aaa.*>q*A)A)C)C&CD		#~';A'>>>%aaa&78	>Y_Q/DK  O %,*>)..0077;;a?L%%n&91===  F+AAA	0B/B/D/D,DE $$+];LL')=)=)?)?@L ,#2&"0(<&*k&D"0 
	
 
	
 
	
 r3   )NNNNNNNNNNNNN)NNNFNNT)rq   rr   rs   _tied_weights_keysr   r[   r  r  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr:   r   r   r   r~   r   r   r   r   r   rm   r	  rt   ru   s   @r1   r  r  {  sG       *+	{ 	 	 	 	 	 	' ' '( ( (  & & &     +*+ABB+DSbccc '+1537FJ59-1$(,0/3/3&*599=l
 l
#l
 !.l
 u/0	l

 ""BCl
   12l
 )*l
 D>l
 $D>l
 'tnl
 'tnl
 d^l
 !!12l
 %U39%56l
  
u//	0!l
 l
 l
 dc CBl
b "5 5 5 5 5 5 5 5r3   r  a  
    The Jamba Model with a sequence classification head on top (linear layer).

    [`JambaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                   v    e Zd Z fdZd Zd Z ee          	 	 	 	 	 	 	 	 	 	 ddee	j
                 dee	j                 dee	j
                 deeeee	j                 f                  d	ee	j                 d
ee	j
                 dee         dee         dee         dee         deeef         fd            Z xZS )JambaForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S rV  )
rZ   r[   
num_labelsr  r  r	   r   ra   scorer  r[  s     r1   r[   z'JambaForSequenceClassification.__init__U  si        +''
Yv14?OOO
 	r3   c                     | j         j        S r   r  ro   s    r1   r  z3JambaForSequenceClassification.get_input_embeddings^  r  r3   c                     || j         _        d S r   r  r  s     r1   r  z3JambaForSequenceClassification.set_input_embeddingsa  r  r3   Nr  r(   r   r   r  r  r   r   r  r  r)   c                 "   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }||j        d         }n|j        d         }| j         j        |dk    rt          d          | j         j        d}nv|rt          j        || j         j                  	                                
                    d          dz
  }||j        d         z  }|                    |j                  }nd}|t          j        ||j                  |f         }d}||                     |||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        	          S )
a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        N)r(   r   r   r  r   r   r  r  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r6   r   )r  r  pooled_logitsr   )r  r  r   rj   r  )r   r  r  r  rB   r  r   r:   r  r   argmaxr-   r9   r  r   r   r   rj   r  )r`   r  r(   r   r   r  r  r   r   r  r  transformer_outputsrj   r  rO   sequence_lengthsr  r  r  s                      r1   rm   z&JambaForSequenceClassification.forwardd  s   ( &1%<kk$+B]"jj)%+'/!5# ) 

 

 ,A.M** "+JJ&,Q/J;#+
a\]]];#+!$#(8It{7O#P#P#T#T#V#V#]#]^`#a#ade#e #3iob6I#I #3#6#6v}#E#E  #% u|Jv}MMMO__`%%VFR_hlhs%ttD 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r3   )
NNNNNNNNNN)rq   rr   rs   r[   r  r  r   r  r   r:   r   r   r   r   r   r   r   r   r   rm   rt   ru   s   @r1   r  r  D  s       "    ' ' '( ( ( +*+ABB 151537KO59-1$(,0/3&*E
 E
E,-E
 !.E
 u/0	E

 "%tE4E/F(F"GHE
   12E
 )*E
 D>E
 $D>E
 'tnE
 d^E
 
u66	7E
 E
 E
 CBE
 E
 E
 E
 E
r3   r  )Nr%   N)Qr   r   typingr   r   r   r   r   r   r:   torch.nn.functionalr	   r<   rk  torch.utils.checkpointactivationsr   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   modeling_utilsr   utilsr   r   r   r   utils.import_utilsr   r   r   r   configuration_jambar   modeling_flash_attention_utilsr   &mamba_ssm.ops.selective_scan_interfacer   r    +mamba_ssm.ops.triton.selective_state_updater!   causal_conv1dr"   r#   r  r%  
get_loggerrq   r   r  r   r   rU   ModulerW   r|   r~   r   r   r   rz  r  rT  r_  rw  r  JAMBA_START_DOCSTRINGr  r  r  r  r  r  r,   r3   r1   <module>r+     s  (    : : : : : : : : : : : : : : : :                     ! ! ! ! ! ! . . . . . . . . ) ) ) ) ) )              
 . - - - - -                       - , , , , ,  KJJJJJJ  QXXXXXXXXRRRRRRR@P=-~ 8DDDDDDDDD-7**.0@BVXfg  
 
	H	%	% "&
-1	Q& Q&uU\':D@AQ&#Q& U\*	Q&
 5<Q& Q& Q& Q&jJ J J J J29 J J J*	UU\ 	U# 	U%, 	U 	U 	U 	UTo To To To To| To To TopW9 W9 W9 W9 W9RY W9 W9 W9v]9 ]9 ]9 ]9 ]9> ]9 ]9 ]9BO1 O1 O1 O1 O1 O1 O1 O1f -  HN HN HN HN HNbi HN HN HNXf f f f fry f f f<2 <2 <2 <2 <2") <2 <2 <2~O O O O O O O OdL L L L LRY L L L^ " Y ? ? ? ? ?? ? ?	 ?.E N )CMcdd  Y 
J J J J J% J J 
J\F F F F F+_ F F FR    V
 V
 V
 V
 V
%9 V
 V
!  V
 V
 V
r3   