




from copy import deepcopy
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union

import torch
from torch import nn
from torch.utils.data import Dataset

from .deepspeed import is_deepspeed_zeroa_enabled
from .generation.configuration_utils import GenerationConfig
from .trainer import Trainer
from .utils import logging


if TYPE_CHECKING:
   from .data.data_collator import DataCollator
   from .modeling_utils import PreTrainedModel
   from .tokenization_utils_base import PreTrainedTokenizerBase
   from .trainer_callback import TrainerCallback
   from .trainer_utils import EvalPrediction, PredictionOutput
   from .training_args import TrainingArguments


UpperCAmelCase__    :							List[str]       		=     logging.get_logger(__name__)

class   UpperCAmelCase    (      A ):






   def __init__(						self :							str    ,       UpperCamelCase_ :							Union["PreTrainedModel", nn.Module] = None    ,       UpperCamelCase_ :							"TrainingArguments" = None    ,       UpperCamelCase_ :							Optional["DataCollator"] = None    ,       UpperCamelCase_ :							Optional[Dataset] = None    ,       UpperCamelCase_ :							Optional[Union[Dataset, Dict[str, Dataset]]] = None    ,       UpperCamelCase_ :							Optional["PreTrainedTokenizerBase"] = None    ,       UpperCamelCase_ :							Optional[Callable[[], "PreTrainedModel"]] = None    ,       UpperCamelCase_ :							Optional[Callable[["EvalPrediction"], Dict]] = None    ,       UpperCamelCase_ :							Optional[List["TrainerCallback"]] = None    ,       UpperCamelCase_ :							Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None)    ,       UpperCamelCase_ :							Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None    ,       )->      List[Any]:
     super().__init__(
         model=UpperCamelCase_    ,       args=UpperCamelCase_    ,       data_collator=UpperCamelCase_    ,       train_dataset=UpperCamelCase_    ,       eval_dataset=UpperCamelCase_    ,       tokenizer=UpperCamelCase_    ,       model_init=UpperCamelCase_    ,       compute_metrics=UpperCamelCase_    ,       callbacks=UpperCamelCase_    ,       optimizers=UpperCamelCase_    ,       preprocess_logits_for_metrics=UpperCamelCase_    ,       )

     # Override self.model.generation_config if a GenerationConfig is specified in args.
     # Priority: args.generation_config > model.generation_config > default GenerationConfig.
     if self.args.generation_config is not None:
       _lowercase:			Optional[int]      =     self.load_generation_config(self.args.generation_config  )
       _lowercase:			Any      =     gen_config






   @staticmethod
   def 			_a    (						UpperCamelCase_ :							Union[str, GenerationConfig]  )->      GenerationConfig:

     # GenerationConfig provided, nothing to do
     if isinstance(UpperCamelCase_    ,       UpperCamelCase_  ):
       return deepcopy(UpperCamelCase_  )

     # str or Path
     _lowercase:			Any      =     Path(UpperCamelCase_  ) if isinstance(UpperCamelCase_    ,       UpperCamelCase_  ) else gen_config_arg
     _lowercase:			Union[str, Any]      =     None

     # Figuring if it is path pointing to a file, pointing to a directory or else a model id or URL
     # This step is required in order to determine config_file_name
     if pretrained_model_name.is_file():
       _lowercase:			Tuple      =     pretrained_model_name.name
       _lowercase:			Any      =     pretrained_model_name.parent
     # dir path
     elif pretrained_model_name.is_dir():
       pass
     # model id or URL
     else:
       _lowercase:			int      =     gen_config_arg

     _lowercase:			Optional[Any]      =     GenerationConfig.from_pretrained(UpperCamelCase_    ,       UpperCamelCase_  )
     return gen_config






   def 			_a    (						self :							Optional[Any]    ,       UpperCamelCase_ :							Optional[Dataset] = None    ,       UpperCamelCase_ :							Optional[List[str]] = None    ,       UpperCamelCase_ :							str = "eval"    ,       **UpperCamelCase_ :							Optional[int]    ,       )->      Dict[str, float]:
     _lowercase:			int      =     gen_kwargs.copy()
     if gen_kwargs.get('max_length'  ) is None and gen_kwargs.get('max_new_tokens'  ) is None:
       _lowercase:			List[str]      =     self.args.generation_max_length
     _lowercase:			List[str]      =     (
         gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'  ) is not None else self.args.generation_num_beams
     )
     _lowercase:			Any      =     gen_kwargs

     return super().evaluate(UpperCamelCase_    ,       ignore_keys=UpperCamelCase_    ,       metric_key_prefix=UpperCamelCase_  )






   def 			_a    (						self :							List[str]    ,       UpperCamelCase_ :							Dataset    ,       UpperCamelCase_ :							Optional[List[str]] = None    ,       UpperCamelCase_ :							str = "test"    ,       **UpperCamelCase_ :							Optional[int]    ,       )->      "PredictionOutput":
     _lowercase:			str      =     gen_kwargs.copy()
     if gen_kwargs.get('max_length'  ) is None and gen_kwargs.get('max_new_tokens'  ) is None:
       _lowercase:			str      =     self.args.generation_max_length
     _lowercase:			List[str]      =     (
         gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'  ) is not None else self.args.generation_num_beams
     )
     _lowercase:			Optional[int]      =     gen_kwargs

     return super().predict(UpperCamelCase_    ,       ignore_keys=UpperCamelCase_    ,       metric_key_prefix=UpperCamelCase_  )






   def 			_a    (						self :							Union[str, Any]    ,       UpperCamelCase_ :							nn.Module    ,       UpperCamelCase_ :							Dict[str, Union[torch.Tensor, Any]]    ,       UpperCamelCase_ :							bool    ,       UpperCamelCase_ :							Optional[List[str]] = None    ,       **UpperCamelCase_ :							Union[str, Any]    ,       )->      Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:

     if not self.args.predict_with_generate or prediction_loss_only:
       return super().prediction_step(
           UpperCamelCase_    ,       UpperCamelCase_    ,       prediction_loss_only=UpperCamelCase_    ,       ignore_keys=UpperCamelCase_  )

     _lowercase:			int      =     'labels' in inputs
     _lowercase:			List[str]      =     self._prepare_inputs(UpperCamelCase_  )

     # XXX: adapt synced_gpus for fairscale as well
     # Priority (handled in generate):
     # gen_kwargs > model.generation_config > default GenerationConfig()

     if len(UpperCamelCase_  ) == 0 and hasattr(self    ,       '_gen_kwargs'  ):
       _lowercase:			Optional[Any]      =     self._gen_kwargs.copy()

     if gen_kwargs.get('max_length'  ) is None and gen_kwargs.get('max_new_tokens'  ) is None:
       _lowercase:			int      =     self.model.config.max_length
     _lowercase:			Optional[Any]      =     (
         gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'  ) is not None else self.model.config.num_beams
     )
     _lowercase:			List[Any]      =     True if is_deepspeed_zeroa_enabled() else False
     _lowercase:			Optional[int]      =     (
         gen_kwargs['synced_gpus'] if gen_kwargs.get('synced_gpus'  ) is not None else default_synced_gpus
     )

     # If the `decoder_input_ids` was created from `labels`, evict the former, so that the model can freely generate
     # (otherwise, it would continue generating from the padded `decoder_input_ids`)
     if (
         "labels" in inputs
         and "decoder_input_ids" in inputs
         and inputs["labels"].shape == inputs["decoder_input_ids"].shape
     ):
       _lowercase:			str      =     {k: v for k, v in inputs.items() if k != 'decoder_input_ids'}
     _lowercase:			Tuple      =     self.model.generate(**UpperCamelCase_    ,       **UpperCamelCase_  )

     # Temporary hack to ensure the generation config is not initialized for each iteration of the evaluation loop
     # TODO: remove this hack when the legacy code that initializes generation_config from a model config is
     # removed in https://github.com/huggingface/transformers/blob/98d88b23f54e5a23e741833f1e973fdf600cc2c5/src/transformers/generation/utils.py#L1183
     if self.model.generation_config._from_model_config:
       _lowercase:			Union[str, Any]      =     False

     # Retrieves GenerationConfig from model.generation_config
     _lowercase:			Tuple      =     self.model.generation_config
     # in case the batch is shorter than max length, the output should be padded
     if generated_tokens.shape[-1] < gen_config.max_length:
       _lowercase:			Dict      =     self._pad_tensors_to_max_len(UpperCamelCase_    ,       gen_config.max_length  )
     elif gen_config.max_new_tokens is not None and generated_tokens.shape[-1] < gen_config.max_new_tokens + 1:
       _lowercase:			str      =     self._pad_tensors_to_max_len(UpperCamelCase_    ,       gen_config.max_new_tokens + 1  )

     with torch.no_grad():
       if has_labels:
         with self.compute_loss_context_manager():
           _lowercase:			Optional[Any]      =     model(**UpperCamelCase_  )
         if self.label_smoother is not None:
           _lowercase:			int      =     self.label_smoother(UpperCamelCase_    ,       inputs['labels']  ).mean().detach()
         else:
           _lowercase:			str      =     (outputs['loss'] if isinstance(UpperCamelCase_    ,       UpperCamelCase_  ) else outputs[0]).mean().detach()
       else:
         _lowercase:			Tuple      =     None

     if self.args.prediction_loss_only:
       return loss, None, None

     if has_labels:
       _lowercase:			str      =     inputs['labels']
       if labels.shape[-1] < gen_config.max_length:
         _lowercase:			str      =     self._pad_tensors_to_max_len(UpperCamelCase_    ,       gen_config.max_length  )
       elif gen_config.max_new_tokens is not None and labels.shape[-1] < gen_config.max_new_tokens + 1:
         _lowercase:			Union[str, Any]      =     self._pad_tensors_to_max_len(UpperCamelCase_    ,       gen_config.max_new_tokens + 1  )
     else:
       _lowercase:			Optional[Any]      =     None

     return loss, generated_tokens, labels






   def 			_a    (						self :							List[str]    ,       UpperCamelCase_ :							Optional[int]    ,       UpperCamelCase_ :							Optional[int]  )->      Optional[int]:
     if self.tokenizer is not None and hasattr(self.tokenizer    ,       'pad_token_id'  ):
       # If PAD token is not defined at least EOS token has to be defined
       _lowercase:			Optional[Any]      =     (
           self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
       )
     else:
       if self.model.config.pad_token_id is not None:
         _lowercase:			List[str]      =     self.model.config.pad_token_id
       else:
         raise ValueError('Pad_token_id must be set in the configuration of the model, in order to pad tensors'  )

     _lowercase:			List[str]      =     pad_token_id * torch.ones(
         (tensor.shape[0], max_length)    ,       dtype=tensor.dtype    ,       device=tensor.device  )
     _lowercase:			Optional[Any]      =     tensor
     return padded_tensor






