

from typing import Callable, List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


A											=     logging.get_logger(__name__)  # pylint: disable=invalid-name


class SCREAMING_SNAKE_CASE  (		__snake_case							,						__snake_case							):






			"""simple docstring"""




			@register_to_config
			def __init__(    self ,				__UpperCamelCase ,				__UpperCamelCase = None ,				__UpperCamelCase = None							):

				"""simple docstring"""


				super().__init__()

				snake_case_      		= learnable

				if self.learnable:
					assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
					assert length is not None, "learnable=True requires `length` to be set"

					snake_case_      		= torch.zeros(__UpperCamelCase ,				__UpperCamelCase							)
				else:
					snake_case_      		= None

				snake_case_      		= torch.nn.Parameter(__UpperCamelCase							)







class SCREAMING_SNAKE_CASE  (		__snake_case							):






			"""simple docstring"""




			__A						  =  42
			__A						  =  42
			__A						  =  42
			__A						  =  42
			__A						  =  42
			__A						  =  42


			def __init__(    self ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase ,				):

				"""simple docstring"""


				super().__init__()

				self.register_modules(
				    vqvae=__UpperCamelCase ,				transformer=__UpperCamelCase ,				text_encoder=__UpperCamelCase ,				tokenizer=__UpperCamelCase ,				scheduler=__UpperCamelCase ,				learned_classifier_free_sampling_embeddings=__UpperCamelCase ,				)


			def 			__lowerCAmelCase (    self ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							):

				"""simple docstring"""


				snake_case_      		= len(__UpperCamelCase							) if isinstance(__UpperCamelCase ,				__UpperCamelCase							) else 1

				# get prompt text embeddings
				snake_case_      		= self.tokenizer(
				    __UpperCamelCase ,				padding='max_length' ,				max_length=self.tokenizer.model_max_length ,				return_tensors='pt' ,				)
				snake_case_      		= text_inputs.input_ids

				if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
					snake_case_      		= self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]							)
					logger.warning(
					    'The following part of your input was truncated because CLIP can only handle sequences up to'
					    f""" {self.tokenizer.model_max_length} tokens: {removed_text}"""							)
					snake_case_      		= text_input_ids[:, : self.tokenizer.model_max_length]
				snake_case_      		= self.text_encoder(text_input_ids.to(self.device							)							)[0]

				# NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
				# While CLIP does normalize the pooled output of the text transformer when combining
				# the image and text embeddings, CLIP does not directly normalize the last hidden state.
				#
				# CLIP normalizing the pooled output.
				# https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
				snake_case_      		= prompt_embeds / prompt_embeds.norm(dim=-1 ,				keepdim=__UpperCamelCase							)

				# duplicate text embeddings for each generation per prompt
				snake_case_      		= prompt_embeds.repeat_interleave(__UpperCamelCase ,				dim=0							)

				if do_classifier_free_guidance:
					if self.learned_classifier_free_sampling_embeddings.learnable:
						snake_case_      		= self.learned_classifier_free_sampling_embeddings.embeddings
						snake_case_      		= negative_prompt_embeds.unsqueeze(0							).repeat(__UpperCamelCase ,				1 ,				1							)
					else:
						snake_case_      		= [''] * batch_size

						snake_case_      		= text_input_ids.shape[-1]
						snake_case_      		= self.tokenizer(
						    __UpperCamelCase ,				padding='max_length' ,				max_length=__UpperCamelCase ,				truncation=__UpperCamelCase ,				return_tensors='pt' ,				)
						snake_case_      		= self.text_encoder(uncond_input.input_ids.to(self.device							)							)[0]
						# See comment for normalizing text embeddings
						snake_case_      		= negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 ,				keepdim=__UpperCamelCase							)

					# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
					snake_case_      		= negative_prompt_embeds.shape[1]
					snake_case_      		= negative_prompt_embeds.repeat(1 ,				__UpperCamelCase ,				1							)
					snake_case_      		= negative_prompt_embeds.view(batch_size * num_images_per_prompt ,				__UpperCamelCase ,				-1							)

					# For classifier free guidance, we need to do two forward passes.
					# Here we concatenate the unconditional and text embeddings into a single batch
					# to avoid doing two forward passes
					snake_case_      		= torch.cat([negative_prompt_embeds, prompt_embeds]							)

				return prompt_embeds


			@torch.no_grad()
			def __call__(    self ,				__UpperCamelCase ,				__UpperCamelCase = 1_00 ,				__UpperCamelCase = 5.0 ,				__UpperCamelCase = 1.0 ,				__UpperCamelCase = 1 ,				__UpperCamelCase = None ,				__UpperCamelCase = None ,				__UpperCamelCase = "pil" ,				__UpperCamelCase = True ,				__UpperCamelCase = None ,				__UpperCamelCase = 1 ,				):

				"""simple docstring"""


				if isinstance(__UpperCamelCase ,				__UpperCamelCase							):
					snake_case_      		= 1
				elif isinstance(__UpperCamelCase ,				__UpperCamelCase							):
					snake_case_      		= len(__UpperCamelCase							)
				else:
					raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(__UpperCamelCase							)}"""							)

				snake_case_      		= batch_size * num_images_per_prompt

				snake_case_      		= guidance_scale > 1.0

				snake_case_      		= self._encode_prompt(__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							)

				if (callback_steps is None) or (
				    callback_steps is not None and (not isinstance(__UpperCamelCase ,				__UpperCamelCase							) or callback_steps <= 0)
				):
					raise ValueError(
					    f"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
					    f""" {type(__UpperCamelCase							)}."""							)

				# get the initial completely masked latents unless the user supplied it

				snake_case_      		= (batch_size, self.transformer.num_latent_pixels)
				if latents is None:
					snake_case_      		= self.transformer.num_vector_embeds - 1
					snake_case_      		= torch.full(__UpperCamelCase ,				__UpperCamelCase							).to(self.device							)
				else:
					if latents.shape != latents_shape:
						raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""							)
					if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
						raise ValueError(
						    'Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,'
						    f""" {self.transformer.num_vector_embeds - 1} (inclusive)."""							)
					snake_case_      		= latents.to(self.device							)

				# set timesteps
				self.scheduler.set_timesteps(__UpperCamelCase ,				device=self.device							)

				snake_case_      		= self.scheduler.timesteps.to(self.device							)

				snake_case_      		= latents

				for i, t in enumerate(self.progress_bar(__UpperCamelCase							)							):
					# expand the sample if we are doing classifier free guidance
					snake_case_      		= torch.cat([sample] * 2							) if do_classifier_free_guidance else sample

					# predict the un-noised image
					# model_output == `log_p_x_0`
					snake_case_      		= self.transformer(__UpperCamelCase ,				encoder_hidden_states=__UpperCamelCase ,				timestep=__UpperCamelCase							).sample

					if do_classifier_free_guidance:
						snake_case_		,       snake_case_      		= model_output.chunk(2							)
						snake_case_      		= model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
						model_output -= torch.logsumexp(__UpperCamelCase ,				dim=1 ,				keepdim=__UpperCamelCase							)

					snake_case_      		= self.truncate(__UpperCamelCase ,				__UpperCamelCase							)

					# remove `log(0)`'s (`-inf`s)
					snake_case_      		= model_output.clamp(-70							)

					# compute the previous noisy sample x_t -> x_t-1
					snake_case_      		= self.scheduler.step(__UpperCamelCase ,				timestep=__UpperCamelCase ,				sample=__UpperCamelCase ,				generator=__UpperCamelCase							).prev_sample

					# call the callback, if provided
					if callback is not None and i % callback_steps == 0:
						callback(__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							)

				snake_case_      		= self.vqvae.config.vq_embed_dim
				snake_case_      		= (batch_size, self.transformer.height, self.transformer.width, embedding_channels)
				snake_case_      		= self.vqvae.quantize.get_codebook_entry(__UpperCamelCase ,				shape=__UpperCamelCase							)
				snake_case_      		= self.vqvae.decode(__UpperCamelCase ,				force_not_quantize=__UpperCamelCase							).sample

				snake_case_      		= (image / 2 + 0.5).clamp(0 ,				1							)
				snake_case_      		= image.cpu().permute(0 ,				2 ,				3 ,				1							).numpy()

				if output_type == "pil":
					snake_case_      		= self.numpy_to_pil(__UpperCamelCase							)

				if not return_dict:
					return (image,)

				return ImagePipelineOutput(images=__UpperCamelCase							)







			def 			__lowerCAmelCase (    self ,				__UpperCamelCase ,				__UpperCamelCase							):

				"""simple docstring"""


				snake_case_		,       snake_case_      		= torch.sort(__UpperCamelCase ,				1 ,				descending=__UpperCamelCase							)
				snake_case_      		= torch.exp(__UpperCamelCase							)
				snake_case_      		= sorted_p_x_0.cumsum(dim=1							) < truncation_rate

				# Ensure that at least the largest probability is not zeroed out
				snake_case_      		= torch.full_like(keep_mask[:, 0:1, :] ,				__UpperCamelCase							)
				snake_case_      		= torch.cat((all_true, keep_mask) ,				dim=1							)
				snake_case_      		= keep_mask[:, :-1, :]

				snake_case_      		= keep_mask.gather(1 ,				indices.argsort(1							)							)

				snake_case_      		= log_p_x_0.clone()

				snake_case_      		= -torch.inf  # -inf = log(0)

				return rv



import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union

import datasets
import numpy as np
import torch
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry


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

A											=     logging.getLogger(__name__)


@dataclass
class SCREAMING_SNAKE_CASE  :






			"""simple docstring"""




			__A						  =  field(
			    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}							)
			__A						  =  field(
			    default=__snake_case							,						metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}							)
			__A						  =  field(
			    default=__snake_case							,						metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}							)
			__A						  =  field(
			    default=__snake_case							,						metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}							,						)
			__A						  =  field(
			    default=__snake_case							,						metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""}							,						)
			__A						  =  field(
			    default="""main"""							,						metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}							,						)
			__A						  =  field(
			    default=__snake_case							,						metadata={
			        """help""": (
			            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
			            """with private models)."""
			        )
			    }							,						)







@dataclass
class SCREAMING_SNAKE_CASE  :






			"""simple docstring"""




			__A						  =  field(default=__snake_case							,						metadata={"""help""": """The input training data file (a text file)."""}							)
			__A						  =  field(
			    default=__snake_case							,						metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""}							,						)
			__A						  =  field(
			    default=__snake_case							,						metadata={"""help""": """Overwrite the cached training and evaluation sets"""}							)
			__A						  =  field(
			    default=__snake_case							,						metadata={"""help""": """The number of processes to use for the preprocessing."""}							,						)
			__A						  =  field(
			    default=__snake_case							,						metadata={
			        """help""": (
			            """The maximum total input sequence length after tokenization. If passed, sequences longer """
			            """than this will be truncated, sequences shorter will be padded."""
			        )
			    }							,						)
			__A						  =  field(
			    default=__snake_case							,						metadata={
			        """help""": (
			            """Whether to pad all samples to the maximum sentence length. """
			            """If False, will pad the samples dynamically when batching to the maximum length in the batch. More """
			            """efficient on GPU but very bad for TPU."""
			        )
			    }							,						)
			__A						  =  field(
			    default=__snake_case							,						metadata={
			        """help""": (
			            """For debugging purposes or quicker training, truncate the number of training examples to this """
			            """value if set."""
			        )
			    }							,						)
			__A						  =  field(
			    default=__snake_case							,						metadata={
			        """help""": (
			            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
			            """value if set."""
			        )
			    }							,						)


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				if self.train_file is not None:
					snake_case_      		= self.train_file.split('.'							)[-1]
					assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
				if self.validation_file is not None:
					snake_case_      		= self.validation_file.split('.'							)[-1]
					assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."







@dataclass
class SCREAMING_SNAKE_CASE  :






			"""simple docstring"""




			__A						  =  42
			__A						  =  True
			__A						  =  None
			__A						  =  None


			def __call__(    self ,				__UpperCamelCase							):

				"""simple docstring"""


				snake_case_      		= 'label' if 'label' in features[0].keys() else 'labels'
				snake_case_      		= [feature.pop(__UpperCamelCase							) for feature in features]
				snake_case_      		= len(__UpperCamelCase							)
				snake_case_      		= len(features[0]['input_ids']							)
				snake_case_      		= [
				    [{k: v[i] for k, v in feature.items()} for i in range(__UpperCamelCase							)] for feature in features
				]
				snake_case_      		= list(chain(*__UpperCamelCase							)							)

				snake_case_      		= self.tokenizer.pad(
				    __UpperCamelCase ,				padding=self.padding ,				max_length=self.max_length ,				pad_to_multiple_of=self.pad_to_multiple_of ,				return_tensors='pt' ,				)

				# Un-flatten
				snake_case_      		= {k: v.view(__UpperCamelCase ,				__UpperCamelCase ,				-1							) for k, v in batch.items()}
				# Add back labels
				snake_case_      		= torch.tensor(__UpperCamelCase ,				dtype=torch.intaa							)
				return batch







def a():





	'''simple docstring'''
	# 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.

	snake_case_      		= HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)
	if len(sys.argv	) == 2 and sys.argv[1].endswith('.json'	):
		# If we pass only one argument to the script and it's the path to a json file,
		# let's parse it to get our arguments.
		snake_case_		,       snake_case_		,       snake_case_      		= parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]	)	)
	else:
		snake_case_		,       snake_case_		,       snake_case_      		= 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_swag'			, lowercase__			, 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()

	snake_case_      		= 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.
	snake_case_      		= None
	if os.path.isdir(training_args.output_dir	) and training_args.do_train and not training_args.overwrite_output_dir:
		snake_case_      		= 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 and training_args.resume_from_checkpoint is 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	)

	# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
	# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
	# (the dataset will be downloaded automatically from the datasets Hub).

	# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
	# 'text' is found. You can easily tweak this behavior (see below).

	# In distributed training, the load_dataset function guarantee that only one local process can concurrently
	# download the dataset.
	if data_args.train_file is not None or data_args.validation_file is not None:
		snake_case_      		= {}
		if data_args.train_file is not None:
			snake_case_      		= data_args.train_file
		if data_args.validation_file is not None:
			snake_case_      		= data_args.validation_file
		snake_case_      		= data_args.train_file.split('.'	)[-1]
		snake_case_      		= load_dataset(
		    lowercase__			, data_files=lowercase__			, cache_dir=model_args.cache_dir			, use_auth_token=True if model_args.use_auth_token else None			, )
	else:
		# Downloading and loading the swag dataset from the hub.
		snake_case_      		= load_dataset(
		    'swag'			, 'regular'			, cache_dir=model_args.cache_dir			, use_auth_token=True if model_args.use_auth_token else None			, )
	# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
	# https://huggingface.co/docs/datasets/loading_datasets.html.

	# Load pretrained model and tokenizer

	# Distributed training:
	# The .from_pretrained methods guarantee that only one local process can concurrently
	# download model & vocab.
	snake_case_      		= AutoConfig.from_pretrained(
	    model_args.config_name if model_args.config_name else model_args.model_name_or_path			, cache_dir=model_args.cache_dir			, revision=model_args.model_revision			, use_auth_token=True if model_args.use_auth_token else None			, )
	snake_case_      		= AutoTokenizer.from_pretrained(
	    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path			, 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			, )
	snake_case_      		= AutoModelForMultipleChoice.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			, )

	# When using your own dataset or a different dataset from swag, you will probably need to change this.
	snake_case_      		= [f"""ending{i}""" for i in range(4	)]
	snake_case_      		= 'sent1'
	snake_case_      		= 'sent2'

	if data_args.max_seq_length is None:
		snake_case_      		= tokenizer.model_max_length
		if max_seq_length > 1024:
			logger.warning(
			    'The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value'
			    ' of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can'
			    ' override this default with `--block_size xxx`.'	)
			snake_case_      		= 1024
	else:
		if data_args.max_seq_length > tokenizer.model_max_length:
			logger.warning(
			    f"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"""
			    f"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."""	)
		snake_case_      		= min(data_args.max_seq_length			, tokenizer.model_max_length	)

	# Preprocessing the datasets.
	def preprocess_function(lowercase__	):
		snake_case_      		= [[context] * 4 for context in examples[context_name]]
		snake_case_      		= examples[question_header_name]
		snake_case_      		= [
		    [f"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(lowercase__	)
		]

		# Flatten out
		snake_case_      		= list(chain(*lowercase__	)	)
		snake_case_      		= list(chain(*lowercase__	)	)

		# Tokenize
		snake_case_      		= tokenizer(
		    lowercase__			, lowercase__			, truncation=lowercase__			, max_length=lowercase__			, padding='max_length' if data_args.pad_to_max_length else False			, )
		# Un-flatten
		return {k: [v[i : i + 4] for i in range(0			, len(lowercase__	)			, 4	)] for k, v in tokenized_examples.items()}

	if training_args.do_train:
		if "train" not in raw_datasets:
			raise ValueError('--do_train requires a train dataset'	)
		snake_case_      		= raw_datasets['train']
		if data_args.max_train_samples is not None:
			snake_case_      		= min(len(lowercase__	)			, data_args.max_train_samples	)
			snake_case_      		= train_dataset.select(range(lowercase__	)	)
		with training_args.main_process_first(desc='train dataset map pre-processing'	):
			snake_case_      		= train_dataset.map(
			    lowercase__			, batched=lowercase__			, num_proc=data_args.preprocessing_num_workers			, load_from_cache_file=not data_args.overwrite_cache			, )

	if training_args.do_eval:
		if "validation" not in raw_datasets:
			raise ValueError('--do_eval requires a validation dataset'	)
		snake_case_      		= raw_datasets['validation']
		if data_args.max_eval_samples is not None:
			snake_case_      		= min(len(lowercase__	)			, data_args.max_eval_samples	)
			snake_case_      		= eval_dataset.select(range(lowercase__	)	)
		with training_args.main_process_first(desc='validation dataset map pre-processing'	):
			snake_case_      		= eval_dataset.map(
			    lowercase__			, batched=lowercase__			, num_proc=data_args.preprocessing_num_workers			, load_from_cache_file=not data_args.overwrite_cache			, )

    # Data collator
	snake_case_      		= (
	    default_data_collator
	    if data_args.pad_to_max_length
	    else DataCollatorForMultipleChoice(tokenizer=lowercase__			, pad_to_multiple_of=8 if training_args.fpaa else None	)
	)

	# Metric
	def compute_metrics(lowercase__	):
		snake_case_		,       snake_case_      		= eval_predictions
		snake_case_      		= np.argmax(lowercase__			, axis=1	)
		return {"accuracy": (preds == label_ids).astype(np.floataa	).mean().item()}

	# Initialize our Trainer
	snake_case_      		= 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			, tokenizer=lowercase__			, data_collator=lowercase__			, compute_metrics=lowercase__			, )

	# Training
	if training_args.do_train:
		snake_case_      		= None
		if training_args.resume_from_checkpoint is not None:
			snake_case_      		= training_args.resume_from_checkpoint
		elif last_checkpoint is not None:
			snake_case_      		= last_checkpoint
		snake_case_      		= trainer.train(resume_from_checkpoint=lowercase__	)
		trainer.save_model()  # Saves the tokenizer too for easy upload
		snake_case_      		= train_result.metrics

		snake_case_      		= (
		    data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase__	)
		)
		snake_case_      		= min(lowercase__			, len(lowercase__	)	)

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

	# Evaluation
	if training_args.do_eval:
		logger.info('*** Evaluate ***'	)

		snake_case_      		= trainer.evaluate()
		snake_case_      		= data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowercase__	)
		snake_case_      		= min(lowercase__			, len(lowercase__	)	)

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

	snake_case_      		= {
	    'finetuned_from': model_args.model_name_or_path,
	    'tasks': 'multiple-choice',
	    'dataset_tags': 'swag',
	    'dataset_args': 'regular',
	    'dataset': 'SWAG',
	    'language': 'en',
	}

	if training_args.push_to_hub:
		trainer.push_to_hub(**lowercase__	)
	else:
		trainer.create_model_card(**lowercase__	)





def a(lowercase__	):





	'''simple docstring'''
	# For xla_spawn (TPUs)
	main()


if __name__ == "__main__":
		main()
