
    i                    r   d dl Z d dlmZ d dlmZ d dlmZ d dlZd dlmZ ddl	m
Z ddlmZ dd	lmZmZ dd
lmZ ddl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 m!Z! ddl"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5  e,jl                  e7      Z8 G d dej                  jr                        Z: G d dejr                        Z; G d dejr                        Z<dejz                  d e>d!ejz                  fd"Z?	 dJd#ejr                  d$ejz                  d%ejz                  d&ejz                  d'ejz                  dz  d(e@d)e@fd*ZAd+ ZB ed,      dKd-       ZC G d. d/ejr                        ZDd0ejz                  d1e>fd2ZEd3 ZFd4 ZG G d5 d6ejr                        ZH G d7 d8ejr                        ZI G d9 d:ejr                        ZJ G d; d<e      ZK G d= d>e      ZLe) G d? d@e$             ZMe) G dA dBeM             ZN G dC dDeMe      ZO e)dEF       G dG dHeM             ZPg dIZQy)L    N)Callable)cycle)Optional)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_func_from_hub)lazy_load_kernel)create_causal_mask)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_torchdynamo_compilinglogging)maybe_autocastmerge_with_config_defaults)resolve_internal_import)capture_outputs   )Zamba2Configc                   (     e Zd Zd fd	ZddZ xZS )Zamba2RMSNormGatedc                     t         |           t        j                  t	        j
                  |            | _        || _        || _        y N)	super__init__r   	Parametertorchonesweightvariance_epsilon
group_size)selfhidden_sizer/   eps	__class__s       {/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/transformers/models/zamba2/modeling_zamba2.pyr)   zZamba2RMSNormGated.__init__4   s6    ll5::k#:; #$    c                 b   |j                   }|j                  t        j                        }|?|t        j
                  j                  |j                  t        j                              z  }|j                  ^ }}|| j                  z  } |j                  g ||| j                   }|j                  d      j                  dd      }|t        j                  || j                  z         z  } |j                  g ||| j                  z   }| j                  |j                  |      z  S N   T)keepdim)dtypetor+   float32r   
functionalsilushaper/   viewpowmeanrsqrtr.   r-   )	r0   hidden_statesgateinput_dtypeprefix_dimslast_dimgroup_counthidden_states_groupvariances	            r4   forwardzZamba2RMSNormGated.forward:   s   #))%((7)BMM,>,>twwu}}?U,VVM!.!4!4h$//10m00\+\{\DOO\&**1-222t2D1EKK4K`K`@`4aa0+00]+]{T__?\]{{]--k:::r5   gư>r'   )__name__
__module____qualname__r)   rM   __classcell__r3   s   @r4   r%   r%   3   s    %;r5   r%   c                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	Zamba2RMSNormr2   returnNc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z<
        Zamba2RMSNorm is equivalent to T5LayerNorm
        N)r(   r)   r   r*   r+   r,   r-   r.   )r0   r1   r2   r3   s      r4   r)   zZamba2RMSNorm.__init__I   s1     	ll5::k#:; #r5   rE   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S r7   )	r;   r<   r+   r=   rB   rC   rD   r.   r-   )r0   rE   rG   rL   s       r4   rM   zZamba2RMSNorm.forwardQ   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r5   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler-   r@   r.   )r0   s    r4   
extra_reprzZamba2RMSNorm.extra_reprX   s*    ))*+6$2G2G1HIIr5   rN   )
rO   rP   rQ   floatr)   r+   TensorrM   r[   rR   rS   s   @r4   rU   rU   H   s7    $ $$ $;U\\ ;ell ;Jr5   rU   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )Zamba2RotaryEmbeddinginv_freqNconfigc                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultr`   F)
persistentoriginal_inv_freq)r(   r)   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenra   rope_parametersrc   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r0   ra   devicerope_init_fnr`   r3   s        r4   r)   zZamba2RotaryEmbedding.__init___   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr5   ro   ztorch.deviceseq_lenrV   ztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}d|t	        j
                  d|dt        j                        j                  |t        j                        |z  z  z  }||fS )	a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetahead_dimNg      ?r   r8   r;   ro   r;   )	rj   getattrr1   num_attention_headsr+   arangeint64r<   r\   )ra   ro   rq   basedimattention_factorr`   s          r4   rk   z5Zamba2RotaryEmbedding.compute_default_rope_parameterso   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r5   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r9   r"   mpscpuF)device_typeenabledr8   r|   ru   )r`   r\   expandr@   r<   ro   
isinstancetypestrr   	transposer+   catcosrl   sinr;   )
r0   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r4   rM   zZamba2RotaryEmbedding.forward   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$r'   NNN)rO   rP   rQ   r+   r]   __annotations__r#   r)   staticmethodr   intrZ   r\   rk   no_gradr   rM   rR   rS   s   @r4   r_   r_   \   s    llV| V  &*+/"*t#*(* t* 
~u$	%	* *: U]]_<  <r5   r_   rE   n_reprV   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r"   N)r@   r   reshape)rE   r   batchnum_key_value_headsslenrt   s         r4   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr5   modulequerykeyvalueattention_maskscalingdropoutc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr8   r   r9   )r|   r;   )ptrainingr"   )r   num_key_value_groupsr+   matmulr   r   r>   softmaxr=   r<   r;   r   r   
contiguous)r   r   r   r   r   r   r   kwargs
key_statesvalue_statesattn_weightsattn_outputs               r4   eager_attention_forwardr      s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r5   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr9   r8   r   )r@   r+   r   )r   x1x2s      r4   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r5   rotary_pos_embc                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer   )qkr   r   unsqueeze_dimq_embedk_embeds          r4   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr5   c                   F    e Zd ZdZ	 	 	 ddededz  dedz  dedz  f fdZ	 	 	 ddej                  ded	ej                  dz  d
e	dz  de
ej                  ej                  f   dz  dee   de
ej                  ej                  dz  e
ej                     dz  f   fdZ xZS )Zamba2AttentionaZ  
    Multi-headed attention from 'Attention Is All You Need' paper.

    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://huggingface.co/papers/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)
    Finally, this attention layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this
    layer is tied, un-tied adapters (formally the same as LoRA but used in the base model) modules are added to the q, k, v projectors to increase
    expressivity with a small memory overhead (see Fig. 2 of https://huggingface.co/papers/2411.15242).
    Nra   	layer_idxnum_fwd_mem_blocksblock_idc           	         t         |           || _        || _        |j                  | _        |j
                  | _        |j                  |j                  z  | _	        |j                  | _
        | j                  dz  dz  | _        d| _        |j                  | _        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      | _        || _        |j,                  | _        || _        |j2                  rt        j4                  g       | _        t        j4                  g       | _        t        j4                  g       | _        t=        | j*                        D ]  }||j>                  z  |k(  r{t        j@                  t        j                  | j                  | j                  jB                  d      t        j                  | j                  jB                  | j                  d            }t        j@                  t        j                  | j                  | j                  jB                  d      t        j                  | j                  jB                  | j                  d            }t        j@                  t        j                  | j                  | j                  jB                  d      t        j                  | j                  jB                  | j                  d            }n<t        jD                         }t        jD                         }t        jD                         }| j6                  jG                  |       | j8                  jG                  |       | j:                  jG                  |       ! tI        | j.                        D 	
