o
    Zh                     @   sj  d Z ddlmZ ddl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  m  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mZ dd	lmZmZmZmZ d
dlmZ d
dl m!Z!m"Z" 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-m.Z. ddl/m0Z0 e- r	 e. rddl1m2Z2 ddl3m4Z4m5Z5 ndZ2e, rddl6m7Z7m8Z8 nd\Z8Z7e9e2e7e8fZ:e*;e<Z=G dd deddZ>G dd dej?Z?G dd deZ@d6dd ZAG d!d" d"eZBG d#d$ d$eZCd%d& ZDG d'd( d(e
jEZFG d)d* d*eZGG d+d, d,eZHG d-d. d.eZIe(G d/d0 d0e$ZJe(G d1d2 d2eJZKG d3d4 d4eZLg d5ZMdS )7zPyTorch Bamba model.    )partial)OptionalTuple	TypedDictUnionN)nn)ACT2FN)JambaAttentionDecoderLayer)LlamaAttentionLlamaForCausalLMLlamaMLPLlamaRMSNormLlamaRotaryEmbeddingrotate_half)MambaRMSNormGatedpad_tensor_by_sizereshape_into_chunkssegment_sum   )AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPast)PreTrainedModel)Unpack)auto_docstringcan_return_tuplelogging)is_causal_conv1d_availableis_flash_attn_2_availableis_mamba_2_ssm_available   )BambaConfig)selective_state_update)mamba_chunk_scan_combined mamba_split_conv1d_scan_combined)causal_conv1d_fncausal_conv1d_update)NNc                   @   s@   e Zd ZU dZejed< ejed< eed< eed< ejed< dS )BambaFlashAttentionKwargsa  
    Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
    Use cases include padding-free training and fewer `torch.compile` graph breaks.

    Attributes:
        cu_seq_lens_q (`torch.LongTensor`)
            Gets cumulative sequence length for query state.
        cu_seq_lens_k (`torch.LongTensor`)
            Gets cumulative sequence length for key state.
        max_length_q (`int`):
            Maximum sequence length for query state.
        max_length_k (`int`):
            Maximum sequence length for key state.
        seq_idx (`torch.IntTensor):
            Index of each packed sequence.
    Zcu_seq_lens_qZcu_seq_lens_kZmax_length_qZmax_length_kseq_idxN)	__name__
__module____qualname____doc__torch
LongTensor__annotations__int	IntTensor r2   r2   V/var/www/auris/lib/python3.10/site-packages/transformers/models/bamba/modular_bamba.pyr'   P   s   
 

r'   F)totalc                       s.   e Zd ZdZejdfdef fddZ  ZS ) HybridMambaAttentionDynamicCachea  
    A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
    (which has a constant shape regardless of seq_len).

    This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
    and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
    For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
    while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
    For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
    while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
    and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
    Nconfigc                    sB  t  | | |j| _d| _|j}|j}g | _g | _g | _t	|j
D ]^}| j| dkr\|  jtj |j|j d|j |  ||dg7  _|  jtj |j|j||dg7  _q$|  jtjg g  dg7  _|  jtjg g  dg7  _| j| q$ fddt	|j
D | _ fddt	|j
D | _d S )	NFmamba   devicedtyper:   c                        g | ]}t jg g  d qS r<   r-   tensor.0_
batch_sizer:   r2   r3   
<listcomp>        z=HybridMambaAttentionDynamicCache.__init__.<locals>.<listcomp>c                    r=   r>   r?   rA   rD   r2   r3   rF      rG   )super__init__layers_block_typehas_previous_statemamba_d_convmamba_d_stateconv_states
ssm_statesZtransformer_layersrangenum_hidden_layersr-   Zzerosmamba_expandhidden_sizemamba_n_groupsmamba_n_headsmamba_d_headr@   appendZ	key_cacheZvalue_cache)selfr6   rE   r;   r:   conv_kernel_sizessm_state_sizei	__class__rD   r3   rI   x   sD   	
   z)HybridMambaAttentionDynamicCache.__init__)	r)   r*   r+   r,   r-   Zfloat16r!   rI   __classcell__r2   r2   r\   r3   r5   j   s    "r5   c                   @      e Zd ZdS )BambaRotaryEmbeddingNr)   r*   r+   r2   r2   r2   r3   r`          r`   c                 C   s   | |}| |}|jd }| dd|f | d|df }}|dd|f |d|df }	}
|| t||  }|	| t|	|  }tj||gdd}tj||
gdd}||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Removes the interleaving of cos and sin from GLM

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    .Ndim)	unsqueezeshaper   r-   cat)qkcossinposition_idsZunsqueeze_dimZ
rotary_dimZq_rotZq_passZk_rotZk_passZq_embedZk_embedr2   r2   r3   apply_rotary_pos_emb   s   


""rn   c                   @   r_   )BambaAttentionNra   r2   r2   r2   r3   ro      rb   ro   c                   @   r_   )BambaRMSNormGatedNra   r2   r2   r2   r3   rp      rb   rp   c                 C   sN   |dur%|j d dkr%|j d dkr%| j}| |dddddf  |} | S )zm
    Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
    Nr    r   )rg   r;   to)hidden_statesattention_maskr;   r2   r2   r3   apply_mask_to_padding_states   s   $ rt   c                       s   e Zd ZdZdedef fddZ				ddejde	e
 d	e	ej d
e	ej de	ej f
ddZ			dde	e
 d	e	ej d
e	ej fddZ				dde	e
 d	e	ej d
e	ej de	ej fddZ  ZS )
BambaMixeruO  
    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)

    The are a few differences between this and Mamba2Mixer:
    - The variable use_precomputed_states is slightly different due to the HybridCache structure
    - There's a few non-obvious bugs fixed with batching in the slow path that exist in main
    - Some extra variables that our layer doesn't need have been removed
    - We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged
    r6   	layer_idxc                    s  t    |j| _|j| _|j| _|j| _t	|j
| j | _|| _|j| _|j| _t|j | _|j| _|j| _|j| _|j| _|j| _dtdf| _d| _d| _ | jd| j | j  | _!t"j#| j!| j!|j| j| j!| jd d| _$| j| j! | j }t"j%| j|| jd| _&t"'t()| j| _*t(+d| jd }t"'t(,|| _-d	| j-_.t/| j| jd
| _0t"'t()| j| _1d	| j1_.t"j%| j| j| jd| _2t3st45d d S t45d d S )N        infgMbP?g?r8   r    )Zin_channelsZout_channelsbiasZkernel_sizegroupspadding)ry   TZepsa  The fast path is not available because on 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-conv1dzDThe fast path for Bamba will be used when running the model on a GPU)6rH   rI   rU   	num_headsrS   rM   rZ   rL   rY   r0   rR   intermediate_sizerv   Zmamba_conv_biasuse_conv_biasZ
hidden_act
activationr   actZmamba_proj_biasZuse_biasrms_norm_epsZlayer_norm_epsilonrT   n_groupsrV   head_dimZmamba_chunk_size
chunk_sizefloattime_step_limitZtime_step_minZtime_step_maxconv_dimr   Conv1dconv1dLinearin_proj	Parameterr-   Zonesdt_biasarangelogA_logZ_no_weight_decayrp   normDout_projis_fast_path_availableloggerwarning_once)rX   r6   rv   Zprojection_sizeAr\   r2   r3   rI      s\   

	zBambaMixer.__init__Nrr   cache_paramscache_positionrs   r(   c                 C   s  t ||}| |}|j\}}}	| j| j }
|d uoD|joD|dkoD|j| j jd |j| j jd   ko8|kn  oD|d uoD|d dk}|r)|	dj
| j| j| jgdd\}}}t||j| j | jj	d| jj| j}tj
|| j|
|
gdd\}}}t| j  }|d d d df d d d d d f d| j| jjtjd}|d d d d d f dd| j}| jd d d df d| j}| jd d d df d| j}||| j|jd | j }||| j|jd | j }||| j| j}t|j| j ||||||d |dd
}||| j| j }| ||}|  |d d d df }|S t| j  }| j!d	td
fkr>i nd| j!i}| j"r||d u r|t#|| jj	d| jj| j|f| j| j$|| j| jj| jj%| j j| j j| j| jddd|}|S |j
| j| j| jgdd\}}}|d ur|&dd}t'j()|| j*|jd  df}|j| j +| | jdvr| ,| |&dddd |f &dd}nt-|&dd| jj	d| jj| j|d&dd}t ||}tj
|| j|
|
gdd\}}}t.|||d| j|||||| jd|||| jdf| j$| jd |d| jdd|\}}|d ur:|d ur:|j| j +| |||d}| ||}|  |}|S )Nr    r   rc   rd   .r;   T)zr   dt_softplusrw   rx   Zdt_limitF)r   r   r(   r   Zrmsnorm_weightZrmsnorm_epsZoutproj_weightZoutproj_biasZheaddimZngroupsZnorm_before_gatereturn_final_statesr8   )ZsiluZswish)xweightry   r   r(   )r   r   r   r(   r   r   r   )/rt   r   rg   r   rZ   rK   rN   rv   rO   squeezesplitr~   r   r}   r&   r   r   ry   r   r-   expr   r   expandr   rq   float32r   r   viewr"   r   r   r   trainingr$   r   Zvariance_epsilon	transposer   
functionalpadrY   copy_r   r%   r#   )rX   rr   r   r   rs   r(   projected_statesrE   seq_lenrC   Zgroups_time_state_sizeuse_precomputed_statesgatehidden_states_B_CdtBCr   r   r   Zhidden_states_reshapedoutZdt_limit_kwargshidden_states_B_C_transposedrN   scan_output	ssm_stater2   r2   r3   cuda_kernels_forward2  s  
	




<"
^"V
$




zBambaMixer.cuda_kernels_forwardc           3   
      s  |j \}}}|j}t||}|}	|	jjjjgdd\}
}}|d uoQ|joQ|dkoQ|j	j
 j d |jj
 j d   koE|kn  oQ|d uoQ|d dk}|r|j	j
 jddd|j	j
< |d d dd d f |j	j
 j|j	j
 d d d d df< |j	j
 jjjjd}tj|jjd dd}jr|jj }|}n8|d ur|dd}tj|j|j d  df}|j	j
 | |dddd |f dd}t||}tj|jjj jj gdd\}}}tj !  }|r[|jj
 j}|d d dd d f d d d df }|dd"||j d j#}j$d	 "j$j d j#}tjj%|||j }t&|j'd j'd }|d
 "jj#jjtj(d}t|d	 | j|d}|)|jddd d d f }|"|jjj |j d * }|)|d|j d }|d	 |dd d d f  }|)|dj#}||d	  j|d}|jj
 |jj
 | |  |)|jddd d d f }|"|jjj |j d * }|)|d|j d }|jj
 j|j|jd}|+|j j#j}|+|j jd}t,||}|+|jj#}j-d	 "j-j d j#}|||  |j}|)|dd d d df }ntj%|j$ }t&|j'd j'd }|)||dj#! }|)||dj! }|)||dj! }|j.jj djd}|j.jj djd}j/|j/  j/  j-d	 t0|  }||d	  }||j| } fdd||||fD \}}}}|1dddd}tj2|dd}tt3|} |d d d d d d d d d d d f |d d d d d d d d d d d f  }!|!jdd}"|"d	 | 1dddddd	  }#|#jdd}$|$d	 |d d d d d f  jdd}%t|d d d d d d dd f | }&||&1ddddd	  }'|'dd d d f |d	  jdd}(|r|jj
 d d d df j|(jd})nt4|(d d d df })tj5|)|(gdd}(tt3tj|d d d d d d df d}*|*dd}*|*d
 |(d d d d d df  jdd}+|+d d d df |+d d df }(},t|}-|dd d d f |(d d d d d df  }.|-1dddd}/|.d|/d	  }0|%|0 }|)|djj#}|| } dkrB|d d d |d d d d f }|)||d}|,d ur_|d ur_|jj
 |, d|_6||
}17|1|}2|2S )Nrc   rd   r    r   )Zshiftsdimsr<   r8   .).N).NNr   r9   )re   Zoutput_sizec                    s   g | ]	}t | jqS r2   )r   r   )rB   tZpad_sizerX   r2   r3   rF   e  s    z,BambaMixer.torch_forward.<locals>.<listcomp>r      )r    r   T)8rg   r;   rt   r   r   r~   r   r}   rK   rN   rv   rO   Zrollrq   r:   r   r   r-   sumr   r   ry   r   r   r   r   r   rY   r   r   rZ   r   r   r   r   r   r   Zsoftplusclampr   r   reshape
contiguousr   Zbmmr   Zrepeat_interleaver   r   Zpermutecumsumr   Z
zeros_likerh   r   r   )3rX   Zinput_statesr   r   rs   rE   r   rC   r;   r   r   r   r   r   rN   r   rr   r   r   r   Zcache_devicer   ZdAZdBZdBxrO   Zssm_states_reshapedZ
C_reshapedyr   Z
D_residualZA_cumsumLZG_intermediateGZM_intermediateMZY_diagZdecay_statesZB_decayZstatesZprevious_statesZdecay_chunkZ
new_statesr   Zstate_decay_outZC_times_statesZstate_decay_out_permutedZY_offr   Zcontextualized_statesr2   r   r3   torch_forward  s   


@,
$"$$$P&*"&0(&
*
 zBambaMixer.torch_forwardc                 K   s   t rd| jjjjv r| |||||S |d urtd|j}|d ur@|jd dkr@|jd dkr@||d d d d d f  	|}| 
||||S )Ncudaz\`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`r    r   )r   r   r   r:   typer   NotImplementedErrorr;   rg   rq   r   )rX   rr   r   r   rs   r(   kwargsr;   r2   r2   r3   forward  s   	$ zBambaMixer.forward)NNNN)NNN)r)   r*   r+   r,   r!   r0   rI   r-   Tensorr   r5   r.   r1   r   r   r   r^   r2   r2   r\   r3   ru      sV    F
 .
 Tru   c                   @   r_   )BambaMLPNra   r2   r2   r2   r3   r     rb   r   c                   @   r_   )BambaRMSNormNra   r2   r2   r2   r3   r     rb   r   c                       s   e Zd Zddededef fddZ							dd	ejd
