
    g:                    P   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
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 dd
lmZ ddlmZ ddlmZmZmZ ddlm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z-  e+            rddl.m/Z/m0Z0 ddl1m2Z2 nd\  Z2Z0Z/ e*            r	ddl3m4Z4m5Z5 nd\  Z5Z4 e6e2e0e4e5e/f          Z7 e'j8        e9          Z:dZ; G d dej<                  Z= e"j>        e=           de	j?        de@de	j?        fdZA G d d e          ZB G d! d"ej<                  ZC G d# d$eC          ZD G d% d&eC          ZEeCeDeEd'ZF G d( d)ej<                  ZG G d* d+ej<                  ZH G d, d-ej<                  ZI G d. d/ej<                  ZJ G d0 d1ej<                  ZKd2ZL e$d3eL           G d4 d5e                       ZMd6ZN e$d3eL           G d7 d8eM                      ZO G d9 d:eMe          ZP e$d;eL           G d< d=eM                      ZQdS )>zPyTorch Zamba model.    N)AnyDictListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)_flash_attention_forward)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)PreTrainedModel)ALL_LAYERNORM_LAYERS)add_start_docstrings%add_start_docstrings_to_model_forward#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings)is_causal_conv1d_availableis_mamba_ssm_available   )ZambaConfig)mamba_inner_fnselective_scan_fn)selective_state_update)NNN)causal_conv1d_fncausal_conv1d_updateNNr!   c                   ,     e Zd Zd fd	Zd Zd Z xZS )ZambaRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z;
        ZambaRMSNorm is equivalent to T5LayerNorm
        N)super__init__r	   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      d/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/zamba/modeling_zamba.pyr-   zZambaRMSNorm.__init__Q   sD     	l5:k#:#:;; #    c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )N   T)keepdim)	dtypetor/   float32powmeanrsqrtr2   r1   )r3   hidden_statesinput_dtypevariances       r7   forwardzZambaRMSNorm.forwardY   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r8   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler1   shaper2   r3   s    r7   
extra_reprzZambaRMSNorm.extra_repr`   s&    )**II$2GIIIr8   )r*   )__name__
__module____qualname__r-   rF   rK   __classcell__r6   s   @r7   r)   r)   P   sb        $ $ $ $ $ $; ; ;J J J J J J Jr8   r)   rC   n_repreturnc                     | 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)rI   expandreshape)rC   rQ   batchnum_key_value_headsslenhead_dims         r7   	repeat_kvrZ   h   s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr8   c                   h   e Zd ZdZej        d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d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           
         || _         |j        | _        d| _        |j        |j        z  }|j        }|j        }|j        | _        g | _        g | _	        g | _
        i | _        i | _        i | _        t          |j                  D ]}| xj        t!          j        |||          gz  c_        | j        || j        z  |f}	| xj	        t!          j        |	|          gz  c_	        | j        |         dk    r| j
                            |           fdt          |j                  D             | _        fdt          |j                  D             | _        d S )NFdevicer=   hybridc                 D    g | ]}t          j        g gz             S r_   r/   tensor.0_
batch_sizer_   s     r7   
<listcomp>z=HybridMambaAttentionDynamicCache.__init__.<locals>.<listcomp>   s/    rrrQ%,tj'8HHHrrrr8   c                 D    g | ]}t          j        g gz             S rb   rd   rf   s     r7   rj   z=HybridMambaAttentionDynamicCache.__init__.<locals>.<listcomp>   s/    tttqEL"
):6JJJtttr8   )r=   layers_block_typehas_previous_statemamba_expandr4   mamba_d_statemamba_d_convn_mamba_headsconv_states
ssm_statestransformer_layers_modules_parameters_buffersrangenum_hidden_layersr/   zerosappend	key_cachevalue_cache)
r3   configri   r=   r_   intermediate_sizessm_state_sizeconv_kernel_sizeicache_shapes
     ` `     r7   r-   z)HybridMambaAttentionDynamicCache.__init__   s   
!'!9"'"/&2DD-!.#1"$v/00 	2 	2AJ(9;KTZbghhh!  &t'9;LPTPb;bdrsKOOKe T T TUUOO%a(H44'..q111rrrrrRWX^XpRqRqrrrtttttTYZ`ZrTsTstttr8   
key_statesvalue_states	layer_idxcache_kwargsrR   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 )Nr;   r   r:   dim)r|   rI   r}   r/   cat)r3   r   r   r   r   s        r7   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Er8   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)	rx   lenr|   r_   index_selectr>   r}   rr   rs   )r3   r   r   r_   s       r7   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r8   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   )rt   r   r|   rI   )r3   r   s     r7   get_seq_lengthz/HybridMambaAttentionDynamicCache.get_seq_length   sS     3<4CZ2Z2ZD+A..`i	t~)++1~i(.r22r8   c                      t          d          NzIHybridMambaAttentionDynamicCache does not have a legacy cache equivalent.NotImplementedErrorrJ   s    r7   to_legacy_cachez0HybridMambaAttentionDynamicCache.to_legacy_cache   s    !"mnnnr8   past_key_valuesr   c                      t          d          r   r   )clsr   s     r7   from_legacy_cachez2HybridMambaAttentionDynamicCache.from_legacy_cache   s     ""mnnnr8   N)r   )rL   rM   rN   __doc__r/   float16r-   Tensorintr   r   strr   r   r   
LongTensorr   r   r   classmethodFloatTensorr    r8   r7   r\   r\   t   s         27t 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r8   r\   c                        e Zd ZdZddedee         f fdZ	 	 	 	 	 	 ddej	        de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 )ZambaAttentiona9  
    Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
    and "Generating Long Sequences with Sparse Transformers".

    Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
    The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
    The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
    (see fig. 2 in https://arxiv.org/pdf/2405.16712).
    Additionally, replaced
    attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
    attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
    Nr~   r   c                 "   t                                                       || _        || _        |j        | _        |j        | _        |j        | _        |j        | _	        |j
        | _
        | j        | j
        z  | _        |j        | _        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 )NTz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).Fbias)r,   r-   r~   r   r4   attention_hidden_sizenum_attention_heads	num_headsattention_head_dimrY   rW   num_key_value_groupsmax_position_embeddings	is_causalattention_dropout
ValueErrorr	   Linearq_projk_projv_projo_projr3   r~   r   r6   s      r7   r-   zZambaAttention.__init__   s}   "!-%+%A"31#)#= $(Nd6N$N!'-'E$!'!9MDN*t/III8RVRb 8 8%)^8 8 8   i :DNT]<Zafgggi :D<TW[Wd<dkpqqqi :D<TW[Wd<dkpqqqi >@PW\]]]r8   FrC   attention_maskposition_idspast_key_valueoutput_attentions	use_cachecache_positionrR   c	                    |                                 \  }
}}|                     |          }|                     |          }|                     |          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }||	                    |||          \  }}t          || j                  }t          || j                  }t          j        ||                    dd                    t          j        | j        dz            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    r5t5          d|
| j        || j        f d	|                                            |                    dd                                          }|                    |
|| j                  }|}|                     |          }|}|sd }|||fS )
Nr    r:   r   r   r;   )r   r=   )ptrainingz `attn_output` should be of size z	, but is )sizer   r   r   viewr   rY   	transposerW   r   rZ   r   r/   matmulmathsqrtrI   r	   
functionalsoftmaxr?   r>   r=   dropoutr   r   r   
contiguousrU   r   r   )r3   rC   r   r   r   r   r   r   r   kwargsbszq_lenrh   query_statesr   r   attn_weightscausal_maskattn_outputs                      r7   rF   zZambaAttention.forward   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`'a'a$J z4+DEE
 t/HII|L*2F2Fq!2L2LMMPTPYZ^ZgjkZkPlPll%(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<<>>!))#ud6PQQ!kk+..!  	 LL.88r8   r   NNNFFN)rL   rM   rN   r   r!   r   r   r-   r/   r   r   r\   boolr   rF   rO   rP   s   @r7   r   r      s,        ^ ^{ ^x} ^ ^ ^ ^ ^ ^: 2637EI"'5989 89|89 89 !.	89
 u/089 !!AB89  89 89 !!1289 