ci c]  \  }	}
|
|	
 c}
}	| _%        y c c}
}	w )Nr8   g      TFbias)&r(   r)   ra   r   attention_hidden_sizeattention_head_dimrt   rx   r   r   rg   r   	is_causalattention_dropoutr   Linearq_projk_projv_projr1   o_projr   hybrid_layer_idslayer_block_mapr   use_shared_attention_adapter
ModuleListlinear_q_adapter_listlinear_k_adapter_listlinear_v_adapter_listrangenum_mem_blocks
Sequentialadapter_rankIdentityappend	enumerate	layer_dic)r0   ra   r   r   r   ilinear_q_adapterlinear_k_adapterlinear_v_adapterindexr   r3   s              r4   r)   zZamba2Attention.__init__   sJ    	"%+%A%A"11$*$>$>&B\B\$\!'-'E'E$)d2!'!9!9ii < <f>X>X[_[h[h>hotuii < <f>X>X[_[h[h>hotuii < <f>X>X[_[h[h>hotuii : :T]] JFL^L^ejk"4%66 ..)+r):D&)+r):D&)+r):D&4223 Dv,,,8')}}		$"<"<dkk>V>V]bc		$++":":D<V<V]bc($ (*}}		$"<"<dkk>V>V]bc		$++":":D<V<V]bc($ (*}}		$"<"<dkk>V>V]bc		$++":":D<V<V]bc($
 (*{{}$'){{}$'){{}$**112BC**112BC**112BC)D, <ETEYEY;Z[<5%%,[[s   Q6rE   r   past_key_valuesposition_embeddingsr   rV   c                    |j                   d d }g |d| j                  }| j                  |      }	| j                  |      }
| j	                  |      }| j
                  j                  rW| j                  |   }|	 | j                  |   |      z   }	|
 | j                  |   |      z   }
| | j                  |   |      z   }|	j                  |      j                  dd      }	|
j                  |      j                  dd      }
|j                  |      j                  dd      }| j
                  j                  r|\  }}t        |	|
||      \  }	}
||j                  |
||      \  }
}t!        j"                  | j
                  j$                  t&              } || |	|
||f| j(                  sdn| j*                  | j,                  d|\  }} |j.                  g |d j1                         }| j3                  |      }||fS )Nr9   r"   r8           )r   r   )r@   rt   r   r   r   ra   r   r   r   r   r   rA   r   use_mem_roper   updater   get_interface_attn_implementationr   r   r   r   r   r   r   )r0   rE   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   adapter_layer_idxr   r   attention_interfacer   r   s                     r4   rM   zZamba2Attention.forward+  s    $))#2.88b8$--8{{=1[[/
{{=1;;33 $y 9'*W$*D*DEV*WXe*ffL#&Sd&@&@AR&STa&bbJ'*W$*D*DEV*WXe*ffL#((6@@AF__\2<<QB
#((6@@AF;;##*HC';L*VY[^'_$L*&'6'='=j,Xa'b$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r5   r   )rO   rP   rQ   __doc__r#   r   r)   r+   r]   r
   rZ   r   r   rM   rR   rS   s   @r4   r   r      s    $ !%)-#6\6\ :6\  $J	6\
 *6\x /3(,HL1)||1) 1) t+	1)
 1) #5<<#=>E1) +,1) 
u||U\\D0%2E2LL	M1)r5   r   input_tensorpad_sizec                     t        | j                        dk(  r
ddddd|ddfnddd|ddf}t        j                  j                  j                  | |dd      S )z
    Padding x tensor with `pad_size` on the seq_len dim (dim=1)

    Assumes that we only have tensors of either size 4 or 3
       r   constant)moder   )lenr@   r+   r   r>   pad)r   r   	pad_shapes      r4   pad_tensor_by_sizer   b  sf     47|7I7I3Ja3OAq!Q!Q/VWYZ\]_gijlmUnI88""<ST"UUr5   c                    t        | |      } t        | j                        dk(  r.| j                  | j                  d   d|| j                  d         S | j                  | j                  d   d|| j                  d   | j                  d         S )z
    Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
    simultaneously splitting it into chunk sequences.

    Assumes that we only have tensors of either size 4 or 3
    r   r   r9   r8   )r   r   r@   r   )r   r   
chunk_sizes      r4   reshape_into_chunksr   m  s     &lH=L
<!###L$6$6q$92z<K]K]^_K`aa ##q!2z<3E3Ea3H,J\J\]^J_
 	
r5   c                 "   | j                  d      } | d   j                  g | j                         | } t        j                  t        j                  ||| j
                  t        j                        d      }| j                  | d      } t        j                  | d      }t        j                  t        j                  ||| j
                  t        j                        d      }|j                  | t        j                         }|S )zo
    More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
    r9   .Nrv   )diagonalr   r   )