e	ej de	ej
 de	e de	e de	e de	ej
 de	eejejf  dee deeje	eejejf  f fddZ  ZS )BambaDecoderLayerr7   r6   rv   
layer_typec                    sl   t    | `d}|dkrtnd }||| _|| _|dkr&t||d| _d S |dkr2t||| _d S t	d)Nr    r7   )r6   rv   	attentionzInvalid layer_type)
rH   rI   	self_attnr   feed_forwardr   ru   r7   ro   
ValueError)rX   r6   rv   r   Znum_expertsZffn_layer_classr\   r2   r3   rI     s   

zBambaDecoderLayer.__init__NFrr   rs   rm   past_key_valueoutput_attentions	use_cacher   position_embeddingsr   returnc	                 K   s   |}
|  |}| jdkr| jd||||d|	}d}n| jdkr4| jd||||||||d|	\}}|
| }|}
| |}| |}|
| }|f}|rR||f7 }|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.
            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.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs. Can be used to provide `BambaFlashAttentionKwargs` for
                padding-free training and/or improve torch.compile performance.
        r7   )rr   r   r   rs   Nr   )rr   rs   rm   r   r   r   r   r   r2   )Zinput_layernormr   r7   r   Zpre_ff_layernormr   )rX   rr   rs   rm   r   r   r   r   r   r   ZresidualZself_attn_weightsZoutputsr2   r2   r3   r     sD   "


	



zBambaDecoderLayer.forward)r7   )NNNFFNN)r)   r*   r+   r!   r0   strrI   r-   r   r   r.   r5   boolr   r   r'   FloatTensorr   r^   r2   r2   r\   r3   r     s<    	
r   c                   @   s:   e Zd ZeZdZdZdgZdZdZ	dZ
dZdZdd ZdS )BambaPreTrainedModelmodelTr   past_key_valuesc                 C   s   | j j}t|tjtjfr%|jjjd|d |j	d ur#|j	j
  d S d S t|ttfr5|jjd d S t|tjrV|jjjd|d |jd urT|jj|j 
  d S d S t|try|jjd ttd|jd |j_|jjd d S d S )Nrw   )meanstdg      ?r    )r6   Zinitializer_range
isinstancer   r   r   r   dataZnormal_ry   Zzero_rp   r   Zfill_	Embeddingpadding_idxru   r   r-   r   r   r}   r   r   )rX   moduler   r2   r2   r3   _init_weights7  s$   


z"BambaPreTrainedModel._init_weightsN)r)   r*   r+   r!   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_is_statefulr   r2   r2   r2   r3   r   +  s    r   c                       s  e Zd Zdef fddZdd Zdd Zee									d!d	e	e
j d
e	e
j de	e
j de	e de	e
j de	e de	e de	e de	e
j dee defddZd
e
jde
jde
jdedef
ddZed
e
jdedede
jde
jdefddZdd  Z  ZS )"
BambaModelr6   c                    s   t  | |j| _|j| _t|j|j| j| _g }t	|j
D ]}|t|||j| d q t|| _|j| _t|j|jd| _t|d| _d| _|   d S )N)rv   r   r|   )r6   F)rH   rI   Zpad_token_idr   Z
vocab_sizer   r   rS   embed_tokensrP   rQ   rW   r   rJ   Z
ModuleListlayers_attn_implementationr   r   final_layernormr`   
rotary_embgradient_checkpointingZ	post_init)rX   r6   Zdecoder_layersr[   r\   r2   r3   rI   K  s   zBambaModel.__init__c                 C   s   | j S Nr   )rX   r2   r2   r3   get_input_embeddings^  s   zBambaModel.get_input_embeddingsc                 C   s
   || _ d S r   r   )rX   valuer2   r2   r3   set_input_embeddingsa  s   
