
    g              
          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 ddlmZmZmZmZmZmZ ddl m!Z!  e            rddl"m#Z#  ej$        e%          Z&dZ' G d de	j(                  Z)d Z*d;dZ+dej,        de-dej,        fdZ.dej,        de-de-deej,                 dej,        f
dZ/ G d de	j(                  Z0 G d  d!e0          Z1 G d" d#e0          Z2e0e1e2d$Z3 G d% d&e	j(                  Z4 G d' d(e	j(                  Z5 G d) d*e	j(                  Z6 G d+ d,e	j(                  Z7 G d- d.e	j(                  Z8 G d/ d0e	j(                  Z9d1Z: ed2e:           G d3 d4e                      Z;d5Z< ed2e:           G d6 d7e;                      Z= ed8e:           G d9 d:e;e                      Z>dS )<zPyTorch DBRX model.    N)AnyOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)MoeCausalLMOutputWithPastMoeModelOutputWithPast)PreTrainedModel)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )
DbrxConfig)_flash_attention_forwardr   c                   R     e Zd Zd fd	Z ej                    dd            Z xZS )DbrxRotaryEmbedding   '  Nc                 :   t                                                       || _        || _        || _        d| j        t          j        d| j        dt
          j                                                  | j        z  z  z  }| 	                    d|d           d S )N      ?r      dtypeinv_freqF)tensor
persistent)
super__init__dimmax_position_embeddingsbasetorcharangeint64floatregister_buffer)selfr)   r*   r+   devicer$   	__class__s         b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/dbrx/modeling_dbrx.pyr(   zDbrxRotaryEmbedding.__init__3   s    '>$	$)Q!5;(W(W(W(](](_(_bfbj(jklZUKKKKK    c                 "   | j                             |j                   | j         d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j
        |d          5  |                                |                                z                      dd          }t          j        ||fd	          }|                                }	|                                }
d d d            n# 1 swxY w Y   |	                    |j        
          |
                    |j        
          fS )Nr   r   mpscpuF)device_typeenabledr!   r)   r"   )r$   tor2   r/   expandshapetype
isinstancestrr,   autocast	transposecatcossinr#   )r1   xposition_idsseq_leninv_freq_expandedposition_ids_expandedr:   freqsembrF   rG   s              r4   forwardzDbrxRotaryEmbedding.forward=   s    	""" M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 vvAGv$$cff17f&;&;;;s   A>EEE)r   r   NN)__name__
__module____qualname__r(   r,   no_gradrO   __classcell__r3   s   @r4   r   r   2   sk        L L L L L L U]__< < < _< < < < <r5   r   c                     | dd| j         d         dz  f         }| d| j         d         dz  df         }t          j        | |fd          S )z*Rotates half the hidden dims of the input..Nr7   r!   r<   )r?   r,   rE   )rH   x1x2s      r4   rotate_halfrZ   P   s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r5   c                     |                     |          }|                     |          }| |z  t          |           |z  z   }||z  t          |          |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        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.
    )	unsqueezerZ   )qkrF   rG   rI   unsqueeze_dimq_embedk_embeds           r4   apply_rotary_pos_embrb   X   sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr5   hidden_statesn_repreturnc                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||z  ||          S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r?   r>   reshape)rc   rd   batchnum_key_value_headsslenhead_dims         r4   	repeat_kvrl   t   s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr5   gate_logitsnum_expertstop_kattention_maskc                    | t          | t                    st          j        d          S t          | t                    r/| d         j        t          j        fd| D             d          }t          j        j                            |d          }t          j	        ||d          \  }}t          j        j        
                    ||          }|@t          j        |                                d          }	t          j        |d          }
n.|j        \  }}|j        d         ||z  z  }|dddddddf                             |||||f                              d||                                        }t          j        |                                |z  d          t          j        |d          z  }	|ddddddf                             ||||f                              d|                                        }t          j        ||z  d          t          j        |d          z  }
t          j        |	|
                    d          z            }||z  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                 :    g | ]}|                               S  )r=   ).0
layer_gatecompute_devices     r4   
<listcomp>z,load_balancing_loss_func.<locals>.<listcomp>   s&    -j-j-jPZjmmN.K.K-j-j-jr5   r<   r7   )rA   tupler,   r%   r2   rE   r   
functionalsoftmaxtopkone_hotmeanr/   r?   r>   rg   r=   sumr\   )rm   rn   ro   rp   concatenated_gate_logitsrouting_weights_selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersexpert_attention_mask router_per_expert_attention_maskoverall_lossrw   s                    @r4   load_balancing_loss_funcr      s   6 *[%"@"@|C   +u%% s$Q.#(9-j-j-j-j^i-j-j-jpq#r#r#r h)112JPR1SSO*_eDDDA(%--.>LLK!J{'8'8':':BBB "'O!C!C!C&4&:#
O4:1=*B^_ 4AAAtT12V&
OUKXYYWR,,R	 	 "Ik&7&7&9&9<Q&QWXYYY\a\e!q]
 ]
 ]
 
 4AAAt+,V&