sizer   r+   trilr,   ro   boolmasked_fillcumsuminf)r   r   masktensor_segsums       r4   segment_sumr    s     ""2&J 2<	*11S<3D3D3FS
SL::ejjZ@S@S[`[e[efqstD++TE15LLL26M ::ejjZ@S@S[`[e[efqrsD!--teeiiZ@Mr5   c                        e Zd ZdZddededz  f fdZ	 	 ddej                  de	dz  dej                  dz  fd	Z
dde	dz  dej                  dz  fd
Z	 	 dde	dz  dej                  dz  fdZ xZS )Zamba2MambaMixeru  
    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)
    Nra   r   c           	         t         |           || _        |j                  | _        |j                  | _        |j                  | _        t        |j                  | j                  z        | _
        || _        |j                  | _        d| _        t        j                         | _        |j"                  | _        |j$                  | _        |j(                  | _        | j                  j,                  | _        |j0                  | _        |j2                  | _        |j4                  | _        |j6                  | _        | j                  d| j&                  z  | j
                  z  z   | _        t        j:                  | j8                  | j8                  d|j                  | j8                  |j                  dz
        | _        | j                  | j8                  z   | j.                  z   }t        j>                  | j                  ||j@                        | _!        t        jD                  tG        jH                  | j.                              | _%        tG        jL                  d| j.                  dz         }t        jD                  tG        jN                  |            | _(        tS        | j                  | j                  | j&                  z  d      | _*        t        jD                  tG        jH                  | j.                              | _+        t        j>                  | j                  | j                  |j@                        | _,        t[        d	      }t]        |d
d       a/t]        |dd       a0t[        d      }tc        |d      a2tc        |d      a3tc        |d      a4tk        td        tf        th        t`        t^        f      a6tl        stn        jq                  d       y y )Nr?   r8   Tr"   )in_channelsout_channelsr   kernel_sizegroupspaddingr   gh㈵>)r/   r2   zcausal-conv1dcausal_conv1d_updatecausal_conv1d_fnz	mamba-ssmz8ops.triton.selective_state_update.selective_state_update)chained_pathz1ops.triton.ssd_combined.mamba_chunk_scan_combinedz8ops.triton.ssd_combined.mamba_split_conv1d_scan_combineda  The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)` is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and https://github.com/Dao-AILab/causal-conv1d)9r(   r)   ra   r1   mamba_d_statessm_state_sizemamba_d_convconv_kernel_sizer   mamba_expandintermediate_sizer   use_conv_bias
activationr   SiLUactuse_mem_eff_pathmamba_ngroupsn_groupsmamba_headdimrt   n_mamba_heads	num_headsr   time_step_limittime_step_mintime_step_maxconv_dimConv1dconv1dr   add_bias_linearin_projr*   r+   r,   dt_biasry   logA_logr%   normDout_projr   rw   r  r  r    selective_state_updatemamba_chunk_scan_combined mamba_split_conv1d_scan_combinedallis_fast_path_availableloggerwarning_once)r0   ra   r   projection_sizeAcausal_conv1d	mamba_ssmr3   s          r4   r)   zZamba2MambaMixer.__init__  s   !--$22 & 3 3!$V%8%84;K;K%K!L"#11 779 & 7 7,,,,22 ++%55#11#11..T]]1BTEXEX1XXii++==''!+
 004==@4>>Qyy''
 ||EJJt~~$>? LLDNNQ./\\%))A,/
