o
    TiS                     @   s   d dl mZmZmZ d dlZd dlmZ ddlm	Z	 ddl
mZmZ ddlT ddlT ddlT ddlmZ d	d
lmZmZ G dd deZdS )    )IterableOptionalTupleN   )
empty_from)ActivationType	DtypeEnum   )*)RaggedBatchWrapper   )PhiNonTransformerContainerPhiTransformerContainerc                   @   s  e Zd ZU dZee ed< 	 eee  ed< 	 	 e	de
fddZ	 e	de
fddZe	de
fd	d
Ze	de
fddZe	de
fddZe	de
fddZe	de
fddZe	de
fddZe	defddZe	defddZe	defddZe	defddZe	dee fddZ	 dedejfd d!Z d"e
d#ejd$ejd%ede!ejejf f
d&d'Z"d$ejd%edejfd(d)Z#d*edejfd+d,Z$d-S ).PhiInferenceModelzP
    Inference model implementation for ragged batching for Llama-2 models.
    _non_transformer_transformerreturnc                 C      | j jS N)_configmax_seq_lengthself r   j/home/ubuntu/.local/lib/python3.10/site-packages/deepspeed/inference/v2/model_implementations/phi/model.pymax_sequence_length(      z%PhiInferenceModel.max_sequence_lengthc                 C   r   r   )r   num_hidden_layersr   r   r   r   
num_layers0   r   zPhiInferenceModel.num_layersc                 C   r   r   )r   hidden_sizer   r   r   r   	model_dim4   r   zPhiInferenceModel.model_dimc                 C   r   r   )r   
vocab_sizer   r   r   r   r!   8   r   zPhiInferenceModel.vocab_sizec                 C   s   | j | j S r   )r    n_headsr   r   r   r   	head_size<   s   zPhiInferenceModel.head_sizec                 C   r   r   )r   num_attention_headsr   r   r   r   r"   @   r   zPhiInferenceModel.n_headsc                 C   r   r   )r   intermediate_sizer   r   r   r   intermediate_dimD   r   z"PhiInferenceModel.intermediate_dimc                 C   r   r   )r   num_key_value_headsr   r   r   r   
n_heads_kvH   r   zPhiInferenceModel.n_heads_kvc                 C   s0   | j jtjkr
tjS | j jtjkrtjS td)Nz Only fp16 and bf16 are supported)	r   torch_dtypetorchfloat16r   fp16bfloat16bf16NotImplementedErrorr   r   r   r   activation_dtypeL   s
   z"PhiInferenceModel.activation_dtypec                 C      t jS r   )r   GELUr   r   r   r   mlp_activation_fnU      z#PhiInferenceModel.mlp_activation_fnc                 C   r1   r   )NormTypeEnum	LayerNormr   r   r   r   	norm_typeY   r4   zPhiInferenceModel.norm_typec                 C   r1   r   )PositionalEmbeddingTyperotate_halfr   r   r   r   positional_embedding_type]   r4   z+PhiInferenceModel.positional_embedding_typec                 C   s"   t | jj| j }t|| jjdS )N)
rotate_dim
theta_base)intr   partial_rotary_factorr#   RotateHalfConfig
rope_theta)r   
rotary_dimr   r   r   positional_embedding_configa   s   z-PhiInferenceModel.positional_embedding_configragged_batchc                 C   s<   |  || jj}|jd | jkrtd|j d| j |S )z
        Performs the embedding lookup prior to running the transformer of the model.

        Arguments:
            ragged_batch (RaggedBatchWrapper): The batch to embed.

        Returns:
            torch.Tensor: The embedded batch.
        zEmbedding output shape z does not match model_dim )embedr   word_embshaper    
ValueError)r   rC   rE   r   r   r   _forward_embedj   s   
z PhiInferenceModel._forward_embed	layer_idxresidualhidden_statesragged_batch_infoc                 C   s   | j | }| j|}|}| j||j|jd}| |||}| j||j|j	d}	|}
| j
|
|j|jd}| j||j|jd}||	 | jdkrPtj|| jd || jd kro| j |d  }| j|||j|jd\}}||fS || ||fS )aL  
        Executes one (slightly offset) layer of the transformer. This implementation does a peak-ahead
        optimization to fuse the layer norm of the next layer into the current layer.

        Arguments:
            layer_idx (int): The index of the layer to execute.
            residual (torch.Tensor): The residual tensor from the previous layer.
            hidden_states (torch.Tensor): The hidden states from the previous layer. This is the
                hidden states after pre normalization.
            ragged_batch_info (RaggedBatchWrapper): The batch metadata.
        )br   group)beta)r   state_manager	get_cacheqkvqkv_wqkv_battnattn_out
attn_out_w
attn_out_bmlp_1mlp_1_wmlp_1_bmlp_2mlp_2_wmlp_2_badd_tp_sizedist
all_reduce_base_mp_groupr   normln_gammaln_beta)r   rJ   rK   rL   rM   
cur_paramskv_cacheattn_ln_outattn_hidden_stateattention_output
mlp_ln_outmlp_hidden_state
mlp_outputnext_paramsr   r   r   _forward_transformer_layer{   s$   



z,PhiInferenceModel._forward_transformer_layerc                 C   s   | j || jj|| jj| jj| jjd}| jdkrQt| j| j|j	d |j	d f}t| j
|j	d | jf}tj||| jd ||ddd|j	d | j |S |S )z
        Performs unembedding of the hidden states to logits. This will only sample the final
        token of each sequence.
        )biasgammarQ   r   r   rO   r	   )unembedr   word_unembed_wword_unembed_bfinal_norm_gammafinal_norm_betarb   r   _comm_logitsrG   _return_logitsr!   rc   all_gather_into_tensorre   copy_permutereshape)r   rL   rM   logitscomm_bufferfull_logitsr   r   r   _forward_unembed   s   
 $z"PhiInferenceModel._forward_unembedwrapped_batchc                 C   s`   |  |}| j|d | jd j| jd jd\}}t| jD ]}| ||||\}}q| ||S )Nr   )rt   rQ   )	rI   rf   r   rg   rh   ranger   rr   r   )r   r   rK   rL   rJ   r   r   r   forward   s   





zPhiInferenceModel.forwardN)%__name__
__module____qualname____doc__r   r   __annotations__r   r   propertyr=   r   r   r    r!   r#   r"   r&   r(   r   r0   r   r3   r5   r7   r8   r:   r?   rB   r   r*   TensorrI   r   rr   r   r   r   r   r   r   r      sV   
 
(r   )typingr   r   r   r*   deepspeed.commcommrc   	allocatorr   inference_utilsr   r    modules.configsmodules.interfacesraggedr   
containersr   r   DSTransformerModelBaser   r   r   r   r   <module>   s   