o
    Zh"                  
   @   s^  d Z ddl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Z ddlmZmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZ ddlmZ ddlmZmZmZ ddl m!Z! e rqddl"m#Z# ddl$m%Z% e rzddlm&Z& e'e(Z)G dd de	j*Z+dd Z,d@ddZ-dej.de/dej.fddZ0dej.de/d e/d!eej. dej.f
d"d#Z1G d$d% d%e	j*Z2G d&d' d'e2Z3G d(d) d)e2Z4e2e3e4d*Z5G d+d, d,e	j*Z6G d-d. d.e	j*Z7G d/d0 d0e	j*Z8G d1d2 d2e	j*Z9G d3d4 d4e	j*Z:G d5d6 d6e	j*Z;eG d7d8 d8eZ<eG d9d: d:e<Z=ed;d<G d=d> d>e<eZ>g d?Z?dS )AzPyTorch DBRX model.    N)AnyOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)MoeCausalLMOutputWithPastMoeModelOutputWithPast)PreTrainedModel)auto_docstringis_torch_flex_attn_availablelogging   )
DbrxConfig)	BlockMask)make_flex_block_causal_mask)_flash_attention_forwardc                       s0   e Zd Zd fdd	Ze d	ddZ  ZS )
DbrxRotaryEmbedding   '  Nc                    sZ   t    || _|| _|| _d| jtjd| jdtjd | j   }| j	d|dd d S )N      ?r      dtypeinv_freqF)tensor
persistent)
super__init__dimmax_position_embeddingsbasetorcharangeZint64floatZregister_buffer)selfr'   r(   r)   devicer"   	__class__ U/var/www/auris/lib/python3.10/site-packages/transformers/models/dbrx/modeling_dbrx.pyr&   0   s   
*zDbrxRotaryEmbedding.__init__c                 C   s   | j |j | j d d d d f  |jd dd}|d d d d d f  }|jj}t|tr7|dkr7|nd}t	j
|dd% | |  dd}t	j||fdd	}| }	| }
W d    n1 shw   Y  |	j|jd
|
j|jd
fS )Nr   r   ZmpscpuF)device_typeenabledr   r'   r    )r"   tor.   r,   expandshapetype
isinstancestrr*   Zautocast	transposecatcossinr!   )r-   xposition_idsseq_lenZinv_freq_expandedZposition_ids_expandedr5   ZfreqsZembr@   rA   r1   r1   r2   forward:   s   (
zDbrxRotaryEmbedding.forward)r   r   NN)__name__
__module____qualname__r&   r*   Zno_gradrE   __classcell__r1   r1   r/   r2   r   /   s    
r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr3   r   r7   )r:   r*   r?   )rB   x1Zx2r1   r1   r2   rotate_halfM   s   rL   c                 C   sD   | |}| |}| | t| |  }|| t||  }||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.
        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.
    )	unsqueezerL   )qkr@   rA   rC   Zunsqueeze_dimZq_embedZk_embedr1   r1   r2   apply_rotary_pos_embU   s
   

rP   hidden_statesn_repreturnc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||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:   r9   reshape)rQ   rR   batchnum_key_value_headsslenhead_dimr1   r1   r2   	repeat_kvq   s
   0rY   gate_logitsnum_expertstop_kattention_maskc                    s  | du s	t | tstdS t | tr&| d j tj fdd| D dd}tjjj|dd}tj	||dd\}}tjj
||}|du rVtj| dd}	tj|dd}
ng|j\}}|jd ||  }|dddddddf |||||fd|| }tj| | ddtj|dd }	|ddddddf ||||fd| }tj|| ddtj|dd }
t|	|
d }|| S )a  Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

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

    Args:
        gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
            Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
            shape [batch_size X sequence_length, num_experts].
        num_experts (`int`):
            Number of experts.
        top_k (`int`):
            The number of experts each token is routed to.
        attention_mask (`torch.Tensor`, *optional*):
            The attention_mask used in forward function
            shape [batch_size X sequence_length] if not None.

    Returns:
        The auxiliary loss.
    N        r   c                    s   g | ]}|  qS r1   )r8   ).0Z