&""t/E/E/V\`
	 ejj89		$"8"8$:J:JQWQgQgh )9&}6LdS"=2DdK %[1	!8$^"
 %<$W%
! ,C$^,
(
 "%&)0 $"
 &> &r5   rE   cache_paramsr   c                    |j                   \  }}}| j                  | j                  z  }d| j                  z  d| j                  z  | j                  z  z   | j                  z   }|W|j                  | j                        r;| j                  |j                  d            }	|	j                   d   |z
  dz  }
|
|
| j                  | j                  | j                  g}t        j                  |	|d      \  }}}}}t        ||j                  | j                     j                  | j                  j                   j                  d      | j                  j"                  | j$                        }t        j                  || j                  ||gd      \  }}}t        j&                  | j(                  j+                                }|d d d df   d d d d d f   j-                  d| j.                  | j                        j1                  t        j2                        }|d d d d d f   j-                  dd| j.                        }| j4                  d d d df   j-                  d| j.                        }| j6                  d d d df   j-                  d| j.                        }|j9                  || j                  |j                   d   | j                  z        }|j9                  || j                  |j                   d   | j                  z        }|j9                  || j                  | j.                        }t;        |j                  | j                     j<                  ||||||d |d
      }|j9                  || j                  | j.                  z        }| j?                  ||      }| jA                  |      d d d df   }|S |Bt        jB                  |dk(        s*|jD                  }||d d d d d f   z  j1                  |      }| j                  |      }t        j&                  | j(                  j+                                }| jF                  i nd	| jF                  i}|t        jB                  |dk(        }nd}| jH                  r| jJ                  r||rtM        || j                  j                   j                  d      | j                  j"                  | j4                  |f| j6                  | jN                  d | j$                  | j>                  j                   | j>                  jP                  | j@                  j                   | j@                  j"                  | j.                  | j                  d
dd|\  }}|S t        j                  || j                  | j                  | j                  gd      \  }}}|j|jS                  dd      }tT        jV                  jY                  || jZ                  |j                   d   z
  df      }|j]                  || j                        }t^        | j$                  dvrJ| ja                  | j                  |jS                  dd            jS                  dd      d d d |f         }nyt_        |jS                  dd      | j                  j                   j                  d      | j                  j"                  | j$                        jS                  dd      d d d |f   }t        j                  || j                  ||gd      \  }}}|Bt        jB                  |dk(        s*|jD                  }||d d d d d f   z  j1                  |      }tc        |j9                  ||d| j.                        |||j9                  ||| j                  d      |j9                  ||| j                  d      f| jN                  | j6                  d d d| j4                  dd|\  }}|||je                  || j                         |j9                  ||d      }| j?                  ||      }| jA                  |      }|S )Nr8   r"   r9   r   .ru   T)zr/  dt_softplusdt_limitF)r3  r   seq_idxr  rmsnorm_weightrmsnorm_epsoutproj_weightoutproj_biasheaddimngroupsnorm_before_gatereturn_final_statesr   )r?   swish)r   r-   r   r  )r   r3  rB  rE  rM  r/  rC  )3r@   r#  r  r  r&  has_previous_stater   r.  squeezer*  r+   splitr  layersconv_statesr,  r-   r   r  expr1  r\   r   rt   r<   r=   r/  r3  rA   r5  recurrent_statesr2  r4  r8  r;   r'  r!  r   r7  r   r.   r   r   r>   r   r  update_conv_stater  r   r6  update_recurrent_state)r0   rE   r@  r   
batch_sizerq   _groups_time_state_sized_to_removein_projected_statesd_mlpsplit_projection_dimrF   hidden_states_B_CdtBCr=  r/  r3  hidden_states_reshapedoutr;   projected_statesdt_limit_kwargsinput_not_masked	ssm_state	time_stephidden_states_B_C_t
conv_statescan_outputs                                  r4   cuda_kernels_forwardz%Zamba2MambaMixer.cuda_kernels_forward  s{    "/!4!4
GQ!%1D1D!D$0001t}}3DtGZGZ3ZZ]a]k]kk #(G(G(W"&,,}/D/DQ/G"H(..r2[@QFE$)5$2H2H$--Y]YgYg#h 05<OQekm0n-Aq$)2 4!##DNN3??""**1-  ! #(++!'')?AWX#M1a
 4::++-..A!T3,1d
+222t}}dFYFYZ]]didqdq]rAAq$J&&r2t}}=Bll1dC<077DMMJGq$|$++B>Az4==!''!*2MNAz4==!''!*2MNA%2%7%7
DNNTXTaTa%b"2##DNN3DD& M *..z4>>DMM;YZM IImT:M--.q$|<Cz 
u )%))Na<O2P%++!.1d
1K!K O OPU V#||M:4::++-..A$($8$8$@bzSWSgSgFhO)#(99^q-@#A #' $$<;OTd!A$KK&&..q1KK$$LL" ff# ##'99#3#3 $		 : :#'==#7#7!%!3!3 MM MM%*(,#"$ &%"YX 
m 6;[[$++T]]DNNK62'  +*;*E*Ea*K'!#!2!2+d.C.CFYF_F_`bFc.cef-g"J ".!?!?
DNN![J#+tFW/W(,$5$?$?1$EFPPQRTUVWXZb[bZbWbc)% )9+55a;#{{1199!<![[--#'??	)
  i1oa'k)3% ',kk%++-CE[\'#q!
 "-eiiRS@S6T)//E%2^Aq$J5O%O$S$STY$ZM)B!&&z7BNFF:wrBFF:wrB*  $ff (, LL $* &*&Y (\-E 77	4>>R)..z7BG"iiT:mmK0
r5   c                 d   |j                   \  }}}|j                  }|-|j                  | j                        r| j	                  |      }n1|||d d d d d f   z  j                  |      }| j	                  |      }|j                   d   d| j                  z  z
  d| j                  z  | j                  z  z
  | j                  z
  dz  }	|j                  |	|	| j                  | j                  | j                  gd      \  }}}
}}|j                  dd      }|d uxr |j                  | j                        }|r|j                  || j                        }t        j                  || j                   j"                  d d dd d f   z  d      }| j$                  r|| j                   j&                  z  }| j)                  |      j                  |      d d d df   }n|Xt*        j,                  j/                  || j0                  |j                   d   z
  df      }|j                  || j                        }| j)                  | j!                  |      dd |f   j                  dd            }|*|j                  }||d d d d d f   z  j                  |      }t        j                  || j                  | j                  | j                  z  | j                  | j                  z  gd      \  }}}t        j2                  | j4                  j7                                }|r`|j8                  dk(  r
|d d d df   n|d d dd d f   d d d df   }|j                  dd      j;                  ||j                   d   | j<                        }| j>                  d   j;                  | j>                  j                   d   | j<                        }t        j*                  j,                  jA                  ||j                  |j                        z         }t        jB                  || jD                        }|d   j;                  | j                  | j<                  | j                        j                  t        jF                  	      }t        j2                  |d   |z        }|jI                  || j                  d      dd d d f   }|j;                  || j                  | j                  | j                  z  |j                   d         jK                         }|jI                  |d|j                   d         }|d   |dd d d f   z  }|jI                  |d| j<                        }||d   z  }|jL                  | j                     jN                  jQ                         }||z  |z   }|jS                  || j                        }|jI                  || j                  d      dd d d f   }|j;                  || j                  | j                  | j                  z  |j                   d         jK                         }|jI                  |d|j                   d         }|j                  |j                        }|jU                  || j                  z  | j<                  | j                        }|jU                  || j                  z  | j                  d      }t        jV                  ||      }|jU                  || j                  | j<                        }| jX                  d   j;                  | jX                  j                   d   | j<                        }|||z  z   j                  |j                        }|jI                  |d      d d d df   }nt*        j,                  jA                  || j>                  z         }t        jB                  || jD                        }|jI                  ||d| j<                        j7                         }|jI                  ||d| j                        j7                         }|jI                  ||d| j                        j7                         }|j[                  | j                  | j                  z  d| j                  
      }|j[                  | j                  | j                  z  d| j                  
      }| j\                  || j\                  z  z
  | j\                  z  }| jX                  d   t_        ||      z  }||d   z  }|j                  |j                        |z  }||||fD cg c]  }ta        ||| j\                         c}\  }}}}|jc                  dddd      }t        jd                  |d      }t        j2                  tg        |            }|d d d d d d d d d d d f   |d d d d d d d d d d d f   z  } | j                  d      }!|!d   |jc                  ddddd      d   z  }"|"j                  d      }#|#d   |d d d d d f   z  j                  d      }$t        j2                  |d d d d d d dd f   |z
        }%||%jc                  dddd      d   z  }&|&jc                  ddddd      d   |jc                  ddddd      dd d d f   z  j                  d      jc                  ddddd      }'t        jh                  |'d d d df         }(t        jj                  |(|'gd      }'t        j2                  tg        t*        j,                  j/                  |d d d d d d df   d                  })|'jc                  ddddd      }*|)d   |*d d d d d df   z  j                  d      }+|+jc                  ddddd      },|,d d d df   |,d d df   }-}'t        j2                  |      }.|dd d d f   |'d d d d d df   z  }/|.jc                  dddd      }0|/j                  d      |0d   z  }1|$|1z   }|jI                  |d| j                  | j<                        }||z   }|dkD  r|d d d |d d d d f   }|jI                  ||d      }|-||jS                  |-| j                         | jm                  ||
      }2| jo                  |2j                  |            }3|3S c c}w )Nr9   r8   r   r"   r   .r   ).NNru   )r|   output_sizer   r   )r"   r   )8r@   r;   rO  r   r.  r<   r  r#  r  r&  rQ  r*  r   rV  r+   sumr,  r-   r  r   r   r   r>   r   r  rT  r1  r\   ndimr   rt   r/  softplusclampr(  r=   r   r   rR  rU  rn   rW  rA   bmmr3  repeat_interleaver   r   r   permuter  r  
zeros_liker   r2  r4  )4r0   input_statesr@  r   rX  rq   rY  r;   re  r]  rF   rE   r`  use_precomputed_staterk  ra  rb  r=  r/  dAdBdBx
ssm_statesssm_states_reshaped
C_reshapedyr3  r   
D_residualtA_cumsumLG_intermediateGM_intermediateMY_diagdecay_statesB_decay_contractionstatesprevious_statesdecay_chunkstates_permutedresult
new_statesrh  state_decay_outC_times_statesstate_decay_out_permutedY_offrl  contextualized_statess4                                                       r4   torch_forwardzZamba2MambaMixer.torch_forward  s   !-!3!3
GQ""#(G(G(W#||L9) ,~aDj/I IMMeT#||L9!''+a$2H2H.HH1t}}K\_c_r_rKrrtx  uC  uC  C  HI  I(8(>(>t55t~~V\^ )? )
%1dM2 &//15 ,D 8 l\=\=\]a]k]k=l !%77t~~VJ!IIj4;;3E3EaAg3N&NTVWM!!!1!11 HH]366u=aslKM']]..!**]-@-@-DDaH
 *;;JW
 HHT[[%?XgX%N%X%XYZ\]%^_M)%++!.1d