zBambaModel.set_input_embeddingsN	input_idsrs   rm   r   inputs_embedsr   r   output_hidden_statesr   r   r   c
                 K   s  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|d u |d uA r*td| jr9| jr9|r9td d}|d u rB| 	|}|}|rO|d u rOtd |	d u r^t
j|jd |jd}	|d u rg|	d}| |||	||}| ||	}| ||}|rdnd }|rdnd }| jD ]P}|jd	kr|n|}|r||f7 }| jr| jr| t|jfi |
|||||||	|	}n||f||||||	|d
|
}|d }|r|d d ur||d f7 }q| |}|r||f7 }|r|jsd|_|sd n|}t||||dS )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzBamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was provided, so no cache will be returned.r    r<   r   r2   r7   )rs   rm   r   r   r   r   r   T)Zlast_hidden_stater   rr   Z
attentions)r6   r   r   r   r   r   r   r   r   r   r-   r   rg   r:   rf   _update_causal_mask_update_mamba_maskr   r   r   Z_gradient_checkpointing_funcr   __call__r   rK   r   )rX   r   rs   rm   r   r   r   r   r   r   r   rr   causal_mask
mamba_maskr   Zall_hidden_statesZall_self_attnsZdecoder_layerZ
layer_maskZlayer_outputsZ
next_cacher2   r2   r3   r   d  s   




	