import argparse
import json
import logging
import os
import sys
from unittest import skip
from unittest.mock import patch

import tensorflow as tf

from transformers.testing_utils import TestCasePlus, get_gpu_count, slow


UpperCAmelCase__    :							Any       		=     [
    os.path.join(os.path.dirname(__file__), dirname)
    for dirname in [
        'text-generation',
        'text-classification',
        'token-classification',
        'language-modeling',
        'multiple-choice',
        'question-answering',
        'summarization',
        'translation',
        'image-classification',
    ]
]
sys.path.extend(SRC_DIRS)


if SRC_DIRS is not None:
   import run_clm
   import run_image_classification
   import run_mlm
   import run_ner
   import run_qa as run_squad
   import run_summarization
   import run_swag
   import run_text_classification
   import run_translation


logging.basicConfig(level=logging.DEBUG)

UpperCAmelCase__    :							Union[str, Any]       		=     logging.getLogger()


def 		_lowerCamelCase					(       )      ->		str:





  """simple docstring"""





  _lowercase:			int      =     argparse.ArgumentParser()
  parser.add_argument('-f'				)
  _lowercase:			Optional[Any]      =     parser.parse_args()
  return args.f


def 		_lowerCamelCase					(       UpperCamelCase				)      ->		Dict:





  """simple docstring"""





  _lowercase:			str      =     {}
  _lowercase:			Union[str, Any]      =     os.path.join(UpperCamelCase       ,  'all_results.json'				)
  if os.path.exists(UpperCamelCase				):
    with open(UpperCamelCase       ,  'r'				) as f:
      _lowercase:			Dict      =     json.load(UpperCamelCase				)
  else:
    raise ValueError(F'can\'t find {path}'				)
  return results