layer_gateZcompute_devicer1   r2   
<listcomp>       z,load_balancing_loss_func.<locals>.<listcomp>r7   r3   )r<   tupler*   r#   r.   r?   r   
functionalsoftmaxtopkone_hotmeanr,   r:   r9   rT   r8   sumrM   )rZ   r[   r\   r]   Zconcatenated_gate_logitsZrouting_weights_Zselected_expertsexpert_maskZtokens_per_expertZrouter_prob_per_expert
batch_sizesequence_lengthZnum_hidden_layersZexpert_attention_maskZ router_per_expert_attention_maskZoverall_lossr1   r`   r2   load_balancing_loss_func}   s>   




rn   c                       s   e Zd ZdZddedee f fddZ					ddej	d	ej
d
eej	 dee dededeej
 dedeej	eej	 ee f fddZ  ZS )DbrxAttentionzMulti-head self attention.Nconfig	block_idxc                    s   t    || _|j| _|j| _| j| j | _|j| _	|| _
|d u r1td| jj dd d  |j}|j| _|j| _|j| _| j| j | _|j| _d| _tj| j| jd| j | j  dd| _tj| j| jdd| _t| j| j	| jd	| _d S )
NzInstantiating z; without passing a `block_idx` is not recommended and will zelead to errors during the forward call if caching is used. Please make sure to provide a `block_idx` zwhen creating this class.Tr   Fbias)r(   r)   )r%   r&   rp   d_modelhidden_sizeZn_heads	num_headsrX   Zmax_seq_lenr(   rq   loggerwarning_oncer0   rG   attn_config
attn_pdropclip_qkvZ
kv_n_headsrV   num_key_value_groupsZ
rope_theta	is_causalr   LinearWqkvout_projr   
rotary_emb)r-   rp   rq   ry   r/   r1   r2   r&      s>   
zDbrxAttention.__init__FrQ   rC   r]   past_key_valueoutput_attentions	use_cachecache_positionkwargsrS   c                 K   s:  |  \}	}
}| |}| jd ur| j nd }| j}|j||d}|j| j| j| j | j| j gdd\}}}||	|
| j	| j
dd}||	|
| j| j
dd}||	|
| j| j
dd}| ||\}}t||||\}}|d ur|||d}|||| j|\}}t|| j}t|| j}t||
ddt| j }|d ur|d d d d d d d |jd f }|| }tjj|dtjd	|j}tjj|| j| jd
}t||}|  |	| j	|
| jfkrtd|	| j	|
| jf dd|    |
dd  }|!|	|
| j}| "|}|sd }|||fS )Nminmaxr   r7   r   rA   r@   r   r   r3   r'   r!   ptrainingz `attn_output` should be of size z, but is )#sizer   r{   clampsplitru   rV   rX   viewrv   r>   r   rP   updaterq   rY   r|   r*   matmulmathsqrtr:   r   rd   re   float32r8   r!   dropoutrz   r   
ValueError
contiguousrT   r   )r-   rQ   rC   r]   r   r   r   r   r   bszq_lenrj   
qkv_statesZmin_valZmax_valquery_states
key_statesvalue_statesr@   rA   cache_kwargsattn_weightscausal_maskattn_outputr1   r1   r2   rE      sR   


	 &

zDbrxAttention.forwardrF   NNFFN)rG   rH   rI   __doc__r   r   intr&   r*   Tensor
LongTensorr	   boolr   r   rE   rJ   r1   r1   r/   r2   ro      s6    %	
ro   c                       s   e Zd ZdZ fddZ						ddejdeej deej d	ee	 d
e
de
deej dedeejeej eeej  f fddZ  ZS )DbrxFlashAttention2zDbrx flash attention module.

    This module inherits from `DbrxAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it
    calls the public API of flash attention.
    c                    s   t  j|i | t | _d S rF   )r%   r&   r   _flash_attn_uses_top_left_mask)r-   argsr   r/   r1   r2   r&   >  s   zDbrxFlashAttention2.__init__NFrQ   r]   rC   r   r   r   r   r   rS   c                 K   s  t |tr	tdtd d}| \}	}
}| |}| jd ur+|j| j | jd}|j	| j
| j| j | j| j gdd\}}}||	|
| j| jdd}||	|
| j| jdd}||	|
| j| jdd}| ||\}}t||||\}}|d ur|||d}|||| j|\}}|dd}|dd}|dd}| jr| jnd	}|j}|tjkrt rt }nt| jd
r| jj}n|j}tdd| d  ||}||}||}t |||||
||| j!| j"d	}|#|	|
| j
$ }| %|}|sd }|||fS )Nz`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformerszZImplicitly setting `output_attentions` to False as it is not supported in Flash Attention.Fr   r   r7   r   r   r^   _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in z(float32. We will cast back the input in .)rC   r   r}   Zuse_top_left_mask)&r<   r   r   rw   infor   r   r{   r   r   ru   rV   rX   r   rv   r>   r   rP   r   rq   r   rz   r!   r*   r   Zis_autocast_enabledZget_autocast_gpu_dtypehasattrrp   r   rx   r8   r   r}   r   rT   r   r   )r-   rQ   r]   rC   r   r   r   r   r   r   r   rj   r   r   r   r   r@   rA   r   Zdropout_rateZinput_dtypeZtarget_dtyper   r   r1   r1   r2   rE   F  sx   














zDbrxFlashAttention2.forwardNNNFFN)rG   rH   rI   r   r&   r*   r   r   r   r	   r   r   r   rE   rJ   r1   r1   r/   r2   r   6  s8    	
r   c                       s   e Zd ZdZ						ddejdeej deej dee de	d	e	d
eej de
ejeej ee
ej  f f fddZ  ZS )DbrxSdpaAttentionz
    Dbrx attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `DbrxAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFrQ   r]   rC   r   r   r   r   rS   c              	      s  |rt d t j|||||||dS | \}}	}