O[QRRWR%%R	 	) "'?=]+]cd!e!e!ehmhq,!i
 i
 i
 "
 9.1G1Q1QRS1T1TTUUL+%%r5   c                        e Zd ZdZddedee         f f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Z xZS )DbrxAttentionzMulti-head self attention.Nconfig	block_idxc                    t                                                       || _        |j        | _        |j        | _        | j        | j        z  | _        |j        | _	        || _
        |.t                              d| j        j         ddz   dz              |j        }|j        | _        |j        | _        |j        | _        | j        | j        z  | _        |j        | _        d| _        t/          j        | j        | j        d| j        z  | j        z  z   d          | _        t/          j        | j        | j        d          | _        t7          | j        | j	        | j        	          | _        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(   r   d_modelhidden_sizen_heads	num_headsrk   max_seq_lenr*   r   loggerwarning_oncer3   rQ   attn_config
attn_pdropclip_qkv
kv_n_headsri   num_key_value_groups
rope_theta	is_causalr   LinearWqkvout_projr   
rotary_emb)r1   r   r   r   r3   s       r4   r(   zDbrxAttention.__init__   sj   !>(DN:'-'9$"u!8uuuyz-.   (%0#,#.#9 $(Nd6N$N!%0Id.T5M1MPTP]1]]di
 
 
	 	$"2D4D5QQQ-M$($@
 
 
r5   Frc   rI   rp   past_key_valueoutput_attentions	use_cachecache_positionkwargsre   c                    |                                 \  }	}
}|                     |          }| j        | j         nd }| j        }|                    ||          }|                    | j        | j        | j        z  | j        | j        z  gd          \  }}}|                    |	|
| j	        | j                  
                    dd          }|                    |	|
| j        | j                  
                    dd          }|                    |	|
| j        | j                  
                    dd          }|                     ||          \  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}t          || j                  }t          || j                  }t#          j        ||
                    dd                    t'          j        | j                  z  }|$|d d d d d d d |j        d         f         }||z   }t,          j                            |dt"          j        	                              |j                  }t,          j                            || j        | j        
          }t#          j        ||          }|                                 |	| j	        |
| j        fk    r9t?          d|	| j	        |
| j        f dd|                                  z             |
                    dd                                           }|!                    |	|
| j                  }| "                    |          }|sd }|||fS )Nminmaxr!   r<   r   rG   rF   r   r   r7   r)   r#   ptrainingz `attn_output` should be of size z, but is )#sizer   r   clampsplitr   ri   rk   viewr   rD   r   rb   updater   rl   r   r,   matmulmathsqrtr?   r   rz   r{   float32r=   r#   dropoutr   r   
ValueError
contiguousrg   r   )r1   rc   rI   rp   r   r   r   r   r   bszq_lenr   
qkv_statesmin_valmax_valquery_states
key_statesvalue_statesrF   rG   cache_kwargsattn_weightscausal_maskattn_outputs                           r4   rO   zDbrxAttention.forward   sv    &**,,UAYY}--
$(M$=4=..4-%%'w%??
1;1A1A (4=8(4=8
  2B 2
 2
.j, $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T_W[Wd,eel<>>#t~udm!LLLhCPTP]3^hhh*k&&((**+  
 "++Aq11<<>>!))#ud6FGGmmK00  	 LL.88r5   rP   NNFFN)rQ   rR   rS   __doc__r   r   intr(   r,   Tensor
LongTensorr
   boolr   r   rO   rU   rV   s   @r4   r   r      s        $$
 
z 
hsm 
 
 
 
 
 
J 26*."'59B9 B9|B9 &B9 !.	B9
 !B9  B9 B9 !!12B9 B9 
u|Xel3Xe_D	EB9 B9 B9 B9 B9 B9 B9 B9r5   r   c                       e Zd ZdZ f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Z x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                 b     t                      j        |i | t                       | _        d S rP   )r'   r(   r   _flash_attn_uses_top_left_mask)r1   argsr   r3   s      r4   r(   zDbrxFlashAttention2.__init__B  s9    $)&)))
 3V2W2W.W+++r5   NFrc   rp   rI   r   r   r   r   r   re   c                    t          |t                    rt          d          t                              d           d}|                                \  }	}
}|                     |          }| j        "|                    | j         | j                  }|	                    | j
        | j        | j        z  | j        | j        z  gd          \  }}}|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                     ||          \  }}t#          ||||          \  }}|&|||d}|                    ||| j        |          \  }}|                    dd          }|                    dd          }|                    dd          }| j        r| j        nd	}|j        }|t.          j        k    rt/          j                    rt/          j                    }n)t7          | j        d
          r| j        j        }n|j        }t                              dd| dz              |                    |          }|                    |          }|                    |          }tA          |||||
