



import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from PIL import Image
from torchvision.transforms import (
    CenterCrop,
    Compose,
    Normalize,
    RandomHorizontalFlip,
    RandomResizedCrop,
    Resize,
    ToTensor,
)

import transformers
from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForImageClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
snake_case    :						str  =						logging.getLogger(__name__)

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

require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-classification/requirements.txt')

snake_case    :						List[str]  =						list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
snake_case    :						int  =						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
def 	snake_case__       (					__lowercase       )		->		str:







						"""simple docstring"""

						with open(__lowercase							,     "rb"       ) as f:
												A__	:							List[Any]						    = Image.open(__lowercase       )
												return im.convert("RGB"       )




@dataclass
class 							lowerCAmelCase__  :
					__A     :    Optional[str]           =						field(
					    default=UpperCamelCase					,							metadata={
					        'help': 'Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'
					    }					,							)
					__A     :    Optional[str]           =						field(
					    default=UpperCamelCase					,							metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}						)
					__A     :    Optional[str]           =						field(default=UpperCamelCase					,							metadata={'help': 'A folder containing the training data.'}						)
					__A     :    Optional[str]           =						field(default=UpperCamelCase					,							metadata={'help': 'A folder containing the validation data.'}						)
					__A     :    Optional[float]           =						field(
					    default=0.15					,							metadata={'help': 'Percent to split off of train for validation.'}						)
					__A     :    Optional[int]           =						field(
					    default=UpperCamelCase					,							metadata={
					        'help': (
					            'For debugging purposes or quicker training, truncate the number of training examples to this '
					            'value if set.'
					        )
					    }					,							)
					__A     :    Optional[int]           =						field(
					    default=UpperCamelCase					,							metadata={
					        'help': (
					            'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
					            'value if set.'
					        )
					    }					,							)







					def  _lowercase			(       self      :     Tuple):
											if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
																	raise ValueError(
																	    "You must specify either a dataset name from the hub or a train and/or validation directory.")




