






"""simple docstring"""
import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 torch import nn

			from transformers import (
			    MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
			    TimesformerForVideoClassification,
			    TimesformerModel,
			)
			from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from transformers import VideoMAEImageProcessor


class _lowerCAmelCase						:







						def __init__(    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_=1_3   ,				lowerCAmelCase_=1_0   ,				lowerCAmelCase_=3   ,				lowerCAmelCase_=2   ,				lowerCAmelCase_=2   ,				lowerCAmelCase_=True   ,				lowerCAmelCase_=True   ,				lowerCAmelCase_=3_2   ,				lowerCAmelCase_=5   ,				lowerCAmelCase_=4   ,				lowerCAmelCase_=3_7   ,				lowerCAmelCase_="gelu"   ,				lowerCAmelCase_=0.1   ,				lowerCAmelCase_=0.1   ,				lowerCAmelCase_=1_0   ,				lowerCAmelCase_=0.02   ,				lowerCAmelCase_="divided_space_time"   ,				lowerCAmelCase_=None   ,				)		->							Optional[int]:
										_SCREAMING_SNAKE_CASE   :		Dict       		=    parent
										_SCREAMING_SNAKE_CASE   :		Dict       		=    batch_size
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    image_size
										_SCREAMING_SNAKE_CASE   :		Any       		=    num_channels
										_SCREAMING_SNAKE_CASE   :		int       		=    patch_size
										_SCREAMING_SNAKE_CASE   :		Any       		=    num_frames
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    is_training
										_SCREAMING_SNAKE_CASE   :		str       		=    use_labels
										_SCREAMING_SNAKE_CASE   :		Dict       		=    hidden_size
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    num_hidden_layers
										_SCREAMING_SNAKE_CASE   :		int       		=    num_attention_heads
										_SCREAMING_SNAKE_CASE   :		int       		=    intermediate_size
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    hidden_act
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    hidden_dropout_prob
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    attention_probs_dropout_prob
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    attention_type
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    initializer_range
										_SCREAMING_SNAKE_CASE   :		str       		=    scope
										_SCREAMING_SNAKE_CASE   :		str       		=    num_labels

										# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
										_SCREAMING_SNAKE_CASE   :		Dict       		=    (image_size // patch_size) ** 2
										_SCREAMING_SNAKE_CASE   :		str       		=    (num_frames) * self.num_patches_per_frame + 1







						def 			A      (    self							)		->							Optional[int]:
										_SCREAMING_SNAKE_CASE   :		int       		=    floats_tensor(
										    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]							)

										_SCREAMING_SNAKE_CASE   :		Tuple       		=    None
										if self.use_labels:
														_SCREAMING_SNAKE_CASE   :		Tuple       		=    ids_tensor([self.batch_size]   ,				self.num_labels							)

										_SCREAMING_SNAKE_CASE   :		List[str]       		=    self.get_config()

										return config, pixel_values, labels







						def 			A      (    self							)		->							Union[str, Any]:
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    TimesformerConfig(
										    image_size=self.image_size   ,				patch_size=self.patch_size   ,				num_channels=self.num_channels   ,				num_frames=self.num_frames   ,				hidden_size=self.hidden_size   ,				num_hidden_layers=self.num_hidden_layers   ,				num_attention_heads=self.num_attention_heads   ,				intermediate_size=self.intermediate_size   ,				hidden_act=self.hidden_act   ,				hidden_dropout_prob=self.hidden_dropout_prob   ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,				initializer_range=self.initializer_range   ,				attention_type=self.attention_type   ,				)
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    self.num_labels
										return config







						def 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							Dict:
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    TimesformerModel(config=lowerCAmelCase_							)
										model.to(lowerCAmelCase_							)
										model.eval()
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    model(lowerCAmelCase_							)
										self.parent.assertEqual(result.last_hidden_state.shape   ,				(self.batch_size, self.seq_length, self.hidden_size)							)







						def 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							Union[str, Any]:
										_SCREAMING_SNAKE_CASE   :		Any       		=    TimesformerForVideoClassification(lowerCAmelCase_							)
										model.to(lowerCAmelCase_							)
										model.eval()

										_SCREAMING_SNAKE_CASE   :		Dict       		=    model(lowerCAmelCase_							)

										# verify the logits shape
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    torch.Size((self.batch_size, self.num_labels)							)
										self.parent.assertEqual(result.logits.shape   ,				lowerCAmelCase_							)







						def 			A      (    self							)		->							Union[str, Any]:
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    self.prepare_config_and_inputs()
										_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		Tuple       		=    config_and_inputs
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    {'pixel_values': pixel_values}
										return config, inputs_dict







