





"""simple docstring"""


import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import CvtForImageClassification, CvtModel
  from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor



class   __SCREAMING_SNAKE_CASE     (    _UpperCamelCase ):







  '''simple docstring'''


  def  __SCREAMING_SNAKE_CASE					(		self :							Any						)		->					Any:
        _UpperCamelCase   :						Dict    =							self.config_class(**self.inputs_dict						)
        self.parent.assertTrue(hasattr(__a       , "embed_dim"						)						)
        self.parent.assertTrue(hasattr(__a       , "num_heads"						)						)





class   __SCREAMING_SNAKE_CASE     :







  '''simple docstring'''


  def __init__(		self :							Optional[int]       , __a :							Dict       , __a :							Optional[Any]=13       , __a :							Tuple=64       , __a :							List[Any]=3       , __a :							Any=[16, 48, 96]       , __a :							Optional[int]=[1, 3, 6]       , __a :							Union[str, Any]=[1, 2, 10]       , __a :							List[Any]=[7, 3, 3]       , __a :							Dict=[4, 2, 2]       , __a :							str=[2, 1, 1]       , __a :							Dict=[2, 2, 2]       , __a :							Optional[int]=[False, False, True]       , __a :							str=[0.0, 0.0, 0.0]       , __a :							Optional[int]=0.02       , __a :							str=1e-1_2       , __a :							Optional[Any]=True       , __a :							Any=True       , __a :							Tuple=2       , )		->					List[str]:
        _UpperCamelCase   :						str    =							parent
        _UpperCamelCase   :						Tuple    =							batch_size
        _UpperCamelCase   :						Union[str, Any]    =							image_size
        _UpperCamelCase   :						Dict    =							patch_sizes
        _UpperCamelCase   :						Union[str, Any]    =							patch_stride
        _UpperCamelCase   :						str    =							patch_padding
        _UpperCamelCase   :						Any    =							is_training
        _UpperCamelCase   :						Any    =							use_labels
        _UpperCamelCase   :						List[Any]    =							num_labels
        _UpperCamelCase   :						Optional[int]    =							num_channels
        _UpperCamelCase   :						int    =							embed_dim
        _UpperCamelCase   :						Dict    =							num_heads
        _UpperCamelCase   :						Tuple    =							stride_kv
        _UpperCamelCase   :						Tuple    =							depth
        _UpperCamelCase   :						Tuple    =							cls_token
        _UpperCamelCase   :						List[str]    =							attention_drop_rate
        _UpperCamelCase   :						Union[str, Any]    =							initializer_range
        _UpperCamelCase   :						Tuple    =							layer_norm_eps

  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]						)		->					int:
        _UpperCamelCase   :						Dict    =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

        _UpperCamelCase   :						Any    =							None
        if self.use_labels:
              _UpperCamelCase   :						Dict    =							ids_tensor([self.batch_size]       , self.num_labels						)

        _UpperCamelCase   :						Optional[Any]    =							self.get_config()
        return config, pixel_values, labels

  def  __SCREAMING_SNAKE_CASE					(		self :							Tuple						)		->					Union[str, Any]:
        return CvtConfig(
            image_size=self.image_size       , num_labels=self.num_labels       , num_channels=self.num_channels       , embed_dim=self.embed_dim       , num_heads=self.num_heads       , patch_sizes=self.patch_sizes       , patch_padding=self.patch_padding       , patch_stride=self.patch_stride       , stride_kv=self.stride_kv       , depth=self.depth       , cls_token=self.cls_token       , attention_drop_rate=self.attention_drop_rate       , initializer_range=self.initializer_range       , )

  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]       , __a :							str       , __a :							List[str]       , __a :							Union[str, Any]						)		->					Any:
        _UpperCamelCase   :						Optional[Any]    =							CvtModel(config=__a						)
        model.to(__a						)
        model.eval()
        _UpperCamelCase   :						List[Any]    =							model(__a						)
        _UpperCamelCase   :						int    =							(self.image_size, self.image_size)
        _UpperCamelCase,	_UpperCamelCase   :						int    =							image_size[0], image_size[1]
        for i in range(len(self.depth						)						):
              _UpperCamelCase   :						Union[str, Any]    =							floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1						)
              _UpperCamelCase   :						Tuple    =							floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1						)
        self.parent.assertEqual(result.last_hidden_state.shape       , (self.batch_size, self.embed_dim[-1], height, width)						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]       , __a :							Optional[int]       , __a :							int       , __a :							Tuple						)		->					List[str]:
        _UpperCamelCase   :						int    =							self.num_labels
        _UpperCamelCase   :						Optional[int]    =							CvtForImageClassification(__a						)
        model.to(__a						)
        model.eval()
        _UpperCamelCase   :						Union[str, Any]    =							model(__a       , labels=__a						)
        self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.num_labels)						)


  def  __SCREAMING_SNAKE_CASE					(		self :							str						)		->					List[str]:
        _UpperCamelCase   :						List[Any]    =							self.prepare_config_and_inputs()
        _UpperCamelCase,	_UpperCamelCase,	_UpperCamelCase   :						Tuple    =							config_and_inputs
        _UpperCamelCase   :						List[str]    =							{"pixel_values": pixel_values}
        return config, inputs_dict