||| j!        | j"        	  	        }|#                    |	|
| 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!   r<   r   r   rr   _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 .)rI   r   r   use_top_left_mask)&rA   r   r   r   infor   r   r   r   r   r   ri   rk   r   r   rD   r   rb   r   r   r   r   r#   r,   r   is_autocast_enabledget_autocast_gpu_dtypehasattrr   r   r   r=   r   r   r   rg   r   r   )r1   rc   rp   rI   r   r   r   r   r   r   r   r   r   r   r   r   rF   rG   r   dropout_rateinput_dtypetarget_dtyper   r   s                           r4   rO   zDbrxFlashAttention2.forwardJ  s}    nk22 	}   	pqqq!%**,,UAYY}--
=$#))t}n$-)PPJ1;1A1A (4=8(4=8
  2B 2
 2
.j, $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J
 $--a33))!Q//
#--a33*.-@tS #(%-''(** 2$;==&?@@ 2#{B+1]L\LLLM   (??<88L#|44J'??<88L.% n"A

 

 

 "))#ud6FGGRRTTmmK00  	 LL.88r5   NNNFFN)rQ   rR   rS   r   r(   r,   r   r   r   r
   r   r   r   rO   rU   rV   s   @r4   r   r   9  s        X X X X X 6:37*."'59e9 e9|e9 !!12e9 u/0	e9
 !e9  e9 e9 !!12e9 e9 
u|Xel3XeEL>Q5RR	Se9 e9 e9 e9 e9 e9 e9 e9r5   r   c                        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Z x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.
    NFrc   rp   rI   r   r   r   r   re   c           	         |rBt                               d           t                                          |||||||          S |                                \  }}	}
|                     |          }| j        "|                    | j         | j                  }|                    | j	        | j
        | j        z  | j
        | j        z  gd          \  }}}|                    ||	| j        | j                                      dd          }|                    ||	| j
        | j                                      dd          }|                    ||	| j
        | j                                      dd          }|                     ||d           \  }}t!          ||||d           \  }}|&|||d}|                    ||| j        |          \  }}t'          || j                  }t'          || j                  }|}||d d d d d d d |j        d	         f         }|j        j        d
k    r>|<|                                }|                                }|                                }||	dk    rdnd}t2          j        j                            ||||| j        r| j        n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.rc   rp   rI   r   r   r   r   r   r!   r<   r   )rJ   r   r   cudaTFrr   )	attn_mask	dropout_pr   r7   ) r   r   r'   rO   r   r   r   r   r   r   ri   rk   r   r   rD   r   rb   r   r   rl   r   r?   r2   r@   r   r,   r   rz   scaled_dot_product_attentionr   r   r   )r1   rc   rp   rI   r   r   r   r   r   r   r   r   r   r   r   rF   rG   r   r   r   r   r3   s                        r4   rO   zDbrxSdpaAttention.forward  sR     	[   77??+-)-"3#- #    &**,,UAYY}--
=$#))t}n$-)PPJ1;1A1A (4=8(4=8
  2B 2
 2
.j, $((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<t?LLS#7jRUWZ\`#a#a j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%%aaaAAA/E1A"1E/E&EFK #v--+2I'2244L#..00J'2244L (/EAIIDD5	h)FF!)-?dooC G 
 
 "++Aq11<<>>!&&sE266mmK00D.00r5   r   )rQ   rR   rS   r   r,   r   r   r   r
   r   r   rO   rU   rV   s   @r4   r   r     s          2637*."'59U1 U1|U1 !.U1 u/0	U1
 !U1  U1 U1 !!12U1 
u|Xel3XeEL>Q5RR	SU1 U1 U1 U1 U1 U1 U1 U1 U1 U1r5   r   )eagerflash_attention_2sdpac                       e Zd Zddedee         f f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Z xZS )DbrxNormAttentionNormNr   r   c                 0   t                                                       || _        |j        | _        t	          j        |j        d          | _        t          |j	                 ||          | _
        t	          j        |j        d          | _        d S )NFr   r   r   )r'   r(   r   resid_pdropr   	LayerNormr   norm_1DBRX_ATTENTION_CLASSES_attn_implementationattnnorm_2r1   r   r   r3   s      r4   r(   zDbrxNormAttentionNorm.__init__  s    "!-l6>>>>*6+FG
 
 
	 l6>>>>r5   Frc   rI   rp   r   r   r   r   r   re   c                 ^   |}	|                      |                              |j                  } | j        d|||||||d|\  }}
}t          j                            || j        | j                  }||	z   }|}	| 	                    |                              |j                  }|	||
|fS )Nr   r   rt   )
r   r=   r#   r   r   rz   r   r   r   r   )r1   rc   rI   rp   r   r   r   r   r   residual_statesr   s              r4   rO   zDbrxNormAttentionNorm.forward$  s     (M2255m6IJJ6?di 	7
')%)/)	7
 	7
 	7
 	7
