



'''simple docstring'''



from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


lowerCAmelCase_  :							Optional[Any]             =    logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCAmelCase_  :							int             =    '\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'
@dataclass
class 						lowerCamelCase_				(       snake_case_      ):
						_lowerCAmelCase  : Union[PIL.Image.Image, np.ndarray]


class 						lowerCamelCase_				(       snake_case_      ):







						def __init__(	self :   Dict					,     lowerCAmelCase__ :   PriorTransformer					,     lowerCAmelCase__ :   CLIPVisionModel					,     lowerCAmelCase__ :   CLIPImageProcessor					,     lowerCAmelCase__ :   HeunDiscreteScheduler					,     lowerCAmelCase__ :   ShapERenderer					,     ):

													"""simple docstring"""
													super().__init__()

													self.register_modules(
													    prior=lowerCAmelCase__					,     image_encoder=lowerCAmelCase__					,     image_processor=lowerCAmelCase__					,     scheduler=lowerCAmelCase__					,     renderer=lowerCAmelCase__					,     )







						def        __lowercase     (	self :   Dict					,     lowerCAmelCase__ :   Optional[int]					,     lowerCAmelCase__ :   List[str]					,     lowerCAmelCase__ :   Tuple					,     lowerCAmelCase__ :   Optional[int]					,     lowerCAmelCase__ :   Any					,     lowerCAmelCase__ :   Dict					):

													"""simple docstring"""
													if latents is None:
																				SCREAMING_SNAKE_CASE       :   Optional[int]         =      randn_tensor(lowerCAmelCase__					,     generator=lowerCAmelCase__					,     device=lowerCAmelCase__					,     dtype=lowerCAmelCase__					)
													else:
																				if latents.shape != shape:
																											raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""					)
																				SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      latents.to(lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Optional[Any]         =      latents * scheduler.init_noise_sigma
													return latents







						def        __lowercase     (	self :   str					,     lowerCAmelCase__ :   Optional[Any]=0					):

													"""simple docstring"""
													if is_accelerate_available():
																				from accelerate import cpu_offload
													else:
																				raise ImportError('''Please install accelerate via `pip install accelerate`'''					)

													SCREAMING_SNAKE_CASE       :   List[Any]         =      torch.device(F"""cuda:{gpu_id}"""					)

													SCREAMING_SNAKE_CASE       :   Any         =      [self.image_encoder, self.prior]
													for cpu_offloaded_model in models:
																				if cpu_offloaded_model is not None:
																											cpu_offload(lowerCAmelCase__					,     lowerCAmelCase__					)







						@property
						def        __lowercase     (	self :   List[Any]					):

													"""simple docstring"""
													if self.device != torch.device('''meta'''					) or not hasattr(self.image_encoder					,     '''_hf_hook'''					):
																				return self.device
													for module in self.image_encoder.modules():
																				if (
																				    hasattr(lowerCAmelCase__					,     '''_hf_hook'''					)
																				    and hasattr(module._hf_hook					,     '''execution_device'''					)
																				    and module._hf_hook.execution_device is not None
																				):
																											return torch.device(module._hf_hook.execution_device					)
													return self.device







						def        __lowercase     (	self :   Optional[int]					,     lowerCAmelCase__ :   Optional[Any]					,     lowerCAmelCase__ :   Optional[int]					,     lowerCAmelCase__ :   Tuple					,     lowerCAmelCase__ :   Any					,     ):

													"""simple docstring"""
													if isinstance(lowerCAmelCase__					,     lowerCAmelCase__					) and isinstance(image[0]					,     torch.Tensor					):
																				SCREAMING_SNAKE_CASE       :   Dict         =      torch.cat(lowerCAmelCase__					,     axis=0					) if image[0].ndim == 4 else torch.stack(lowerCAmelCase__					,     axis=0					)

													if not isinstance(lowerCAmelCase__					,     torch.Tensor					):
																				SCREAMING_SNAKE_CASE       :   int         =      self.image_processor(lowerCAmelCase__					,     return_tensors='''pt'''					).pixel_values[0].unsqueeze(0					)

													SCREAMING_SNAKE_CASE       :   str         =      image.to(dtype=self.image_encoder.dtype					,     device=lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   List[str]         =      self.image_encoder(lowerCAmelCase__					)['''last_hidden_state''']
													SCREAMING_SNAKE_CASE       :   Dict         =      image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

													SCREAMING_SNAKE_CASE       :   Optional[Any]         =      image_embeds.repeat_interleave(lowerCAmelCase__					,     dim=0					)

													if do_classifier_free_guidance:
																				SCREAMING_SNAKE_CASE       :   str         =      torch.zeros_like(lowerCAmelCase__					)

																				# 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
																				SCREAMING_SNAKE_CASE       :   List[Any]         =      torch.cat([negative_image_embeds, image_embeds]					)

													return image_embeds







						@torch.no_grad()
						@replace_example_docstring(lowerCAmelCase__					)
						def __call__(	self :   List[Any]					,     lowerCAmelCase__ :   Union[PIL.Image.Image, List[PIL.Image.Image]]					,     lowerCAmelCase__ :   int = 1					,     lowerCAmelCase__ :   int = 25					,     lowerCAmelCase__ :   Optional[Union[torch.Generator, List[torch.Generator]]] = None					,     lowerCAmelCase__ :   Optional[torch.FloatTensor] = None					,     lowerCAmelCase__ :   float = 4.0					,     lowerCAmelCase__ :   int = 64					,     lowerCAmelCase__ :   Optional[str] = "pil"					,     lowerCAmelCase__ :   bool = True					,     ):

													"""simple docstring"""

													if isinstance(lowerCAmelCase__					,     PIL.Image.Image					):
																				SCREAMING_SNAKE_CASE       :   Tuple         =      1
													elif isinstance(lowerCAmelCase__					,     torch.Tensor					):
																				SCREAMING_SNAKE_CASE       :   List[str]         =      image.shape[0]
													elif isinstance(lowerCAmelCase__					,     lowerCAmelCase__					) and isinstance(image[0]					,     (torch.Tensor, PIL.Image.Image)					):
																				SCREAMING_SNAKE_CASE       :   Any         =      len(lowerCAmelCase__					)
													else:
																				raise ValueError(
																				    F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(lowerCAmelCase__					)}"""					)

													SCREAMING_SNAKE_CASE       :   List[str]         =      self._execution_device

													SCREAMING_SNAKE_CASE       :   List[str]         =      batch_size * num_images_per_prompt

													SCREAMING_SNAKE_CASE       :   List[Any]         =      guidance_scale > 1.0
													SCREAMING_SNAKE_CASE       :   int         =      self._encode_image(lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					)

													# prior

													self.scheduler.set_timesteps(lowerCAmelCase__					,     device=lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   Dict         =      self.scheduler.timesteps

													SCREAMING_SNAKE_CASE       :   int         =      self.prior.config.num_embeddings
													SCREAMING_SNAKE_CASE       :   Optional[Any]         =      self.prior.config.embedding_dim

													SCREAMING_SNAKE_CASE       :   Dict         =      self.prepare_latents(
													    (batch_size, num_embeddings * embedding_dim)					,     image_embeds.dtype					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     self.scheduler					,     )

													# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
													SCREAMING_SNAKE_CASE       :   Tuple         =      latents.reshape(latents.shape[0]					,     lowerCAmelCase__					,     lowerCAmelCase__					)

													for i, t in enumerate(self.progress_bar(lowerCAmelCase__					)					):
																				# expand the latents if we are doing classifier free guidance
																				SCREAMING_SNAKE_CASE       :   Optional[int]         =      torch.cat([latents] * 2					) if do_classifier_free_guidance else latents
																				SCREAMING_SNAKE_CASE       :   List[str]         =      self.scheduler.scale_model_input(lowerCAmelCase__					,     lowerCAmelCase__					)

																				SCREAMING_SNAKE_CASE       :   int         =      self.prior(
																				    lowerCAmelCase__					,     timestep=lowerCAmelCase__					,     proj_embedding=lowerCAmelCase__					,     ).predicted_image_embedding

																				# remove the variance
																				SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   Any         =      noise_pred.split(
																				    scaled_model_input.shape[2]					,     dim=2					)  # batch_size, num_embeddings, embedding_dim

																				if do_classifier_free_guidance is not None:
																											SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   Optional[Any]         =      noise_pred.chunk(2					)
																											SCREAMING_SNAKE_CASE       :   Dict         =      noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

																				SCREAMING_SNAKE_CASE       :   str         =      self.scheduler.step(
																				    lowerCAmelCase__					,     timestep=lowerCAmelCase__					,     sample=lowerCAmelCase__					,     ).prev_sample

													if output_type == "latent":
																				return ShapEPipelineOutput(images=lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Dict         =      []
													for i, latent in enumerate(lowerCAmelCase__					):
																				print()
																				SCREAMING_SNAKE_CASE       :   str         =      self.renderer.decode(
																				    latent[None, :]					,     lowerCAmelCase__					,     size=lowerCAmelCase__					,     ray_batch_size=40_96					,     n_coarse_samples=64					,     n_fine_samples=1_28					,     )

																				images.append(lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Optional[Any]         =      torch.stack(lowerCAmelCase__					)

													if output_type not in ["np", "pil"]:
																				raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}"""					)

													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      images.cpu().numpy()

													if output_type == "pil":
																				SCREAMING_SNAKE_CASE       :   str         =      [self.numpy_to_pil(lowerCAmelCase__					) for image in images]

													# Offload last model to CPU
													if hasattr(self					,     '''final_offload_hook'''					) and self.final_offload_hook is not None:
																				self.final_offload_hook.offload()

													if not return_dict:
																				return (images,)

													return ShapEPipelineOutput(images=lowerCAmelCase__					)









'''simple docstring'''



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')

lowerCAmelCase_  :							Optional[int]             =    logging.getLogger(__name__)
@dataclass
class 						lowerCamelCase_				:
						_lowerCAmelCase  : str						  =					field(
						    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}      )
						_lowerCAmelCase  : Optional[str]						  =					field(
						    default=snake_case_     ,					metadata={'help': 'Pretrained config name or path if not the same as model_name'}      )
						_lowerCAmelCase  : Optional[str]						  =					field(
						    default=snake_case_     ,					metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}      )
						_lowerCAmelCase  : Optional[str]						  =					field(
						    default=snake_case_     ,					metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}     ,					)
						_lowerCAmelCase  : bool						  =					field(
						    default=snake_case_     ,					metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'}     ,					)
						_lowerCAmelCase  : str						  =					field(
						    default='main'     ,					metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}     ,					)
						_lowerCAmelCase  : bool						  =					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 						lowerCamelCase_				:
						_lowerCAmelCase  : Optional[str]						  =					field(default=snake_case_     ,					metadata={'help': 'The input training data file (a text file).'}      )
						_lowerCAmelCase  : Optional[str]						  =					field(
						    default=snake_case_     ,					metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'}     ,					)
						_lowerCAmelCase  : bool						  =					field(
						    default=snake_case_     ,					metadata={'help': 'Overwrite the cached training and evaluation sets'}      )
						_lowerCAmelCase  : Optional[int]						  =					field(
						    default=snake_case_     ,					metadata={'help': 'The number of processes to use for the preprocessing.'}     ,					)
						_lowerCAmelCase  : Optional[int]						  =					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.'
						        )
						    }     ,					)
						_lowerCAmelCase  : bool						  =					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.'
						        )
						    }     ,					)
						_lowerCAmelCase  : Optional[int]						  =					field(
						    default=snake_case_     ,					metadata={
						        'help': (
						            'For debugging purposes or quicker training, truncate the number of training examples to this '
						            'value if set.'
						        )
						    }     ,					)
						_lowerCAmelCase  : Optional[int]						  =					field(
						    default=snake_case_     ,					metadata={
						        'help': (
						            'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
						            'value if set.'
						        )
						    }     ,					)







						def        __lowercase     (	self :   Tuple					):

													"""simple docstring"""
													if self.train_file is not None:
																				SCREAMING_SNAKE_CASE       :   List[str]         =      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:
																				SCREAMING_SNAKE_CASE       :   List[Any]         =      self.validation_file.split('''.'''					)[-1]
																				assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."