u|Xel3XeEL>Q5RR	S89 89 89 89 89 89 89 89r8   r   c                        e Zd ZdZ fdZ	 	 	 	 	 	 ddej        de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 )ZambaFlashAttention2aF  
    Zamba flash attention module. This module inherits from `ZambaAttention` 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   )r,   r-   r   _flash_attn_uses_top_left_mask)r3   argsr   r6   s      r7   r-   zZambaFlashAttention2.__init__<  s9    $)&)))
 3V2W2W.W+++r8   NFrC   r   r   r   r   r   r   r   c	           	         |                                 \  }
}}|                     |          }|                     |          }|                     |          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }|                    |
|| j        | j                                      dd          }||	                    |||          \  }}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        }t.                              d| d           |                    |          }|                    |          }|                    |          }|                    dd          }|                    dd          }|                    dd          }dt5          j        | j        dz            z  }t9          |||||||          }|                    |
|| 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 .)r   softmax_scale)!r   r   r   r   r   r   rY   r   rW   r   rZ   r   r   r   r=   r/   r?   is_autocast_enabledget_autocast_gpu_dtypehasattrr~   r   r1   loggerwarning_oncer>   r   r   r   rU   r   r   r   )r3   rC   r   r   r   r   r   r   r   r   r   r   rh   r   r   r   dropout_raterD   target_dtyper   r   r   s                         r7   rF   zZambaFlashAttention2.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`'a'a$J z4+DEE
 t/HII"&-KssT5K
 #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L $--a33))!Q//
#--a33DIdma&7888. '
 
 
 "))#ud6PQQ\\^^kk+..  	 LL.88r8   r   )rL   rM   rN   r   r-   r/   r   r   r   r   r\   r   rF   rO   rP   s   @r7   r   r   4  s         X X X X X 2637EI"'59N9 N9|N9 N9 !.	N9
 u/0N9 !!ABN9  N9 N9 !!12N9 N9 N9 N9 N9 N9 N9 N9r8   r   c                       e Zd ZdZ	 	 	 	 	 	 ddej        de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 )ZambaSdpaAttentionz
    Zamba attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `ZambaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFrC   r   r   r   r   r   r   r   rR   c	           	      t   |rAt                               d           t                                          ||||||          S |                                \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j	        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }||                    |||          \  }}t          || j                  }t          || j                  }|}||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }dt)          j        | j
        dz            z  }t,          j        j                            ||||| j        r| j        nd| j        o	|d u o|
