o
    hG                     @   sh  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	m
Z
mZ d dlZd dlmZ d dlmZ d dlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZ ddlmZ e red dlZerd dlm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3 e4e5Z6G dd deZ7dS )    N)deepcopy)Path)TYPE_CHECKINGAnyCallableOptionalUnion)nn)FullyShardedDataParallel)Dataset   )GenerationConfig)is_deepspeed_zero3_enabled)is_fsdp_managed_module)Trainer)is_datasets_availablelogging)deprecate_kwarg)IterableDataset)DataCollator)FeatureExtractionMixin)BaseImageProcessor)PreTrainedModel)ProcessorMixin)PreTrainedTokenizerBase)TrainerCallback)EvalPredictionPredictionOutput)TrainingArgumentsc                       s  e Zd Zeddddd												d1ded	ejf d
dded deeeddf  deeee	e
ef f  deed  deeg d	f  dee deedge	f  deed  deejjejjjf deeejejgejf  f fddZedee
ef defdd Z			!d2dee d"eee
  d#e
de	e
ef f fd$d%Z		&d3d'ed"eee
  d#e
dd(f fd)d*Z	d4dejd+e	e
eejef f d,ed"eee
  deee eej eej f f
 fd-d.Zd/d0 Z  ZS )5Seq2SeqTrainer	tokenizerprocessing_classz5.0.0T)new_nameversionraise_if_both_namesNNNmodelr   argsr   data_collatorr   train_datasetr   zdatasets.Dataseteval_dataset)r   r   r   r   
model_initcompute_loss_funccompute_metricsr   	callbacksr   
optimizerspreprocess_logits_for_metricsc                    sN   t  j|||||||||	|
||d | jjd ur%| | jj}|| j_d S d S )N)r&   r'   r(   r)   r*   r!   r+   r,   r-   r.   r/   r0   )super__init__r'   generation_configload_generation_configr&   )selfr&   r'   r(   r)   r*   r!   r+   r,   r-   r.   r/   r0   
gen_config	__class__ p/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/trainer_seq2seq.pyr2   7   s$   zSeq2SeqTrainer.__init__gen_config_argreturnc              
   C   s   t | tr
t| }n%t | trt| n| }d}| r"|j}|j}n| r'n| }t	||}z.t
jdd}|  W d   n1 sEw   Y  t|dkr[ttdd |D W |S  tyq } ztdt| d}~ww )aW  
        Loads a `~generation.GenerationConfig` from the `Seq2SeqTrainingArguments.generation_config` arguments.

        Args:
            gen_config_arg (`str` or [`~generation.GenerationConfig]`):
                `Seq2SeqTrainingArguments.generation_config` argument.

        Returns:
            A `~generation.GenerationConfig`.
        NT)recordr   c                 S   s   g | ]}|j qS r9   )message).0wr9   r9   r:   
<listcomp>   s    z9Seq2SeqTrainer.load_generation_config.<locals>.<listcomp>zThe loaded generation config instance is invalid -- `GenerationConfig.validate()` throws warnings and/or exceptions. Fix these issues to train your model.

Thrown during validation:
)
isinstancer   r   strr   is_filenameparentis_dirfrom_pretrainedwarningscatch_warningsvalidatelen
ValueError)r;   r6   pretrained_model_nameconfig_file_namecaught_warningsexcr9   r9   r:   r4   ^   s6   


z%Seq2SeqTrainer.load_generation_configevalignore_keysmetric_key_prefixc                       |  }|ddu r|ddu r| jjdur| jj|d< |ddu r1| jjdur1| jj|d< | jj| _|| _t	 j
|||dS )a  
        Run evaluation and returns metrics.

        The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
        (pass it to the init `compute_metrics` argument).

        You can also subclass and override this method to inject custom behavior.

        Args:
            eval_dataset (`Dataset`, *optional*):
                Pass a dataset if you wish to override `self.eval_dataset`. If it is an [`~datasets.Dataset`], columns
                not accepted by the `model.forward()` method are automatically removed. It must implement the `__len__`
                method.
            ignore_keys (`List[str]`, *optional*):
                A list of keys in the output of your model (if it is a dictionary) that should be ignored when
                gathering predictions.
            metric_key_prefix (`str`, *optional*, defaults to `"eval"`):
                An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
                "eval_bleu" if the prefix is `"eval"` (default)
            max_length (`int`, *optional*):
                The maximum target length to use when predicting with the generate method.
            num_beams (`int`, *optional*):
                Number of beams for beam search that will be used when predicting with the generate method. 1 means no
                beam search.
            gen_kwargs:
                Additional `generate` specific kwargs.

        Returns:
            A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
            dictionary also contains the epoch number which comes from the training state.
        