| |}| jd ur/|j| j | jd}|j| j	| j
| j | j
| j gdd\}}}|||	| j| jdd}|||	| j
| jdd}|||	| j
| jdd}| j||d d\}}t||||d \}}|d ur|||d}|||| j|\}}t|| j}t|| j}|}|d ur|d d d d d d d |jd	 f }|jjd
kr|d ur| }| }| }|d u r|	dkrdnd}tjjj||||| jr| jnd|d}|dd }|||	d}| |}|d |fS )Na  DbrxModel is using DbrxSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.rQ   r]   rC   r   r   r   r   r   r   r7   r   )rD   r   r   cudaTFr^   )Z	attn_maskZ	dropout_pr}   r3   ) rw   rx   r%   rE   r   r   r{   r   r   ru   rV   rX   r   rv   r>   r   rP   r   rq   rY   r|   r:   r.   r;   r   r*   r   rd   Zscaled_dot_product_attentionr   rz   r   )r-   rQ   r]   rC   r   r   r   r   r   r   rj   r   r   r   r   r@   rA   r   r   r}   r   r/   r1   r2   rE     sl   





	&	

zDbrxSdpaAttention.forwardr   )rG   rH   rI   r   r*   r   r   r   r	   r   r   rE   rJ   r1   r1   r/   r2   r     s2    		r   )eagerflash_attention_2sdpac                       s   e Zd Zddedee f fddZ					ddejdej	d	eej d
ee
 dededeej	 dedeejejeej ee
 f fddZ  ZS )DbrxNormAttentionNormNrp   rq   c                    sT   t    || _|j| _tj|jdd| _t|j	 ||d| _
tj|jdd| _d S )NFrr   rp   rq   )r%   r&   rq   resid_pdropr   	LayerNormrt   norm_1DBRX_ATTENTION_CLASSES_attn_implementationattnnorm_2r-   rp   rq   r/   r1   r2   r&     s   
zDbrxNormAttentionNorm.__init__FrQ   rC   r]   r   r   r   r   r   rS   c              
   K   s|   |}	|  ||j}| jd|||||||d|\}}
}tjj|| j| jd}||	 }|}	| 	||j}|	||
|fS )Nr   r   r1   )
r   r8   r!   r   r   rd   r   r   r   r   )r-   rQ   rC   r]   r   r   r   r   r   Zresidual_statesr   r1   r1   r2   rE      s$   zDbrxNormAttentionNorm.forwardrF   r   )rG   rH   rI   r   r   r   r&   r*   r   r   r	   r   r   r   rE   rJ   r1   r1   r/   r2   r     s4    	
r   c                       s^   e Zd Zdedededee dee f
 fddZdejd	e	ejejej