3|^ --mt?OZ^Zg-hh%7'M2255m6IJJ|^KKr5   rP   r   )rQ   rR   rS   r   r   r   r(   r,   r   r   r
   r   r   r   rO   rU   rV   s   @r4   r   r     s       	? 	?z 	?hsm 	? 	? 	? 	? 	? 	? 26*."'59L L|L &L !.	L
 !L  L L !!12L L 
u|U\8EL+A8E?R	SL L L L L L L Lr5   r   c                        e Zd Zdedededee         dee         f
 fdZdej        de	ej        ej        ej
        f         fd	Z xZS )

DbrxRouterr   moe_num_experts	moe_top_kmoe_jitter_epsmoe_normalize_expert_weightsc                     t                                                       || _        || _        || _        || _        || _        t          j        | j        | j        d          | _	        d S NFr   )
r'   r(   r   r  r  r  r  r   r   layer)r1   r   r  r  r  r  r3   s         r4   r(   zDbrxRouter.__init__G  sd     	&.",,H)Yt/1EERRR


r5   rc   re   c                 D   | j         rB| j        ;|t          j        |                              d| j        z
  d| j        z             z  }|                    d|j        d                   }|                     |                              dt          j	                  }t          j
        || j        d          \  }}| j        t          j        || j        dd          nd}||z  }|                    |j                  }|                    |j                  }|||fS )Nr    r7   r   r<   T)r   r)   keepdim)r   r  r,   
empty_likeuniform_r   r?   r  r{   r   r|   r  r  normr=   r#   )r1   rc   weightstop_weightstop_expertstop_weights_scales         r4   rO   zDbrxRouter.forwardX  s&   = 	T0<U-m<<EEd))31D+D  M &**2}/B2/FGG**]++33%-3PP#(:gt~2#N#N#N [ 0< J{d&GRY]^^^^ 	
 "$55**]011!nn]%899[00r5   )rQ   rR   rS   r   r   r/   r(   r,   r   r   r   rO   rU   rV   s   @r4   r   r   F  s        SS S 	S
 !S '/uoS S S S S S"1U\ 1eEL%,X]Xh<h6i 1 1 1 1 1 1 1 1r5   r   c            
       ~     e Zd Zdedededef fdZdej        dej        dej        d	ej        d
ej        f
dZ xZ	S )DbrxExpertGLUr   ffn_hidden_sizer  
ffn_act_fnc                    t                                                       || _        || _        || _        t          j        t          j        ||z  |                    | _	        t          j        t          j        ||z  |                    | _
        t          j        t          j        ||z  |                    | _        |                    dd          }t          |         | _        d S )Nnamesilu)r'   r(   r   r  r  r   	Parameterr,   emptyw1v1w2getr	   activation_fn)r1   r   r  r  r  act_fn_namer3   s         r4   r(   zDbrxExpertGLU.__init__n  s    &..,u{?_+LkZZ[[,u{?_+LkZZ[[,u{?_+LkZZ[[ nnVV44#K0r5   rH   	expert_w1	expert_v1	expert_w2re   c                     |                     |                                          }|                     |                                          }|                     |          }||z  }|                     |          }|S rP   )r   tr  )	r1   rH   r   r!  r"  	gate_projup_projintermediate_states	down_projs	            r4   rO   zDbrxExpertGLU.forward{  sm     HHY[[]]++	((9;;==))&&y11	''1'..y99	r5   )