dk    |          }|                    dd                                          }|                    |	|
| j                  }|                     |          }|d |fS )	Na  ZambaModel is using ZambaSdpaAttention, 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.)rC   r   r   r   r   r   r    r:   r   cudar   )	attn_mask	dropout_pr   scale)r   r   r,   rF   r   r   r   r   r   r   rY   r   rW   r   rZ   r   rI   r_   typer   r   r   r/   r	   r   scaled_dot_product_attentionr   r   r   r   r   )r3   rC   r   r   r   r   r   r   r   r   r   rh   r   r   r   r   r   r   r6   s                     r7   rF   zZambaSdpaAttention.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`'a'a$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DIdma&7888h)FF!04Fd,,3nM4)?MEAI G 	
 	
 "++Aq11<<>>!&&sE43MNNkk+..D.00r8   r   )rL   rM   rN   r   r/   r   r   r   r   r\   r   r   rF   rO   rP   s   @r7   r   r     s         2637EI"'59G1 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1r8   r   )eagerflash_attention_2sdpac                   b     e Zd ZdZdef fdZ	 d
dej        defdZ	d
defdZ
d
defd	Z xZS )ZambaMambaMixeruE  
    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)

    This module differs from `transformers.models.mamba.modeling_mamba.MambaMixer` in two ways:
    - Added multi-head: the output of `self.in_proj` is split into `self.n_mamba_heads` heads, and each head
    undergoes an independent forward pass, identical to the original `MambaMixer`, up until the pre-activations of
    `self.out_proj`. The pre-activations, coming from different mamba heads, are then concatenated and fed into `self.out_proj`.
    r~   c           	         t                                                       || _        || _        |j        | _        |j        | _        |j        | _        |j	        |j        z  | _
        |j        | _        |j        | _        | j
        | j        z  | _        |j        | _        |j        | _        t'          j        | j
        | j
        | j        | j        | j
        | j        dz
            | _        |j        | _        t0          |j                 | _        |j        | _        t'          j        | j        | j
        dz  | j                  | _        t'          j        t?          j         | j        | j        | j        dz  z   | j                            | _!        t'          j        t?          j         | j        | j        | j                  dz
  dz  | j        dz  z            | _"        t'          j        t?          j         | j        | j                            | _#        t?          j$        d| j        dz   t>          j%                  d d d f         }|&                    | j
        d          '                                }t'          j        t?          j(        |          )                    | j        | j        d                    | _*        t'          j        t?          j+        | j        | j                            | _,        t'          j        | j
        | j        | j                  | _-        t\          st^          0                    d           d S d S )	Nr    )in_channelsout_channelsr   kernel_sizegroupspaddingr:   r   g      ?)r=   r;   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)1r,   r-   r~   r   r4   ro   r   rp   r   rn   r   mamba_dt_ranktime_step_rankrq   mamba_head_dimmamba_conv_biasuse_conv_biasmamba_proj_biasuse_biasr	   Conv1dconv1dhidden_mamba_act
activationr   actuse_mamba_kernelsuse_fast_kernelsr   in_projr.   r/   rz   x_proj_weightdt_proj_weightdt_proj_biasaranger?   rT   r   logrU   A_logr0   Dout_projis_fast_path_availabler   r   )r3   r~   r   Ar6   s       r7   r-   zZambaMambaMixer.__init__  s   "!-$2 & 3!'!4v7I!I$2#1"48JJ#3.i./#-))A-
 
 
 !1&12 & 8 y!143IA3MTXTabbb  \&'$*=*AA' 
 
 !l[+T-@$BUVVY\\!3&'
 

 LT5GI\)])]^^ LD/!35=III$PQPQPQ'RHHT+R00;;==\%)A,,"6"6t7I4K^`b"c"cdd
ej);T=PQQRR	$"8$:JQUQ^___% 	^    	 	r8   NrC   cache_paramsc                    |j         \  }}}|d uo|j        o|dk    }|                     |                              dd          }|                    |dd|                              dd          \  }}	|                    d                                          }|	                    d          }	|	                    || j	        d|                              dd          }	| j
        j                            | j
        j                            d          | j
        j                            d                    }
|r[t          |                    d          |j        | j                 |
| j
        j        | j                  }|                    d          }n|0t'          j        |dk              s||                    d          z  }|Zt*          j                            || j        |j         d         z
  df          }|j        | j                                     |           t5          ||
| j
        j        | j                  }|0t'          j        |dk              s||                    d          z  }|                    d| j	        | j        |                              dd          }| j        d d d d d d d f         |z                      dd          }t'          j        || j        | j        | j        gd          \  }}}| j         d d d f         |                    dd          z  }t'          j!        | j"        #                                           }| j$        | j$        #                                nd }t'          j%        |d|f|j&        |j'                  }|rtQ          | j	                  D ]}tS          |j*        | j                 d d |f         ||d	df         ||d	df         ||         ||d d df         ||d d df         | j+        |         |	|d	df         ||         d

  
                            d          }t'          j,        ||fd          }nOt'          j%        |d| j        | j        f|j&        |j'                  }tQ          | j	                  D ]}t[          ||         ||         ||         ||                             dd          ||                             dd          | j+        |         #                                |	|         ||         d
d

  
        \  }}t'          j,        ||fd                                          }t'          j,        ||                    d          fd          }|'|%|j*        | j                                     |           | .                    |                    dd                    }|S )Nr    r:   r;   r   r   )r  r   r^   .T)dt_softplus)delta_softplusreturn_last_state)/rI   rm   r  r   r   chunksqueezer   rU   rq   r  r1   r   r&   rr   r   r   r  	unsqueezer/   allr	   r   padr   copy_r%   r   r  splitr   r   r  expr  floatr  emptyr_   r=   rx   r$   rs   r  r   r#   r  )r3   rC   r  r   ri   seq_lenrh   use_precomputed_statesprojected_statesgateconv_weightsrr   ssm_parameters	time_stepBCdiscrete_time_stepr  time_proj_biasscan_outputsnscan_outputs_	ssm_state