zBambaModel.forwardinput_tensorc                 C   s   | j jdkr|d urd|v r|S d S |d ur| nd}| j jdkr0|s0tj|||| jdr0d S |j}|jd }t|t	j
rC|jd n|| d }	| j|||	|||jd d}
| j jdkru|d uru|jjd	v ru|sut	|j}t|
|}
|
S )
NZflash_attention_2rw   r   Zsdpa)r   Zpast_key_values_lengthZis_trainingr    rc   )sequence_lengthtarget_lengthr;   r   rE   )r   ZxpuZnpu)r6   r   Zget_seq_lengthr   Z_ignore_causal_mask_sdpar   r;   rg   r   r-   r   5_prepare_4d_causal_attention_mask_with_cache_positionr:   r   finfominZ_unmask_unattended)rX   rs   r   r   r   r   Zpast_seen_tokensr;   r   r   r   	min_dtyper2   r2   r3   r     sF   



zBambaModel._update_causal_maskr   r   r;   rE   c                 K   s|  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	| ddddddf | ddddddf kdddd| dddf |}
|ddddddd|	f |
 }|dk}|ddddddd|	f |||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        Nr   )Z
fill_valuer;   r:   r    )Zdiagonalr<   rc   r   )re   r-   r  r  fullr:   Ztriur   r   r   clonerg   rq   Zmasked_fill)rs   r   r   r;   r   rE   r   r   r  Zmask_lengthZpadding_attention_maskZpadding_maskr2   r2   r3   r     s2    $
.$  z@BambaModel._prepare_4d_causal_attention_mask_with_cache_positionc                 C   s.   |}|d dks|durt |dkrd}|S )zv
        No need for zeroing states when
            1. Cached forward
            2. Attending to all inputs
        r   Nr    )r-   all)rX   rs   r   r   r2   r2   r3   r   I  s   "zBambaModel._update_mamba_mask)	NNNNNNNNN)r)   r*   r+   r!   rI   r   r   r   r   r   r-   r.   r   r5   r   r   r   r'   r   r   r   staticmethodr0   r;   r   r   r^   r2   r2   r\   r3   r   I  s    	
