
from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


lowerCamelCase_						: Optional[Any]         =  logging.get_logger(__name__)

# General docstring
lowerCamelCase_						: Tuple         =  """RegNetConfig"""

# Base docstring
lowerCamelCase_						: List[Any]         =  """facebook/regnet-y-040"""
lowerCamelCase_						: Any         =  [1, 10_88, 7, 7]

# Image classification docstring
lowerCamelCase_						: Optional[Any]         =  """facebook/regnet-y-040"""
lowerCamelCase_						: List[str]         =  """tabby, tabby cat"""

lowerCamelCase_						: Any         =  [
    """facebook/regnet-y-040""",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]

class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			def __init__(       self :       Any						,	snake_case_ :       int						,	snake_case_ :       int = 3						,	snake_case_ :       int = 1						,	snake_case_ :       int = 1						,	snake_case_ :       Optional[str] = "relu"						,	**snake_case_ :       List[Any]						,	):
							super().__init__(**snake_case_      )
							# The padding and conv has been verified in
							# https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
							UpperCamelCase_:							int	=						tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2      )
							UpperCamelCase_:							Optional[Any]	=						tf.keras.layers.ConvaD(
							    filters=snake_case_						,	kernel_size=snake_case_						,	strides=snake_case_						,	padding="""VALID"""						,	groups=snake_case_						,	use_bias=snake_case_						,	name="""convolution"""						,	)
							UpperCamelCase_:							List[str]	=						tf.keras.layers.BatchNormalization(epsilon=1e-5						,	momentum=0.9						,	name="""normalization"""      )
							UpperCamelCase_:							Dict	=						ACTaFN[activation] if activation is not None else tf.identity




			def       lowerCAmelCase__	(       self :       str						,	snake_case_ :       Union[str, Any]      ):
							UpperCamelCase_:							Dict	=						self.convolution(self.padding(snake_case_      )      )
							UpperCamelCase_:							int	=						self.normalization(snake_case_      )
							UpperCamelCase_:							int	=						self.activation(snake_case_      )
							return hidden_state




class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			def __init__(       self :       Union[str, Any]						,	snake_case_ :       RegNetConfig						,	**snake_case_ :       Any      ):
							super().__init__(**snake_case_      )
							UpperCamelCase_:							Union[str, Any]	=						config.num_channels
							UpperCamelCase_:							List[Any]	=						TFRegNetConvLayer(
							    out_channels=config.embedding_size						,	kernel_size=3						,	stride=2						,	activation=config.hidden_act						,	name="""embedder"""						,	)




			def       lowerCAmelCase__	(       self :       Union[str, Any]						,	snake_case_ :       str      ):
							UpperCamelCase_:							str	=						shape_list(snake_case_      )[1]
							if tf.executing_eagerly() and num_channels != self.num_channels:
											raise ValueError(
											    """Make sure that the channel dimension of the pixel values match with the one set in the configuration."""      )

							# When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
							# So change the input format from `NCHW` to `NHWC`.
							# shape = (batch_size, in_height, in_width, in_channels=num_channels)
							UpperCamelCase_:							str	=						tf.transpose(snake_case_						,	perm=(0, 2, 3, 1)      )
							UpperCamelCase_:							str	=						self.embedder(snake_case_      )
							return hidden_state




class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			def __init__(       self :       Union[str, Any]						,	snake_case_ :       int						,	snake_case_ :       int = 2						,	**snake_case_ :       Optional[Any]      ):
							super().__init__(**snake_case_      )
							UpperCamelCase_:							str	=						tf.keras.layers.ConvaD(
							    filters=snake_case_						,	kernel_size=1						,	strides=snake_case_						,	use_bias=snake_case_						,	name="""convolution"""      )
							UpperCamelCase_:							int	=						tf.keras.layers.BatchNormalization(epsilon=1e-5						,	momentum=0.9						,	name="""normalization"""      )




			def       lowerCAmelCase__	(       self :       Any						,	snake_case_ :       tf.Tensor						,	snake_case_ :       bool = False      ):
							return self.normalization(self.convolution(snake_case_      )						,	training=snake_case_      )