rQ   rR   rS   r   dictr(   r,   r   rO   rU   rV   s   @r4   r  r  m  s        1C 1# 1PS 1ae 1 1 1 1 1 1*/,CH<\a\h	       r5   r  c            
       ~     e Zd Zdedededef fdZdej        dej        dej        d	ej        d
ej        f
dZ	 xZ
S )DbrxExpertsr   r  r  r  c                     t                                                       || _        t          ||||          | _        d S )Nr   r  r  r  )r'   r(   r  r  mlp)r1   r   r  r  r  r3   s        r4   r(   zDbrxExperts.__init__  sG    . #++!	
 
 
r5   rH   r  r  r  re   c                    |j         \  }}}|                    d|          }t          j        |          }t          j                            || j                                      ddd          }	| j	        j
                            | j	        j        | j	        j        | j	        j                                      | j        d          }
| j	        j                            | j	        j        | j	        j        | j	        j                                      | j        d          }| j	        j                            | j	        j        | j	        j        | j	        j                                      | j        d          }d |
D             }
d |D             }d	 |D             }t!          d| j                  D ]}t          j        |	|                   \  }}|j         d         dk    r1|}|}|d |f                             d|          }| 	                    ||
|         ||         ||                   |||d f         z  }|                    d||           |                    |||          }|S )
Nr7   )num_classesr!   r   r   r<   c                 :    g | ]}|                     d           S r   r<   squeeze)ru   r  s     r4   rx   z'DbrxExperts.forward.<locals>.<listcomp>  &    ===BbjjQj''===r5   c                 :    g | ]}|                     d           S r2  r3  )ru   r  s     r4   rx   z'DbrxExperts.forward.<locals>.<listcomp>  r5  r5   c                 :    g | ]}|                     d           S r2  r3  )ru   r  s     r4   rx   z'DbrxExperts.forward.<locals>.<listcomp>  r5  r5   )r?   r   r,   
zeros_liker   rz   r}   r  permuter.  r  r  r   chunkr  r  rangewhererg   
index_add_)r1   rH   r  r  r  r   r   r   outr   
w1_chunked
v1_chunked
w2_chunked
expert_idxtopk_idx	token_idx
token_list	topk_listexpert_tokens
expert_outs                       r4   rO   zDbrxExperts.forward  sk    #$'UKFF2{##q!!m++KTEY+ZZbbcdfgijkkX[%%dh&>@XZ^ZbZnoouu a v 
 

 X[%%dh&>@XZ^ZbZnoouu a v 
 

 X[%%dh&>@XZ^ZbZnoouu a v 
 

 >=*===
==*===
==*===
4#788 	5 	5J"'+k*.E"F"FHiq!Q&&"J IdJ./77KHHM
:(>
:@VXbcmXnooj)T9:; 
 NN1i4444kk#uk22
r5   )rQ   rR   rS   r   r)  r(   r,   r   r   rO   rU   rV   s   @r4   r+  r+    s        
C 
# 
PS 
ae 
 
 
 
 
 
&&(-&CH<&^c^n&	& & & & & & & &r5   r+  c                   b     e Zd Zdef fdZdej        deej        ej        f         fdZ xZ	S )DbrxFFNr   c                    t                                                       |j        }t          |j        |j        |j        |j        |j                  | _	        t          |j        |j        |j        |j                  | _        d S )N)r   r  r  r  r  r-  )r'   r(   
ffn_configr   r   r  r  r  r  routerr+  r  r  experts)r1   r   rL  r3   s      r4   r(   zDbrxFFN.__init__  s    &
 &6 *%4)3)P
 
 
 #&6&6!,	
 
 