ssm_state_contextualized_statess                            r7   cuda_kernels_forwardz$ZambaMambaMixer.cuda_kernels_forward;  s    "/!4
GQ!-T!9!nl>]!nbimnbn  <<66@@AFF.33JAwOOUUVW]^U__t%--a00;;==||A||J(:BHHRRSTVWXX {)..t{/A/F/Fq/I/I4;K]KbKbcdKeKeff! 	L0%%b))(8  M *33B77MM)%)Na<O2P2P) -0H0H0K0K K' m//@UXeXklnXo@oqr?stt(8>>{KKK,]L$+JZgkgvwwwM)%)Na<O2P2P) -0H0H0K0K K
 &--b$2DdFY[bccmmnoqrss,QQQaaa];mKVVWY[]^^+T0$2EtGZ[ac
 
 
	1a "0D9I<O<OPRTV<W<WWYtz''))*** 7;6G6S*00222Y]{J7#;MDX`m`sttt! &	I4-.. O O 6 +DN;AAAqDA!!S!),&q#qy1aDaAgJaAgJF1ICO"1% $! ! ! )B--   %y,)FANNNO  Q 3T5HI$+#)  I
 4-.. S S,=!!$&q)aDaDNN1a((aDNN1a((F1IOO%%G"1%#'&*- - -)z  %y,)FANNNYY[[!Iy*2F2Fq2I2I&JPQRRR		$)A'7==iHHH !%l.D.DQ.J.J K K$$r8   c           
      *   |j         \  }}}|j        }|                     |                              dd          }|                    |dd|                              dd          \  }	}
|	                    d                                          }	|
                    d          }
|
                    || j	        d|                              dd          }
t          |t                    }|r|j        | j                 j         d         |k    re| 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          }	n|Ht)          j        |dk              s0|	|d d |	j         d          d f                             d          z  }	t<          j                             |	| j!        |	j         d         z
  df          }||j        | j        <   |                     |                     |	          dd |f                   }	|Ht)          j        |dk              s0|	|d d |	j         d          d f                             d          z  }	nt)          j"        || j	        | j#        | j$        f|	j        |          }|0t)          j        |dk              s|	|                    d          z  }	|                     |                     |	          dd |f                   }	|0t)          j        |dk              s|	|                    d          z  }	|	                    d| j	        | j#        |                              dd          }	| j%        d d d d d d d f         |	z                      dd	          }t)          j&        || j'        | j$        | j$        gd          \  }}}| j(        d d d f         |                    dd	          z  | j)        d d d d d d f         z   }t<          j        *                    |          }t)          j+        | j,        -                                           }t)          j+        |d d d d d d d d f         |d d d d d d d d d f         z            }|d d d d d d d d d f         |d d d d d d d d d f         -                                z  }||	d d d d d d d d d f         -                                z  }g }t]          |          D ]}|d d d d d d |d d f                             dd          |z  |d d d d d d |d d f                             dd          z   }t)          j/        |                    dd                              |          |d d d d |d d f                             d                    }|0                    |d d d d d d df                    t)          j1        |d          }||	| j2        d d d d d d f         z  z   }||                     |
          z  }|r||j        | j        <   | 3                    |                    dd                              |d|                              dd                    }|S )
Nr    r:   r;   r   r   )shiftsdims.r^   r   )4rI   r=   r  r   r   r  r  r   rU   rq   
isinstancer\   rs   r   r   cloner>   r_   rm   rr   r/   rollsumr  r1   r  r   r  r  r  r	   r   r  r   rz   r   r   r  r!  r   r  r  softplusr"  r  r#  rx   r   r{   stackr  r  )r3   input_statesr  r   ri   r%  rh   r=   r'  rC   r(  r   r3  
conv_stater*  r+  r,  r-  r.  r  
discrete_A
discrete_BdeltaB_ur0  r   scan_outputr5  s                              r7   slow_forwardzZambaMambaMixer.slow_forward  s"   !-!3
GQ"<<55??1EE.33JAwOOUUVW]^U__t%--a00;;==||A||J(:BHHRRSTVWXX|-MNN	 (	L0@FqIZWW} D(3DNCIIKK		(3DNC	!]%9::I /oqLL ,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!-eiRS@S6T6T-$1N111}GZ[]G^F^F`F`C`4a4k4klm4n4n$nM]..}t?TWdWjkmWn?npq>rss
;E(8 $])C)CC'M)R S S!-eiRS@S6T6T-$1N111}GZ[]G^F^F`F`C`4a4k4klm4n4n$nMT/1DdFYZ$+  I
 )%)Na<O2P2P) -0H0H0K0K K HHT[[%?%?XgX%NOOM)%)Na<O2P2P) -0H0H0K0K K &--b$2DdFY[bccmmnoqrss,QQQaaa];mKVVWY[]^^+T0$2EtGZ[ac
 
 
	1a #1!!!T':Y=P=PQSUW=X=XX\`\mAAtQQQ]
 
  ]334FGG Ytz''))***YqD!!!T111!458J111aaaQRQRQRTUTUTUW[K[8\\]]
'111aaaD(89AaaaD!!!QQQ>N<O<U<U<W<WW
aaaAAAqqq$.> ? E E G GGw 	9 	9A"111aaaAqqq=1;;AqAAIMPXYZYZYZ\]\]\]_`_`_`bcefefefYfPgPqPqrsuvPwPwwI,y':':1a'@'@'C'CE'J'JAaaaQRQRQRTUWXWXWXjMLcLcdfLgLghhKAAAqqq!!!QJ 78888k,B777!]TVAAAtQQQ<L5M%MN!DHHTNN2 	@6?L#DN3 !%!!!Q''//
BHHRRSTVWXX!
 !
 %$r8   c                     | j         rAt          rd| j        j        j        vrt          d          |                     |||          S |                     |||          S )Nr   zFast Mamba kernels are not available. Make sure to they are installed and that the mamba module is on a CUDA device. lease run 'pip install causal-conv1d>=1.2.0' and 'pip install mamba-ssm', or set use_mamba_kernels=False in the model's config.)r   )r
  r  r  r_   r   r   r6  rF  )r3   rC   r  r   s       r7   rF   zZambaMambaMixer.forward  sz      	i) V4;M;T;Y-Y-Y i  
 ,,]LYg,hhh  ^ \\\r8   r'   )rL   rM   rN   r   r!   r-   r/   r   r\   r6  rF  rF   rO   rP   s   @r7   r   r     s        
 