1K!K O OPU V#kk-$:P:PRVR_R_bfbubuRuw{  xE  xE  HL  H[  H[  x[  :\  bd  eq!YYtzz'')**  &(WW\AtSL!r!Q'{1dC<7PBa#**:rxx|T]]SBll9-44T\\5G5G5JDMMZG$$--b7::bhh3G.GHBR!3!34B/"))$..$--I\I\]``glgtgt`uA2i=1,-B
 		*dmmR8dAFAT]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6AI3a<0B *11*b$--PM}Y//C &,,T^^<MMSSUJ#b3.J%<<ZXJ 		*dmmR8dAFAT]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6A $qww/J",//*t~~2Mt}}^b^q^q"r
T^^ ;T=P=PRSTJ		-z:Az4>>4==AA y!((a$--HA]Q&&**1773A 		*b)!T3,7A ''T\\(9:BR!3!34B)11*gr4==Y__aM		*gD4G4GHNNPA		*gr43F3FGMMOA##DNNdmm$CX\XfXf#gA##DNNdmm$CX\XfXf#gA'DOO*CCtVH	*-?x-XXJ *ByM9M](()B.A cpqrtuwxay%z\]&9!Xt&W%z"M1a 		!Q1%A||A2.H 		+a.)A q!Qa23a1dAq!8K6LLN""r"*A y\AIIaAq!,DY,OON""r"*A 	l]1a:%>>CCAFF !99XaArsl%;h%FGL"#l&:&:1aA&Fy&Q"Q)11!Q1a@K}OdOdefhiklnoqrOstwy}  @A  uA  PB  B  G  G  LM  G  N  V  V  WX  Z[  ]^  `a  cd  eF#..va!e}=OYY8a@F))K0A0A(1aQRTV;BWY_0`$abK$nnQ1a;O!/2_Q4QT_5UUZZ_`ZaF1aA6J *1crc6 2Jq"u4EIF $ii1OT1oq!T30GGN'6'>'>q!Q'J$#''+.Fy.QQE A		*b$..$--HAJA!|a'1a'(		*gr2A$)A33It~~Nii4(
 !%knnU.C D$$C &{s   .r-c                     t         rId| j                  j                  j                  j                  v rt               s| j                  |||      S | j                  |||      S )Ncuda)r9  r.  r-   ro   r   r   rm  r  )r0   rE   r@  r   r   s        r4   rM   zZamba2MambaMixer.forwardE  sT     "f0C0C0J0J0O0O&OXpXr,,]L.YY!!-~NNr5   r'   NN)rO   rP   rQ   r   r#   r   r)   r+   r]   r
   rm  r  rM   rR   rS   s   @r4   r  r    s    Y| Yd
 Y| &*.2	T||T dlT t+	Tns% s%[`[g[gjn[n s%r &*.2	
O dl
O t+	
Or5   r  c                   8     e Zd Zddededz  f fdZddZ xZS )	Zamba2MLPNra   r   c           	          t         	|           || _        |j                  | _        |j                  | _        || _        || _        t        j                  | j                  d| j                  z  |j                        | _
        t        j                  | j                  | j                  |j                        | _        t        |j                     | _        t        j                  g       | _        t#        | j
                        D ]  }||j$                  z  |k(  rt        j&                  t        j                  | j                  j                  | j                  j(                  d      t        j                  | j                  j(                  d| j                  z  d            }nt        j*                         }| j                   j-                  |        |j.                  }t1        |      D ci c]  \  }}||
 c}}| _        yc c}}w )aQ  
        This MLP layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this layer
        is tied, un-tied adapter modules (formally same as LoRA, but used in the base model) are added to the up and gate projectors to increase expressivity with a small memory overhead.
        r8   r   FN)r(   r)   ra   r1   r  r   r   r   r   r-  gate_up_proj	down_projr	   
hidden_actact_fnr   gate_up_proj_adapter_listr   r   r   r   r   r   r   r   r   )
r0   ra   r   r   r   gate_up_proj_adapterr   r   r   r3   s
            r4   r)   zZamba2MLP.__init__S  s   
 	!--!'!9!9"4 IId&6&6D<R<R8RY_YoYop4#9#94;K;KRXRhRhiV../)+r):&t../ 	HA6(((H4')}}IIdkk55t{{7O7OV[\IIdkk66D<R<R8RY^_($
 (*{{}$**112FG	H !11;D_;UV<5%%,VVs   3H
c                     | j                  |      }| j                  |   }| | j                  |   |      z   }t        j                  |dd      }| j                  |d         |d   z  }| j                  |      }|S )Nr8   r9   r   r   r"   )r  r   r  r+   chunkr  r  )r0   hidden_stater   gate_up_stateoutputs        r4   rM   zZamba2MLP.forwardq  s    )),7NN9-	%(Q(F(Fy(QR^(__M1"={{=#34}Q7GG-r5   r  r'   )rO   rP   rQ   r#   r   r)   rM   rR   rS   s   @r4   r  r  R  s%    W| WPSVZPZ W<r5   r  c                        e Zd Zddededz  dedz  f fdZ	 	 	 ddej                  dej                  dedej                  dz  d	edz  d
ej                  dz  de
e   deej                     fdZ xZS )Zamba2AttentionDecoderLayerNra   r   r   c                 @   t         |           || _        t        |j                        }t        |d||      | _        t        |||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        y )Nr9   )r   r   r   )r   r   r2   )r(   r)   r   r   r   r   	self_attnr  feed_forwardrU   r   rms_norm_epsinput_layernormr1   pre_ff_layernorm)r0   ra   r   r   num_gsr3   s        r4   r)   z$Zamba2AttentionDecoderLayer.__init__}  s     V,,-(2RXckl%fRZ[,V-I-IvObObc -f.@.@fFYFY Zr5   rE   original_hidden_statesr   r   r   r   rV   c           	          t        j                  ||gd      }| j                  |      } | j                  d|||||d|\  }}| j	                  |      }| j                  ||      }|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://huggingface.co/papers/2405.16712).
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_values (`Cache`, *optional*): cached past key and value projection states
            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`).
            position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
        r9   r   )rE   r   r   r   r    )r+   concatenater  r  r  r  )	r0   rE   r  r   r   r   r   r   rY  s	            r4   rM   z#Zamba2AttentionDecoderLayer.forward  s    6 ))=:P*QWYZ,,];)4>> 