r5   rH   re   c                 l    |                      |          \  }}}|                     ||||          }||fS rP   )rM  rN  )r1   rH   r  r  r  r>  s         r4   rO   zDbrxFFN.forward  s9    ,0KKNN)kll1g{K@@G|r5   )
rQ   rR   rS   r   r(   r,   r   r   rO   rU   rV   s   @r4   rJ  rJ    sv        
z 
 
 
 
 
 
& %el0J*K        r5   rJ  c            !       x    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej        deej                 d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Z xZS )	DbrxBlockr   r   c                     t                                                       |j        | _        |j        | _        || _        t          ||          | _        t          |          | _	        d S )Nr   )r   )
r'   r(   r   r   r   r   r   norm_attn_normrJ  ffnr   s      r4   r(   zDbrxBlock.__init__  sj    !>!-"3
 
 
 &)))r5   NFrc   rp   rI   r   r   output_router_logitsr   r   r   re   c	                     | j         d|||||||d|	\  }
}}}|                     |          \  }}t          j                            || j        | j                  }|
|z   }|f}|r||fz  }|r||fz  }|r||fz  }|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   rt   )rS  rT  r   rz   r   r   r   )r1   rc   rp   rI   r   r   rU  r   r   r   resid_statesself_attn_weightspresent_key_valuerouter_logitsoutputss                  r4   rO   zDbrxBlock.forward  s    L M`DL_ 	M
')%)/)	M
 	M
 	M
 	M
Im%68I (,xx'>'>$}--mt?OZ^Zg-hh$}4 " 	,)++G 	,)++G 	(''Gr5   )NNNFFFN)rQ   rR   rS   r   r   r(   r,   r   r   r   r
   r   r   r   r   rO   rU   rV   s   @r4   rQ  rQ    s       	*z 	*c 	* 	* 	* 	* 	* 	* 26)-*.,1/4$)59A A|A !.A &	A
 !A $D>A 'tnA D>A !!12A A 
elelHU\223elHUO+,elHU\2HUOCDelHU\2HU\4JJKelHUOXel-CCDelHU\2HUOXelE[[\	^
A A A A A A A Ar5   rQ  aI  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`DbrxConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zRThe bare DBRX Model outputting raw hidden-states without any specific head on top.c                   P    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ZdS )DbrxPreTrainedModeltransformerTrQ  past_key_valuesmodulec                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rU|j        j                            d|           |j        +|j        j        |j                 	                                 d S d S t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t                    re|j        j                            d|           |j        j                            d|           |j        j                            d|           d S d S )Nrr   )r~   std)r   initializer_rangerA   r   r   weightdatanormal_r   zero_	Embeddingpadding_idxr   r  r  r  r  )r1   r`  rb  s      r4   _init_weightsz!DbrxPreTrainedModel._init_weightsE  s   k+fbi(( 	6M&&CS&999{& &&((((( '&-- 	6M&&CS&999!-"6#56<<>>>>> .--- 	6M&&CS&999{& &&((((( '&.. 	6IN"""555IN"""555IN"""55555	6 	6r5   N)rQ   rR   rS   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cacher   Modulerj  rt   r5   r4   r]  r]  5  sr        
 L%&*#$#4"5!N  $!6BI 6 6 6 6 6 6r5   r]  a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        output_router_logits (`bool`, *optional*):
            Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
            should not be returned during inference.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                   "    e Zd ZdZdef fdZdej        fdZdej        f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         dee         deej                 deeef         fd            Zd
ej        dej        dej        dedef
dZed
ej        dededej        dej        dej        defd            Z x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.
    r   c                    t                                                     j        | _        j        | _        j        | _        t          j        j        j        | j                  | _	        t          j
        fdt          j                  D                       | _        t          j        j        d          | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S rt   )rQ  )ru   r   r   s     r4   rx   z&DbrxModel.__init__.<locals>.<listcomp>  s#    $j$j$jiYvy%A%A$j$j$jr5   Fr   )r'   r(   pad_token_idri  
vocab_size	emb_pdropr   rh  r   wte
ModuleListr;  n_layersblocksr   norm_fgradient_checkpointing	post_initr1   r   r3   s    `r4   r(   zDbrxModel.__init__  s       !. +)< 16>4CSTTm$j$j$j$jSXY_YhSiSi$j$j$jkkl6>>>>&+# 	r5   re   c                     | j         S rP   r}  r1   s    r4   get_input_embeddingszDbrxModel.get_input_embeddings  s	    xr5   valuec                     || _         d S rP   r  r1   r  s     r4   set_input_embeddingszDbrxModel.set_input_embeddings  s    r5   N	input_idsrp   rI   r_  inputs_embedsr   r   output_hidden_statesrU  return_dictr   c                 b   ||n| j         j        }||n| j         j        }|	|	n| j         j        }	||n| j         j        }|
|
n| j         j        }
|d u |d uz  rt          d          | j        r%| j        r|rt          
                    d           d}||                     |          }t          j                            || j        | j                  }d}|rVt!          |t"                    sAd}|t%                      }n.t%          j        |          }t          
                    d           |B||                                nd}t+          j        |||j        d         z   |j        	          }||                    d          }|                     |||||          }|}|rd
nd }|rd
nd }|	rd
nd }d }| j        D ]}|r||fz  }| j        r*| j        r#|                     |j        ||||||	||	  	        }n |||||||	||          }|d         }|r||rdnd         }|r||d         fz  }|	r||d         fz  }|                     |          }|r||fz  }|r|nd }|r|                                }|
stA          d |||||fD                       S tC          |||||          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   r2   rt   )rp   rI   r   r   rU  r   r   r!   r7   c              3      K   | ]}||V  	d S rP   rt   )ru   vs     r4   	<genexpr>z$DbrxModel.forward.<locals>.<genexpr>E  s0        =  === r5   )last_hidden_stater_  rc   
attentionsrZ  )"r   r   r  rU  r   use_return_dictr   r  r   r   r   r}  r   rz   r   r|  rA   r
   r   from_legacy_cacheget_seq_lengthr,   r-   r?   r2   r\   _update_causal_maskr  _gradient_checkpointing_func__call__r  to_legacy_cachery   r   )r1   r  rp   rI   r_  r  r   r   r  rU  r  r   return_legacy_cachepast_seen_tokensr   rc   all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cacheblockblock_outputs