class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			def __init__(       self :       Tuple						,	snake_case_ :       int						,	snake_case_ :       int						,	**snake_case_ :       List[str]      ):
							super().__init__(**snake_case_      )
							UpperCamelCase_:							str	=						tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case_						,	name="""pooler"""      )
							UpperCamelCase_:							List[Any]	=						[
							    tf.keras.layers.ConvaD(filters=snake_case_						,	kernel_size=1						,	activation="""relu"""						,	name="""attention.0"""      ),
							    tf.keras.layers.ConvaD(filters=snake_case_						,	kernel_size=1						,	activation="""sigmoid"""						,	name="""attention.2"""      ),
							]




			def       lowerCAmelCase__	(       self :       List[Any]						,	snake_case_ :       Dict      ):
							# [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels]
							UpperCamelCase_:							List[str]	=						self.pooler(snake_case_      )
							for layer_module in self.attention:
											UpperCamelCase_:							Union[str, Any]	=						layer_module(snake_case_      )
							UpperCamelCase_:							Dict	=						hidden_state * pooled
							return hidden_state




class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			def __init__(       self :       str						,	snake_case_ :       RegNetConfig						,	snake_case_ :       int						,	snake_case_ :       int						,	snake_case_ :       int = 1						,	**snake_case_ :       Dict      ):
							super().__init__(**snake_case_      )
							UpperCamelCase_:							List[str]	=						in_channels != out_channels or stride != 1
							UpperCamelCase_:							Tuple	=						max(1						,	out_channels // config.groups_width      )
							UpperCamelCase_:							Tuple	=						(
							    TFRegNetShortCut(snake_case_						,	stride=snake_case_						,	name="""shortcut"""      )
							    if should_apply_shortcut
							    else tf.keras.layers.Activation("""linear"""						,	name="""shortcut"""      )
							)
							# `self.layers` instead of `self.layer` because that is a reserved argument.
							UpperCamelCase_:							Any	=						[
							    TFRegNetConvLayer(snake_case_						,	kernel_size=1						,	activation=config.hidden_act						,	name="""layer.0"""      ),
							    TFRegNetConvLayer(
							        snake_case_						,	stride=snake_case_						,	groups=snake_case_						,	activation=config.hidden_act						,	name="""layer.1"""      ),
							    TFRegNetConvLayer(snake_case_						,	kernel_size=1						,	activation=snake_case_						,	name="""layer.2"""      ),
							]
							UpperCamelCase_:							Union[str, Any]	=						ACTaFN[config.hidden_act]




			def       lowerCAmelCase__	(       self :       List[Any]						,	snake_case_ :       Tuple      ):
							UpperCamelCase_:							Optional[Any]	=						hidden_state
							for layer_module in self.layers:
											UpperCamelCase_:							Union[str, Any]	=						layer_module(snake_case_      )
							UpperCamelCase_:							Optional[int]	=						self.shortcut(snake_case_      )
							hidden_state += residual
							UpperCamelCase_:							List[str]	=						self.activation(snake_case_      )
							return hidden_state




class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			def __init__(       self :       Optional[Any]						,	snake_case_ :       RegNetConfig						,	snake_case_ :       int						,	snake_case_ :       int						,	snake_case_ :       int = 1						,	**snake_case_ :       List[Any]      ):
							super().__init__(**snake_case_      )
							UpperCamelCase_:							Union[str, Any]	=						in_channels != out_channels or stride != 1
							UpperCamelCase_:							str	=						max(1						,	out_channels // config.groups_width      )
							UpperCamelCase_:							List[str]	=						(
							    TFRegNetShortCut(snake_case_						,	stride=snake_case_						,	name="""shortcut"""      )
							    if should_apply_shortcut
							    else tf.keras.layers.Activation("""linear"""						,	name="""shortcut"""      )
							)
							UpperCamelCase_:							str	=						[
							    TFRegNetConvLayer(snake_case_						,	kernel_size=1						,	activation=config.hidden_act						,	name="""layer.0"""      ),
							    TFRegNetConvLayer(
							        snake_case_						,	stride=snake_case_						,	groups=snake_case_						,	activation=config.hidden_act						,	name="""layer.1"""      ),
							    TFRegNetSELayer(snake_case_						,	reduced_channels=int(round(in_channels / 4      )      )						,	name="""layer.2"""      ),
							    TFRegNetConvLayer(snake_case_						,	kernel_size=1						,	activation=snake_case_						,	name="""layer.3"""      ),
							]
							UpperCamelCase_:							List[str]	=						ACTaFN[config.hidden_act]




			def       lowerCAmelCase__	(       self :       List[Any]						,	snake_case_ :       int      ):
							UpperCamelCase_:							Union[str, Any]	=						hidden_state
							for layer_module in self.layers:
											UpperCamelCase_:							str	=						layer_module(snake_case_      )
							UpperCamelCase_:							Optional[int]	=						self.shortcut(snake_case_      )
							hidden_state += residual
							UpperCamelCase_:							Optional[int]	=						self.activation(snake_case_      )
							return hidden_state




class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			def __init__(       self :       List[str]						,	snake_case_ :       RegNetConfig						,	snake_case_ :       int						,	snake_case_ :       int						,	snake_case_ :       int = 2						,	snake_case_ :       int = 2						,	**snake_case_ :       Any      ):
							super().__init__(**snake_case_      )

							UpperCamelCase_:							Dict	=						TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer
							UpperCamelCase_:							str	=						[
							    # downsampling is done in the first layer with stride of 2
							    layer(snake_case_						,	snake_case_						,	snake_case_						,	stride=snake_case_						,	name="""layers.0"""      ),
							    *[layer(snake_case_						,	snake_case_						,	snake_case_						,	name=f'''layers.{i+1}'''      ) for i in range(depth - 1      )],
							]




			def       lowerCAmelCase__	(       self :       List[Any]						,	snake_case_ :       List[Any]      ):
							for layer_module in self.layers:
											UpperCamelCase_:							Any	=						layer_module(snake_case_      )
							return hidden_state




class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			def __init__(       self :       Tuple						,	snake_case_ :       RegNetConfig						,	**snake_case_ :       Optional[int]      ):
							super().__init__(**snake_case_      )
							UpperCamelCase_:							Any	=						[]
							# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
							self.stages.append(
							    TFRegNetStage(
							        snake_case_						,	config.embedding_size						,	config.hidden_sizes[0]						,	stride=2 if config.downsample_in_first_stage else 1						,	depth=config.depths[0]						,	name="""stages.0"""						,	)      )
							UpperCamelCase_:							Union[str, Any]	=						zip(config.hidden_sizes						,	config.hidden_sizes[1:]      )
							for i, ((in_channels, out_channels), depth) in enumerate(zip(snake_case_						,	config.depths[1:]      )      ):
											self.stages.append(TFRegNetStage(snake_case_						,	snake_case_						,	snake_case_						,	depth=snake_case_						,	name=f'''stages.{i+1}'''      )      )




			def       lowerCAmelCase__	(       self :       List[str]						,	snake_case_ :       tf.Tensor						,	snake_case_ :       bool = False						,	snake_case_ :       bool = True      ):
							UpperCamelCase_:							int	=						() if output_hidden_states else None

							for stage_module in self.stages:
											if output_hidden_states:
															UpperCamelCase_:							str	=						hidden_states + (hidden_state,)

											UpperCamelCase_:							List[Any]	=						stage_module(snake_case_      )

							if output_hidden_states:
											UpperCamelCase_:							Union[str, Any]	=						hidden_states + (hidden_state,)

							if not return_dict:
											return tuple(v for v in [hidden_state, hidden_states] if v is not None      )

							return TFBaseModelOutputWithNoAttention(last_hidden_state=snake_case_						,	hidden_states=snake_case_      )




@keras_serializable
class        _UpperCamelCase				(					tf.keras.layers.Layer  ):






			'''simple docstring'''

			__UpperCamelCase      :						Any					      = RegNetConfig

			def __init__(       self :       Dict						,	snake_case_ :       Union[str, Any]						,	**snake_case_ :       Tuple      ):
							super().__init__(**snake_case_      )
							UpperCamelCase_:							Optional[int]	=						config
							UpperCamelCase_:							Tuple	=						TFRegNetEmbeddings(snake_case_						,	name="""embedder"""      )
							UpperCamelCase_:							Union[str, Any]	=						TFRegNetEncoder(snake_case_						,	name="""encoder"""      )
							UpperCamelCase_:							Any	=						tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case_						,	name="""pooler"""      )




			@unpack_inputs
			def       lowerCAmelCase__	(       self :       Optional[Any]						,	snake_case_ :       tf.Tensor						,	snake_case_ :       Optional[bool] = None						,	snake_case_ :       Optional[bool] = None						,	snake_case_ :       bool = False						,	):
							UpperCamelCase_:							Optional[Any]	=						(
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							UpperCamelCase_:							str	=						return_dict if return_dict is not None else self.config.use_return_dict

							UpperCamelCase_:							str	=						self.embedder(snake_case_						,	training=snake_case_      )

							UpperCamelCase_:							List[str]	=						self.encoder(
							    snake_case_						,	output_hidden_states=snake_case_						,	return_dict=snake_case_						,	training=snake_case_      )

							UpperCamelCase_:							Optional[int]	=						encoder_outputs[0]
							UpperCamelCase_:							Tuple	=						self.pooler(snake_case_      )

							# Change to NCHW output format have uniformity in the modules
							UpperCamelCase_:							Union[str, Any]	=						tf.transpose(snake_case_						,	perm=(0, 3, 1, 2)      )
							UpperCamelCase_:							Any	=						tf.transpose(snake_case_						,	perm=(0, 3, 1, 2)      )

							# Change the other hidden state outputs to NCHW as well
							if output_hidden_states:
											UpperCamelCase_:							List[Any]	=						tuple([tf.transpose(snake_case_						,	perm=(0, 3, 1, 2)      ) for h in encoder_outputs[1]]      )

							if not return_dict:
											return (last_hidden_state, pooled_output) + encoder_outputs[1:]

							return TFBaseModelOutputWithPoolingAndNoAttention(
							    last_hidden_state=snake_case_						,	pooler_output=snake_case_						,	hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states						,	)




class        _UpperCamelCase				(					_A  ):






			'''simple docstring'''

			__UpperCamelCase      :						Any					      = RegNetConfig
			__UpperCamelCase      :						Union[str, Any]					      = """regnet"""
			__UpperCamelCase      :						str					      = """pixel_values"""

			@property
			def       lowerCAmelCase__	(       self :       Optional[Any]      ):
							return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224)						,	dtype=tf.floataa      )}