max_lengthNmax_new_tokens	num_beamsrS   rT   )copygetr'   generation_max_lengthgeneration_num_beamsacceleratorgathergather_function_gen_kwargsr1   evaluate)r5   r*   rS   rT   
gen_kwargsr7   r9   r:   rb      s   '
zSeq2SeqTrainer.evaluatetesttest_datasetr   c                    rU   )a&  
        Run prediction and returns predictions and potential metrics.

        Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
        will also return metrics, like in `evaluate()`.

        Args:
            test_dataset (`Dataset`):
                Dataset to run the predictions on. If it is a [`~datasets.Dataset`], columns not accepted by the
                `model.forward()` method are automatically removed. Has to implement the method `__len__`
            ignore_keys (`List[str]`, *optional*):
                A list of keys in the output of your model (if it is a dictionary) that should be ignored when
                gathering predictions.
            metric_key_prefix (`str`, *optional*, defaults to `"eval"`):
                An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
                "eval_bleu" if the prefix is `"eval"` (default)
            max_length (`int`, *optional*):
                The maximum target length to use when predicting with the generate method.
            num_beams (`int`, *optional*):
                Number of beams for beam search that will be used when predicting with the generate method. 1 means no
                beam search.
            gen_kwargs:
                Additional `generate` specific kwargs.

        <Tip>

        If your predictions or labels have different sequence lengths (for instance because you're doing dynamic
        padding in a token classification task) the predictions will be padded (on the right) to allow for
        concatenation into one array. The padding index is -100.

        </Tip>

        Returns: *NamedTuple* A namedtuple with the following keys:

            - predictions (`np.ndarray`): The predictions on `test_dataset`.
            - label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some).
            - metrics (`Dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained
              labels).
        rV   NrW   rX   rY   )rZ   r[   r'   r\   r]   r^   r_   r`   ra   r1   predict)r5   re   rS   rT   rc   r7   r9   r:   rf      s   /
zSeq2SeqTrainer.predictinputsprediction_loss_onlyc              	      s  | j jr|rt j||||dS d|v }| |}t|dkr)t| dr)| j }d|v r8|d du r8|	d d|v rG|d du rG|	d t
 pNt| j}|d||d< | }d|v rvd	|v rv|d j|d	 jkrvd
d | D }t| jtrt| jnt }	|	 | jjdi ||}
W d   n1 sw   Y  | jjjrd| jj_| jj}|
jd |jk r| |
|j}
n|jdur|
jd |jd k r| |
|jd }
t N |r"|   |di |}W d   n1 sw   Y  | jdur| ||d    }nt|t!r|d n|d    }nd}W d   n	1 s/w   Y  | j j"r>|ddfS |rq|d }|jd |jk rV| ||j}n|jdurp|jd |jd k rp| ||jd }nd}||
|fS )a  
        Perform an evaluation step on `model` using `inputs`.

        Subclass and override to inject custom behavior.

        Args:
            model (`nn.Module`):
                The model to evaluate.
            inputs (`Dict[str, Union[torch.Tensor, Any]]`):
                The inputs and targets of the model.

                The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
                argument `labels`. Check your model's documentation for all accepted arguments.
            prediction_loss_only (`bool`):
                Whether or not to return the loss only.
            gen_kwargs:
                Additional `generate` specific kwargs.

        Return:
            Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and
            labels (each being optional).
        )rh   rS   labelsr   ra   rX   NrV   synced_gpusdecoder_input_idsc                 S   s   i | ]\}}|d vr||qS ))rk   decoder_attention_maskr9   )r?   kvr9   r9   r:   
<dictcomp>B  s    z2Seq2SeqTrainer.prediction_step.<locals>.<dictcomp>Fr   lossr9   )#r'   predict_with_generater1   prediction_step_prepare_inputsrL   hasattrra   rZ   popr   r   r&   r[   shapeitemsrB   r
   summon_full_params
contextlibnullcontextgenerater3   _from_model_configrV   _pad_tensors_to_max_lenrW   torchno_gradcompute_loss_context_managerlabel_smootherdetachmeandictrh   )r5   r&   rg   rh   rS   rc   
has_labelsdefault_synced_gpusgeneration_inputssummon_full_params_contextgenerated_tokensr6   outputsrq   ri   r7   r9   r:   rs     sr   








&

"
zSeq2SeqTrainer.prediction_stepc                 C   s   | j d urt| j dr| j jd ur| j jn| j j}n| jjjd ur'| jjj}ntd|tj|j	d |f|j
|jd }||d d d |j	d f< |S )Npad_token_idzSPad_token_id must be set in the configuration of the model, in order to pad tensorsr   )dtypedevicerp   )r!   ru   r   eos_token_idr&   configrM   r   onesrw   r   r   )r5   tensorrV   r   padded_tensorr9   r9   r:   r~   v  s   z&Seq2SeqTrainer._pad_tensors_to_max_len)NNNNNNNNNNr%   N)NNrR   )Nrd   )N) __name__
__module____qualname__r   r   r	   Moduler   r   r   rC   r   listtupler   optim	Optimizerlr_schedulerLambdaLRTensorr2   staticmethodr   r4   floatrb   rf   r   boolrs   r~   __classcell__r9   r9   r7   r:   r   6   s    

&2

;
E
or   )8rz   rI   rZ   r   pathlibr   typingr   r   r   r   r   r   r	   torch.distributed.fsdpr
   torch.utils.datar   generation.configuration_utilsr   integrations.deepspeedr   integrations.fsdpr   trainerr   utilsr   r   utils.deprecationr   datasetsr   data.data_collatorr   feature_extraction_utilsr   image_processing_utilsr   modeling_utilsr   processing_utilsr   tokenization_utils_baser   trainer_callbackr   trainer_utilsr   r   training_argsr   
get_loggerr   loggerr   r9   r9   r9   r:   <module>   s<   