next_caches                          r4   rO   zDbrxModel.forward  s    2C1N--TXT_Tq$8$D  $+Jj 	 %9$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	4= 	Y 	j   I  HHY//M--mt~X\Xe-ff $ 
	Z?? 
	"&&"..."."@"Q"Q##^   !CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 

 & #7@BBD0:d"6@BBD![ %	: %	:E# 6!m%55!* t}  $ A AN! #%("
! 
! !&!#.!-#2&7)='#1	! 	! 	! *!,M R%28I3P11q%Q"  6=#3"55# :!mB&7%99!M22   	2-!11+4>''$
 	6#3355J 	  '5FXij     
 &+&+%+
 
 
 	
r5   input_tensorc           
         | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }| j         j        dk    r#|s!|st          j        |||| j                  rd S |j        |j	        }	}|j
        d         }
|r|                                }n/t          |t          j                  r|j
        d         n||
z   dz   }|                     ||
|||	||j
        d                   }| j         j        dk    rB|@|j	        j        d	k    r0|s.t          j        |          j        }t          j        ||          }|S )
Nr   rr   r   r   )r  past_key_values_lengthis_trainingr   r7   )r   target_lengthr#   r2   r   r   r   )r   r   r  rA   r   r   _ignore_causal_mask_sdpar   r#   r2   r?   get_max_cache_shaper,   r   5_prepare_4d_causal_attention_mask_with_cache_positionr@   finfor   _unmask_unattended)r1   rp   r  r   r_  r   r  using_static_cacher#   r2   r   r  r   	min_dtypes                 r4   r  zDbrxModel._update_causal_maskS  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE ;+v55>P5Yj5%>*'7 M	    t$*L,?v&,Q/ 	+??AAMM nel;;<$R((%7!;  PP+')#)!, Q 
 
 K,66*%*f44% 5 E**.I0CKQZ[[Kr5   r   r  r#   r2   r   c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        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.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer#   r2   r   )diagonalr  r7   r   )r)   r,   r  r   fulltriur-   rg   r>   cloner?   masked_fill)rp   r   r  r#   r2   r   r   r   r   r  mask_lengthpadding_masks               r4   r  z?DbrxModel._prepare_4d_causal_attention_mask_with_cache_position  s   D %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r5   )NNNNNNNNNNN)rQ   rR   rS   r   r   r(   r   rh  r  r  r   DBRX_INPUTS_DOCSTRINGr   r,   r   r   r
   r   r   r   r   rO   r  staticmethodr   r#   r2   r  rU   rV   s   @r4   rw  rw    sd       
 z      bl    ",     +*+@AA 151537+/04$(,0/3/3&*59G
 G
E,-G
 !.G
 u/0	G

 "%G
  -G
 D>G
 $D>G
 'tnG
 'tnG
 d^G
 !!12G
 
u,,	-G
 G
 G
 BAG
T?? l? 	?
 ?  ? ? ? ?B 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r5   rw  z8The DBRX Model transformer for causal language modeling.c            !           e Zd Zdef fdZdej        fdZdej        fdZdej	        fdZ
dej	        fd	Zd
efdZdefdZ ee           e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j                 dee         dee         dee         dee         dee         deej                 dedeeef         fd                        Z xZS )DbrxForCausalLMr   c                 d   t                                          |           t          |          | _        |j        | _        t          j        |j        |j        d          | _        |j	        j
        | _
        |j	        j        | _        |j	        j        | _        |                                  d S r  )r'   r(   rw  r^  r{  r   r   r   lm_headrL  moe_loss_weightr  rn   r  num_experts_per_tokr  r  s     r4   r(   zDbrxForCausalLM.__init__  s       $V,, +y!3V5FUSSS%0@!,<#)#4#>  	r5   re   c                 4    | j                                         S rP   )r^  r  r  s    r4   r  z$DbrxForCausalLM.get_input_embeddings  s    44666r5   r  c                 :    | j                             |           d S rP   )r^  r  r  s     r4   r  z$DbrxForCausalLM.set_input_embeddings  s    --e44444r5   c                     | j         S rP   r  r  s    r4   get_output_embeddingsz%DbrxForCausalLM.get_output_embeddings  s
    |r5   new_embeddingsc                     || _         d S rP   r  )r1   r  s     r4   set_output_embeddingsz%DbrxForCausalLM.set_output_embeddings  s    %r5   decoderc                     || _         d S rP   r^  )r1   r  s     r4   set_decoderzDbrxForCausalLM.set_decoder  s    "r5   c                     | j         S rP   r  r  s    r4   get_decoderzDbrxForCausalLM.get_decoder  s    r5   )output_typerk  Nr   r  rp   rI   r_  r  labelsr   r   r  rU  r  r   num_logits_to_keepc                    ||n| j         j        }|	|	n| j         j        }	|