lowerCamelCase_						: Tuple         =  r"""
    Parameters:
    This model is a Tensorflow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and
    behavior.
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""

lowerCamelCase_						: Tuple         =  r"""
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConveNextImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""

@add_start_docstrings(
    """The bare RegNet model outputting raw features without any specific head on top."""     ,       _A     ,       )
class        _UpperCamelCase				(					_A  ):






			'''simple docstring'''

			def __init__(       self :       Tuple						,	snake_case_ :       RegNetConfig						,	*snake_case_ :       int						,	**snake_case_ :       Union[str, Any]      ):
							super().__init__(snake_case_						,	*snake_case_						,	**snake_case_      )
							UpperCamelCase_:							int	=						TFRegNetMainLayer(snake_case_						,	name="""regnet"""      )




			@unpack_inputs
			@add_start_docstrings_to_model_forward(snake_case_      )
			@add_code_sample_docstrings(
			    checkpoint=_CHECKPOINT_FOR_DOC						,	output_type=snake_case_						,	config_class=_CONFIG_FOR_DOC						,	modality="""vision"""						,	expected_output=_EXPECTED_OUTPUT_SHAPE						,	)
			def       lowerCAmelCase__	(       self :       Tuple						,	snake_case_ :       tf.Tensor						,	snake_case_ :       Optional[bool] = None						,	snake_case_ :       Optional[bool] = None						,	snake_case_ :       List[str]=False						,	):
							UpperCamelCase_:							Union[str, Any]	=						(
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							UpperCamelCase_:							Optional[int]	=						return_dict if return_dict is not None else self.config.use_return_dict

							UpperCamelCase_:							Union[str, Any]	=						self.regnet(
							    pixel_values=snake_case_						,	output_hidden_states=snake_case_						,	return_dict=snake_case_						,	training=snake_case_						,	)
							if not return_dict:
											return (outputs[0],) + outputs[1:]

							return TFBaseModelOutputWithPoolingAndNoAttention(
							    last_hidden_state=outputs.last_hidden_state						,	pooler_output=outputs.pooler_output						,	hidden_states=outputs.hidden_states						,	)




@add_start_docstrings(
    """
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """     ,       _A     ,       )
class        _UpperCamelCase				(					_A     ,       _A  ):






			'''simple docstring'''

			def __init__(       self :       Dict						,	snake_case_ :       RegNetConfig						,	*snake_case_ :       Tuple						,	**snake_case_ :       Union[str, Any]      ):
							super().__init__(snake_case_						,	*snake_case_						,	**snake_case_      )
							UpperCamelCase_:							Union[str, Any]	=						config.num_labels
							UpperCamelCase_:							Optional[Any]	=						TFRegNetMainLayer(snake_case_						,	name="""regnet"""      )
							# classification head
							UpperCamelCase_:							Tuple	=						[
							    tf.keras.layers.Flatten(),
							    tf.keras.layers.Dense(config.num_labels						,	name="""classifier.1"""      ) if config.num_labels > 0 else tf.identity,
							]




			@unpack_inputs
			@add_start_docstrings_to_model_forward(snake_case_      )
			@add_code_sample_docstrings(
			    checkpoint=_IMAGE_CLASS_CHECKPOINT						,	output_type=snake_case_						,	config_class=_CONFIG_FOR_DOC						,	expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT						,	)
			def       lowerCAmelCase__	(       self :       List[Any]						,	snake_case_ :       tf.Tensor = None						,	snake_case_ :       tf.Tensor = None						,	snake_case_ :       bool = None						,	snake_case_ :       bool = None						,	snake_case_ :       Union[str, Any]=False						,	):
							UpperCamelCase_:							int	=						(
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							UpperCamelCase_:							Optional[int]	=						return_dict if return_dict is not None else self.config.use_return_dict

							UpperCamelCase_:							List[str]	=						self.regnet(
							    snake_case_						,	output_hidden_states=snake_case_						,	return_dict=snake_case_						,	training=snake_case_      )

							UpperCamelCase_:							Optional[Any]	=						outputs.pooler_output if return_dict else outputs[1]

							UpperCamelCase_:							List[Any]	=						self.classifier[0](snake_case_      )
							UpperCamelCase_:							Dict	=						self.classifier[1](snake_case_      )

							UpperCamelCase_:							List[Any]	=						None if labels is None else self.hf_compute_loss(labels=snake_case_						,	logits=snake_case_      )

							if not return_dict:
											UpperCamelCase_:							Tuple	=						(logits,) + outputs[2:]
											return ((loss,) + output) if loss is not None else output

							return TFSequenceClassifierOutput(loss=snake_case_						,	logits=snake_case_						,	hidden_states=outputs.hidden_states      )






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_						: List[str]         =  logging.getLogger(__name__)

@dataclass
class        _UpperCamelCase				:






			'''simple docstring'''

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




@dataclass
class        _UpperCamelCase				:






			'''simple docstring'''

			__UpperCamelCase      :						Optional[str]					      = field(default=_A     ,       metadata={"""help""": """The input training data file (a text file)."""}  )
			__UpperCamelCase      :						Optional[str]					      = field(
			    default=_A     ,       metadata={"""help""": """An optional input evaluation data file to evaluate the perplexity on (a text file)."""}     ,       )
			__UpperCamelCase      :						bool					      = field(
			    default=_A     ,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}  )
			__UpperCamelCase      :						Optional[int]					      = field(
			    default=_A     ,       metadata={"""help""": """The number of processes to use for the preprocessing."""}     ,       )
			__UpperCamelCase      :						Optional[int]					      = field(
			    default=_A     ,       metadata={
			        """help""": (
			            """The maximum total input sequence length after tokenization. If passed, sequences longer """
			            """than this will be truncated, sequences shorter will be padded."""
			        )
			    }     ,       )
			__UpperCamelCase      :						bool					      = field(
			    default=_A     ,       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."""
			        )
			    }     ,       )
			__UpperCamelCase      :						Optional[int]					      = field(
			    default=_A     ,       metadata={
			        """help""": (
			            """For debugging purposes or quicker training, truncate the number of training examples to this """
			            """value if set."""
			        )
			    }     ,       )
			__UpperCamelCase      :						Optional[int]					      = field(
			    default=_A     ,       metadata={
			        """help""": (
			            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
			            """value if set."""
			        )
			    }     ,       )

			def       lowerCAmelCase__	(       self :       Dict      ):
							if self.train_file is not None:
											UpperCamelCase_:							Union[str, Any]	=						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:
											UpperCamelCase_:							Dict	=						self.validation_file.split("""."""      )[-1]
											assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."




@dataclass
class        _UpperCamelCase				:






			'''simple docstring'''

			__UpperCamelCase      :						PreTrainedTokenizerBase
			__UpperCamelCase      :						Union[bool, str, PaddingStrategy]					      = True
			__UpperCamelCase      :						Optional[int]					      = None
			__UpperCamelCase      :						Optional[int]					      = None

			def __call__(       self :       Optional[int]						,	snake_case_ :       Dict      ):
							UpperCamelCase_:							Dict	=						"""label""" if """label""" in features[0].keys() else """labels"""
							UpperCamelCase_:							int	=						[feature.pop(snake_case_      ) for feature in features]
							UpperCamelCase_:							Optional[Any]	=						len(snake_case_      )
							UpperCamelCase_:							List[str]	=						len(features[0]["""input_ids"""]      )
							UpperCamelCase_:							Tuple	=						[
							    [{k: v[i] for k, v in feature.items()} for i in range(snake_case_      )] for feature in features
							]
							UpperCamelCase_:							Any	=						list(chain(*snake_case_      )      )

							UpperCamelCase_:							List[Any]	=						self.tokenizer.pad(
							    snake_case_						,	padding=self.padding						,	max_length=self.max_length						,	pad_to_multiple_of=self.pad_to_multiple_of						,	return_tensors="""pt"""						,	)

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







def        A__					(						)  ->	Tuple:
				# 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.

				UpperCamelCase_:							str	=						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.
								UpperCamelCase_,   UpperCamelCase_,   UpperCamelCase_:							int	=						parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
				else:
								UpperCamelCase_,   UpperCamelCase_,   UpperCamelCase_:							List[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_swag"""     ,    lowerCamelCase     ,    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()

				UpperCamelCase_:							Dict	=						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.
				UpperCamelCase_:							List[str]	=						None
				if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
								UpperCamelCase_:							List[str]	=						get_last_checkpoint(training_args.output_dir						)
								if last_checkpoint is None and len(os.listdir(training_args.output_dir						)						) > 0:
												raise ValueError(
												    F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
												    """Use --overwrite_output_dir to overcome."""						)
								elif last_checkpoint is not None 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:
								UpperCamelCase_:							List[str]	=						{}
								if data_args.train_file is not None:
												UpperCamelCase_:							List[Any]	=						data_args.train_file
								if data_args.validation_file is not None:
												UpperCamelCase_:							Optional[int]	=						data_args.validation_file
								UpperCamelCase_:							Any	=						data_args.train_file.split("""."""						)[-1]
								UpperCamelCase_:							Tuple	=						load_dataset(
								    lowerCamelCase     ,    data_files=lowerCamelCase     ,    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.
								UpperCamelCase_:							int	=						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.
				UpperCamelCase_:							Optional[int]	=						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     ,    )
				UpperCamelCase_:							Union[str, Any]	=						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     ,    )
				UpperCamelCase_:							List[str]	=						AutoModelForMultipleChoice.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     ,    )

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

				if data_args.max_seq_length is None:
								UpperCamelCase_:							int	=						tokenizer.model_max_length
								if max_seq_length > 10_24:
												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`."""						)
												UpperCamelCase_:							Optional[Any]	=						10_24
				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}.'''						)
								UpperCamelCase_:							Union[str, Any]	=						min(data_args.max_seq_length     ,    tokenizer.model_max_length						)

				# Preprocessing the datasets.
				def preprocess_function(lowerCamelCase						):
								UpperCamelCase_:							Optional[Any]	=						[[context] * 4 for context in examples[context_name]]
								UpperCamelCase_:							Dict	=						examples[question_header_name]
								UpperCamelCase_:							List[str]	=						[
								    [F'''{header} {examples[end][i]}''' for end in ending_names] for i, header in enumerate(lowerCamelCase						)
								]

								# Flatten out
								UpperCamelCase_:							str	=						list(chain(*lowerCamelCase						)						)
								UpperCamelCase_:							Any	=						list(chain(*lowerCamelCase						)						)

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

    # Data collator
				UpperCamelCase_:							str	=						(
				    default_data_collator
				    if data_args.pad_to_max_length
				    else DataCollatorForMultipleChoice(tokenizer=lowerCamelCase     ,    pad_to_multiple_of=8 if training_args.fpaa else None						)
				)

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

				# Initialize our Trainer
				UpperCamelCase_:							Union[str, 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     ,    tokenizer=lowerCamelCase     ,    data_collator=lowerCamelCase     ,    compute_metrics=lowerCamelCase     ,    )

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

								UpperCamelCase_:							Tuple	=						(
								    data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCamelCase						)
								)
								UpperCamelCase_:							Optional[Any]	=						min(lowerCamelCase     ,    len(lowerCamelCase						)						)

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

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

								UpperCamelCase_:							Optional[Any]	=						trainer.evaluate()
								UpperCamelCase_:							Tuple	=						data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCamelCase						)
								UpperCamelCase_:							Optional[Any]	=						min(lowerCamelCase     ,    len(lowerCamelCase						)						)

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

				UpperCamelCase_:							Optional[int]	=						{
				    """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(**lowerCamelCase						)
				else:
								trainer.create_model_card(**lowerCamelCase						)







def        A__					(						lowerCamelCase						)  ->	Tuple:
				# For xla_spawn (TPUs)
				main()


if __name__ == "__main__":
							main()






