CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
trainer_seq2seq.cpython-310.pyc169 linesDownload Raw Back to __pycache__
1o

2.�YiQF�@s`ddlZddlmZddlmZddlmZmZmZm	Z	m3Z4ddlZddlmZddl
mZddlmZdd	lmZdd5lmZddlmZddlmZdd
lmZmZddlmZe�raddlZer�ddlmZddl m!Z!ddl"m#Z#ddl$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/m0Z0ddl1m2Z2e�3e4�Z5Gdd�de�Z6dS)�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)�TrainingArgumentscs�eZdZeddddd�												d1deed	ejfd6edded
deeeddfdeeee	e7effdeeddeegd	fdeedeedge	fdeedde
eejjeejjjfdeeejejgejff�fdd�
�Zedee8efdefdd ��Z			!d2deed"eee9d#e10de	e11eff�fd$d%�
Z		&d3d'ed"eee12d#e13dd(f�fd)d*�
Z	d4dejd+e	e14eejeffd,ed"eee15de
eeeejeejff16�fd-d.�
Zd/d0�Z�ZS)5�Seq2SeqTrainer�	tokenizer�processing_classz5.0.0T)�new_name�versionZraise_if_both_namesN�NN�modelr�argsr�
data_collatorr�
train_datasetrzdatasets.Dataset�eval_dataset)rrrr�17model_init�compute_loss_func�compute_metricsr�	callbacksr�18optimizers�preprocess_logits_for_metricsc
sNt�j|||||||||	|19||d�|jjdur%|�|jj�}
|
|j_dSdS)N)r%r&r'r(r)r!r*r+r,r-r.r/)�super�__init__r&�generation_config�load_generation_configr%)�selfr%r&r'r(r)r!r*r+r,r-r.r/�20gen_config��	__class__���E:\DocsHouse\542 percep lab latest\PerceptionLab\PerceptionLab_Portable\python_embed\Lib\site-packages\transformers/trainer_seq2seq.pyr16s$��zSeq2SeqTrainer.__init__�gen_config_arg�returnc21Cs�t|t�r22t|�}n%t|t�rt|�n|}d}|��r"|j}|j}n|��r'n|}t�	||�}z	|j23dd�W|StyL}ztt|�d��d}~ww)aW24        Loads a `~generation.GenerationConfig` from the `Seq2SeqTrainingArguments.generation_config` arguments.25 26        Args:27            gen_config_arg (`str` or [`~generation.GenerationConfig]`):28                `Seq2SeqTrainingArguments.generation_config` argument.29 30        Returns:31            A `~generation.GenerationConfig`.32        NT)�strictz'33 34Fix these issues to train your model.)�35isinstancer
r�strr�is_file�name�parent�is_dirZfrom_pretrained�validate�36ValueError)r:r5Zpretrained_model_nameZconfig_file_name�excr8r8r9r3]s$3738���z%Seq2SeqTrainer.load_generation_config�eval�ignore_keys�metric_key_prefixc�|��}|�d�dur|�d�dur|jjdur|jj|d<|�d�dur1|jjdur1|jj|d<|jj|_||_t	�j39|||d�S)a�40        Run evaluation and returns metrics.41 42        The calling script will be responsible for providing a method to compute metrics, as they are task-dependent43        (pass it to the init `compute_metrics` argument).44 45        You can also subclass and override this method to inject custom behavior.46 47        Args:48            eval_dataset (`Dataset`, *optional*):49                Pass a dataset if you wish to override `self.eval_dataset`. If it is an [`~datasets.Dataset`], columns50                not accepted by the `model.forward()` method are automatically removed. It must implement the `__len__`51                method.52            ignore_keys (`list[str]`, *optional*):53                A list of keys in the output of your model (if it is a dictionary) that should be ignored when54                gathering predictions.55            metric_key_prefix (`str`, *optional*, defaults to `"eval"`):56                An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named57                "eval_bleu" if the prefix is `"eval"` (default)58            max_length (`int`, *optional*):59                The maximum target length to use when predicting with the generate method.60            num_beams (`int`, *optional*):61                Number of beams for beam search that will be used when predicting with the generate method. 1 means no62                beam search.63            gen_kwargs:64                Additional `generate` specific kwargs.65 66        Returns:67            A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The68            dictionary also contains the epoch number which comes from the training state.6970max_lengthN�max_new_tokens�	num_beams�rGrH)�copy�getr&�generation_max_length�generation_num_beams�accelerator�gather�gather_function�_gen_kwargsr0�evaluate)r4r)rGrH�71gen_kwargsr6r8r9rV�s'72zSeq2SeqTrainer.evaluate�test�test_datasetrcrI)a&73        Run prediction and returns predictions and potential metrics.74 75        Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method76        will also return metrics, like in `evaluate()`.77 78        Args:79            test_dataset (`Dataset`):80                Dataset to run the predictions on. If it is a [`~datasets.Dataset`], columns not accepted by the81                `model.forward()` method are automatically removed. Has to implement the method `__len__`82            ignore_keys (`list[str]`, *optional*):83                A list of keys in the output of your model (if it is a dictionary) that should be ignored when84                gathering predictions.85            metric_key_prefix (`str`, *optional*, defaults to `"eval"`):86                An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named87                "eval_bleu" if the prefix is `"eval"` (default)88            max_length (`int`, *optional*):89                The maximum target length to use when predicting with the generate method.90            num_beams (`int`, *optional*):91                Number of beams for beam search that will be used when predicting with the generate method. 1 means no92                beam search.93            gen_kwargs:94                Additional `generate` specific kwargs.95 96        <Tip>97 98        If your predictions or labels have different sequence lengths (for instance because you're doing dynamic99        padding in a token classification task) the predictions will be padded (on the right) to allow for100        concatenation into one array. The padding index is -100.101 102        </Tip>103 104        Returns: *NamedTuple* A namedtuple with the following keys:105 106            - predictions (`np.ndarray`): The predictions on `test_dataset`.107            - label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some).108            - metrics (`dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained109              labels).110        rJNrKrLrM)rNrOr&rPrQrRrSrTrUr0�predict)r4rYrGrHrWr6r8r9rZ�s/111zSeq2SeqTrainer.predict�inputs�prediction_loss_onlyc	s�|jjr|rt�j||||d�Sd|v}|�|�}t|�dkr)t|d�r)|j��}d|vr8|ddur8|�	d�d|vrG|ddurG|�	d�t112�pNt|j�}|�
d|�|d<|��}d|vrvd	|vrv|dj|d	jkrvd113d�|��D�}t|jt�r�t�|j�nt��}	|	�|jjdi|�|��}114Wd�n1s�wY|jjjr�d|jj_|jj}|115jd
|jkr�|�|116|j�}117n|jdur�|118jd
|jdkr�|�|119|jd�}120t���N|�r"|���|di|��}Wd�n1s�wY|jdu�r|�||d���� �}
nt|t!��r|dn|d��� �}
nd}
Wd�n	1�s/wY|jj"�r>|
ddfS|�rq|d}|jd
|jk�rV|�||j�}n|jdu�rp|jd
|jdk�rp|�||jd�}nd}|
|121|fS)a�122        Perform an evaluation step on `model` using `inputs`.123 124        Subclass and override to inject custom behavior.125 126        Args:127            model (`nn.Module`):128                The model to evaluate.129            inputs (`dict[str, Union[torch.Tensor, Any]]`):130                The inputs and targets of the model.131 132                The dictionary will be unpacked before being fed to the model. Most models expect the targets under the133                argument `labels`. Check your model's documentation for all accepted arguments.134            prediction_loss_only (`bool`):135                Whether or not to return the loss only.136            gen_kwargs:137                Additional `generate` specific kwargs.138 139        Return:140            tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and141            labels (each being optional).142        )r\rG�labelsrrUrLNrJZsynced_gpus�decoder_input_idscSsi|]\}}|dvr||�qS))r^Zdecoder_attention_maskr8)�.0�k�vr8r8r9�143<dictcomp><sz2Seq2SeqTrainer.prediction_step.<locals>.<dictcomp>F�����r�lossr8)#r&Zpredict_with_generater0�prediction_stepZ_prepare_inputs�len�hasattrrUrN�poprrr%rO�shape�itemsr=r144Zsummon_full_params�145contextlib�nullcontext�generater2Z_from_model_configrJ�_pad_tensors_to_max_lenrK�torchZno_gradZcompute_loss_context_managerZlabel_smoother�detach�mean�dictr\)r4r%r[r\rGrWZ146has_labelsZdefault_synced_gpusZgeneration_inputsZsummon_full_params_contextZgenerated_tokensr5Zoutputsrdr]r6r8r9resr�147148149150�151���152153154155�&��156157"�158zSeq2SeqTrainer.prediction_stepcCs�|jdurt|jd�r|jjdur|jjn|jj}n|jjjdur'|jjj}ntd��|tj|j	d|f|j159|jd�}||dd�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�devicerc)r!rgrsZeos_token_idr%�configrDroZonesrirtru)r4ZtensorrJrsZ
padded_tensorr8r8r9rnps���z&Seq2SeqTrainer._pad_tensors_to_max_len)NNNNNNNNNNr$N)NNrF)NrX)N) �__name__�160__module__�__qualname__rrrr	�Modulerrrr>r�list�tupleroZoptimZ	OptimizerZlr_schedulerZLambdaLRZTensorr1�staticmethodr
r3�floatrVrZr�boolrern�
__classcell__r8r8r6r9r5s���������161���162
���&-��163��164�;��165���E����166��or)7rkrNr�pathlibr�typingrrrrrror	Ztorch.distributed.fsdpr167Ztorch.utils.datarZgeneration.configuration_utilsr
Zintegrations.deepspeedrZintegrations.fsdprZtrainerr�utilsrrZutils.deprecationrZdatasetsrZdata.data_collatorrZfeature_extraction_utilsrZimage_processing_utilsrZmodeling_utilsrZprocessing_utilsrZtokenization_utils_baserZtrainer_callbackrZ
trainer_utilsrrZ
training_argsrZ168get_loggerrw�loggerrr8r8r8r9�<module>s:169