f fd
dZ  ZS )
DbrxRouterru   moe_num_experts	moe_top_kmoe_jitter_epsmoe_normalize_expert_weightsc                    sB   t    || _|| _|| _|| _|| _tj| j| jdd| _	d S NFrr   )
r%   r&   ru   r   r   r   r   r   r~   layer)r-   ru   r   r   r   r   r/   r1   r2   r&   C  s   
zDbrxRouter.__init__rQ   rS   c                 C   s   | j r| jd ur|t|d| j d| j 9 }|d|jd }| |jdtj	d}tj
|| jdd\}}| jd urGtj|| jdddnd}|| }||j}||j}|||fS )Nr   r3   r   r7   T)r   r'   Zkeepdim)r   r   r*   Z
empty_likeZuniform_r   r:   r   re   r   rf   r   r   Znormr8   r!   )r-   rQ   weightstop_weightstop_expertsZtop_weights_scaler1   r1   r2   rE   T  s   

zDbrxRouter.forward)rG   rH   rI   r   r   r,   r&   r*   r   r   r   rE   rJ   r1   r1   r/   r2   r   B  s    ,r   c                
       sV   e Zd Zdedededef fddZdejdejd	ejd
ejdejf
ddZ  Z	S )DbrxExpertGLUru   ffn_hidden_sizer   
ffn_act_fnc                    s~   t    || _|| _|| _tt|| || _	tt|| || _
tt|| || _|dd}t| | _d S )NnameZsilu)r%   r&   ru   r   r   r   	Parameterr*   emptyw1v1w2getr   activation_fn)r-   ru   r   r   r   Zact_fn_namer/   r1   r2   r&   j  s   
zDbrxExpertGLU.__init__rB   	expert_w1	expert_v1	expert_w2rS   c           	      C   s<   | | }| | }| |}|| }| |}|S rF   )r   tr   )	r-   rB   r   r   r   Z	gate_projZup_projZintermediate_statesZ	down_projr1   r1   r2   rE   w  s   

zDbrxExpertGLU.forward)
rG   rH   rI   r   dictr&   r*   r   rE   rJ   r1   r1   r/   r2   r   i  s    r   c                
       sV   e Zd Zdedededef fddZdejdejd	ejd