@require_torch
class   __SCREAMING_SNAKE_CASE     (    _UpperCamelCase		,	_UpperCamelCase		,	unittest.TestCase ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__				:Any						  =       (CvtModel, CvtForImageClassification) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE__				:Optional[int]						  =       (
      {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE__				:str						  =       False
  SCREAMING_SNAKE_CASE__				:List[Any]						  =       False
  SCREAMING_SNAKE_CASE__				:List[Any]						  =       False
  SCREAMING_SNAKE_CASE__				:str						  =       False
  SCREAMING_SNAKE_CASE__				:List[str]						  =       False

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					Dict:
        _UpperCamelCase   :						Union[str, Any]    =							CvtModelTester(self						)
        _UpperCamelCase   :						Optional[Any]    =							ConfigTester(self       , config_class=__a       , has_text_modality=__a       , hidden_size=37						)

  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]						)		->					List[Any]:
        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					int:
        return

  @unittest.skip(reason="Cvt does not output attentions"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]						)		->					Any:
        pass

  @unittest.skip(reason="Cvt does not use inputs_embeds"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Any						)		->					Union[str, Any]:
        pass

  @unittest.skip(reason="Cvt does not support input and output embeddings"						)
  def  __SCREAMING_SNAKE_CASE					(		self :							List[str]						)		->					List[Any]:
        pass

  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					Any:
        _UpperCamelCase,	_UpperCamelCase   :						str    =							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _UpperCamelCase   :						Dict    =							model_class(__a						)
              _UpperCamelCase   :						str    =							inspect.signature(model.forward						)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              _UpperCamelCase   :						Optional[int]    =							[*signature.parameters.keys()]

              _UpperCamelCase   :						Any    =							["pixel_values"]
              self.assertListEqual(arg_names[:1]       , __a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					List[Any]:
        _UpperCamelCase   :						int    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					int:
        def check_hidden_states_output(__a :							Optional[int]       , __a :							Any       , __a :							Dict						):
              _UpperCamelCase   :						Any    =							model_class(__a						)
              model.to(__a						)
              model.eval()

              with torch.no_grad():
                    _UpperCamelCase   :						Any    =							model(**self._prepare_for_class(__a       , __a						)						)

              _UpperCamelCase   :						str    =							outputs.hidden_states

              _UpperCamelCase   :						List[Any]    =							len(self.model_tester.depth						)
              self.assertEqual(len(__a						)       , __a						)

              # verify the first hidden states (first block)
              self.assertListEqual(
                  list(hidden_states[0].shape[-3:]						)       , [
                      self.model_tester.embed_dim[0],
                      self.model_tester.image_size // 4,
                      self.model_tester.image_size // 4,
                  ]       , )

        _UpperCamelCase,	_UpperCamelCase   :						List[Any]    =							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _UpperCamelCase   :						Any    =							True
              check_hidden_states_output(__a       , __a       , __a						)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              _UpperCamelCase   :						Tuple    =							True

              check_hidden_states_output(__a       , __a       , __a						)

  def  __SCREAMING_SNAKE_CASE					(		self :							int						)		->					Optional[int]:
        _UpperCamelCase   :						Any    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__a						)

  @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					str:
        pass


  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							Dict						)		->					List[str]:
        for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase   :						Dict    =							CvtModel.from_pretrained(__a						)
              self.assertIsNotNone(__a						)





def        lowercase__     (       )       ->		Dict:




      """simple docstring"""

      _UpperCamelCase   :						Dict    =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
      return image



@require_torch
@require_vision
class   __SCREAMING_SNAKE_CASE     (    unittest.TestCase ):







  '''simple docstring'''


  @cached_property
  def  __SCREAMING_SNAKE_CASE					(		self :							Optional[Any]						)		->					int:
        return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)


  @slow
  def  __SCREAMING_SNAKE_CASE					(		self :							List[Any]						)		->					List[Any]:
        _UpperCamelCase   :						List[Any]    =							CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(__a						)

        _UpperCamelCase   :						List[str]    =							self.default_image_processor
        _UpperCamelCase   :						int    =							prepare_img()
        _UpperCamelCase   :						Dict    =							image_processor(images=__a       , return_tensors="pt"						).to(__a						)

        # forward pass
        with torch.no_grad():
              _UpperCamelCase   :						Any    =							model(**__a						)

        # verify the logits
        _UpperCamelCase   :						str    =							torch.Size((1, 1000)						)
        self.assertEqual(outputs.logits.shape       , __a						)

        _UpperCamelCase   :						str    =							torch.tensor([0.92_85, 0.90_15, -0.31_50]						).to(__a						)

        self.assertTrue(torch.allclose(outputs.logits[0, :3]       , __a       , atol=1e-4						)						)







"""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()