@require_torch
class _lowerCAmelCase						(    __UpperCAmelCase   ,  __UpperCAmelCase   ,  unittest.TestCase       ):
						SCREAMING_SNAKE_CASE_:					Dict 					=				(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
						SCREAMING_SNAKE_CASE_:					int 					=				(
						    {'feature-extraction': TimesformerModel, 'video-classification': TimesformerForVideoClassification}
						    if is_torch_available()
						    else {}
						)

						SCREAMING_SNAKE_CASE_:					Any 					=				False
						SCREAMING_SNAKE_CASE_:					Optional[Any] 					=				False
						SCREAMING_SNAKE_CASE_:					Union[str, Any] 					=				False
						SCREAMING_SNAKE_CASE_:					Dict 					=				False







						def 			A      (    self							)		->							Union[str, Any]:
										_SCREAMING_SNAKE_CASE   :		int       		=    TimesformerModelTester(self							)
										_SCREAMING_SNAKE_CASE   :		int       		=    ConfigTester(
										    self   ,				config_class=lowerCAmelCase_   ,				has_text_modality=lowerCAmelCase_   ,				hidden_size=3_7							)







						def 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_=False							)		->							int:
										_SCREAMING_SNAKE_CASE   :		str       		=    copy.deepcopy(lowerCAmelCase_							)

										if return_labels:
														if model_class in get_values(lowerCAmelCase_							):
																		_SCREAMING_SNAKE_CASE   :		str       		=    torch.zeros(
																		    self.model_tester.batch_size   ,				dtype=torch.long   ,				device=lowerCAmelCase_							)

										return inputs_dict







						def 			A      (    self							)		->							Optional[Any]:
										self.config_tester.run_common_tests()







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







						def 			A      (    self							)		->							Any:
										_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		int       		=    self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_SCREAMING_SNAKE_CASE   :		List[str]       		=    model_class(lowerCAmelCase_							)
														self.assertIsInstance(model.get_input_embeddings()   ,				(nn.Module)							)
														_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    model.get_output_embeddings()
														self.assertTrue(x is None or isinstance(lowerCAmelCase_   ,				nn.Linear							)							)







						def 			A      (    self							)		->							List[str]:
										_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		List[Any]       		=    self.model_tester.prepare_config_and_inputs_for_common()

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

														_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    ['pixel_values']
														self.assertListEqual(arg_names[:1]   ,				lowerCAmelCase_							)







						def 			A      (    self							)		->							List[Any]:
										_SCREAMING_SNAKE_CASE   :		str       		=    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase_							)







						def 			A      (    self							)		->							List[Any]:
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_video_classification(*lowerCAmelCase_							)







						@slow
						def 			A      (    self							)		->							str:
										for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														_SCREAMING_SNAKE_CASE   :		Tuple       		=    TimesformerModel.from_pretrained(lowerCAmelCase_							)
														self.assertIsNotNone(lowerCAmelCase_							)







						def 			A      (    self							)		->							Union[str, Any]:
										if not self.has_attentions:
														pass

										else:
														_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		List[Any]       		=    self.model_tester.prepare_config_and_inputs_for_common()
														_SCREAMING_SNAKE_CASE   :		Dict       		=    True

														for model_class in self.all_model_classes:
																		_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    self.model_tester.seq_length
																		_SCREAMING_SNAKE_CASE   :		int       		=    self.model_tester.num_frames

																		_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    True
																		_SCREAMING_SNAKE_CASE   :		str       		=    False
																		_SCREAMING_SNAKE_CASE   :		int       		=    True
																		_SCREAMING_SNAKE_CASE   :		str       		=    model_class(lowerCAmelCase_							)
																		model.to(lowerCAmelCase_							)
																		model.eval()
																		with torch.no_grad():
																						_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    model(**self._prepare_for_class(lowerCAmelCase_   ,				lowerCAmelCase_							)							)
																		_SCREAMING_SNAKE_CASE   :		Tuple       		=    outputs.attentions
																		self.assertEqual(len(lowerCAmelCase_							)   ,				self.model_tester.num_hidden_layers							)

																		# check that output_attentions also work using config
																		del inputs_dict["output_attentions"]
																		_SCREAMING_SNAKE_CASE   :		Dict       		=    True
																		_SCREAMING_SNAKE_CASE   :		Any       		=    model_class(lowerCAmelCase_							)
																		model.to(lowerCAmelCase_							)
																		model.eval()
																		with torch.no_grad():
																						_SCREAMING_SNAKE_CASE   :		Tuple       		=    model(**self._prepare_for_class(lowerCAmelCase_   ,				lowerCAmelCase_							)							)
																		_SCREAMING_SNAKE_CASE   :		List[Any]       		=    outputs.attentions
																		self.assertEqual(len(lowerCAmelCase_							)   ,				self.model_tester.num_hidden_layers							)

																		# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
																		self.assertListEqual(
																		    list(attentions[0].shape[-3:]							)   ,				[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]   ,				)
																		_SCREAMING_SNAKE_CASE   :		Tuple       		=    len(lowerCAmelCase_							)

																		# Check attention is always last and order is fine
																		_SCREAMING_SNAKE_CASE   :		Any       		=    True
																		_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    True
																		_SCREAMING_SNAKE_CASE   :		Dict       		=    model_class(lowerCAmelCase_							)
																		model.to(lowerCAmelCase_							)
																		model.eval()
																		with torch.no_grad():
																						_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    model(**self._prepare_for_class(lowerCAmelCase_   ,				lowerCAmelCase_							)							)

																		self.assertEqual(out_len + 1   ,				len(lowerCAmelCase_							)							)

																		_SCREAMING_SNAKE_CASE   :		Tuple       		=    outputs.attentions

																		self.assertEqual(len(lowerCAmelCase_							)   ,				self.model_tester.num_hidden_layers							)

																		# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
																		self.assertListEqual(
																		    list(self_attentions[0].shape[-3:]							)   ,				[self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]   ,				)







						def 			A      (    self							)		->							str:
										def check_hidden_states_output(lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							):
														_SCREAMING_SNAKE_CASE   :		Tuple       		=    model_class(lowerCAmelCase_							)
														model.to(lowerCAmelCase_							)
														model.eval()

														with torch.no_grad():
																		_SCREAMING_SNAKE_CASE   :		List[Any]       		=    model(**self._prepare_for_class(lowerCAmelCase_   ,				lowerCAmelCase_							)							)

														_SCREAMING_SNAKE_CASE   :		Dict       		=    outputs.hidden_states
														_SCREAMING_SNAKE_CASE   :		int       		=    self.model_tester.num_hidden_layers + 1
														self.assertEqual(len(lowerCAmelCase_							)   ,				lowerCAmelCase_							)

														_SCREAMING_SNAKE_CASE   :		Tuple       		=    self.model_tester.seq_length

														self.assertListEqual(
														    list(hidden_states[0].shape[-2:]							)   ,				[seq_length, self.model_tester.hidden_size]   ,				)

										_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		int       		=    self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_SCREAMING_SNAKE_CASE   :		List[Any]       		=    True
														check_hidden_states_output(lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)

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

														check_hidden_states_output(lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)







