





"""simple docstring"""




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


lowerCamelCase_					:						Dict      = logging.get_logger(__name__)

class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''

      def __init__(					self ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = (None, None) ,				snake_case_ = None ,				):

        """simple docstring"""

        super().__init__(
            model=snake_case_ ,				args=snake_case_ ,				data_collator=snake_case_ ,				train_dataset=snake_case_ ,				eval_dataset=snake_case_ ,				tokenizer=snake_case_ ,				model_init=snake_case_ ,				compute_metrics=snake_case_ ,				callbacks=snake_case_ ,				optimizers=snake_case_ ,				preprocess_logits_for_metrics=snake_case_ ,				)

        # 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:
          A_  :	str    						=  self.load_generation_config(self.args.generation_config  )
          A_  :	List[str]    						=  gen_config

      @staticmethod
      def  lowerCamelCase_      (					snake_case_  ):

        """simple docstring"""

        if isinstance(snake_case_ ,				snake_case_  ):
          return deepcopy(snake_case_  )

        # str or Path
        A_  :	Tuple    						=  Path(snake_case_  ) if isinstance(snake_case_ ,				snake_case_  ) else gen_config_arg
        A_  :	List[str]    						=  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():
          A_  :	str    						=  pretrained_model_name.name
          A_  :	str    						=  pretrained_model_name.parent
        # dir path
        elif pretrained_model_name.is_dir():
          pass
        # model id or URL
        else:
          A_  :	Optional[Any]    						=  gen_config_arg

        A_  :	Tuple    						=  GenerationConfig.from_pretrained(snake_case_ ,				snake_case_  )
        return gen_config

      def  lowerCamelCase_      (					self ,				snake_case_ = None ,				snake_case_ = None ,				snake_case_ = "eval" ,				**snake_case_ ,				):

        """simple docstring"""

        A_  :	List[str]    						=  gen_kwargs.copy()
        if gen_kwargs.get('max_length'  ) is None and gen_kwargs.get('max_new_tokens'  ) is None:
          A_  :	Dict    						=  self.args.generation_max_length
        A_  :	Optional[int]    						=  (
            gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'  ) is not None else self.args.generation_num_beams
        )
        A_  :	Tuple    						=  gen_kwargs

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

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ = None ,				snake_case_ = "test" ,				**snake_case_ ,				):

        """simple docstring"""

        A_  :	Optional[Any]    						=  gen_kwargs.copy()
        if gen_kwargs.get('max_length'  ) is None and gen_kwargs.get('max_new_tokens'  ) is None:
          A_  :	Union[str, Any]    						=  self.args.generation_max_length
        A_  :	Union[str, Any]    						=  (
            gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'  ) is not None else self.args.generation_num_beams
        )
        A_  :	int    						=  gen_kwargs

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

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_ = None ,				**snake_case_ ,				):

        """simple docstring"""

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

        A_  :	List[str]    						=  'labels' in inputs
        A_  :	List[str]    						=  self._prepare_inputs(snake_case_  )

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

        if len(snake_case_  ) == 0 and hasattr(self ,				'_gen_kwargs'  ):
          A_  :	str    						=  self._gen_kwargs.copy()

        if gen_kwargs.get('max_length'  ) is None and gen_kwargs.get('max_new_tokens'  ) is None:
          A_  :	List[str]    						=  self.model.config.max_length
        A_  :	int    						=  (
            gen_kwargs['num_beams'] if gen_kwargs.get('num_beams'  ) is not None else self.model.config.num_beams
        )
        A_  :	Union[str, Any]    						=  True if is_deepspeed_zeroa_enabled() else False
        A_  :	Union[str, Any]    						=  (
            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
        ):
          A_  :	List[str]    						=  {k: v for k, v in inputs.items() if k != 'decoder_input_ids'}
        A_  :	Tuple    						=  self.model.generate(**snake_case_ ,				**snake_case_  )

        # 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:
          A_  :	Any    						=  False

        # Retrieves GenerationConfig from model.generation_config
        A_  :	List[str]    						=  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:
          A_  :	int    						=  self._pad_tensors_to_max_len(snake_case_ ,				gen_config.max_length  )
        elif gen_config.max_new_tokens is not None and generated_tokens.shape[-1] < gen_config.max_new_tokens + 1:
          A_  :	List[Any]    						=  self._pad_tensors_to_max_len(snake_case_ ,				gen_config.max_new_tokens + 1  )

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

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

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

        return loss, generated_tokens, labels

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_  ):

        """simple docstring"""

        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
          A_  :	str    						=  (
              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:
            A_  :	Any    						=  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'  )

        A_  :	str    						=  pad_token_id * torch.ones(
            (tensor.shape[0], max_length) ,				dtype=tensor.dtype ,				device=tensor.device  )
        A_  :	int    						=  tensor
        return padded_tensor






"""simple docstring"""




from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


lowerCamelCase_					:						Union[str, Any]      = logging.get_logger(__name__)

lowerCamelCase_					:						Optional[Any]      = {
    'gpt2': 'https://huggingface.co/gpt2/resolve/main/config.json',
    'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/config.json',
    'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/config.json',
    'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/config.json',
    'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/config.json',
}

class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_				:			Optional[Any]        =       """gpt2"""
      lowercase_				:			Optional[int]        =       ["""past_key_values"""]
      lowercase_				:			Dict        =       {
          """hidden_size""": """n_embd""",
          """max_position_embeddings""": """n_positions""",
          """num_attention_heads""": """n_head""",
          """num_hidden_layers""": """n_layer""",
      }

      def __init__(					self ,				snake_case_=5_0_2_5_7 ,				snake_case_=1_0_2_4 ,				snake_case_=7_6_8 ,				snake_case_=1_2 ,				snake_case_=1_2 ,				snake_case_=None ,				snake_case_="gelu_new" ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=1E-5 ,				snake_case_=0.02 ,				snake_case_="cls_index" ,				snake_case_=True ,				snake_case_=None ,				snake_case_=True ,				snake_case_=0.1 ,				snake_case_=True ,				snake_case_=True ,				snake_case_=5_0_2_5_6 ,				snake_case_=5_0_2_5_6 ,				snake_case_=False ,				snake_case_=False ,				**snake_case_ ,				):

        """simple docstring"""

        A_  :	Union[str, Any]    						=  vocab_size
        A_  :	List[Any]    						=  n_positions
        A_  :	List[Any]    						=  n_embd
        A_  :	Tuple    						=  n_layer
        A_  :	List[Any]    						=  n_head
        A_  :	List[str]    						=  n_inner
        A_  :	str    						=  activation_function
        A_  :	Optional[Any]    						=  resid_pdrop
        A_  :	int    						=  embd_pdrop
        A_  :	Tuple    						=  attn_pdrop
        A_  :	str    						=  layer_norm_epsilon
        A_  :	Any    						=  initializer_range
        A_  :	Union[str, Any]    						=  summary_type
        A_  :	Optional[Any]    						=  summary_use_proj
        A_  :	Dict    						=  summary_activation
        A_  :	Optional[int]    						=  summary_first_dropout
        A_  :	Optional[int]    						=  summary_proj_to_labels
        A_  :	Any    						=  scale_attn_weights
        A_  :	Optional[Any]    						=  use_cache
        A_  :	Dict    						=  scale_attn_by_inverse_layer_idx
        A_  :	Any    						=  reorder_and_upcast_attn

        A_  :	Optional[Any]    						=  bos_token_id
        A_  :	List[Any]    						=  eos_token_id

        super().__init__(bos_token_id=snake_case_ ,				eos_token_id=snake_case_ ,				**snake_case_  )


class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''

      def __init__(					self ,				snake_case_ ,				snake_case_ = "default" ,				snake_case_ = None ,				snake_case_ = False ,				):

        """simple docstring"""

        super().__init__(snake_case_ ,				task=snake_case_ ,				patching_specs=snake_case_ ,				use_past=snake_case_  )
        if not getattr(self._config ,				'pad_token_id' ,				snake_case_  ):
          # TODO: how to do that better?
          A_  :	Tuple    						=  0

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Dict    						=  OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}  )
        if self.use_past:
          self.fill_with_past_key_values_(snake_case_ ,				direction='inputs'  )
          A_  :	List[str]    						=  {0: 'batch', 1: 'past_sequence + sequence'}
        else:
          A_  :	Tuple    						=  {0: 'batch', 1: 'sequence'}

        return common_inputs

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return self._config.n_layer

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return self._config.n_head

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ = -1 ,				snake_case_ = -1 ,				snake_case_ = False ,				snake_case_ = None ,				):

        """simple docstring"""

        A_  :	int    						=  super(snake_case_ ,				self  ).generate_dummy_inputs(
            snake_case_ ,				batch_size=snake_case_ ,				seq_length=snake_case_ ,				is_pair=snake_case_ ,				framework=snake_case_  )

        # We need to order the input in the way they appears in the forward()
        A_  :	Optional[Any]    						=  OrderedDict({'input_ids': common_inputs['input_ids']}  )

        # Need to add the past_keys
        if self.use_past:
          if not is_torch_available():
            raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'  )
          else:
            import torch

            A_						,	A_  :	List[str]    						=  common_inputs['input_ids'].shape
            # Not using the same length for past_key_values
            A_  :	Optional[Any]    						=  seqlen + 2
            A_  :	Any    						=  (
                batch,
                self.num_attention_heads,
                past_key_values_length,
                self._config.hidden_size // self.num_attention_heads,
            )
            A_  :	Any    						=  [
                (torch.zeros(snake_case_  ), torch.zeros(snake_case_  )) for _ in range(self.num_layers  )
            ]

        A_  :	List[Any]    						=  common_inputs['attention_mask']
        if self.use_past:
          A_  :	List[Any]    						=  ordered_inputs['attention_mask'].dtype
          A_  :	Any    						=  torch.cat(
              [ordered_inputs['attention_mask'], torch.ones(snake_case_ ,				snake_case_ ,				dtype=snake_case_  )] ,				dim=1  )

        return ordered_inputs

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        return 1_3