ejdejf
ddZ	  Z
S )DbrxExpertsru   r   r   r   c                    s&   t    || _t||||d| _d S )Nru   r   r   r   )r%   r&   r   r   mlp)r-   ru   r   r   r   r/   r1   r2   r&     s   
zDbrxExperts.__init__rB   r   r   r   rS   c                 C   s  |j \}}}|d|}t|}tjj|| jdddd}	| j	j
| j	j| j	j| j	jj| jdd}
| j	j| j	j| j	j| j	jj| jdd}| j	j| j	j| j	j| j	jj| jdd}dd |
D }
d	d |D }d
d |D }td| jD ]=}t|	| \}}|j d dkrqy|}|}|d |f d|}| 	||
| || || |||d f  }|d|| qy||||}|S )Nr3   )Znum_classesr   r   r   r7   c                 S      g | ]}|j d dqS r   r7   Zsqueeze)r_   r   r1   r1   r2   ra         z'DbrxExperts.forward.<locals>.<listcomp>c                 S   r   r   r   )r_   r   r1   r1   r2   ra     r   c                 S   r   r   r   )r_   r   r1   r1   r2   ra     r   )r:   r   r*   Z
zeros_liker   rd   rg   r   Zpermuter   r   r   ru   chunkr   r   rangewhererT   Z
index_add_)r-   rB   r   r   r   r   r   ru   outrk   Z
w1_chunkedZ
v1_chunkedZ
w2_chunkedZ
expert_idxZtopk_idxZ	token_idxZ
token_listZ	topk_listZexpert_tokensZ
expert_outr1   r1   r2   rE     s<   
zDbrxExperts.forward)rG   rH   rI   r   r   r&   r*   r   r   rE   rJ   r1   r1   r/   r2   r     s    
r   c                       sB   e Zd Zdef fddZdejdeejejf fddZ  Z	S )DbrxFFNrp   c                    sL   t    |j}t|j|j|j|j|jd| _	t
|j|j|j|jd| _d S )N)ru   r   r   r   r   r   )r%   r&   
ffn_configr   rt   r   r   r   r   routerr   r   r   experts)r-   rp   r   r/   r1   r2   r&     s   
zDbrxFFN.__init__rB   rS   c                 C   s(   |  |\}}}| ||||}||fS rF   )r   r   )r-   rB   r   r   r   r   r1   r1   r2   rE     s   zDbrxFFN.forward)
rG   rH   rI   r   r&   r*   r   r   rE   rJ   r1   r1   r/   r2   r     s    (r   c                !       s$  e Zd Z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 deej	 dedeeej eejeej f eejee
 f eejeej ee
 f eejeej eej f eejee
 eej f eejeej ee
 eej f f fddZ  ZS )	DbrxBlockrp   rq   c                    s>   t    |j| _|j| _|| _t||d| _t|d| _	d S )Nr   rp   )
r%   r&   rt   ru   r   rq   r   norm_attn_normr   ffnr   r/   r1   r2   r&     s   
zDbrxBlock.__init__NFrQ   r]   rC   r   r   output_router_logitsr   r   r   rS   c	              
   K   s   | j d|||||||d|	\}
}}}| |\}}tjj|| j| jd}|
| }|f}|r4||f7 }|r;||f7 }|rB||f7 }|S )a  Forward function for DbrxBlock.

        Args:
            hidden_states (`torch.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            position_ids (`torch.LongTensor`): position ids of shape `(batch, seq_len)`
            attention_mask (`torch.Tensor`, *optional*): attention mask of size (batch_size, sequence_length)
                if flash attention is used or (batch_size, 1, query_sequence_length, key_sequence_length)
                if default attention is used.
            past_key_value (`Tuple(torch.Tensor)`, *optional*): cached past key and value projection states
            output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all
                attention layers. See `attentions` under returned tensors for more detail.
            output_router_logits (`bool`, *optional*): Whether or not to return the router logits.
            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`, *optional*): position ids of the cache
        r   r   Nr1   )r   r   r   rd   r   r   r   )r-   rQ   r]   rC   r   r   r   r   r   r   Zresid_statesZself_attn_weightsZpresent_key_valuerouter_logitsoutputsr1   r1   r2   rE     s,   &


zDbrxBlock.forward)NNNFFFN)rG   rH   rI   r   r   r&   r*   r   r   r   r	   r   r   r   r   rE   rJ   r1   r1   r/   r2   r     sN    	
 r   c                   @   sH   e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdejfddZd	S )
DbrxPreTrainedModeltransformerTr   past_key_valuesFmodulec                 C   s  | j j}t|tjr"|jjjd|d |jd ur |jj	  d S d S t|tj
rC|jjjd|d |jd urA|jj|j 	  d S d S t|tjr_|jjd |jd ur]|jj	  d S d S t|tr|jjjd|d |jjjd|d |jjjd|d d S d S )Nr^   )rh   stdr   )rp   Zinitializer_ranger<   r   r~   weightdataZnormal_rs   Zzero_	Embeddingpadding_idxr   Zfill_r   r   r   r   )r-   r   r   r1   r1   r2   _init_weights/  s*   