')+ 3
 
q --m<))-Cr5   r  r   )rO   rP   rQ   r#   r   r)   r+   r]   r
   
LongTensorr   r   rZ   FloatTensorrM   rR   rS   s   @r4   r  r  |  s    [| [sTz [UX[_U_ [ /3(,7;)||) !&) 	)
 t+) ) #--4) +,) 
u  	!)r5   r  c                   r    e Zd Zdedef fdZ	 	 	 	 	 	 	 	 ddej                  dej                  dz  dedz  dej                  dz  dej                  dz  d	edz  d
e	dz  dej                  dz  dej                  dz  dee   deej                  eej                  ej                  f   dz  f   fdZ xZS )Zamba2MambaDecoderLayerra   r   c                     t         |           t        ||      | _        t	        |j
                  |j                        | _        || _        y )N)ra   r   r  )	r(   r)   r  mambarU   r1   r  r  r   )r0   ra   r   r3   s      r4   r)   z Zamba2MambaDecoderLayer.__init__  s>    %VyI
,V-?-?VEXEXY"r5   NrE   r  r   causal_maskr   	use_cacher   transformer_hidden_statesr   rV   c
                 t    |}|	||	z   n|}| j                  |      } | j                  d|||d|
}||z   }|S )aX  
        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_values (`Cache`, *optional*): cached past key and value projection states
            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`).
        )rE   r@  r   r  )r  r  )r0   rE   r  r   r   r  r   r  r   r  r   residuals               r4   rM   zZamba2MambaDecoderLayer.forward  sn    0 !
 :S9^M55dq 	 ,,];"

 
'()
 	
 !=0r5   NNNNNFNN)rO   rP   rQ   r#   r   r)   r+   r]   r
   r  r  r   r   rZ   r  rM   rR   rS   s   @r4   r  r    s   #| # # 7; $.2+/(,!&049=*||* !&t 3* :	*
 t+* \\D(* * $;* &&-* $)<<$#6* +,* 
u  %(9(95;L;L(L"MPT"TT	U*r5   r  c                       e Zd Zdedej
                  def fdZ	 	 	 	 	 	 	 	 ddej                  dej                  dz  de
dz  d	ej                  dz  d
ej                  dz  dedz  dedz  dej                  dz  dej                  dz  dee   deej"                  eej"                  ej"                  f   dz  f   fdZ xZS )Zamba2HybridLayershared_transformerlinearr  c                 L    t         |           || _        || _        || _        y r'   )r(   r)   r  mamba_decoderr  )r0   r  r  r  r3   s       r4   r)   zZamba2HybridLayer.__init__  s'     	""4r5   NrE   r  r   r   r  r   r  r   r   r   rV   c
           
           | j                   |f||||||	d|
}| j                  |      } | j                  |f|||||d|
}|S )ap  
        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_values (`Cache`, *optional*): cached past key and value projection states
            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`).
            position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
        )r  r   r   r   r   r   )r  r   r   r  r   )r  r  r  )r0   rE   r  r   r   r  r   r  r   r   r   r  s               r4   rM   zZamba2HybridLayer.forward  s    < %<D$;$;	%
