





"""simple docstring"""


# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
# and https://github.com/hojonathanho/diffusion
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from diffusers.utils import BaseOutput, deprecate



@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
class   __SCREAMING_SNAKE_CASE     (    _UpperCamelCase ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:torch.FloatTensor
  SCREAMING_SNAKE_CASE__				:Optional[torch.FloatTensor]						  =       None





def        lowercase__     (       lowercase_		,lowercase_=0.999		,lowercase_="cosine"		,)       ->		str:




      """simple docstring"""

      if alpha_transform_type == "cosine":

            def alpha_bar_fn(lowercase_      ):
                  return math.cos((t + 0.008) / 1.008 * math.pi / 2      ) ** 2

      elif alpha_transform_type == "exp":

            def alpha_bar_fn(lowercase_      ):
                  return math.exp(t * -12.0      )

      else:
            raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}'''      )

      _UpperCamelCase   :						List[Any]    =							[]
      for i in range(lowercase_      ):
            _UpperCamelCase   :						Optional[Any]    =							i / num_diffusion_timesteps
            _UpperCamelCase   :						Any    =							(i + 1) / num_diffusion_timesteps
            betas.append(min(1 - alpha_bar_fn(lowercase_      ) / alpha_bar_fn(lowercase_      )		,lowercase_      )      )
      return torch.tensor(lowercase_		,dtype=torch.floataa      )



class   __SCREAMING_SNAKE_CASE     (    _UpperCamelCase		,	_UpperCamelCase ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:int						  =       1

  @register_to_config
  def __init__(		self :							Tuple       , __a :							int = 1000       , __a :							float = 0.00_01       , __a :							float = 0.02       , __a :							str = "linear"       , __a :							Optional[Union[np.ndarray, List[float]]] = None       , __a :							bool = True       , __a :							bool = True       , __a :							int = 0       , __a :							str = "epsilon"       , __a :							float = 1.0       , **__a :							Optional[Any]       , )		->					Optional[int]:
        if kwargs.get("set_alpha_to_one"       , __a						) is not None:
              _UpperCamelCase   :						Tuple    =							(
                  "The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead."
              )
              deprecate("set_alpha_to_one"       , "1.0.0"       , __a       , standard_warn=__a						)
              _UpperCamelCase   :						Union[str, Any]    =							kwargs["set_alpha_to_one"]
        if trained_betas is not None:
              _UpperCamelCase   :						Any    =							torch.tensor(__a       , dtype=torch.floataa						)
        elif beta_schedule == "linear":
              _UpperCamelCase   :						Union[str, Any]    =							torch.linspace(__a       , __a       , __a       , dtype=torch.floataa						)
        elif beta_schedule == "scaled_linear":
              # this schedule is very specific to the latent diffusion model.
              _UpperCamelCase   :						int    =							(
                  torch.linspace(beta_start**0.5       , beta_end**0.5       , __a       , dtype=torch.floataa						) ** 2
              )
        elif beta_schedule == "squaredcos_cap_v2":
              # Glide cosine schedule
              _UpperCamelCase   :						List[str]    =							betas_for_alpha_bar(__a						)
        else:
              raise NotImplementedError(F'''{beta_schedule} does is not implemented for {self.__class__}'''						)

        _UpperCamelCase   :						str    =							1.0 - self.betas
        _UpperCamelCase   :						Optional[int]    =							torch.cumprod(self.alphas       , dim=0						)

        # At every step in inverted ddim, we are looking into the next alphas_cumprod
        # For the final step, there is no next alphas_cumprod, and the index is out of bounds
        # `set_alpha_to_zero` decides whether we set this parameter simply to zero
        # in this case, self.step() just output the predicted noise
        # or whether we use the final alpha of the "non-previous" one.
        _UpperCamelCase   :						Optional[int]    =							torch.tensor(0.0						) if set_alpha_to_zero else self.alphas_cumprod[-1]

        # standard deviation of the initial noise distribution
        _UpperCamelCase   :						List[Any]    =							1.0

        # setable values
        _UpperCamelCase   :						Union[str, Any]    =							None
        _UpperCamelCase   :						Any    =							torch.from_numpy(np.arange(0       , __a						).copy().astype(np.intaa						)						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Dict       , __a :							torch.FloatTensor       , __a :							Optional[int] = None						)		->					torch.FloatTensor:
        return sample

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[int]       , __a :							int       , __a :							Union[str, torch.device] = None						)		->					Dict:

        if num_inference_steps > self.config.num_train_timesteps:
              raise ValueError(
                  F'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:'''
                  F''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle'''
                  F''' maximal {self.config.num_train_timesteps} timesteps.'''						)

        _UpperCamelCase   :						Optional[int]    =							num_inference_steps
        _UpperCamelCase   :						Union[str, Any]    =							self.config.num_train_timesteps // self.num_inference_steps
        # creates integer timesteps by multiplying by ratio
        # casting to int to avoid issues when num_inference_step is power of 3
        _UpperCamelCase   :						int    =							(np.arange(0       , __a						) * step_ratio).round().copy().astype(np.intaa						)
        _UpperCamelCase   :						Tuple    =							torch.from_numpy(__a						).to(__a						)
        self.timesteps += self.config.steps_offset

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]       , __a :							torch.FloatTensor       , __a :							int       , __a :							torch.FloatTensor       , __a :							float = 0.0       , __a :							bool = False       , __a :							Optional[torch.FloatTensor] = None       , __a :							bool = True       , )		->					Union[DDIMSchedulerOutput, Tuple]:
        # 1. get previous step value (=t+1)
        _UpperCamelCase   :						int    =							timestep + self.config.num_train_timesteps // self.num_inference_steps

        # 2. compute alphas, betas
        # change original implementation to exactly match noise levels for analogous forward process
        _UpperCamelCase   :						int    =							self.alphas_cumprod[timestep]
        _UpperCamelCase   :						Dict    =							(
            self.alphas_cumprod[prev_timestep]
            if prev_timestep < self.config.num_train_timesteps
            else self.final_alpha_cumprod
        )

        _UpperCamelCase   :						List[str]    =							1 - alpha_prod_t

        # 3. compute predicted original sample from predicted noise also called
        # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
        if self.config.prediction_type == "epsilon":
              _UpperCamelCase   :						Any    =							(sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
              _UpperCamelCase   :						Optional[Any]    =							model_output
        elif self.config.prediction_type == "sample":
              _UpperCamelCase   :						Optional[Any]    =							model_output
              _UpperCamelCase   :						Tuple    =							(sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
        elif self.config.prediction_type == "v_prediction":
              _UpperCamelCase   :						Union[str, Any]    =							(alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
              _UpperCamelCase   :						str    =							(alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
        else:
              raise ValueError(
                  F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or'''
                  " `v_prediction`"						)

        # 4. Clip or threshold "predicted x_0"
        if self.config.clip_sample:
              _UpperCamelCase   :						List[str]    =							pred_original_sample.clamp(
                  -self.config.clip_sample_range       , self.config.clip_sample_range						)

        # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
        _UpperCamelCase   :						Any    =							(1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon

        # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
        _UpperCamelCase   :						List[Any]    =							alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction

        if not return_dict:
              return (prev_sample, pred_original_sample)
        return DDIMSchedulerOutput(prev_sample=__a       , pred_original_sample=__a						)


  def __len__(		self :							Dict						)		->					str:
        return self.config.num_train_timesteps







"""simple docstring"""


import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")

lowerCamelCase__						= logging.getLogger(__name__)



@dataclass
class   __SCREAMING_SNAKE_CASE     :







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:Optional[int]						  =       field(
      default=128		,	metadata={
          "help": (
              "The maximum total input sequence length after tokenization. Sequences longer "
              "than this will be truncated, sequences shorter will be padded."
          )
      }		,	)
  SCREAMING_SNAKE_CASE__				:bool						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Overwrite the cached preprocessed datasets or not."} )
  SCREAMING_SNAKE_CASE__				:bool						  =       field(
      default=_UpperCamelCase		,	metadata={
          "help": (
              "Whether to pad all samples to `max_seq_length`. "
              "If False, will pad the samples dynamically when batching to the maximum length in the batch."
          )
      }		,	)
  SCREAMING_SNAKE_CASE__				:Optional[int]						  =       field(
      default=_UpperCamelCase		,	metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of training examples to this "
              "value if set."
          )
      }		,	)
  SCREAMING_SNAKE_CASE__				:Optional[int]						  =       field(
      default=_UpperCamelCase		,	metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
              "value if set."
          )
      }		,	)
  SCREAMING_SNAKE_CASE__				:Optional[int]						  =       field(
      default=_UpperCamelCase		,	metadata={
          "help": (
              "For debugging purposes or quicker training, truncate the number of prediction examples to this "
              "value if set."
          )
      }		,	)