@dataclass
class 							lowerCAmelCase__  :
					__A     :    str           =						field(
					    default='google/vit-base-patch16-224-in21k'					,							metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}					,							)
					__A     :    Optional[str]           =						field(
					    default=UpperCamelCase					,							metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(UpperCamelCase						)}					,							)
					__A     :    Optional[str]           =						field(
					    default=UpperCamelCase					,							metadata={'help': 'Pretrained config name or path if not the same as model_name'}						)
					__A     :    Optional[str]           =						field(
					    default=UpperCamelCase					,							metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'}						)
					__A     :    str           =						field(
					    default='main'					,							metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}					,							)
					__A     :    str           =						field(default=UpperCamelCase					,							metadata={'help': 'Name or path of preprocessor config.'}						)
					__A     :    bool           =						field(
					    default=UpperCamelCase					,							metadata={
					        'help': (
					            'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
					            'with private models).'
					        )
					    }					,							)
					__A     :    bool           =						field(
					    default=UpperCamelCase					,							metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'}					,							)




def 	snake_case__       (					__lowercase       )		->		str:







						"""simple docstring"""

						A__	:							List[str]						    = torch.stack([example["pixel_values"] for example in examples]       )
						A__	:							Any						    = torch.tensor([example["labels"] for example in examples]       )
						return {"pixel_values": pixel_values, "labels": labels}
def 	snake_case__       (					)		->		int:







						"""simple docstring"""

						A__	:							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.
												A__    ,       A__    ,       A__	:							str						    = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
						else:
												A__    ,       A__    ,       A__	:							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_image_classification"							,     __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()

						A__	:							List[Any]						    = training_args.get_process_log_level()
						logger.setLevel(__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.
						A__	:							List[Any]						    = None
						if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
												A__	:							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       )

						# Initialize our dataset and prepare it for the 'image-classification' task.
						if data_args.dataset_name is not None:
												A__	:							Optional[int]						    = load_dataset(
												    data_args.dataset_name							,     data_args.dataset_config_name							,     cache_dir=model_args.cache_dir							,     task="image-classification"							,     use_auth_token=True if model_args.use_auth_token else None							,     )
						else:
												A__	:							Optional[int]						    = {}
												if data_args.train_dir is not None:
																		A__	:							Optional[Any]						    = os.path.join(data_args.train_dir							,     "**"       )
												if data_args.validation_dir is not None:
																		A__	:							int						    = os.path.join(data_args.validation_dir							,     "**"       )
												A__	:							Optional[Any]						    = load_dataset(
												    "imagefolder"							,     data_files=__lowercase							,     cache_dir=model_args.cache_dir							,     task="image-classification"							,     )

						# If we don't have a validation split, split off a percentage of train as validation.
						A__	:							Any						    = None if "validation" in dataset.keys() else data_args.train_val_split
						if isinstance(data_args.train_val_split							,     __lowercase       ) and data_args.train_val_split > 0.0:
												A__	:							Dict						    = dataset["train"].train_test_split(data_args.train_val_split       )
												A__	:							Union[str, Any]						    = split["train"]
												A__	:							Optional[int]						    = split["test"]

						# Prepare label mappings.
						# We'll include these in the model's config to get human readable labels in the Inference API.
						A__	:							int						    = dataset["train"].features["labels"].names
						A__    ,       A__	:							List[Any]						    = {}, {}
						for i, label in enumerate(__lowercase       ):
												A__	:							Dict						    = str(__lowercase       )
												A__	:							Tuple						    = label

						# Load the accuracy metric from the datasets package
						A__	:							List[Any]						    = evaluate.load("accuracy"       )

						# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
						# predictions and label_ids field) and has to return a dictionary string to float.
						def compute_metrics(__lowercase       ):
												return metric.compute(predictions=np.argmax(p.predictions							,     axis=1       )							,     references=p.label_ids       )

						A__	:							List[str]						    = AutoConfig.from_pretrained(
						    model_args.config_name or model_args.model_name_or_path							,     num_labels=len(__lowercase       )							,     labelaid=__lowercase							,     idalabel=__lowercase							,     finetuning_task="image-classification"							,     cache_dir=model_args.cache_dir							,     revision=model_args.model_revision							,     use_auth_token=True if model_args.use_auth_token else None							,     )
						A__	:							Union[str, Any]						    = AutoModelForImageClassification.from_pretrained(
						    model_args.model_name_or_path							,     from_tf=bool(".ckpt" in model_args.model_name_or_path       )							,     config=__lowercase							,     cache_dir=model_args.cache_dir							,     revision=model_args.model_revision							,     use_auth_token=True if model_args.use_auth_token else None							,     ignore_mismatched_sizes=model_args.ignore_mismatched_sizes							,     )
						A__	:							int						    = AutoImageProcessor.from_pretrained(
						    model_args.image_processor_name or 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							,     )

						# Define torchvision transforms to be applied to each image.
						if "shortest_edge" in image_processor.size:
												A__	:							Union[str, Any]						    = image_processor.size["shortest_edge"]
						else:
												A__	:							Optional[int]						    = (image_processor.size["height"], image_processor.size["width"])
						A__	:							Optional[int]						    = Normalize(mean=image_processor.image_mean							,     std=image_processor.image_std       )
						A__	:							Optional[int]						    = Compose(
						    [
						        RandomResizedCrop(__lowercase       ),
						        RandomHorizontalFlip(),
						        ToTensor(),
						        normalize,
						    ]       )
						A__	:							str						    = Compose(
						    [
						        Resize(__lowercase       ),
						        CenterCrop(__lowercase       ),
						        ToTensor(),
						        normalize,
						    ]       )

						def train_transforms(__lowercase       ):
												A__	:							Any						    = [
												    _train_transforms(pil_img.convert("RGB"       )       ) for pil_img in example_batch["image"]
												]
												return example_batch

						def val_transforms(__lowercase       ):
												A__	:							str						    = [_val_transforms(pil_img.convert("RGB"       )       ) for pil_img in example_batch["image"]]
												return example_batch

						if training_args.do_train:
												if "train" not in dataset:
																		raise ValueError("--do_train requires a train dataset"       )
												if data_args.max_train_samples is not None:
																		A__	:							Union[str, Any]						    = (
																		    dataset["train"].shuffle(seed=training_args.seed       ).select(range(data_args.max_train_samples       )       )
																		)
												# Set the training transforms
												dataset["train"].set_transform(__lowercase       )

						if training_args.do_eval:
												if "validation" not in dataset:
																		raise ValueError("--do_eval requires a validation dataset"       )
												if data_args.max_eval_samples is not None:
																		A__	:							Tuple						    = (
																		    dataset["validation"].shuffle(seed=training_args.seed       ).select(range(data_args.max_eval_samples       )       )
																		)
												# Set the validation transforms
												dataset["validation"].set_transform(__lowercase       )

						# Initalize our trainer
						A__	:							Tuple						    = Trainer(
						    model=__lowercase							,     args=__lowercase							,     train_dataset=dataset["train"] if training_args.do_train else None							,     eval_dataset=dataset["validation"] if training_args.do_eval else None							,     compute_metrics=__lowercase							,     tokenizer=__lowercase							,     data_collator=__lowercase							,     )

						# Training
						if training_args.do_train:
												A__	:							Union[str, Any]						    = None
												if training_args.resume_from_checkpoint is not None:
																		A__	:							Optional[Any]						    = training_args.resume_from_checkpoint
												elif last_checkpoint is not None:
																		A__	:							List[Any]						    = last_checkpoint
												A__	:							Optional[int]						    = trainer.train(resume_from_checkpoint=__lowercase       )
												trainer.save_model()
												trainer.log_metrics("train"							,     train_result.metrics       )
												trainer.save_metrics("train"							,     train_result.metrics       )
												trainer.save_state()

						# Evaluation
						if training_args.do_eval:
												A__	:							Optional[Any]						    = trainer.evaluate()
												trainer.log_metrics("eval"							,     __lowercase       )
												trainer.save_metrics("eval"							,     __lowercase       )

						# Write model card and (optionally) push to hub
						A__	:							List[str]						    = {
						    "finetuned_from": model_args.model_name_or_path,
						    "tasks": "image-classification",
						    "dataset": data_args.dataset_name,
						    "tags": ["image-classification", "vision"],
						}
						if training_args.push_to_hub:
												trainer.push_to_hub(**__lowercase       )
						else:
												trainer.create_model_card(**__lowercase       )


if __name__ == "__main__":
		main()




# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
		import jax
		import jaxlib

snake_case    :						Optional[int]  =						get_logger()

snake_case    :						Optional[dict]  =						None




class 							lowerCAmelCase__  (	TensorFormatter[Mapping, 'jax.Array', Mapping]						):







					def __init__(       self      :     Optional[Any]			,		_A      :     Optional[int]=None			,		_A      :     str=None			,		**_A      :     Tuple):
											super().__init__(features=_A)
											import jax
											from jaxlib.xla_client import Device

											if isinstance(_A			,		_A):
																	raise ValueError(
																	    F'Expected {device} to be a `str` not {type(_A)}, as `jaxlib.xla_extension.Device` '
																	    "is not serializable neither with `pickle` nor with `dill`. Instead you can surround "
																	    "the device with `str()` to get its string identifier that will be internally mapped "
																	    "to the actual `jaxlib.xla_extension.Device`.")
											A__	:							Union[str, Any]						    = device if isinstance(_A			,		_A) else str(jax.devices()[0])
											# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
											# with `pickle` nor with `dill`, so we need to use a global variable instead
											global DEVICE_MAPPING
											if DEVICE_MAPPING is None:
																	A__	:							Any						    = self._map_devices_to_str()
											if self.device not in list(DEVICE_MAPPING.keys()):
																	logger.warning(
																	    F'Device with string identifier {self.device} not listed among the available '
																	    F'devices: {list(DEVICE_MAPPING.keys())}, so falling back to the default '
																	    F'device: {str(jax.devices()[0])}.')
																	A__	:							str						    = str(jax.devices()[0])
											A__	:							List[Any]						    = jnp_array_kwargs







					@staticmethod
					def  _lowercase			(       ):
											import jax

											return {str(_A): device for device in jax.devices()}







					def  _lowercase			(       self      :     Tuple			,		_A      :     int):
											import jax
											import jax.numpy as jnp

											if isinstance(_A			,		_A) and column:
																	if all(
																	    isinstance(_A			,		jax.Array) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column):
																							return jnp.stack(_A			,		axis=0)
											return column







					def  _lowercase			(       self      :     List[str]			,		_A      :     Union[str, Any]):
											import jax
											import jax.numpy as jnp

											if isinstance(_A			,		(str, bytes, type(_A))):
																	return value
											elif isinstance(_A			,		(np.character, np.ndarray)) and np.issubdtype(value.dtype			,		np.character):
																	return value.tolist()

											A__	:							Dict						    = {}

											if isinstance(_A			,		(np.number, np.ndarray)) and np.issubdtype(value.dtype			,		np.integer):
																	# the default int precision depends on the jax config
																	# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
																	if jax.config.jax_enable_xaa:
																							A__	:							Union[str, Any]						    = {"dtype": jnp.intaa}
																	else:
																							A__	:							int						    = {"dtype": jnp.intaa}
											elif isinstance(_A			,		(np.number, np.ndarray)) and np.issubdtype(value.dtype			,		np.floating):
																	A__	:							str						    = {"dtype": jnp.floataa}
											elif config.PIL_AVAILABLE and "PIL" in sys.modules:
																	import PIL.Image

																	if isinstance(_A			,		PIL.Image.Image):
																							A__	:							Any						    = np.asarray(_A)

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
											global DEVICE_MAPPING
											if DEVICE_MAPPING is None:
																	A__	:							Optional[Any]						    = self._map_devices_to_str()

											with jax.default_device(DEVICE_MAPPING[self.device]):
																	# calling jnp.array on a np.ndarray does copy the data
																	# see https://github.com/google/jax/issues/4486
																	return jnp.array(_A			,		**{**default_dtype, **self.jnp_array_kwargs})







					def  _lowercase			(       self      :     Dict			,		_A      :     Any):
											import jax

											# support for torch, tf, jax etc.
											if config.TORCH_AVAILABLE and "torch" in sys.modules:
																	import torch

																	if isinstance(_A			,		torch.Tensor):
																							return self._tensorize(data_struct.detach().cpu().numpy()[()])
											if hasattr(_A			,		"__array__") and not isinstance(_A			,		jax.Array):
																	A__	:							Any						    = data_struct.__array__()
											# support for nested types like struct of list of struct
											if isinstance(_A			,		np.ndarray):
																	if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
																							return self._consolidate([self.recursive_tensorize(_A) for substruct in data_struct])
											elif isinstance(_A			,		(list, tuple)):
																	return self._consolidate([self.recursive_tensorize(_A) for substruct in data_struct])
											return self._tensorize(_A)







					def  _lowercase			(       self      :     Optional[Any]			,		_A      :     dict):
											return map_nested(self._recursive_tensorize			,		_A			,		map_list=_A)







					def  _lowercase			(       self      :     List[str]			,		_A      :     pa.Table):
											A__	:							Dict						    = self.numpy_arrow_extractor().extract_row(_A)
											A__	:							int						    = self.python_features_decoder.decode_row(_A)
											return self.recursive_tensorize(_A)







					def  _lowercase			(       self      :     int			,		_A      :     pa.Table):
											A__	:							int						    = self.numpy_arrow_extractor().extract_column(_A)
											A__	:							Optional[int]						    = self.python_features_decoder.decode_column(_A			,		pa_table.column_names[0])
											A__	:							Dict						    = self.recursive_tensorize(_A)
											A__	:							List[Any]						    = self._consolidate(_A)
											return column







					def  _lowercase			(       self      :     Tuple			,		_A      :     pa.Table):
											A__	:							Any						    = self.numpy_arrow_extractor().extract_batch(_A)
											A__	:							str						    = self.python_features_decoder.decode_batch(_A)
											A__	:							Optional[Any]						    = self.recursive_tensorize(_A)
											for column_name in batch:
																	A__	:							Optional[int]						    = self._consolidate(batch[column_name])
											return batch