#9&+ 3%	%
 	%
! %)KK0I$J!***
&?)+ 3
 
 r5   r  )rO   rP   rQ   r  r   r   r  r)   r+   r]   r   r
   r  r  r   r   rZ   r  rM   rR   rS   s   @r4   r  r    s"   5"=5GIyy5Yp5 7; $.2+/(,!&7;044||4 !&t 34 :	4
 t+4 \\D(4 4 $;4 #--44 &&-4 +,4 
u  %(9(95;L;L(L"MPT"TT	U4r5   r  c                        e Zd ZU eed<   dZdZddgZdZdZ	dZ
dZdZeedZ ej"                          fd       Z xZS )	Zamba2PreTrainedModelra   modelTr  r  r   )rE   
attentionsc                    t         |   |       t        |t              rt	        j
                  t	        j                  | j                  j                        t        j                  | j                  j                        t        j                  | j                  j                        z
  z  t        j                  | j                  j                        z         j                  | j                  j                        }|t	        j                  t	        j                  |              z   }t!        j"                  |j$                  |       t	        j&                  d|j(                  dz         }t!        j"                  |j*                  t	        j                  |             t!        j,                  |j.                         y y )N)minr"   )r(   _init_weightsr   r  r+   rT  randra   r%  mathr0  r)  r(  rs  time_step_floorexpm1initcopy_r/  ry   r&  r1  ones_r3  )r0   r   r`  inv_dtr=  r3   s        r4   r  z#Zamba2PreTrainedModel._init_weights6  s(   f%f./

4;;44588DKK556$++B[B[9\\^((4;;4456 e33e4	  %))U[["%5$566FJJv~~v.Q 0 01 45AJJv||UYYq\2JJvxx  0r5   )rO   rP   rQ   r#   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_flex_attn_supports_sdpa_is_statefulr  r   _can_record_outputsr+   r   r  rR   rS   s   @r4   r  r  &  sg    &*#,.GH"3NL0%
 U]]_! !r5   r  c                       e Zd ZdZdef fdZeee	 	 	 	 	 	 dde	j                  dz  de	j                  dz  de	j                  dz  dedz  d	e	j                  dz  d
edz  dee   deez  fd                     Zd Z xZS )Zamba2Modelzh
    Model consisting of *config.num_hidden_layers* layers.

    Args:
        config: Zamba2Config
    ra   c                 L   t         |   |       || _        |j                  | _        |j
                  | _        t        j                  |j
                  |j                  | j                        | _	        |j                  | _
        | j                         | _        |j                  | _        t        |j                  |j                        | _        |j"                  r1|j$                  rt&        j)                  d       t+        |      | _        d| _        | j1                          y )Nr  ze`use_long_context` set to `True`: using rescaled `rope_theta` and extended `max_position_embeddings`.F)r(   r)   ra   pad_token_idpadding_idx
vocab_sizer   	Embeddingr1   embed_tokenslayers_block_type
get_layersrR  r   rU   r  final_layernormr   use_long_contextr:  r;  r_   
rotary_embgradient_checkpointing	post_initr0   ra   r3   s     r4   r)   zZamba2Model.__init__Q  s     !.. ++LL):):F<N<NPTP`P`a!'!9!9oo'$*$?$?!,V-?-?VEXEXY&&##{ 4F;DO&+# 	r5   N	input_idsr   r   r   inputs_embedsr  r   rV   c           	         |d u |d uz  rt        d      || j                  |      }|}t        j                  |      }	|r|t	        | j
                        }|V||j                         nd}
t        j                  |j                  d   |j                        |
z   }|j                  d      }t        | j
                  ||||      }| j
                  j                  r| j                  ||      }nd }t        | j                        D ]  \  }} |||	|||f||||d|} | j!                  |      }t#        ||r|	      S d 	      S )
NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either one)ra   r   r"   ro   )ra   r  r   r   r   )r   )r   r  r   r   )last_hidden_stater   )
ValueErrorr  r+   rn   r   ra   get_seq_lengthry   r@   ro   r   r   r   r  r   rR  r  r   )r0   r  r   r   r   r  r  r   rE   r  past_seen_tokensr  r   r   layers                  r4   rM   zZamba2Model.forwardh  s    -t";<s    --i8M%!&]!; 0*$++>OCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L(;;')+%
 ;;##"&//-l/"["& )$++ 6 	Iu!& !0#$7) M	 ,,];&+/8O
 	
>B
 	
r5   c                     g }i | _         d| _        g }t        | j                        D ]O  \  }}t	        | j
                  |      }|dk(  rd| d}t        |t              r"t        |      | j
                  j                  k\  rDt        |t              rt        |      }t        |      }| j                   j                  ||i       n|j                  |       || j
                  j                  z  }t        | j
                  |      }	t        j                   | j
                  j"                  | j
                  j"                  d      }