@dataclass
class   __SCREAMING_SNAKE_CASE     :







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:str						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
  SCREAMING_SNAKE_CASE__				:str						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."} )
  SCREAMING_SNAKE_CASE__				:Optional[str]						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Train language if it is different from the evaluation language."} )
  SCREAMING_SNAKE_CASE__				:Optional[str]						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Pretrained config name or path if not the same as model_name"} )
  SCREAMING_SNAKE_CASE__				:Optional[str]						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} )
  SCREAMING_SNAKE_CASE__				:Optional[str]						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}		,	)
  SCREAMING_SNAKE_CASE__				:Optional[bool]						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"}		,	)
  SCREAMING_SNAKE_CASE__				:bool						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}		,	)
  SCREAMING_SNAKE_CASE__				:str						  =       field(
      default="main"		,	metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}		,	)
  SCREAMING_SNAKE_CASE__				:bool						  =       field(
      default=_UpperCamelCase		,	metadata={
          "help": (
              "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
              "with private models)."
          )
      }		,	)
  SCREAMING_SNAKE_CASE__				:bool						  =       field(
      default=_UpperCamelCase		,	metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}		,	)





def        lowercase__     (       )       ->		Dict:




      """simple docstring"""

      _UpperCamelCase   :						Tuple    =							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )
      _UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase   :						str    =							parser.parse_args_into_dataclasses()

      # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
      # information sent is the one passed as arguments along with your Python/PyTorch versions.
      send_example_telemetry("run_xnli"		,lowercase_      )

      # Setup logging
      logging.basicConfig(
          format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"		,datefmt="%m/%d/%Y %H:%M:%S"		,handlers=[logging.StreamHandler(sys.stdout      )]		,)

      if training_args.should_log:
            # The default of training_args.log_level is passive, so we set log level at info here to have that default.
            transformers.utils.logging.set_verbosity_info()

      _UpperCamelCase   :						str    =							training_args.get_process_log_level()
      logger.setLevel(lowercase_      )
      datasets.utils.logging.set_verbosity(lowercase_      )
      transformers.utils.logging.set_verbosity(lowercase_      )
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()

      # Log on each process the small summary:
      logger.warning(
          F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
          + F'''distributed training: {bool(training_args.local_rank != -1      )}, 16-bits training: {training_args.fpaa}'''      )
      logger.info(F'''Training/evaluation parameters {training_args}'''      )

      # Detecting last checkpoint.
      _UpperCamelCase   :						Optional[Any]    =							None
      if os.path.isdir(training_args.output_dir      ) and training_args.do_train and not training_args.overwrite_output_dir:
            _UpperCamelCase   :						List[str]    =							get_last_checkpoint(training_args.output_dir      )
            if last_checkpoint is None and len(os.listdir(training_args.output_dir      )      ) > 0:
                  raise ValueError(
                      F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                      "Use --overwrite_output_dir to overcome."      )
            elif last_checkpoint is not None:
                  logger.info(
                      F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                      "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."      )

    # Set seed before initializing model.
      set_seed(training_args.seed      )

      # In distributed training, the load_dataset function guarantees that only one local process can concurrently
      # download the dataset.
      # Downloading and loading xnli dataset from the hub.
      if training_args.do_train:
            if model_args.train_language is None:
                  _UpperCamelCase   :						List[Any]    =							load_dataset(
                      "xnli"		,model_args.language		,split="train"		,cache_dir=model_args.cache_dir		,use_auth_token=True if model_args.use_auth_token else None		,)
            else:
                  _UpperCamelCase   :						Optional[int]    =							load_dataset(
                      "xnli"		,model_args.train_language		,split="train"		,cache_dir=model_args.cache_dir		,use_auth_token=True if model_args.use_auth_token else None		,)
            _UpperCamelCase   :						str    =							train_dataset.features["label"].names

      if training_args.do_eval:
            _UpperCamelCase   :						int    =							load_dataset(
                "xnli"		,model_args.language		,split="validation"		,cache_dir=model_args.cache_dir		,use_auth_token=True if model_args.use_auth_token else None		,)
            _UpperCamelCase   :						List[Any]    =							eval_dataset.features["label"].names

      if training_args.do_predict:
            _UpperCamelCase   :						int    =							load_dataset(
                "xnli"		,model_args.language		,split="test"		,cache_dir=model_args.cache_dir		,use_auth_token=True if model_args.use_auth_token else None		,)
            _UpperCamelCase   :						List[str]    =							predict_dataset.features["label"].names

      # Labels
      _UpperCamelCase   :						List[Any]    =							len(lowercase_      )

      # Load pretrained model and tokenizer
      # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.
      _UpperCamelCase   :						Any    =							AutoConfig.from_pretrained(
          model_args.config_name if model_args.config_name else model_args.model_name_or_path		,num_labels=lowercase_		,idalabel={str(lowercase_      ): label for i, label in enumerate(lowercase_      )}		,labelaid={label: i for i, label in enumerate(lowercase_      )}		,finetuning_task="xnli"		,cache_dir=model_args.cache_dir		,revision=model_args.model_revision		,use_auth_token=True if model_args.use_auth_token else None		,)
      _UpperCamelCase   :						Optional[Any]    =							AutoTokenizer.from_pretrained(
          model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path		,do_lower_case=model_args.do_lower_case		,cache_dir=model_args.cache_dir		,use_fast=model_args.use_fast_tokenizer		,revision=model_args.model_revision		,use_auth_token=True if model_args.use_auth_token else None		,)
      _UpperCamelCase   :						List[str]    =							AutoModelForSequenceClassification.from_pretrained(
          model_args.model_name_or_path		,from_tf=bool(".ckpt" in model_args.model_name_or_path      )		,config=lowercase_		,cache_dir=model_args.cache_dir		,revision=model_args.model_revision		,use_auth_token=True if model_args.use_auth_token else None		,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes		,)

      # Preprocessing the datasets
      # Padding strategy
      if data_args.pad_to_max_length:
            _UpperCamelCase   :						Any    =							"max_length"
      else:
            # We will pad later, dynamically at batch creation, to the max sequence length in each batch
            _UpperCamelCase   :						Optional[Any]    =							False

      def preprocess_function(lowercase_      ):
            # Tokenize the texts
            return tokenizer(
                examples["premise"]		,examples["hypothesis"]		,padding=lowercase_		,max_length=data_args.max_seq_length		,truncation=lowercase_		,)

      if training_args.do_train:
            if data_args.max_train_samples is not None:
                  _UpperCamelCase   :						Optional[Any]    =							min(len(lowercase_      )		,data_args.max_train_samples      )
                  _UpperCamelCase   :						Optional[Any]    =							train_dataset.select(range(lowercase_      )      )
            with training_args.main_process_first(desc="train dataset map pre-processing"      ):
                  _UpperCamelCase   :						Union[str, Any]    =							train_dataset.map(
                      lowercase_		,batched=lowercase_		,load_from_cache_file=not data_args.overwrite_cache		,desc="Running tokenizer on train dataset"		,)
            # Log a few random samples from the training set:
            for index in random.sample(range(len(lowercase_      )      )		,3      ):
                  logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.'''      )

      if training_args.do_eval:
            if data_args.max_eval_samples is not None:
                  _UpperCamelCase   :						List[Any]    =							min(len(lowercase_      )		,data_args.max_eval_samples      )
                  _UpperCamelCase   :						str    =							eval_dataset.select(range(lowercase_      )      )
            with training_args.main_process_first(desc="validation dataset map pre-processing"      ):
                  _UpperCamelCase   :						Dict    =							eval_dataset.map(
                      lowercase_		,batched=lowercase_		,load_from_cache_file=not data_args.overwrite_cache		,desc="Running tokenizer on validation dataset"		,)

      if training_args.do_predict:
            if data_args.max_predict_samples is not None:
                  _UpperCamelCase   :						Optional[int]    =							min(len(lowercase_      )		,data_args.max_predict_samples      )
                  _UpperCamelCase   :						int    =							predict_dataset.select(range(lowercase_      )      )
            with training_args.main_process_first(desc="prediction dataset map pre-processing"      ):
                  _UpperCamelCase   :						Union[str, Any]    =							predict_dataset.map(
                      lowercase_		,batched=lowercase_		,load_from_cache_file=not data_args.overwrite_cache		,desc="Running tokenizer on prediction dataset"		,)

    # Get the metric function
      _UpperCamelCase   :						Union[str, Any]    =							evaluate.load("xnli"      )

      # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
      # predictions and label_ids field) and has to return a dictionary string to float.
      def compute_metrics(lowercase_      ):
            _UpperCamelCase   :						int    =							p.predictions[0] if isinstance(p.predictions		,lowercase_      ) else p.predictions
            _UpperCamelCase   :						Union[str, Any]    =							np.argmax(lowercase_		,axis=1      )
            return metric.compute(predictions=lowercase_		,references=p.label_ids      )

      # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
      if data_args.pad_to_max_length:
            _UpperCamelCase   :						str    =							default_data_collator
      elif training_args.fpaa:
            _UpperCamelCase   :						Tuple    =							DataCollatorWithPadding(lowercase_		,pad_to_multiple_of=8      )
      else:
            _UpperCamelCase   :						List[Any]    =							None

      # Initialize our Trainer
      _UpperCamelCase   :						List[str]    =							Trainer(
          model=lowercase_		,args=lowercase_		,train_dataset=train_dataset if training_args.do_train else None		,eval_dataset=eval_dataset if training_args.do_eval else None		,compute_metrics=lowercase_		,tokenizer=lowercase_		,data_collator=lowercase_		,)

      # Training
      if training_args.do_train:
            _UpperCamelCase   :						str    =							None
            if training_args.resume_from_checkpoint is not None:
                  _UpperCamelCase   :						Optional[Any]    =							training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  _UpperCamelCase   :						Optional[Any]    =							last_checkpoint
            _UpperCamelCase   :						Optional[Any]    =							trainer.train(resume_from_checkpoint=lowercase_      )
            _UpperCamelCase   :						Tuple    =							train_result.metrics
            _UpperCamelCase   :						Optional[Any]    =							(
                data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase_      )
            )
            _UpperCamelCase   :						Tuple    =							min(lowercase_		,len(lowercase_      )      )

            trainer.save_model()  # Saves the tokenizer too for easy upload

            trainer.log_metrics("train"		,lowercase_      )
            trainer.save_metrics("train"		,lowercase_      )
            trainer.save_state()

      # Evaluation
      if training_args.do_eval:
            logger.info("*** Evaluate ***"      )
            _UpperCamelCase   :						Union[str, Any]    =							trainer.evaluate(eval_dataset=lowercase_      )

            _UpperCamelCase   :						Optional[Any]    =							data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowercase_      )
            _UpperCamelCase   :						Dict    =							min(lowercase_		,len(lowercase_      )      )

            trainer.log_metrics("eval"		,lowercase_      )
            trainer.save_metrics("eval"		,lowercase_      )

      # Prediction
      if training_args.do_predict:
            logger.info("*** Predict ***"      )
            _UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase   :						Tuple    =							trainer.predict(lowercase_		,metric_key_prefix="predict"      )

            _UpperCamelCase   :						Tuple    =							(
                data_args.max_predict_samples if data_args.max_predict_samples is not None else len(lowercase_      )
            )
            _UpperCamelCase   :						Dict    =							min(lowercase_		,len(lowercase_      )      )

            trainer.log_metrics("predict"		,lowercase_      )
            trainer.save_metrics("predict"		,lowercase_      )

            _UpperCamelCase   :						Dict    =							np.argmax(lowercase_		,axis=1      )
            _UpperCamelCase   :						List[Any]    =							os.path.join(training_args.output_dir		,"predictions.txt"      )
            if trainer.is_world_process_zero():
                  with open(lowercase_		,"w"      ) as writer:
                        writer.write("index\tprediction\n"      )
                        for index, item in enumerate(lowercase_      ):
                              _UpperCamelCase   :						int    =							label_list[item]
                              writer.write(F'''{index}\t{item}\n'''      )


if __name__ == "__main__":
  main()
