o
    wi5                     @   s   d dl Z d dl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 d dlmZmZmZ d dlmZ d dlmZmZmZ e d	Zd
gZG dd deZdS )    N)AnyListOptional)	PeftModel)batch)Tensor)	AutoModelAutoModelForCausalLMAutoTokenizer)ITritonDeployable)broadcast_listcast_outputstr_ndarray2listNeMotext-generationc                   @   s   e Zd ZdZ									ddee dee dee d	ee d
ee dee fddZdddZ	de
dee fddZdd Zedd Zedd ZedejfddZdS )HuggingFaceLLMDeployay  A Triton inference server compatible wrapper for HuggingFace models.

    This class provides a standardized interface for deploying HuggingFace models
    in Triton inference server. It supports various NLP tasks and handles model
    loading, inference, and deployment configurations.

    Args:
        hf_model_id_path (Optional[str]): Path to the HuggingFace model or model identifier.
            Can be a local path or a model ID from HuggingFace Hub.
        hf_peft_model_id_path (Optional[str]): Path to the PEFT model or model identifier.
            Can be a local path or a model ID from HuggingFace Hub.
        tokenizer_id_path (Optional[str]): Path to the tokenizer or tokenizer identifier.
            If None, will use the same path as hf_model_id_path.
        model (Optional[AutoModel]): Pre-loaded HuggingFace model.
        tokenizer (Optional[AutoTokenizer]): Pre-loaded HuggingFace tokenizer.
        tokenizer_padding (bool): Whether to enable padding in tokenizer. Defaults to True.
        tokenizer_truncation (bool): Whether to enable truncation in tokenizer. Defaults to True.
        tokenizer_padding_side (str): Which side to pad on ('left' or 'right'). Defaults to 'left'.
        task (str): HuggingFace task type (e.g., "text-generation"). Defaults to "text-generation".
        **hf_kwargs: Additional keyword arguments to pass to HuggingFace model loading.
    NTleftr   hf_model_id_pathhf_peft_model_id_pathtokenizer_id_pathmodel	tokenizertaskc
                 K   s   |d u r|d u rt d|d ur|d urtd |	tv s$J d|	|| _|| _|	| _|| _|| _	|| _
|| _|| _|d u rD|| _n|| _|d u rU| jdi |
 d S d S )Nz6hf_model_id_path or model parameters has to be passed.zahf_model_id_path will be ignored and the HuggingFace model set with model parameter will be used.zTask {0} is not a support task. )
ValueErrorLOGGERwarningSUPPORTED_TASKSformatr   r   r   r   r   tokenizer_paddingtokenizer_truncationtokenizer_padding_sider   _load)selfr   r   r   r   r   r   r    r!   r   	hf_kwargsr   r   Z/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/nemo/deploy/nlp/hf_deployable.py__init__9   s*   zHuggingFaceLLMDeploy.__init__returnc                 K   s   | j dus	J d| j dkr(tj| jfi || _| jdur't| j| j| _ntd| j | j	  t
j| j|dd| j| j| jd| _| jjdu rV| jj| j_dS dS )aV  
        Load the HuggingFace pipeline with the specified model and task.

        This method initializes the HuggingFace AutoModel classes using the provided model
        configuration and task type. It handles the model and tokenizer loading
        process.

        Raises:
            AssertionError: If task is not specified.
        Nz/A task has to be given for the generation task.r   zTask {0} is not supported.trust_remote_codeF)r(   padding
truncationpadding_side)r   r	   from_pretrainedr   r   r   r   r   r   cudar
   r   popr   r    r!   r   	pad_token	eos_token)r#   r$   r   r   r%   r"   `   s$   



zHuggingFaceLLMDeploy._loadkwargsc                 K   s  | j std| j|d d| j| jd}i ||}|d | D ]\}}t|r2|	 ||< q#t
  | j jdi |}W d   n1 sKw   Y  |dd}|r~d| jj|d	 d