o
<7r   c                       s   e Zd Z											dde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j de
eejf def fddZ						dddZ  ZS )BambaForCausalLMNr   r   rs   rm   r   r   labelsr   r   r   r   logits_to_keepr   c                    s(   t  j|||||||||	|
|fi |S )aJ  
        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, BambaForCausalLM

        >>> model = BambaForCausalLM.from_pretrained("...")
        >>> tokenizer = AutoTokenizer.from_pretrained("...")

        >>> 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."
        ```)rH   r   )rX   r   rs   rm   r   r   r	  r   r   r   r   r
  r   r\   r2   r3   r   V  s   %zBambaForCausalLM.forwardTc              	   K   s  |d u }	|	s5|d us|d |j d kr"|d d |j d  d f }n!|j d |j d kr4|d d |f }nt| j|j d | j| jd}|d url|d u rl| dd }||dkd |	sl|d d |j d  d f }|d urw|	rwd|i}
nd| i}
|
	||||| jj
|d |
S )Nrc   r    r   r<   r   r   )rm   r   r   rs   r
  r   )rg   r5   r6   r;   r:   longr   Zmasked_fill_r   updateZnum_logits_to_keep)rX   r   r   rs   r   r   rm   r   r   Zempty_past_kvZmodel_inputsr2   r2   r3   prepare_inputs_for_generation  s:   

z.BambaForCausalLM.prepare_inputs_for_generation)NNNNNNNNNNr   )NNNNNT)r)   r*   r+   r   r-   r.   r   r5   r   r   r   r0   r   r   r  r^   r2   r2   r\   r3   r  U  sX    	
7r  )r   r  r   )Nr    )Nr,   	functoolsr   typingr   r   r   r   r-   Ztorch.utils.checkpointr   Z(transformers.models.jamba.modeling_jambamodelsZjambaZmodeling_jambaZtransformers.activationsr   r	   Z(transformers.models.llama.modeling_llamar
   r   r   r   r   r   Z*transformers.models.mamba2.modeling_mamba2r   r   r   r   Zmodeling_attn_mask_utilsr   Zmodeling_outputsr   r   Zmodeling_utilsr   Zprocessing_utilsr   utilsr   r   r   Zutils.import_utilsr   r   r   Zconfiguration_bambar!   Z+mamba_ssm.ops.triton.selective_state_updater"   Z!mamba_ssm.ops.triton.ssd_combinedr#   r$   Zcausal_conv1dr%   r&   r  r   Z
get_loggerr)   r   r'   r5   r`   rn   ro   rp   rt   Moduleru   r   r   r   r   r   r  __all__r2   r2   r2   r3   <module>   sf    
6
(   e`  p