@dataclass
class 						lowerCamelCase_				:
						_lowerCAmelCase  : PreTrainedTokenizerBase
						_lowerCAmelCase  : Union[bool, str, PaddingStrategy]						  =					True
						_lowerCAmelCase  : Optional[int]						  =					None
						_lowerCAmelCase  : Optional[int]						  =					None







						def __call__(	self :   List[Any]					,     lowerCAmelCase__ :   List[Any]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Dict         =      '''label''' if '''label''' in features[0].keys() else '''labels'''
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      [feature.pop(lowerCAmelCase__					) for feature in features]
													SCREAMING_SNAKE_CASE       :   List[Any]         =      len(lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   Any         =      len(features[0]['''input_ids''']					)
													SCREAMING_SNAKE_CASE       :   str         =      [
													    [{k: v[i] for k, v in feature.items()} for i in range(lowerCAmelCase__					)] for feature in features
													]
													SCREAMING_SNAKE_CASE       :   Optional[int]         =      list(chain(*lowerCAmelCase__					)					)

													SCREAMING_SNAKE_CASE       :   Dict         =      self.tokenizer.pad(
													    lowerCAmelCase__					,     padding=self.padding					,     max_length=self.max_length					,     pad_to_multiple_of=self.pad_to_multiple_of					,     return_tensors='''pt'''					,     )

													# Un-flatten
													SCREAMING_SNAKE_CASE       :   int         =      {k: v.view(lowerCAmelCase__					,     lowerCAmelCase__					,     -1					) for k, v in batch.items()}
													# Add back labels
													SCREAMING_SNAKE_CASE       :   List[str]         =      torch.tensor(lowerCAmelCase__					,     dtype=torch.intaa					)
													return batch


def        UpperCAmelCase (    ):
							# 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       :   Optional[Any]         =      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.
														SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   Tuple         =      parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]					)					)
							else:
														SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      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'''       ,		A       ,		A					)

							# 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       :   Tuple         =      training_args.get_process_log_level()
							logger.setLevel(A					)
							datasets.utils.logging.set_verbosity(A					)
							transformers.utils.logging.set_verbosity(A					)
							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       :   Dict         =      None
							if os.path.isdir(training_args.output_dir					) and training_args.do_train and not training_args.overwrite_output_dir:
														SCREAMING_SNAKE_CASE       :   Optional[int]         =      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:
														SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      {}
														if data_args.train_file is not None:
																					SCREAMING_SNAKE_CASE       :   Dict         =      data_args.train_file
														if data_args.validation_file is not None:
																					SCREAMING_SNAKE_CASE       :   Dict         =      data_args.validation_file
														SCREAMING_SNAKE_CASE       :   List[str]         =      data_args.train_file.split('''.'''					)[-1]
														SCREAMING_SNAKE_CASE       :   Optional[int]         =      load_dataset(
														    A       ,		data_files=A       ,		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.
														SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      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.
							SCREAMING_SNAKE_CASE       :   Tuple         =      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       ,		)
							SCREAMING_SNAKE_CASE       :   Tuple         =      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       ,		)
							SCREAMING_SNAKE_CASE       :   int         =      AutoModelForMultipleChoice.from_pretrained(
							    model_args.model_name_or_path       ,		from_tf=bool('''.ckpt''' in model_args.model_name_or_path					)       ,		config=A       ,		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.
							SCREAMING_SNAKE_CASE       :   Optional[Any]         =      [F"""ending{i}""" for i in range(4					)]
							SCREAMING_SNAKE_CASE       :   Any         =      '''sent1'''
							SCREAMING_SNAKE_CASE       :   Tuple         =      '''sent2'''

							if data_args.max_seq_length is None:
														SCREAMING_SNAKE_CASE       :   List[str]         =      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`.'''					)
																					SCREAMING_SNAKE_CASE       :   List[str]         =      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}."""					)
														SCREAMING_SNAKE_CASE       :   Tuple         =      min(data_args.max_seq_length       ,		tokenizer.model_max_length					)

							# Preprocessing the datasets.
							def preprocess_function(A	:					Any					):
														SCREAMING_SNAKE_CASE       :   int         =      [[context] * 4 for context in examples[context_name]]
														SCREAMING_SNAKE_CASE       :   str         =      examples[question_header_name]
														SCREAMING_SNAKE_CASE       :   List[Any]         =      [
														    [F"""{header} {examples[end][i]}""" for end in ending_names] for i, header in enumerate(A					)
														]

														# Flatten out
														SCREAMING_SNAKE_CASE       :   List[str]         =      list(chain(*A					)					)
														SCREAMING_SNAKE_CASE       :   int         =      list(chain(*A					)					)

														# Tokenize
														SCREAMING_SNAKE_CASE       :   Optional[int]         =      tokenizer(
														    A       ,		A       ,		truncation=A       ,		max_length=A       ,		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(A					)       ,		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'''					)
														SCREAMING_SNAKE_CASE       :   str         =      raw_datasets['''train''']
														if data_args.max_train_samples is not None:
																					SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      min(len(A					)       ,		data_args.max_train_samples					)
																					SCREAMING_SNAKE_CASE       :   Optional[Any]         =      train_dataset.select(range(A					)					)
														with training_args.main_process_first(desc='''train dataset map pre-processing'''					):
																					SCREAMING_SNAKE_CASE       :   str         =      train_dataset.map(
																					    A       ,		batched=A       ,		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'''					)
														SCREAMING_SNAKE_CASE       :   str         =      raw_datasets['''validation''']
														if data_args.max_eval_samples is not None:
																					SCREAMING_SNAKE_CASE       :   List[Any]         =      min(len(A					)       ,		data_args.max_eval_samples					)
																					SCREAMING_SNAKE_CASE       :   int         =      eval_dataset.select(range(A					)					)
														with training_args.main_process_first(desc='''validation dataset map pre-processing'''					):
																					SCREAMING_SNAKE_CASE       :   Tuple         =      eval_dataset.map(
																					    A       ,		batched=A       ,		num_proc=data_args.preprocessing_num_workers       ,		load_from_cache_file=not data_args.overwrite_cache       ,		)

    # Data collator
							SCREAMING_SNAKE_CASE       :   Optional[int]         =      (
							    default_data_collator
							    if data_args.pad_to_max_length
							    else DataCollatorForMultipleChoice(tokenizer=A       ,		pad_to_multiple_of=8 if training_args.fpaa else None					)
							)

							# Metric
							def compute_metrics(A	:					str					):
														SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   Optional[Any]         =      eval_predictions
														SCREAMING_SNAKE_CASE       :   Any         =      np.argmax(A       ,		axis=1					)
														return {"accuracy": (preds == label_ids).astype(np.floataa					).mean().item()}

							# Initialize our Trainer
							SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      Trainer(
							    model=A       ,		args=A       ,		train_dataset=train_dataset if training_args.do_train else None       ,		eval_dataset=eval_dataset if training_args.do_eval else None       ,		tokenizer=A       ,		data_collator=A       ,		compute_metrics=A       ,		)

							# Training
							if training_args.do_train:
														SCREAMING_SNAKE_CASE       :   Optional[Any]         =      None
														if training_args.resume_from_checkpoint is not None:
																					SCREAMING_SNAKE_CASE       :   Dict         =      training_args.resume_from_checkpoint
														elif last_checkpoint is not None:
																					SCREAMING_SNAKE_CASE       :   List[Any]         =      last_checkpoint
														SCREAMING_SNAKE_CASE       :   List[Any]         =      trainer.train(resume_from_checkpoint=A					)
														trainer.save_model()  # Saves the tokenizer too for easy upload
														SCREAMING_SNAKE_CASE       :   List[str]         =      train_result.metrics

														SCREAMING_SNAKE_CASE       :   str         =      (
														    data_args.max_train_samples if data_args.max_train_samples is not None else len(A					)
														)
														SCREAMING_SNAKE_CASE       :   Dict         =      min(A       ,		len(A					)					)

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

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

														SCREAMING_SNAKE_CASE       :   Optional[int]         =      trainer.evaluate()
														SCREAMING_SNAKE_CASE       :   int         =      data_args.max_eval_samples if data_args.max_eval_samples is not None else len(A					)
														SCREAMING_SNAKE_CASE       :   List[str]         =      min(A       ,		len(A					)					)

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

							SCREAMING_SNAKE_CASE       :   Dict         =      {
							    '''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(**A					)
							else:
														trainer.create_model_card(**A					)
def        UpperCAmelCase (    A	:					str					):
							# For xla_spawn (TPUs)
							main()


if __name__ == "__main__":
							main()