={ = = = = = =@ rv_% _%"\_%9Y_% _% _% _%B[% [%7W [% [% [% [%z	] 	]3S 	] 	] 	] 	] 	] 	] 	] 	]r8   r   c                   $     e Zd Z fdZd Z xZS )ZambaMLPc                    t                                                       |j        | _        |j        | _        t	          j        | j        | j        d          | _        t	          j        | j        | j        d          | _        t	          j        | j        | j        d          | _        t          |j
                 | _        d S NFr   )r,   r-   r4   r   r	   r   	gate_projup_proj	down_projr   
hidden_actact_fnr3   r~   r6   s     r7   r-   zZambaMLP.__init__  s    !-!'!94#3T5KRWXXXy!143IPUVVV4#94;KRWXXXV./r8   c                     |                      |                     |                     |                    |                     |          z            S r   )rN  rP  rL  rM  )r3   hidden_states     r7   rF   zZambaMLP.forward  s>    ~~dkk$..*F*FGG$,,WcJdJddeeer8   )rL   rM   rN   r-   rF   rO   rP   s   @r7   rI  rI    sN        0 0 0 0 0f f f f f f fr8   rI  c                   8    e Zd Zddedee         f fdZ	 	 	 	 	 	 ddej        dej        dedeej                 d	eej	                 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 )ZambaAttentionDecoderLayerNr~   r   c                 0   t                                                       t          |j                 ||          | _        t          |          | _        t          |j        |j	                  | _
        t          |j        |j	                  | _        d S )Nr5   )r,   r-   ZAMBA_ATTENTION_CLASSES_attn_implementation	self_attnrI  feed_forwardr)   r   rms_norm_epsinput_layernormr4   pre_ff_layernormr   s      r7   r-   z#ZambaAttentionDecoderLayer.__init__  s    01LMfV_``$V,,+F,HfNabbb ,V-?VEX Y Y Yr8   FrC   original_hidden_statesr   r   r   r   r   r   rR   c
                    t          j        ||gd          }|                     |          } | j        d||||||||	d|
\  }}}|                     |          }|                     |          }|f}|r||fz  }|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
            original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
                This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
                concatenated tensor is then used as input of the pre-attention RMSNorm
                (see fig. 2 in https://arxiv.org/pdf/2405.16712).
            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.
            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.
        r;   r   )rC   r   r   r   r   r   r   r   r   )r/   concatenater]  rZ  r^  r[  )r3   rC   r_  r   r   r   r   r   r   r   r   self_attn_weightspresent_key_valueoutputss                 r7   rF   z"ZambaAttentionDecoderLayer.forward  s    @ )=:P*QWYZZZ,,];;>Ldn 
?
')%)/)
?
 
?
 
?
 
?
;(*; --m<<))-88 " 	,)++G 	,)++Gr8   r   r   )rL   rM   rN   r!   r   r   r-   r/   r   r   r\   r   r   r   rF   rO   rP   s   @r7   rU  rU    s7       Z Z{ Zx} Z Z Z Z Z Z 2637EI,1$)599 9|9 !&9 	9
 !.9 u/09 !!AB9 $D>9 D>9 !!129 
u (51BEDU1U+V"WW	X9 9 9 9 9 9 9 9r8   rU  c                   r    e Zd Zdedef fdZ	 	 	 	 	 	 	 	 	 	 ddej        deej                 dedeej                 d	eej                 d
eej	                 dee
         dee         dee         deej	                 deej                 deej        eeej        ej        f                  f         fdZ xZS )ZambaMambaDecoderLayerr~   r   c                     t                                                       t          ||          | _        t	          |j        |j                  | _        || _        d S )N)r~   r   rW  )	r,   r-   r   mambar)   r4   r\  r]  r   r   s      r7   r-   zZambaMambaDecoderLayer.__init__Z  sS    $FiHHH