def 		_lowerCamelCase					(       )      ->		Any:





  """simple docstring"""





  return bool(tf.config.list_physical_devices('GPU'				)				)


UpperCAmelCase__    :							List[Any]       		=     logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)





class   UpperCAmelCase    (      A ):






   @skip('Skipping until shape inference for to_tf_dataset PR is merged.'  )
   def 			_a    (						self :							Union[str, Any]  )->      Optional[Any]:
     _lowercase:			List[str]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			List[str]      =     f'\n            run_text_classification.py\n            --model_name_or_path distilbert-base-uncased\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n            --do_train\n            --do_eval\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --learning_rate=1e-4\n            --max_steps=10\n            --warmup_steps=2\n            --seed=42\n            --max_seq_length=128\n            '.split()

     if is_cuda_available():
       testargs.append('--fp16'  )

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_text_classification.main()
       # Reset the mixed precision policy so we don't break other tests
       tf.keras.mixed_precision.set_global_policy('float32'  )
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['eval_accuracy']    ,       0.75  )






   def 			_a    (						self :							Optional[Any]  )->      int:
     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			str      =     f'\n            run_clm.py\n            --model_name_or_path distilgpt2\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --do_train\n            --do_eval\n            --block_size 128\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --num_train_epochs 2\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            '.split()

     if len(tf.config.list_physical_devices('GPU'  )  ) > 1:
       # Skipping because there are not enough batches to train the model + would need a drop_last to work.
       return

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_clm.main()
       _lowercase:			str      =     get_results(UpperCamelCase_  )
       self.assertLess(result['eval_perplexity']    ,       1_00  )






   def 			_a    (						self :							Union[str, Any]  )->      Optional[int]:
     _lowercase:			int      =     self.get_auto_remove_tmp_dir()
     _lowercase:			int      =     f'\n            run_mlm.py\n            --model_name_or_path distilroberta-base\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --max_seq_length 64\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --do_train\n            --do_eval\n            --prediction_loss_only\n            --num_train_epochs=1\n            --learning_rate=1e-4\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_mlm.main()
       _lowercase:			str      =     get_results(UpperCamelCase_  )
       self.assertLess(result['eval_perplexity']    ,       42  )






   def 			_a    (						self :							int  )->      Any:
     # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
     _lowercase:			List[Any]      =     7 if get_gpu_count() > 1 else 2

     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Optional[int]      =     f'\n            run_ner.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/conll/sample.json\n            --validation_file tests/fixtures/tests_samples/conll/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --do_train\n            --do_eval\n            --warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=2\n            --num_train_epochs={epochs}\n            --seed 7\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_ner.main()
       _lowercase:			Optional[Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['accuracy']    ,       0.75  )






   def 			_a    (						self :							Tuple  )->      Optional[int]:
     _lowercase:			List[Any]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			int      =     f'\n            run_qa.py\n            --model_name_or_path bert-base-uncased\n            --version_2_with_negative\n            --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=10\n            --warmup_steps=2\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_squad.main()
       _lowercase:			Union[str, Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['f1']    ,       30  )
       self.assertGreaterEqual(result['exact']    ,       30  )






   def 			_a    (						self :							List[str]  )->      Tuple:
     _lowercase:			str      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Any      =     f'\n            run_swag.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/swag/sample.json\n            --validation_file tests/fixtures/tests_samples/swag/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=20\n            --warmup_steps=2\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_swag.main()
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['val_accuracy']    ,       0.8  )






   @slow
   def 			_a    (						self :							Dict  )->      Tuple:
     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			str      =     f'\n            run_summarization.py\n            --model_name_or_path t5-small\n            --train_file tests/fixtures/tests_samples/xsum/sample.json\n            --validation_file tests/fixtures/tests_samples/xsum/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=50\n            --warmup_steps=8\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_summarization.main()
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['rouge1']    ,       10  )
       self.assertGreaterEqual(result['rouge2']    ,       2  )
       self.assertGreaterEqual(result['rougeL']    ,       7  )
       self.assertGreaterEqual(result['rougeLsum']    ,       7  )






   @slow
   def 			_a    (						self :							Tuple  )->      str:
     _lowercase:			List[Any]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			List[str]      =     f'\n            run_translation.py\n            --model_name_or_path Rocketknight1/student_marian_en_ro_6_1\n            --source_lang en\n            --target_lang ro\n            --train_file tests/fixtures/tests_samples/wmt16/sample.json\n            --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --warmup_steps=8\n            --do_train\n            --do_eval\n            --learning_rate=3e-3\n            --num_train_epochs 12\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --source_lang en_XX\n            --target_lang ro_RO\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_translation.main()
       _lowercase:			Optional[int]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['bleu']    ,       30  )






   def 			_a    (						self :							int  )->      List[Any]:
     _lowercase:			str      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Dict      =     f'\n            run_image_classification.py\n            --dataset_name hf-internal-testing/cats_vs_dogs_sample\n            --model_name_or_path microsoft/resnet-18\n            --do_train\n            --do_eval\n            --learning_rate 1e-4\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --dataloader_num_workers 16\n            --num_train_epochs 2\n            --train_val_split 0.1\n            --seed 42\n            --ignore_mismatched_sizes True\n            '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_image_classification.main()
       _lowercase:			Union[str, Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['accuracy']    ,       0.7  )
