
    .`i}                        d 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 dd
lmZmZmZ ddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZ ddlm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9m:Z:  G d dej;                  Z< G d dej;                  Z= G d dej;                  Z> G d  d!ej;                  Z? G d" d#ej;                  Z@ G d$ d%ej;                  ZAe G d& d'ej;                              ZB G d( d)ej;        e4e5e6          ZCdS )*aG  PyTorch Zamba2 model implementation for vLLM.

This module implements the Zamba2 architecture from
https://arxiv.org/abs/2411.15242, which combines Mamba and Transformer
architectures in a hybrid model optimized for efficient sequence modeling. The
model alternates between state space model layers and attention-based layers.
    )Iterable)cycle)AnyN)nn)Zamba2Config)	Attention)support_torch_compile)CacheConfigModelConfig
VllmConfig)$get_tensor_model_parallel_world_size)
GeluAndMul)RMSNorm)ColumnParallelLinearMergedColumnParallelLinearQKVParallelLinearReplicatedLinearRowParallelLinear)LogitsProcessor)MambaMixer2)MambaStateCopyFuncMambaStateCopyFuncCalculatorMambaStateDtypeCalculatorMambaStateShapeCalculator)QuantizationConfig)get_rope)ParallelLMHeadVocabParallelEmbedding)default_weight_loader)IntermediateTensors   )HasInnerStateIsHybridSupportsMambaPrefixCaching)AutoWeightsLoaderWeightsMappermaybe_prefixc                   l     e Zd ZdZ	 	 ddededeee         z  dedz  def
 fd	Zd
e	j
        fdZ xZS )
Zamba2LoRAz}LoRA layer for the Zamba2 model.

    Implements a LoRA layer that is used in shared attention and gated MLP
    blocks.
    N 	input_dimrank
output_dimquant_configprefixc           	          t                                                       t          ||d|d| d          | _        t	          |t
                    rt          }nt          } |||d|| d          | _        dS )zInitialize the attention layer.

        Args:
            input_dim: input dimension
            rank: LoRA rank
            output_dim: output dimension
            quant_config: Configuration for model quantization
        FTz.A)biasr.   gather_outputr/   z.Br1   r.   r/   N)super__init__r   A
isinstancelistr   B)selfr+   r,   r-   r.   r/   B_class	__class__s          u/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/vllm/model_executor/models/zamba2.pyr5   zZamba2LoRA.__init__<   s      	%%===
 
 
 j$'' 	+0GG*G%===
 
 
    hidden_statesc                 f    |                      |          \  }}|                     |          \  }}|S N)r6   r9   )r:   r?   lora_output_s       r=   forwardzZamba2LoRA.forwardc   s4     ..Q,,Qr>   Nr*   )__name__
__module____qualname____doc__intr8   r   strr5   torchTensorrD   __classcell__r<   s   @r=   r)   r)   5   s          37%
 %
%
 %
 $s)O	%

 )4/%
 %
 %
 %
 %
 %
 %
N|       r>   r)   c                        e Zd ZdZ	 	 	 ddededededz  dedz  d	ed
df fdZ	de
j        dede
j        d
e
j        fdZ xZS )Zamba2Attentiona  Multi-head attention mechanism for the Zamba2 model.

    Implements attention with parallel computation, QKV projections, optional
    adapters and rotary position embeddings. The attention is computed across
    distributed blocks for efficient processing.
    Nr*   configbare_block_idxnum_hybrid_layerscache_configr.   r/   returnc           
         t                                                       t                      }|| _        || _        |j        | _        |j        | _        | j        |z  dk    sJ |j        |z  | _        |j        | _        | j        |z  | _	        | j        dz  dz  | _
        | j        | j        z  | j        k    r t          d| j         d| j         d          t          | j        | j        | j        d|| d	          | _        t          | j        |j        d|| d
	          | _        t#          j        g           | _        || j        |j        z   dz
  z  |j        z  }t+          | j                  D ]k}	|	|j        z  |k    r.t-          | j        | j        | j
        || d|           }
|dz  }nt#          j                    }
| j                            |
           l|j        rlt#          j        g           | _        t#          j        g           | _        t#          j        g           | _        t+          | j                  D ]}	|	|j        z  |k    rst;          | j        |j        | j        || d          }t;          | j        |j        | j        || d          }t;          | j        |j        | j        || d          }n9t#          j                    }t#          j                    }t#          j                    }| j                            |           | j                            |           | j                            |           |j        r)tA          | j        |j!        |j"        d          | _#        dS dS )a  Initialize the attention layer.

        Args:
            config: The Zamba2 model configuration
            bare_block_idx: Index of the bare attention block
            num_hybrid_layers: Total number of hybrid layers
            cache_config: Configuration for key-value caching
            quant_config: Configuration for model quantization
            prefix: Optional prefix for parameter names
        r      g      z]attention_hidden_size must be divisible by num_attention_heads (got `attention_hidden_size`: z and `num_heads`: z).Fz	.qkv_projr3   z.o_projr!   z.attn.)rU   r/   z.linear_q_adapter)r.   r/   z.linear_k_adapterz.linear_v_adapterT)	head_sizemax_positionrope_parametersis_neox_styleN)$r4   r5   r   rR   rT   attention_hidden_sizenum_attention_headstotal_num_attention_headsattention_head_dimqkv_sizescale
ValueErrorr   qkv_projr   hidden_sizeo_projr   
ModuleListdpa_listnum_mem_blocksranger   Identityappenduse_shared_attention_adapterlinear_q_adapter_listlinear_k_adapter_listlinear_v_adapter_listr)   adapter_rankuse_mem_roper   max_position_embeddingsr[   
rotary_emb)r:   rR   rS   rT   rU   r.   r/   tp_sizej	block_idxdpalinear_q_adapterlinear_k_adapterlinear_v_adapterr<   s                 r=   r5   zZamba2Attention.__init__t   s#   & 	688!2%+%A")/)C&-71<<<<#)#=#H "(";2g=-1d:
 #d&DD'( ( B262LB B &*%=B B B   *&#*%'''
 
 
 (&%%%%
 
 
 b))%(==AC$% 	

 t566 	& 	&I600NBB,+J!-$//A//   QkmmM  %%%% . #	D)+r):):D&)+r):):D&)+r):):D&"4#9:: D D	v44FF'12+2%1"(;;;( ( ($ (22+2%1"(;;;( ( ($ (22+2%1"(;;;( ( ($$ (*{}}$'){}}$'){}}$*112BCCC*112BCCC*112BCCCC 	&1#; & 6"	  DOOO	 	r>   r?   rw   position_idsc                    |                      |          \  }}|                    | j        gdz  d          \  }}}| j        j        r| j        |         }	t          |	t          j                  rJ  |	|          }
||
z   }| j	        |         }t          |t          j                  rJ  ||          }||z   }| j
        |         }t          |t          j                  rJ  ||          }||z   }| j        j        r|                     |||          \  }} | j        |         |||          }|                     |          \  }}|S )aZ  Forward pass through the attention layer.

        Args:
            hidden_states: Input tensor [batch_size, seq_len, hidden_size]
            position_ids: Position IDs for positional embeddings
            block_idx: Current shared transformer block index

        Returns:
            Output tensor [batch_size, seq_len, hidden_size]
           dim)rd   splitra   rR   rm   rn   r7   r   rk   ro   rp   rr   rt   rh   rf   )r:   r?   rw   r|   qkvrC   query_states
key_statesvalue_states	q_adapterq_lora_output	k_adapterk_lora_output	v_adapterv_lora_outputys                   r=   rD   zZamba2Attention.forward   sf     }--Q14DM?Q;NTV1W1W.j,;3 	829=I!)R[99999%Im44M'-7L29=I!)R[99999%Im44M#m3J29=I!)R[99999%Im44M'-7L;# 	'+lJ( ($L* %DM)$\:|LL{{1~~1r>   NNr*   rF   rG   rH   rI   r   rJ   r
   r   rK   r5   rL   rM   rD   rN   rO   s   @r=   rQ   rQ   l   s          ,026@ @@ @ 	@
 "D(@ )4/@ @ 
@ @ @ @ @ @D+|+ + l	+
 
+ + + + + + + +r>   rQ   c                        e Zd ZdZ	 	 ddededeeef         dedz  ded	df fd
Z	de
j        ded	e
j        fdZ xZS )	Zamba2MLPa  Feed-forward MLP layer for the Zamba2 model.

    Implements a gated feed-forward network that projects inputs to a larger
    intermediate size, applies GELU activation with gating, then projects back
    to the original size. Includes optional adapter layers for model adaptation.
    Nr*   rR   rS   rT   r.   r/   rV   c           
         t                                                       || _        t                      | _        || _        |j        | _        |j        | _        t          | j        d| j        gz  | j        j	        || d          | _
        t          | j        | j        | j        j	        || d          | _        |j        dk    rt          d|j         d          t                      | _        t#          j        g           | _        t)          | j                  D ]j}||j        z  |k    r-t-          |j        |j        d| j        gz  || d| 	          }nt#          j                    }| j                            |           kd
S )a!  Initialize the MLP layer.

        Args:
            config: The Zamba2 model configuration
            bare_block_idx: Index of the bare block in the model
            num_hybrid_layers: Total number of hybrid layers
            quant_config: Configuration for model quantization
        rX   z.gate_up_projr3   z
.down_projgeluz5Only GELU activation is supported (got `hidden_act`: )z.gate_up_proj_adapter_list.r/   N)r4   r5   rR   r   ru   rT   re   intermediate_sizer   add_bias_lineargate_up_projr   	down_proj
hidden_actrc   r   act_fnr   rg   gate_up_proj_adapter_listrj   ri   r)   rq   rk   rl   )	r:   rR   rS   rT   r.   r/   rw   gate_up_proj_adapterr<   s	           r=   r5   zZamba2MLP.__init__,  s     	;==!2!-!'!9 7'((,%+++
 
 
 +",%(((
 
 
 &&;&,&7; ; ;   !ll *,r):):&t566 	H 	HI600NBB'1&'/00 $LLLL( ( ($$ (*{}}$*112FGGGG	H 	Hr>   r?   rw   c                    |                      |          \  }}| j        |         }t          |t          j                  rJ  ||          }||z   }|                     |          }|                     |          \  }}|S )aP  Forward pass through the MLP layer.

        Args:
            hidden_states: Input tensor [batch_size, seq_len, hidden_size]
            block_idx: Current shared transformer block index

        Returns:
            Output tensor [batch_size, seq_len, hidden_size] after applying
            gated feed-forward transformation
        )r   r   r7   r   rk   r   r   )r:   r?   rw   gate_up_statesrC   adapterrB   outputs           r=   rD   zZamba2MLP.forwardk  s     !--m<< 0;gr{33333gm,,'+5 N33 NN=11	r>   rE   )rF   rG   rH   rI   r   rJ   dictr   rK   r5   rL   rM   rD   rN   rO   s   @r=   r   r   $  s          37=H =H=H =H  S>	=H
 )4/=H =H 
=H =H =H =H =H =H~U\ c el        r>   r   c                        e Zd ZdZ	 	 	 ddededededz  dedz  d	ed
df fdZ	de
j        de
j        dede
j        d
e
j        f
dZ xZS )Zamba2AttentionDecoderLayera  Single decoder layer combining attention and feed-forward networks.

    This layer implements a standard transformer block with:
    - Input layer normalization
    - Multi-head self-attention
    - Pre-feed-forward layer normalization
    - Feed-forward network (MLP)
    Nr*   rR   rS   rT   rU   r.   r/   rV   c                 :   t                                                       t          ||||||          | _        t	          ||||| d          | _        t          d|j        z  |j                  | _	        t          |j        |j                  | _
        dS )a  Initialize the decoder layer.

        Args:
            config: The Zamba2 model configuration
            bare_block_idx: Index of the bare block
            num_hybrid_layers: Total number of hybrid layers
            cache_config: Configuration for key-value caching
            quant_config: Configuration for model quantization
            prefix: Optional prefix for parameter names
        rS   rT   rU   r.   r/   z.feed_forward)rS   rT   r.   r/   rX   epsN)r4   r5   rQ   	self_attnr   feed_forwardr   re   rms_norm_epsinput_layernormpre_ff_layernorm)r:   rR   rS   rT   rU   r.   r/   r<   s          r=   r5   z$Zamba2AttentionDecoderLayer.__init__  s    & 	 ))/%%
 
 
 &)/%+++
 
 
  'q6+='=6CVWWW '(:@S T T Tr>   r?   original_hidden_statesrw   	positionsc                     t          j        ||gd          }|                     |          }|                     |||          }|                     |          }|                     ||          }|S )a  Forward pass through the decoder layer.

        Args:
            hidden_states: Input tensor from previous layer
            original_hidden_states: Original input tensor for residual
                connection
            block_idx: Current shared transformer block index
            positions: IDs for positional embeddings

        Returns:
            Transformed hidden states after attention and feed-forward
        r   r   )r|   rw   )rw   )rL   concatenater   r   r   r   )r:   r?   r   rw   r   s        r=   rD   z#Zamba2AttentionDecoderLayer.forward  s    0 )23
 
 

 ,,];; " ' 
 
 --m<< ))-9)MMr>   r   r   rO   s   @r=   r   r     s          ,026,U ,U,U ,U 	,U
 "D(,U )4/,U ,U 
,U ,U ,U ,U ,U ,U\,|, !&, 	,
 <, 
, , , , , , , ,r>   r   c                        e Zd ZdZ	 	 	 	 ddededz  dedz  dedz  ded	df fd
Z		 	 	 dde
j        de
j        dz  de
j        dz  de
j        dz  d	e
j        f
dZ xZS )Zamba2MambaDecoderLayerzSingle Mamba decoder layer with normalization.

    This implements a  Mamba block. It includes input normalization
    and can process sequences using either chunked or full
    computation depending on configuration.
    Nr*   rR   model_configrU   r.   r/   rV   c                 R   t                                                       |j        |j        z  }t	          |j        |j        |j        ||j        |j        |j	        |j
        ||j
        z  |j        d|||| d          | _        t          |j        |j                  | _        dS )zInitialize the Mamba decoder layer.

        Args:
            config: The Zamba2 model configuration
            quant_config: Configuration for model quantization
        siluz.mixer)re   ssm_state_sizeconv_kernel_sizer   use_conv_biasuse_biasn_groups	num_headshead_dimr   
activationr   rU   r.   r/   r   N)r4   r5   mamba_expandre   r   mamba_d_statemamba_d_convr   r   mamba_ngroupsn_mamba_headsr   mambar   r   )r:   rR   r   rU   r.   r/   r   r<   s          r=   r5   z Zamba2MambaDecoderLayer.__init__  s     	 #/&2DD *!/#0/ .+)*&&*>>,%%%$$$
 
 

&  'v'9v?RSSSr>   r?   transformer_hidden_statesr   r   c                 v    |}|||z   }|                      |          }|                     |          }||z   }|S )a  Forward pass through the Mamba decoder layer.

        Args:
            hidden_states: Input tensor [batch_size, seq_len, hidden_size]
            transformer_hidden_states: Optional output from transformer path
                Added to input if provided (used in hybrid architecture)
            positions: Optional position IDs (unused in Mamba)
            original_hidden_states: Optional original inputs (unused in Mamba)

        Returns:
            Transformed hidden states with residual connection applied
        )r   r   )r:   r?   r   r   r   residualr   s          r=   rD   zZamba2MambaDecoderLayer.forward  sV    ( ! %0),EEM ,,];; M** !6)r>   NNNr*   )NNN)rF   rG   rH   rI   r   r   r
   r   rK   r5   rL   rM   rD   rN   rO   s   @r=   r   r     s         ,0+/26%T %T%T "D(%T "D(	%T
 )4/%T %T 
%T %T %T %T %T %TT :>)-6:( (|( $)<$#6( <$&	(
 !&t 3( 
( ( ( ( ( ( ( (r>   r   c                        e Zd ZdZ	 	 	 	 ddededededz  dedz  d	e	dz  d
e
ddf fdZdej        dej        dej        dej        fdZ xZS )Zamba2HybridLayeraY  Hybrid layer combining Transformer and Mamba architectures.

    This layer implements the hybrid architecture described in the Zamba paper,
    where a shared transformer pathway processes input in parallel with a Mamba
    pathway. The transformer output is projected and added to the Mamba input
    for enhanced representation learning.
    Nr*   shared_transformerrR   rw   r   rU   r.   r/   rV   c                     t                                                       || _        || _        t	          |j        |j        d|| d          | _        t          |||||          | _        dS )zInitialize the hybrid layer.

        Args:
            shared_transformer: Transformer decoder layer for attention pathway
        Fz.linearr3   r   rU   r.   r/   N)	r4   r5   rw   r   r   re   linearr   mamba_decoder)	r:   r   rR   rw   r   rU   r.   r/   r<   s	           r=   r5   zZamba2HybridLayer.__init__Q  s     	""4&%%%%
 
 
 5%%%
 
 
r>   r?   r   r   c                     |                      ||| j        |          }|                     |          \  }}|                     ||          }|S )a  Forward pass through the hybrid layer.

        Processes input through parallel transformer and Mamba paths:
        1. Transformer path processes input with attention
        2. Transformer output is projected to match hidden size
        3. Projected output is added to Mamba path input
        4. Final output combines both paths' representations

        Args:
            hidden_states: Input tensor [batch_size, seq_len, hidden_size]
            original_hidden_states: Original input for transformer residual
                connection
            positions: Position IDs for positional embeddings

        Returns:
            Output tensor combining transformer and Mamba representations
        )r   rw   r   )r   )r   rw   r   r   )r:   r?   r   r   r   rC   layer_outputss          r=   rD   zZamba2HybridLayer.forwardr  sq    0 %)$;$;#9n	 %< %
 %
! (,{{3L'M'M$!1 **&? + 
 

 r>   r   )rF   rG   rH   rI   r   r   rJ   r   r
   r   rK   r5   rL   rM   rD   rN   rO   s   @r=   r   r   H  s          ,0+/26
 
7
 
 	

 "D(
 "D(
 )4/
 
 

 
 
 
 
 
B(|( !&( <	(
 
( ( ( ( ( ( ( (r>   r   c            
            e Zd ZdZdddededdf fdZd	ej        dej        fd
Z		 dd	ej        dej        dej        dz  dej        e
z  fdZdeeeej        f                  dee         fdZ xZS )Zamba2ModelzCore Zamba2 model combining transformer and Mamba architectures.

    The model processes input through a sequence of hybrid and Mamba-only
    layers, using token embeddings and final layer normalization.
    r*   r   vllm_configr/   rV   Nc                   t                                                       |j        j        |j        }|j        |j        |j        }t          |          }|rJ | _        j	        | _	        t          | j	        j                  | _        d t          j                  D             t          fdt!          j                  D                       }g }t          j                  D ]\  }}	t'          t)                    |z             |	dk    rAt+          |          }
|         }|                    t/          |
||                     k|                    t1          |                     t3          j        |          | _        t9          j        j                  | _        dS )zInitialize the Zamba2 model.

        Args:
            vllm_config: Configuration object containing model, cache,
                quantization and LoRA settings
            prefix: Optional prefix for parameter names in state dict
        c                     i | ]\  }}||	S  r   ).0rw   	layer_idxs      r=   
<dictcomp>z(Zamba2Model.__init__.<locals>.<dictcomp>  s.     
 
 
$	9 y
 
 
r>   c           
      V    g | ]%}t          |t                                &S )r   )r   len)r   idxrU   rR   layer2block_mapr/   r.   s     r=   
<listcomp>z(Zamba2Model.__init__.<locals>.<listcomp>  sV     
 
 
  ,#&&)/&:&:!-!-$;  
 
 
r>   hybridr   r   N)r4   r5   r   	hf_configrU   r.   lora_configboolrR   
vocab_sizer   re   embed_tokens	enumeratehybrid_layer_idsr   rj   ri   layers_block_typerK   r   nextrl   r   r   r   rg   layersr   r   final_layernorm)r:   r   r/   r   r   is_lora_enabledblocksr   r   
layer_typeblockrw   rU   rR   r   r.   r<   s     `         @@@@r=   r5   zZamba2Model.__init__  s-    	)3"/"/"/!-{++"""" + 3O
 

 
(1&2I(J(J
 
 
 
 
 
 
 
 
 
 
 !!677
 
 

 
 %.v/G%H%H 	 	!Iz _--	9::FX%%V+I6	%!%1%1%1%  
 
 
 
 +%1%1%1%      mF++  'v'9v?RSSSr>   	input_idsc                 ,    |                      |          S )zConvert input token IDs to embeddings.

        Args:
            input_ids: Tensor of input token IDs

        Returns:
            Embedded representation of the input tokens
        )r   r:   r   s     r=   embed_input_idszZamba2Model.embed_input_ids  s       +++r>   r   inputs_embedsc                     ||                      |          }|}t          j        |          }t          | j                  D ]\  }} ||||          }|}|                     |          }|S )aI  Forward pass through the model.

        Args:
            input_ids: Input token IDs
            positions: Position IDs for embeddings
            inputs_embeds: Optional pre-computed input embeddings

        Returns:
            Either final hidden states or intermediate tensors for pipeline
            parallelism
        N)r   r   )r   rL   cloner   r   r   )	r:   r   r   r   r?   r   r   layerr   s	            r=   rD   zZamba2Model.forward  s    $   00;;M% "']!;!; )$+ 6 6 	* 	*Iu!E'=#  M
 *MM,,];;r>   weightsc                    g d}t          |                                           }t                      }|D ]\  }}|D ]>\  }}}	||vr|                    ||          }||         }
|
j        } ||
||	            n/||vrK||         }
t          |
dt                    } ||
|           |                    |           |S )N))rd   q_projq)rd   k_projk)rd   v_projvweight_loader)r   named_parameterssetreplacer   getattrr   add)r:   r   stacked_params_mappingparams_dictloaded_paramschkpt_weight_nameloaded_weight
param_nameweight_nameshard_idparamr   s               r=   load_weightszZamba2Model.load_weights'  s   "
 "
 "
 4002233"%%%07 	1 	1,}5K 4 41
K&777$5$=$=k:$V$V!#$56 % 3e]H===$K77#$56 '@U V Ve]333/0000r>   rA   )rF   rG   rH   rI   r   rK   r5   rL   rM   r   r    rD   r   tupler  r  rN   rO   s   @r=   r   r     s9         BD RT RT RTz RT3 RT RT RT RT RT RT RTh	, 	,%, 	, 	, 	, 	, .2	! !<! <! |d*	!
 
+	+! ! ! !FHU33D-E$F 3s8        r>   r   c                       e Zd ZdZ edddd          Zeddd	eej	        ej	        f         fd
            Z
eddd	eeeef         eeeef         f         fd            Zed	eeef         fd            Zdddeded	df fdZdej        d	ej        fdZ	 ddej        dej        dej        dz  ded	ej        f
dZdej        d	ej        dz  fdZdeeeej        f                  d	ee         fdZ xZS )Zamba2ForCausalLMa1  Zamba2 model with causal language modeling head.

    This class wraps the core Zamba2 model and adds:
    - A language modeling head for next token prediction
    - Mamba state caching functionality
    - Support for model parallelism and quantization
    - Sampling capabilities for text generation
    r6   zA.weightzB.weight)A_logz0.weightz1.weight)orig_to_new_substrr   r   rV   c                 j    t          j        |j        j        |j        j        |j        j                  S rA   )r   mamba2_state_dtyper   dtyperU   mamba_cache_dtypemamba_ssm_cache_dtype)clsr   s     r=   !get_mamba_state_dtype_from_configz3Zamba2ForCausalLM.get_mamba_state_dtype_from_configW  s4    
 );$*$6$:
 
 	
r>   c           	          |j         }|j        j        }|j        |j        z  }t          j        ||j        |j        |j	        |j
        |j        |j                  S )a3  Calculate shapes for Mamba's convolutional and state caches.

        Args:
            vllm_config: vLLM config

        Returns:
            Tuple containing:
            - conv_state_shape: Shape for convolutional state cache
            - temporal_state_shape: Shape for state space model cache
        )r   tp_world_sizer   r   r   
state_sizeconv_kernel)parallel_configr   r   r   re   r   mamba2_state_shapetensor_parallel_sizer   r   mamba_headdimr   r   )r  r   r   r   r   s        r=   !get_mamba_state_shape_from_configz3Zamba2ForCausalLM.get_mamba_state_shape_from_configb  si      &5,6	%2Y5JJ(;/)>,-, .!.
 
 
 	
r>   c                 (    t          j                    S rA   )r   mamba2_state_copy_func)r  s    r=   get_mamba_state_copy_funcz+Zamba2ForCausalLM.get_mamba_state_copy_func  s    +BDDDr>   r*   r   r/   Nc                   |j         j        }|j        }t                                                       || _        || _        || _        |j         | _         t          |t          |d                    | _	        t          |j        |j        t          |d                    | _        | j                            | j	        j                  | _        t!          |j                  | _        dS )a~  Initialize the Zamba2 model for causal language modeling.

        Args:
            vllm_config: Configuration containing model, cache, quantization,
                        LoRA and scheduler settings
            prefix: Optional prefix for parameter names

        Raises:
            AssertionError: If prefix caching is enabled
                (not supported by Mamba)
        model)r   r/   lm_headr   N)r   r   scheduler_configr4   r5   rR   r   r   r'   r)  r   r   re   r*  tie_weightsr   r   logits_processor)r:   r   r/   rR   r+  r<   s        r=   r5   zZamba2ForCausalLM.__init__  s     )3&7& 0'4 !#L,I,I
 
 


 &	22
 
 
 |//
0GHH !00A B Br>   r   c                 6    | j                             |          S )zConvert input token IDs to embeddings.
        Args:
            input_ids: Tensor of input token IDs
        Returns:
            Embedded representation of the input tokens
        )r)  r   r   s     r=   r   z!Zamba2ForCausalLM.embed_input_ids  s     z)))444r>   r   r   kwargsc                 4    |                      |||          }|S )aI  Forward pass through the model.

        Args:
            input_ids: Input token IDs
            positions: Position IDs for embeddings
            inputs_embeds: Optional pre-computed input embeddings
            **kwargs: Additional arguments passed to cache manager

        Returns:
            Output hidden states
        )r)  )r:   r   r   r   r/  r?   s         r=   rD   zZamba2ForCausalLM.forward  s(    & 


 
 r>   r?   c                 <    |                      | j        |          }|S )zCompute logits for next token prediction.

        Args:
            hidden_states: Hidden states from model forward pass

        Returns:
            Logits for next token prediction
        )r-  r*  )r:   r?   logitss      r=   compute_logitsz Zamba2ForCausalLM.compute_logits  s      &&t|]CCr>   r   c                 X    t          |           }|                    || j                  S )N)mapper)r%   r  hf_to_vllm_mapper)r:   r   loaders      r=   r  zZamba2ForCausalLM.load_weights  s+    "4((""743I"JJJr>   rA   )rF   rG   rH   rI   r&   r6  classmethodr  rL   r  r  rJ   r$  r   r'  r   rK   r5   rM   r   r   rD   r3  r   r  r  rN   rO   s   @r=   r  r  D  s]         &""
 
   
!
 
u{EK'	(
 
 
 [
 
!
 
uS#Xc3m 44	5
 
 
 [
: E%0BDV0V*W E E E [E BD %C %C %Cz %C3 %C %C %C %C %C %C %CN5 5%, 5 5 5 5 .2	 < < |d*	
  
   6| 
	   KHU33D-E$F K3s8 K K K K K K K Kr>   r  )DrI   collections.abcr   	itertoolsr   typingr   rL   r   transformersr   vllm.attention.layerr   vllm.compilation.decoratorsr	   vllm.configr
   r   r   vllm.distributedr   %vllm.model_executor.layers.activationr   $vllm.model_executor.layers.layernormr   !vllm.model_executor.layers.linearr   r   r   r   r   +vllm.model_executor.layers.logits_processorr   -vllm.model_executor.layers.mamba.mamba_mixer2r   ,vllm.model_executor.layers.mamba.mamba_utilsr   r   r   r   'vllm.model_executor.layers.quantizationr   +vllm.model_executor.layers.rotary_embeddingr   3vllm.model_executor.layers.vocab_parallel_embeddingr   r   -vllm.model_executor.model_loader.weight_utilsr   vllm.sequencer    
interfacesr"   r#   r$   utilsr%   r&   r'   Moduler)   rQ   r   r   r   r   r   r  r   r>   r=   <module>rO     s    % $ $ $ $ $                    % % % % % % * * * * * * = = = = = = < < < < < < < < < < A A A A A A < < < < < < 8 8 8 8 8 8              H G G G G G E E E E E E            G F F F F F @ @ @ @ @ @        P O O O O O - - - - - - K K K K K K K K K K A A A A A A A A A A4 4 4 4 4 4 4 4nu u u u ubi u u up` ` ` ` `	 ` ` `Fd d d d d") d d dNW W W W Wbi W W WtR R R R R	 R R Rj c c c c c") c c cL\K \K \K \K \K	=(<V \K \K \K \K \Kr>   