+F,>FDWXXX"r8   NFrC   r_  r   r   r   r   r   r   r   transformer_hidden_statesrR   c                     |}|||z   n|}|                      |          }|                     |||          }d}||z   }|f}|r||fz  }|	r||fz  }|S )a  
        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.
            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.
        N)rC   r  r   )r]  rh  )r3   rC   r_  r   r   r   r   r   r   r   r   ri  residualrb  rd  s                  r7   rF   zZambaMambaDecoderLayer.forward`  s    < !
 :S9^M555dq 	 ,,];;

'') # 
 
 ! !=0 " 	,)++G 	)((Gr8   )
NNNNNNFFNN)rL   rM   rN   r!   r   r-   r/   r   r   r   r\   r   r   r   rF   rO   rP   s   @r7   rf  rf  Y  sX       #{ #s # # # # # # :>15.237EI,1$)59<@: :|: !) 6: 	:
 !.: el+: u/0: !!AB: $D>: D>: !!12: $,EL#9: 
u (51BEDU1U+V"WW	X: : : : : : : :r8   rf  c                   d    e Zd Zdedej        def fdZ	 	 	 	 	 	 	 	 	 ddej	        de
ej	                 d	ed
e
ej	                 de
ej	                 de
ej                 de
e         de
e         de
e         de
ej                 deej        e
eej        ej        f                  f         fdZ xZS )HybridLayershared_transflinearrh  c                 r    t                                                       || _        || _        || _        d S r   )r,   r-   rn  ro  mamba_decoder)r3   rn  ro  rh  r6   s       r7   r-   zHybridLayer.__init__  s6    *"r8   NFrC   r_  r   r   r   r   r   r   r   r   rR   c                     |                      ||||||||	|
	  	        }|d         }|r|d         }|                     |          }|                     |||||||	|
          }|r|d         |f|dd         z   }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
            hidden activations to form the input of the shared transformer layer.
            layer_idx (`int`): layer number.
            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.
            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.
        )r_  r   r   r   r   r   r   r   r   r    )ri  r   r   r   r   r   r   r:   N)rn  ro  rq  )r3   rC   r_  r   r   r   r   r   r   r   r   layer_outputsri  rb  s                 r7   rF   zHybridLayer.forward  s    @ **#9&%)/) + 

 

 %2!$4! 	1 -a 0$(KK0I$J$J!**&?)%)/) + 	
 	
  	V*1-/@AMRSRTRTDUUMr8   )	NNNNNNFFN)rL   rM   rN   rU  r	   r   rf  r-   r/   r   r   r   r   r\   r   r   r   rF   rO   rP   s   @r7   rm  rm    sc       #&@ #") #\r # # # # # # :>15.237EI,1$)59A A|A !) 6A 	A
 !.A el+A u/0A !!ABA $D>A D>A !!12A 
u (51BEDU1U+V"WW	XA A A A A A A Ar8   rm  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 ([`ZambaConfig`]):
            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 Zamba 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ee	 	 	 	 dd	eej                 d
eeeeeef         f                  dedef fd                        Z xZS )ZambaPreTrainedModelmodelTrU  rf  r   Fc                    | j         j        }t          |t          j        t          j        f          rJ|j        j                            d|           |j	         |j	        j        
                                 d S d S t          |t          j                  rU|j        j                            d|           |j        +|j        j        |j                 
                                 d S d S t          |t                    rd|j        _        d|j        _        |j        j                            d|           | j         j        dz  }t          j                            |j        | |           | j         j        | j         j        z  | j         j        z  }t3          j        t3          j        | j         j        |          t9          j        | j         j                  t9          j        | j         j                  z
  z  t9          j        | j         j                  z                                  | j         j!                  }|t3          j        t3          j"        |                      z   }t3          j#                    5  |j$        %                    |           d d d            n# 1 swxY w Y   d|j$        _&        d S d S )Nr   )rA   stdTg      )min)'r~   initializer_ranger:  r	   r   r  r1   datanormal_r   zero_	Embeddingpadding_idxr   r  _no_weight_decayr  r  r   inituniform_r  rn   r4   rq   r/   r"  randr   r  time_step_maxtime_step_minclamptime_step_floorexpm1no_gradr  r   
_no_reinit)r3   modulerx  dt_init_stdr   dtinv_dts          r7   _init_weightsz"ZambaPreTrainedModel._init_weights  s   k+fry")455 	2M&&CS&999{& &&((((( '&-- 	2M&&CS&999!-"6#56<<>>>>> .-00 	2,0FL)(,FH% %--3C-@@@+3T9KGV2[L+NNN![58OOSWS^SllN
4;4nEE8DK566$+B[9\9\\^(4;4556  e3e44	  %)U["%5%5$5666F 2 2#))&1112 2 2 2 2 2 2 2 2 2 2 2 2 2 2-1F***'	2 	2s   J((J,/J,Ntorch_dtype
device_maphard_check_onlycheck_device_mapc                 |    t                                          |||||          }|s|j        dk    rd|_        |S )z
        Overloads `PreTrainedModel._check_and_enable_flash_attn_2` so as to DISABLE Flash Attention 2 by default on Zamba models.
        Flash attention 2 is currently not supported in the HuggingFace implementation of Zamba v1.
        )r  r  r   r   )r,   _check_and_enable_flash_attn_2rY  )r   r~   r  r  r  r  r6   s         r7   r  z3ZambaPreTrainedModel._check_and_enable_flash_attn_2'  sT     77K__o 8 
 

  	26#>BU#U#U*1F'r8   )NNFF)rL   rM   rN   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   r   r/   r=   r   r   r   r   r   r  rO   rP   s   @r7   ru  ru    s        
 L&*#57OP"3"N L2 2 2>  .2;? %!&  ek* U3S#X#678	
       [ [    r8   ru  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.
        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.
c                   T    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
j                 deeef         fd            Zd Z xZS )
ZambaModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ZambaDecoderLayer`]

    Args:
        config: ZambaConfig
    r~   c           
        
 t                                          |           |j        | _        |j        | _        t          j        |j        |j        | j                  | _        t          |          }g }g }|j
        | _
        t          |j                  D ]}|j
        |         dk    r%|                    t          ||                     8|j
        |         dk    rb|                    t          j        | j        j        | j        j        d                     |                    t          ||                     t#          |          }t#          |          }g }g | _        t'          | j
                  D ]\  }}|dk    red| d
g d}	g | j        
fd	|	D             | _        |                    t)          |t+          |          t+          |                               p|                    t+          |                     t          j        |          | _        |j        | _        t3          |j        |j        
          | _        d| _        |                                  d S )Nrh  )r   r`   Fr   zlayers.r   )	z%shared_transf.self_attn.q_proj.weightz%shared_transf.self_attn.k_proj.weightz%shared_transf.self_attn.v_proj.weightz%shared_transf.self_attn.o_proj.weightz+shared_transf.feed_forward.gate_proj.weightz)shared_transf.feed_forward.up_proj.weightz+shared_transf.feed_forward.down_proj.weightz$shared_transf.input_layernorm.weightz%shared_transf.pre_ff_layernorm.weightc                     g | ]}|z   S r   r   )rg   keyprefix_names     r7   rj   z'ZambaModel.__init__.<locals>.<listcomp>  s     FnFnFn]`{UXGXFnFnFnr8   rW  )r,   r-   pad_token_idr  