|j                  t%        |	|
|             ?|j                  |       R t        j&                  |      S )	Nr   )r   hybridzlayers.z.shared_transformer)r   Fr   )_tied_weights_keysfirst_transformer_layer_idr   r  r  ra   r   listr   r   r   nextr   r   r  r   r   r1   r  r   )r0   rR  unique_hybrid_blockslayer_id
layer_typemamba_layerprefix_patterntarget_patternr   
attn_blocklinear_layers              r4   r  zZamba2Model.get_layers  sQ   "$*+'!$-d.D.D$E 	+ Hj1$++RKX%#*8*4G!H ##7>/0DKK4N4NN!"6=/45I/J,%)*>%?N++22NN3ST )//?#dkk&@&@@8xX
!yy)@)@$++BYBY`ef/
L+VWk*3	+4 }}V$$r5   )NNNNNN)rO   rP   rQ   r   r#   r)   r   r!   r   r+   r  r]   r
   r  r  r   r   rZ   r   rM   r  rR   rS   s   @r4   r  r  H  s    | .   .2.204(,26!%@
##d*@
 t+@
 &&-	@

 @
 ((4/@
 $;@
 +,@
 
(	(@
    @
D %r5   r  c                   N    e Zd ZddiZdef fdZee	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  d	edz  d
ej                  dz  dej                  dz  dedz  deej                  z  dee   deez  fd              Z	 	 	 	 	 	 d fd	Z xZS )Zamba2ForCausalLMzlm_head.weightzmodel.embed_tokens.weightra   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y NFr   )
r(   r)   r  r  r  r   r   r1   lm_headr  r  s     r4   r)   zZamba2ForCausalLM.__init__  sU      (
 ++yy!3!3V5F5FUS 	r5   Nr  r   r   r   r  labelsr  logits_to_keepr   rV   c	           
      b    | j                   d||||||d|	}
|
j                  }t        |t              rt	        | d      n|}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |	}t        |||
j                  |
j                  |
j                        S )al  
        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]`.

        Example:

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

        >>> model = Zamba2ForCausalLM.from_pretrained("Zyphra/Zamba2-7B-v1")
        >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba2-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."
        ```)r  r   r   r   r  r  Nlosslogitsr   rE   r  r  )r  r  r   r   slicer  loss_functionr  r   r   rE   r  )r0   r  r   r   r   r  r  r  r  r   outputsrE   slice_indicesr  r  s                  r4   rM   zZamba2ForCausalLM.forward  s    H ,64:: ,
)%+',
 ,
  118B>SV8W~ot4]kmA}a,?@A%4%% 	D &#33!//))
 	
r5   c           
      h    | j                   j                  |d<   t        
|   |f||||||d|}	|	S )Nr  )r   r   r  r   r  is_first_iteration)ra   num_logits_to_keepr(   prepare_inputs_for_generation)r0   r  r   r   r  r   r  r  r   model_inputsr3   s             r4   r  z/Zamba2ForCausalLM.prepare_inputs_for_generation!  sU     $(;;#A#A w<	
+)'%1	
 	
 r5   NNNNNNNr   )NNNNTF)rO   rP   rQ   r  r#   r)   r   r   r+   r  r]   r
   r  r  r   r   r   rZ   r   rM   r  rR   rS   s   @r4   r
  r
    s0   *,GH|   .2.204(,26*.!%-.@
##d*@
 t+@
 &&-	@

 @
 ((4/@
   4'@
 $;@
 ell*@
 +,@
 
'	'@
  @
J   r5   r
  a  
    The Zamba2 Model with a sequence classification head on top (linear layer).

    [`Zamba2ForSequenceClassification`] 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).
    )custom_introc                   .    e Zd Zdef fdZee	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  de
dz  dej                  dz  d	ej                  dz  d
edz  deej                  z  dee   deez  fd              Z xZS )Zamba2ForSequenceClassificationra   c                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y r  )
r(   r)   
num_labelsr  r  r   r   r1   scorer  r  s     r4   r)   z(Zamba2ForSequenceClassification.__init__J  sS      ++ (
YYv114??O
 	r5   Nr  r   r   r   r  r  r  r  r   rV   c	           	          | j                   |f|||||d|	}
|
d   }| j                  |      }||j                  d   }n|j                  d   }| j                  j                  |dk7  rt        d      | j                  j                  d}n||| j                  j                  k7  j                  |j                  t        j                        }t        j                  |j                  d   |j                  t        j                        }||z  j                  d      }n.d}t        j                  | j                  j                   d       |t        j                  ||j                  	      |f   }d}|! | j                   d|||| j                  d
|	}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).
        )r   r   r   r  r  r   Nr"   z=Cannot handle batch sizes > 1 if no padding token is defined.r9   rv   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r  )r  r  pooled_logitsra   r  r  )r  r#  r@   ra   r  r  r<   ro   r+   int32ry   argmaxr:  r;  r3   rO   r  r   r   rE   r  )r0   r  r   r   r   r  r  r  r  r   transformer_outputsrE   r  rX  last_non_pad_tokennon_pad_masktoken_indicesr%  r  s                      r4   rM   z'Zamba2ForSequenceClassification.forwardS  s   ( 8Btzz8
)%+'8
 8
 ,A.M* "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||Jv}}MOaab%4%% $V=Y]YdYdhnD 0 /??-;;*55
 	
r5   r  )rO   rP   rQ   r#   r)   r   r   r+   r  r]   r
   r  r  r   r   r   rZ   r   rM   rR   rS   s   @r4   r   r   ;  s   |   .2.204(,26*.!%-.@
##d*@
 t+@
 &&-	@

 @
 ((4/@
   4'@
 $;@
 ell*@
 +,@
 
1	1@
  @
r5   r   )r
  r   r  r  )r   )r"   )Rr  collections.abcr   	itertoolsr   typingr   r+   r    r   r  activationsr	   cache_utilsr
   r   
generationr   integrationsr   integrations.hub_kernelsr   masking_utilsr   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.genericr   r   utils.import_utilsr    utils.output_capturingr!   configuration_zamba2r#   
get_loggerrO   r:  Moduler%   rU   r_   r]   r   r   r\   r   r   r   r   r   r   r  r  r  r  r  r  r  r  r
  r   __all__r  r5   r4   <module>rC     sQ  *  $     & ! . ) 4 8 / 9 q q K F & l l G 9 5 . 
		H	%; ;*JBII J(><BII ><B	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % %2( *+ ,2y)bii y)~VU\\ VS V
((zOryy zOz'		 'T3")) 3l18 1h=2 =@ !O ! !B D%' D% D%Pg- gT L
&; L
L
^ kr5   