di}|ddrp|d |d< |ddr||d |d< |S | jj|d
d}|S )a  Generate text based on the provided input prompts.

        This method processes input prompts through the loaded pipeline and
        generates text according to the specified parameters.

        Args:
            **kwargs: Generation parameters including:
                - text_inputs: List of input prompts
                - max_length: Maximum number of tokens to generate
                - num_return_sequences: Number of sequences to generate per prompt
                - temperature: Sampling temperature
                - top_k: Number of highest probability tokens to consider
                - top_p: Cumulative probability threshold for token sampling
                - do_sample: Whether to use sampling
                - return_full_text: Whether to return full text or only generated part

        Returns:
            If output logits and output scores are False:
            List[str]: A list of generated texts, one for each input prompt.
            If output logits and output scores are True:
            Dict: A dictionary containing:
                - sentences: List of generated texts
                - logits: List of logits
                - scores: List of scores

        Raises:
            RuntimeError: If the pipeline is not initialized.
        zModel is not initializedtext_inputspt)return_tensorsr)   r*   Nreturn_dict_in_generateF	sentences	sequencesT)skip_special_tokensoutput_logitslogitsoutput_scoresscoresr   )r   RuntimeErrorr   r   r    r.   itemstorch	is_tensorr-   no_gradgenerategetbatch_decode)r#   r1   inputskeyvalgenerated_idsr5   outputr   r   r%   rB      s6   !


zHuggingFaceLLMDeploy.generatec           
      C   s   	 t jdt jdd}t jj|dd |dkrAtdgdd}tdgdd\}}}}}}d	}	|s0|r2d}	| j|d|||||||	d
	 ndS q)zD
        Generate function for ranks other than the rank 0.
        T   r-   dtypedevicer   srcNdatarO   F	r2   	do_sampletop_ktop_ptemperaturemax_new_tokensr9   r;   r5   )r?   emptylongdistributed	broadcastr   rB   )
r#   messagepromptsrV   rT   rU   num_tokens_to_generater9   r;   r5   r   r   r%   generate_other_ranks   s0   z)HuggingFaceLLMDeploy.generate_other_ranksc                 C   s   t ddtdt ddtjddt ddtjddt ddtjddt d	dtjddt d
dtjddt ddtjddt ddtjddt ddtjddt ddtjddf
}|S )Nr]   nameshaperL   
max_lengthT)rc   rd   rL   optionalmax_batch_sizerT   rU   rV   random_seedr9   r;   )r   bytesnpint_singlebool_)r#   rE   r   r   r%   get_triton_input   s   z%HuggingFaceLLMDeploy.get_triton_inputc                 C   s,   t ddtdt ddtjdt ddtjdfS )Nr6   r`   rb   r:   r<   )r   ri   rj   rl   )r#   r   r   r%   get_triton_output   s   z&HuggingFaceLLMDeploy.get_triton_outputrE   c                 K   s  i }z<t |d}d|v r|dd d nd}td|v r(|dd d nd}d|v r8|dd d nd}d	|v rG|d	d d nd
}d|v rV|dd d nd}d|v re|dd d nd}	d}
|sm|	rod}
tj rtj dkrtjjtjdgtj	dddd t
|dd t
||||||	gdd | j|d||||||	|
d	}t|tr5dt|d tji}d| v rg }	|d D ]}t|   }t|dkr|	dg q|	| qt|	ddd|d< d| v r2g }|d D ]"}t|   }t|dkr|dg q || q t|ddd|d< W |S W |S dt|tji}W |S  tyc } zdt|}t|gtj|d< W Y d }~|S d }~ww )Nr]   rV   r   g      ?rT   rJ   rU   g        re      r9   Fr;   Tr-   rK   rN   rP   rR   r6   r<      r:   zAn error occurred: {0})r   r.   intr?   rZ   is_initializedget_world_sizer[   tensorrY   r   rB   
isinstancedictr   rj   bytes_keyscpudetachnumpylenappendarray	transpose	Exceptionr   str)r#   rE   output_inferr]   rV   rT   rU   r^   r9   r;   r5   rI   rlperrorerr_msgr   r   r%   triton_infer_fn   s   "
 z$HuggingFaceLLMDeploy.triton_infer_fn)	NNNNNTTr   r   )r'   N)__name__
__module____qualname____doc__r   r   r   r
   r&   r"   r   r   rB   r_   propertyrn   ro   r   rj   ndarrayr   r   r   r   r%   r   "   sJ    


'!
= 

r   )loggingtypingr   r   r   r|   rj   r?   peftr   pytriton.decoratorsr   pytriton.model_configr   transformersr   r	   r
   nemo.deployr   nemo.deploy.utilsr   r   r   	getLoggerr   r   r   r   r   r   r%   <module>   s   