vocab_sizer	   r~  r4   embed_tokensrU  rl   rx   ry   r{   rf  r   r~   iter_tied_weights_keys	enumeraterm  next
ModuleListlayersrY  r)   r\  final_layernormgradient_checkpointing	post_init)r3   r~   blockmamba_layerslinear_layersr   r  layer_id
layer_type	tied_keysr  r6   s             @r7   r-   zZambaModel.__init__  sp      !. +L):F<NPTP`aa*622!'!9v/00 	Q 	QA'*g55##$:6Q$O$O$OPPPP)!,88$$RYt{/FH_fk%l%l%lmmm##$:6Q$O$O$OPPPL))]++"$$-d.D$E$E 	2 	2 HjX%%3333
 
 
	 +pD,C*oFnFnFnFndmFnFnFn*o'k%m1D1Dd<FXFXYYZZZZd<001111mF++$*$?!+F,>FDWXXX&+#r8   c                     | j         S r   r  rJ   s    r7   get_input_embeddingszZambaModel.get_input_embeddings  s      r8   c                     || _         d S r   r  r3   values     r7   set_input_embeddingszZambaModel.set_input_embeddings  s    !r8   N	input_idsr   r   r   inputs_embedsr   r   output_hidden_statesreturn_dictr   rR   c                 >   ||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}|| 
                    |          }|}t          j        |          }|r|t          	                    d           |
&t          j        |j        d         |j                  }
||
                    d          }|                     |||
          }|rdnd }|rdnd }t%          | j                  D ]s\  }}|r||fz  }| j        r,| j        r%|                     |j        ||||||||||
          }n |||||||||||
	
  
        }|d         }|r|d         ||d         fz  }t|                     |          }|r||fz  }|r|j        sd
|_        |sd n|}|	st1          d ||||fD                       S t3          ||||          S )NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either onezX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzZamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was provided, so no cache will be returned.r    rc   r   r   )	r_  r   r   r   r   r   r   r   r   Tc              3      K   | ]}||V  	d S r   r   )rg   vs     r7   	<genexpr>z%ZambaModel.forward.<locals>.<genexpr>1  s(      ttqfgfsfsfsfsfsttr8   )last_hidden_stater   rC   
attentions)r~   r   r  r   use_return_dictr   r  r   r   r   r  r/   r;  r  rI   r_   r  _update_causal_maskr  r  _gradient_checkpointing_func__call__r  rm   rH   r   )r3   r  r   r   r   r  r   r   r  r  r   rC   r_  r   all_hidden_statesall_self_attnsr   layerrs  
next_caches                       r7   rF   zZambaModel.forward  s'    2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	s   & 	4= 	Y 	j   I  --i88M%!&]!;!;  	0:  
 !"\-*=a*@I]^^^N)33A66L..~}n]]"6@BBD0:d )$+ 6 6 $	: $	:Iu# 6!m%55!* t}  $ A AN!*" #%"! ! !&!+A'#1 +!-#2&7'#1! ! ! *!,M  : #/"}Q'7&99N,,];;   	2-!11 	6?#E 	615O.!*?TT
 	utt]J@QSa$btttttt&+&+%	
 
 
 	
r8   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    r;   )
fill_valuer=   r_   )diagonalrc   r   r:   .r   r   )r~   rY  r=   r_   r/   finfory  rI   fulltriur  rU   rT   r;  r   eqmasked_fillr   r   _unmask_unattended)r3   r   input_tensorr   r=   r_   	min_dtypesequence_lengthtarget_lengthr   mask_lengthpadding_masks               r7   r  zZambaModel._update_causal_mask;  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r8   
NNNNNNNNNN)rL   rM   rN   r   r!   r-   r  r  r   ZAMBA_INPUTS_DOCSTRINGr/   r   r   r   r\   r   r   r   r   r   rF   r  rO   rP   s   @r7   r  r    s       
 -{ - - - - - -^! ! !" " " +*+ABB '+1537FJ59$(,0/3&*59q
 q
#q
 !.q
 u/0	q

 ""BCq
   12q
 D>q
 $D>q
 'tnq
 d^q
 !!12q
 
u--	.q
 q
 q
 CBq
h! ! ! ! ! ! !r8   r  c                       e Zd 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j                 dedeeef         fd                        Z	 	 	 	 	 	 ddZ xZS )ZambaForCausalLMr~   c                 &   t                                          |           t          |          | _        dg| j        j        | _        |j        | _        t          j        |j        |j        d          | _	        | 
                                 d S )Nzlm_head.weightFr   )r,   r-   r  rv  r  r  r	   r   r4   lm_headr  rQ  s     r7   r-   zZambaForCausalLM.__init__a  s       ''
#3"Tdj6S"T +y!3V5FUSSS 	r8   c                     | j         j        S r   rv  r  rJ   s    r7   r  z%ZambaForCausalLM.get_input_embeddingsk      z&&r8   c                     || j         _        d S r   r  r  s     r7   r  z%ZambaForCausalLM.set_input_embeddingsn      "'
r8   c                     | j         S r   r  rJ   s    r7   get_output_embeddingsz&ZambaForCausalLM.get_output_embeddingsq  s
    |r8   c                     || _         d S r   r  )r3   new_embeddingss     r7   set_output_embeddingsz&ZambaForCausalLM.set_output_embeddingst  s    %r8   c                     || _         d S r   rv  )r3   decoders     r7   set_decoderzZambaForCausalLM.set_decoderw  s    


r8   c                     | j         S r   r  rJ   s    r7   get_decoderzZambaForCausalLM.get_decoderz  s
    zr8   )output_typer  Nr   r  r   r   r   r  labelsr   r   r  r  r   num_logits_to_keeprR   c                    ||n| j         j        }|	|	n| j         j        }	|
|
n| j         j        }
|                     ||||||||	||

  
        }|d         }|                     |dd| dddf                   }d}| | j        ||| j        fi |}|
s|f|dd         z   }||f|z   n|S t          |||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, ZambaForCausalLM

        >>> model = ZambaForCausalLM.from_pretrained("Zyphra/Zamba-7B-v1")
        >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba-7B-v1")

        >>> 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    losslogitsr   rC   r  )r~   r   r  r  rv  r  loss_functionr  r   r   rC   r  )r3   r  r   r   r   r  r  r   r   r  r  r   r  loss_kwargsrd  rC   r  r  outputs                      r7   rF   zZambaForCausalLM.forward}  sM   b 2C1N--TXT_Tq %9$D  $+Jj 	 &1%<kk$+B] **)%+'/!5)#  
 
  
mAAA0B/B/C/CQQQ,FGHH%4%ffdoUUUUD 	DY,F'+'7D7V##VC%#3!/)
 
 
 	
r8   Tc           	      J   |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=   r_   r;   r  r  )r   r   r   r   r  r   )rI   r\   r~   r=   r_   longcumsummasked_fill_r   r   r  )r3   r  r   r   r  r   r   r   r   empty_past_kvmodel_inputss              r7   prepare_inputs_for_generationz.ZambaForCausalLM.prepare_inputs_for_generation  s    (4/  	 (%aaa.*>q*A)A)C)C&CD		#~';A'>>>%aaa&78	>Y_Q/tz$+  O %,*>)..0077;;a?L%%n&91===  F+AAA	0B/B/D/D,DE $$+];LL')=)=)?)?@L ,#2&"0&*k&D"0 		
 		
 		
 r8   )NNNNNNNNNNNr   )NNNNNT)rL   rM   rN   r!   r-   r  r  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr/   r   r   r   r\   r   r   r   r   r   rF   r  rO   rP   s   @r7   r  r  `  s       {      ' ' '( ( (  & & &     +*+ABB+AP_``` '+1537FJ59-1$(,0/3&*59"#V
 V
#V
 !.V
 u/0	V

 ""BCV
   12V
 )*V
 D>V
 $D>V
 'tnV
 d^V
 !!12V
  V
 
u,,	-V
 V
 V
 a` CBV
v 4 4 4 4 4 4 4 4r8   r  a  
    The Zamba Model with a sequence classification head on top (linear layer).

    [`ZambaForSequenceClassification`] 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 )ZambaForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        | j        j        | _        t          j        |j        | j        d          | _	        | 
                                 d S rK  )r,   r-   
num_labelsr  rv  r  r	   r   r4   scorer  rQ  s     r7   r-   z'ZambaForSequenceClassification.__init__  sv        +''
"&*"?Yv14?OOO
 	r8   c                     | j         j        S r   r  rJ   s    r7   r  z3ZambaForSequenceClassification.get_input_embeddings(  r  r8   c                     || j         _        d S r   r  r  s     r7   r  z3ZambaForSequenceClassification.set_input_embeddings+  r  r8   Nr  r   r   r   r  r  r   r   r  r  rR   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}|t|                    |j                  }| j         j        f| j        dk    rd| j         _        nN| j        dk    r7|j        t          j        k    s|j        t          j	        k    rd	| j         _        nd
| j         _        | j         j        dk    rWt%                      }| j        dk    r1 ||                                |                                          }n |||          }n| j         j        d	k    rGt)                      } ||                    d| j                  |                    d                    }n*| j         j        d
k    rt-                      } |||          }|
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.r;   rc   
regressionsingle_label_classificationmulti_label_classificationr  )r~   r  rv  r  rI   r  r   r/   r  r   argmaxr>   r_   r  problem_typer  r=   r  r   r  r   r   r
   r   r   rC   r  )r3   r  r   r   r   r  r  r   r   r  r  transformer_outputsrC   r  ri   sequence_lengthspooled_logitsr  loss_fctr  s                       r7   rF   z&ZambaForSequenceClassification.forward.  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__`YYv}--F{'/?a''/;DK,,_q((flej.H.HFL\a\eLeLe/LDK,,/KDK,{'<77"99?a''#8M$9$9$;$;V^^=M=MNNDD#8M6::DD)-JJJ+--x 2 22t G GUWYY)-III,..xv66 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r8   r  )rL   rM   rN   r-   r  r  r   r  r   r/   r   r   r   r   r   r   r   r   r   rF   rO   rP   s   @r7   r	  r	    s            ' ' '( ( ( +*+ABB 151537KO59-1$(,0/3&*X
 X
E,-X
 !.X
 u/0	X

 "%tE4E/F(F"GHX
   12X
 )*X
 D>X
 $D>X
 'tnX
 d^X
 