z!DbrxPreTrainedModel._init_weightsN)rG   rH   rI   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_supports_quantized_cacheZ_supports_static_cacher   Moduler   r1   r1   r1   r2   r   "  s    r   c                       s6  e Zd ZdZdef fddZdejfddZdejfd	d
Z	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 dee deej deeef fddZ	d%deejdf 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  ZS )&	DbrxModela  Transformer decoder consisting of *config.num_hidden_layers*. Each layer is a [`DbrxBlock`] layer.

    Args:
        config ([`DbrxConfig`]): Model configuration class with all parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
    rp   c                    s~   t     j| _ j| _ j| _t j j| j| _	t
 fddt jD | _tj jdd| _d| _|   d S )Nc                    s   g | ]}t  |qS r1   )r   )r_   rq   r   r1   r2   ra   T  rb   z&DbrxModel.__init__.<locals>.<listcomp>Frr   )r%   r&   Zpad_token_idr   
vocab_size	emb_pdropr   r   rt   wteZ
ModuleListr   Zn_layersblocksr   norm_fgradient_checkpointing	post_initr-   rp   r/   r   r2   r&   M  s    zDbrxModel.__init__rS   c                 C      | j S rF   r  r-   r1   r1   r2   get_input_embeddings[     zDbrxModel.get_input_embeddingsvaluec                 C   
   || _ d S rF   r
  r-   r  r1   r1   r2   set_input_embeddings^     
zDbrxModel.set_input_embeddingsN	input_idsr]   rC   r   inputs_embedsr   r   output_hidden_statesr   return_dictr   c                 K   s  |d ur|n| j j}|d ur|n| j j}|	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rM| jrM|rMt	
d d}|d u rV| |}tjj|| j| jd}d}|r~t|ts~d}|d u rtt }n
t|}t	
d |d u r|d ur| nd}tj|||jd  |jd	}|d u r|d}| |||||}|}|rd
nd }|rd
nd }|	rd
nd }d }| jD ]L}|r||f7 }| jr| jr| |j||||||	||	}n|||||||	||d}|d }|r||rdnd }|r||d f7 }|	r||d f7 }q| |}|r||f7 }|r$|nd }|r-| }|
s>t dd |||||fD S 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`.Fr   TzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r   r   r.   r1   )r]   rC   r   r   r   r   r   r   r3   c                 s   s    | ]	}|d ur|V  qd S rF   r1   )r_   vr1   r1   r2   	<genexpr>  s    z$DbrxModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   rQ   
attentionsr   )"rp   r   r  r   r   use_return_dictr   r  r   rw   rx   r  r   rd   r   r  r<   r	   r
   Zfrom_legacy_cacheget_seq_lengthr*   r+   r:   r.   rM   _update_causal_maskr  Z_gradient_checkpointing_func__call__r  Zto_legacy_cacherc   r   )r-   r  r]   rC   r   r  r   r   r  r   r  r   r   Zreturn_legacy_cachepast_seen_tokensr   rQ   Zall_hidden_statesZall_self_attnsZall_router_logitsZnext_decoder_cacheblockZblock_outputsZ
next_cacher1   r1   r2   rE   a  s   







zDbrxModel.forwardFr   input_tensorc                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )Nr   r^   Zflex_attentionr   Fr   )r  Zpast_key_values_lengthZis_trainingr   r3   )rm   target_lengthr!   r   rl   )r   ZxpuZnpu)rp   r   anyr<   r*   r   r   r  Zis_compileabler   Z_ignore_causal_mask_sdpar   r!   r:   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr.   r;   finfor   Z_unmask_unattended)r-   r]   r!  r   r   r   r  Zusing_compilable_cacher!   rm   r"  r   	min_dtyper1   r1   r2   r    sT   




zDbrxModel._update_causal_maskrm   r"  r!   rl   c                 K   sD  | 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d|	f | ddddddf |j }
|
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.
        N   )Z
fill_valuer!   r.   r   )Zdiagonalr  r3   r   )r'   r*   r%  r   fullr.   Ztriur+   rT   r9   cloner:   r8   Zmasked_fill)r]   rm   r"  r!   r   rl   r   r   r&  Zmask_lengthZpadding_maskr1   r1   r2   r$  1  s,    $
6  z?DbrxModel._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNN)F)rG   rH   rI   r   r   r&   r   r   r  r  r   r   r*   r   r   r	   r   r   r   r   rE   r  staticmethodr   r!   r$  rJ   r1   r1   r/   r2   r   C  s    	

 
Dr   zB
    The DBRX Model transformer for causal language modeling.
    )Zcustom_introc                        s.  e Zd Zdef fddZdejfddZdejfdd	Zdej	fd
dZ
dej	fddZdefddZdefddZe													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 d ee d!eej d"eeejf deeef fd#d$Z  ZS )&DbrxForCausalLMrp   c                    s^   t  | t|| _|j| _tj|j|jdd| _|j	j
| _
|j	j| _|j	j| _|   d S r   )r%   r&   r   r   r  r   r~   ru   lm_headr   moe_loss_weightr   r[   r   num_experts_per_tokr  r  r/   r1   r2   r&   p  s   



zDbrxForCausalLM.__init__rS   c                 C   s
   | j  S rF   )r   r  r  r1   r1   r2   r  |  r  z$DbrxForCausalLM.get_input_embeddingsr  c                 C   s   | j | d S rF   )r   r  r  r1   r1   r2   r    s   z$DbrxForCausalLM.set_input_embeddingsc                 C   r	  rF   r,  r  r1   r1   r2   get_output_embeddings  r  z%DbrxForCausalLM.get_output_embeddingsnew_embeddingsc                 C   r  rF   r/  )r-   r1  r1   r1   r2   set_output_embeddings  r  z%DbrxForCausalLM.set_output_embeddingsdecoderc                 C   r  rF   r   )r-   r3  r1   r1   r2   set_decoder  r  zDbrxForCausalLM.set_decoderc                 C   r	  rF   r4  r  r1   r1   r2   get_decoder  r  zDbrxForCausalLM.get_decoderNr   r  r]   rC   r   r  labelsr   r   r  r   r  r   logits_to_keepc                 K   s|  |dur|n| j j}|	dur|	n| j j}	|
dur|
n| j j}
|dur$|n| j j}| j||||||||	|
||d}|d }t|trGt| dn|}| 	|dd|ddf }d}|durk| j
||fd| j ji|}d}|
rt|ru|jn|d | j| j|}|dur|dur|| j||j 7 }|s|f|dd  }|
r|f| }|dur|f| S |S t||||j|j|j|jdS )as  
        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, DbrxForCausalLM

        >> model = DbrxForCausalLM.from_pretrained("databricks/dbrx-instruct")
        >> tokenizer = AutoTokenizer.from_pretrained("databricks/dbrx-instruct")

        >> prompt = "Hey, are you conscious? Can you talk to me?"
        >> inputs = tokenizer(prompt, return_tensors="pt")

        >> # Generate
        >> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```
        N)r  r]   rC   r   r  r   r   r  r   r  r   r   r  r3   r   )lossaux_losslogitsr   rQ   r  r   )rp   r   r  r   r  r   r<   r   slicer,  Zloss_functionr  rn   r   r[   r.  r-  r8   r.   r   r   rQ   r  )r-   r  r]   rC   r   r  r7  r   r   r  r   r  r   r8  r   r   rQ   Zslice_indicesr;  r9  r:  outputr1   r1   r2   rE     sp   )
zDbrxForCausalLM.forward)NNNNNNNNNNNNr   )rG   rH   rI   r   r&   r   r   r  r  r~   r0  r2  r   r5  r6  r   r   r*   r   r   r	   r   r   r   r   r   rE   rJ   r1   r1   r/   r2   r+  j  sf    	

r+  )r+  r   r   )Nr   )@r   r   typingr   r   r   r   r*   Ztorch.utils.checkpointr   Zactivationsr   Zcache_utilsr	   r
   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   Zmodeling_utilsr   utilsr   r   r   Zconfiguration_dbrxr   Z!torch.nn.attention.flex_attentionr   Zintegrations.flex_attentionr   r   Z
get_loggerrG   rw   r   r   rL   rP   r   r   rY   rn   ro   r   r   r   r   r   r   r   r   r   r   r   r+  __all__r1   r1   r1   r2   <module>   sz   


Pix`.'6P   ( 