def 				lowercase__		(					):
				_SCREAMING_SNAKE_CASE   :		int       		=    hf_hub_download(
				    repo_id='hf-internal-testing/spaghetti-video',						filename='eating_spaghetti.npy',						repo_type='dataset'       )
				_SCREAMING_SNAKE_CASE   :		int       		=    np.load(lowerCamelCase       )
				return list(lowerCamelCase       )






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







						@cached_property
						def 			A      (    self							)		->							Tuple:
										# logits were tested with a different mean and std, so we use the same here
										return (
										    VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]   ,				image_std=[0.5, 0.5, 0.5]							)
										    if is_vision_available()
										    else None
										)







						@slow
						def 			A      (    self							)		->							Optional[Any]:
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    TimesformerForVideoClassification.from_pretrained('facebook/timesformer-base-finetuned-k400'							).to(
										    lowerCAmelCase_							)

										_SCREAMING_SNAKE_CASE   :		str       		=    self.default_image_processor
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    prepare_video()
										_SCREAMING_SNAKE_CASE   :		List[str]       		=    image_processor(video[:8]   ,				return_tensors='pt'							).to(lowerCAmelCase_							)

										# forward pass
										with torch.no_grad():
														_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    model(**lowerCAmelCase_							)

										# verify the logits
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    torch.Size((1, 4_0_0)							)
										self.assertEqual(outputs.logits.shape   ,				lowerCAmelCase_							)

										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    torch.tensor([-0.3_016, -0.7_713, -0.4_205]							).to(lowerCAmelCase_							)

										self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,				lowerCAmelCase_   ,				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 _lowerCAmelCase						:
						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 _lowerCAmelCase						:
						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__		(					):
				# See all possible arguments in src/transformers/training_args.py
				# or by passing the --help flag to this script.
				# We now keep distinct sets of args, for a cleaner separation of concerns.

				_SCREAMING_SNAKE_CASE   :		str       		=    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
				_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		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',						lowerCamelCase       )

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

				_SCREAMING_SNAKE_CASE   :		Any       		=    training_args.get_process_log_level()
				logger.setLevel(lowerCamelCase       )
				datasets.utils.logging.set_verbosity(lowerCamelCase       )
				transformers.utils.logging.set_verbosity(lowerCamelCase       )
				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.
				_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    None
				if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
								_SCREAMING_SNAKE_CASE   :		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:
												_SCREAMING_SNAKE_CASE   :		Optional[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:
												_SCREAMING_SNAKE_CASE   :		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,						)
								_SCREAMING_SNAKE_CASE   :		Dict       		=    train_dataset.features['label'].names

				if training_args.do_eval:
								_SCREAMING_SNAKE_CASE   :		Any       		=    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,						)
								_SCREAMING_SNAKE_CASE   :		List[Any]       		=    eval_dataset.features['label'].names

				if training_args.do_predict:
								_SCREAMING_SNAKE_CASE   :		Optional[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,						)
								_SCREAMING_SNAKE_CASE   :		int       		=    predict_dataset.features['label'].names

				# Labels
				_SCREAMING_SNAKE_CASE   :		List[Any]       		=    len(lowerCamelCase       )

				# Load pretrained model and tokenizer
				# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.
				_SCREAMING_SNAKE_CASE   :		Dict       		=    AutoConfig.from_pretrained(
				    model_args.config_name if model_args.config_name else model_args.model_name_or_path,						num_labels=lowerCamelCase,						idalabel={str(lowerCamelCase       ): label for i, label in enumerate(lowerCamelCase       )},						labelaid={label: i for i, label in enumerate(lowerCamelCase       )},						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,						)
				_SCREAMING_SNAKE_CASE   :		List[str]       		=    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,						)
				_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    AutoModelForSequenceClassification.from_pretrained(
				    model_args.model_name_or_path,						from_tf=bool('.ckpt' in model_args.model_name_or_path       ),						config=lowerCamelCase,						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:
								_SCREAMING_SNAKE_CASE   :		Tuple       		=    'max_length'
				else:
								# We will pad later, dynamically at batch creation, to the max sequence length in each batch
								_SCREAMING_SNAKE_CASE   :		Tuple       		=    False

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

				if training_args.do_train:
								if data_args.max_train_samples is not None:
												_SCREAMING_SNAKE_CASE   :		List[Any]       		=    min(len(lowerCamelCase       ),						data_args.max_train_samples       )
												_SCREAMING_SNAKE_CASE   :		Tuple       		=    train_dataset.select(range(lowerCamelCase       )       )
								with training_args.main_process_first(desc='train dataset map pre-processing'       ):
												_SCREAMING_SNAKE_CASE   :		Tuple       		=    train_dataset.map(
												    lowerCamelCase,						batched=lowerCamelCase,						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(lowerCamelCase       )       ),						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:
												_SCREAMING_SNAKE_CASE   :		Dict       		=    min(len(lowerCamelCase       ),						data_args.max_eval_samples       )
												_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    eval_dataset.select(range(lowerCamelCase       )       )
								with training_args.main_process_first(desc='validation dataset map pre-processing'       ):
												_SCREAMING_SNAKE_CASE   :		Tuple       		=    eval_dataset.map(
												    lowerCamelCase,						batched=lowerCamelCase,						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:
												_SCREAMING_SNAKE_CASE   :		Tuple       		=    min(len(lowerCamelCase       ),						data_args.max_predict_samples       )
												_SCREAMING_SNAKE_CASE   :		Dict       		=    predict_dataset.select(range(lowerCamelCase       )       )
								with training_args.main_process_first(desc='prediction dataset map pre-processing'       ):
												_SCREAMING_SNAKE_CASE   :		Tuple       		=    predict_dataset.map(
												    lowerCamelCase,						batched=lowerCamelCase,						load_from_cache_file=not data_args.overwrite_cache,						desc='Running tokenizer on prediction dataset',						)

    # Get the metric function
				_SCREAMING_SNAKE_CASE   :		Tuple       		=    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(lowerCamelCase       ):
								_SCREAMING_SNAKE_CASE   :		Dict       		=    p.predictions[0] if isinstance(p.predictions,						lowerCamelCase       ) else p.predictions
								_SCREAMING_SNAKE_CASE   :		int       		=    np.argmax(lowerCamelCase,						axis=1       )
								return metric.compute(predictions=lowerCamelCase,						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:
								_SCREAMING_SNAKE_CASE   :		List[str]       		=    default_data_collator
				elif training_args.fpaa:
								_SCREAMING_SNAKE_CASE   :		List[Any]       		=    DataCollatorWithPadding(lowerCamelCase,						pad_to_multiple_of=8       )
				else:
								_SCREAMING_SNAKE_CASE   :		Tuple       		=    None

				# Initialize our Trainer
				_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    Trainer(
				    model=lowerCamelCase,						args=lowerCamelCase,						train_dataset=train_dataset if training_args.do_train else None,						eval_dataset=eval_dataset if training_args.do_eval else None,						compute_metrics=lowerCamelCase,						tokenizer=lowerCamelCase,						data_collator=lowerCamelCase,						)

				# Training
				if training_args.do_train:
								_SCREAMING_SNAKE_CASE   :		List[Any]       		=    None
								if training_args.resume_from_checkpoint is not None:
												_SCREAMING_SNAKE_CASE   :		List[str]       		=    training_args.resume_from_checkpoint
								elif last_checkpoint is not None:
												_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    last_checkpoint
								_SCREAMING_SNAKE_CASE   :		List[Any]       		=    trainer.train(resume_from_checkpoint=lowerCamelCase       )
								_SCREAMING_SNAKE_CASE   :		Dict       		=    train_result.metrics
								_SCREAMING_SNAKE_CASE   :		str       		=    (
								    data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCamelCase       )
								)
								_SCREAMING_SNAKE_CASE   :		Tuple       		=    min(lowerCamelCase,						len(lowerCamelCase       )       )

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

								trainer.log_metrics('train',						lowerCamelCase       )
								trainer.save_metrics('train',						lowerCamelCase       )
								trainer.save_state()

				# Evaluation
				if training_args.do_eval:
								logger.info('*** Evaluate ***'       )
								_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    trainer.evaluate(eval_dataset=lowerCamelCase       )

								_SCREAMING_SNAKE_CASE   :		Tuple       		=    data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCamelCase       )
								_SCREAMING_SNAKE_CASE   :		Any       		=    min(lowerCamelCase,						len(lowerCamelCase       )       )

								trainer.log_metrics('eval',						lowerCamelCase       )
								trainer.save_metrics('eval',						lowerCamelCase       )

				# Prediction
				if training_args.do_predict:
								logger.info('*** Predict ***'       )
								_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		Any       		=    trainer.predict(lowerCamelCase,						metric_key_prefix='predict'       )

								_SCREAMING_SNAKE_CASE   :		List[Any]       		=    (
								    data_args.max_predict_samples if data_args.max_predict_samples is not None else len(lowerCamelCase       )
								)
								_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    min(lowerCamelCase,						len(lowerCamelCase       )       )

								trainer.log_metrics('predict',						lowerCamelCase       )
								trainer.save_metrics('predict',						lowerCamelCase       )

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


if __name__ == "__main__":
			main()