u66	7X
 X
 X
 CBX
 X
 X
 X
 X
r8   r	  )Rr   r   typingr   r   r   r   r   r   r/   torch.utils.checkpointr	   torch.nnr
   r   r   activationsr   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r   utils.import_utilsr   r   configuration_zambar!   &mamba_ssm.ops.selective_scan_interfacer"   r#   +mamba_ssm.ops.triton.selective_state_updater$   causal_conv1dr%   r&   r  r  
get_loggerrL   r   r  Moduler)   r{   r   r   rZ   r\   r   r   r   rX  r   rI  rU  rf  rm  ZAMBA_START_DOCSTRINGru  r  r  r  r	  r   r8   r7   <module>r-     sl  (    : : : : : : : : : : : : : : : :            A A A A A A A A A A ! ! ! ! ! ! . . . . . . . . ) ) ) ) ) )      G F F F F F         
 . - - - - - 1 1 1 1 1 1                     - , , , , ,  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	%	%J J J J J29 J J J(   L ) ) )	UU\ 	U# 	U%, 	U 	U 	U 	UXo Xo Xo Xo Xo| Xo Xo Xov_9 _9 _9 _9 _9RY _9 _9 _9J^9 ^9 ^9 ^9 ^9> ^9 ^9 ^9FN1 N1 N1 N1 N1 N1 N1 N1d -  S] S] S] S] S]bi S] S] S]nf f f f fry f f fB B B B B B B BJA A A A ARY A A AHH H H H H") H H HV " Y @ @ @ @ @? @ @	 @FB J Y S S S S S% S S	 Snk k k k k+_ k k k\   j
 j
 j
 j
 j
%9 j
 j
 j
 j
 j
r8   