|
n| j         j        }
||n| j         j        }|                     ||||||||	|
||          }|d         }|                     |dd| dddf                   }d}||dddddf                                         }|dddf                                         }t          j	                    }|
                    d| j         j                  }|
                    d          }|                    |j                  } |||          }d}|
rTt          |r|j        n|d         | j        | j        |          }|'|%|| j        |                    |j                  z  z  }|s |f|dd         z   }|
r|f|z   }||f|z   n|S t'          ||||j        |j        |j        |j                  S )ai  Forward function for causal language modeling.

        Args:
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

            num_logits_to_keep (`int`, *optional*):
                Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.

        Returns:

        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  rp   rI   r_  r  r   r   r  rU  r  r   r   .r7   r   )lossaux_losslogitsr_  rc   r  rZ  )r   r   r  rU  r  r^  r  r   r   CrossEntropyLossr   r{  r=   r2   r   rZ  rn   r  r  r   r_  rc   r  )r1   r  rp   rI   r_  r  r  r   r   r  rU  r  r   r  r[  rc   r  r  shift_logitsshift_labelsloss_fctr  outputs                          r4   rO   zDbrxForCausalLM.forward  su   d 2C1N--TXT_Tq$8$D  $+Jj 	 %9$D  $+Jj 	 &1%<kk$+B] "")%+'/!5!5#) # 
 
  
mAAA0B/B/C/CQQQ,FGHH!#ssAAA+.99;;L!#qrr'?5577L*,,H',,R1GHHL',,R00L'??<+>??L8L,77D 	H/)4E%%'"+ (	 H !d&6,x{{4;/G/GGG 	DY,F# ."v-'+'7D7V##VC(#3!/)!/
 
 
 	
r5   )NNNNNNNNNNNNr   )rQ   rR   rS   r   r(   r   rh  r  r  r   r  r  rw  r  r  r   r  r   r   _CONFIG_FOR_DOCr   r,   r   r   r
   r   r   r   r   rO   rU   rV   s   @r4   r  r    sZ       
z 
 
 
 
 
 
7bl 7 7 7 75", 5 5 5 5ry    &BI & & & &#9 # # # # Y         +*+@AA+DSbccc 151537+/04-1$(,0/3/3&*59"#r
 r
E,-r
 !.r
 u/0	r

 "%r
  -r
 )*r
 D>r
 $D>r
 'tnr
 'tnr
 d^r
 !!12r
  r
 
u//	0r
 r
 r
 dc BAr
 r
 r
 r
 r
r5   r  )Nr   )?r   r   typingr   r   r   r   r,   torch.utils.checkpointr   activationsr	   cache_utilsr
   r   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   modeling_utilsr   utilsr   r   r   r   r   r   configuration_dbrxr   modeling_flash_attention_utilsr   
get_loggerrQ   r   r  ru  r   rZ   rb   r   r   rl   r   r   r   r   r   r   r   r  r+  rJ  rQ  DBRX_START_DOCSTRINGr]  r  rw  r  rt   r5   r4   <module>r     s<      . . . . . . . . . . . .            ! ! ! ! ! ! ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) ) > > > > > > Q Q Q Q Q Q Q Q - - - - - -                + * * * * *  KJJJJJJ		H	%	%< < < < <") < < <<( ( (   8	UU\ 	U# 	U%, 	U 	U 	U 	UM&M&M& M& U\*	M&
 \M& M& M& M&`f9 f9 f9 f9 f9BI f9 f9 f9Rv9 v9 v9 v9 v9- v9 v9 v9r\1 \1 \1 \1 \1 \1 \1 \1@ ,  +L +L +L +L +LBI +L +L +L\$1 $1 $1 $1 $1 $1 $1 $1N    BI   21 1 1 1 1") 1 1 1h    bi   4M M M M M	 M M M` " X 6 6 6 6 6/ 6 6	 6@K \ X ` ` ` ` `# ` `	 `F	 PRfggS
 S
 S
 S
 S
)? S
 S
 hgS
 S
 S
r5   