



import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
						import jax
						import jax.numpy as jnp

						from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor






class 				SCREAMING_SNAKE_CASE     (							unittest.TestCase   ):





							def __init__(				self						:						Optional[int] ,			__lowercase						:						str ,			__lowercase						:						str=3 ,			__lowercase						:						Optional[int]=32 ,			__lowercase						:						Union[str, Any]=3 ,			__lowercase						:						str=10 ,			__lowercase						:						int=[10, 20, 30, 40] ,			__lowercase						:						Any=[1, 1, 2, 1] ,			__lowercase						:						Optional[int]=True ,			__lowercase						:						Optional[int]=True ,			__lowercase						:						int="relu" ,			__lowercase						:						Union[str, Any]=3 ,			__lowercase						:						List[str]=None ,			):

											'''simple docstring'''
											__a					       =						parent
											__a					       =						batch_size
											__a					       =						image_size
											__a					       =						num_channels
											__a					       =						embeddings_size
											__a					       =						hidden_sizes
											__a					       =						depths
											__a					       =						is_training
											__a					       =						use_labels
											__a					       =						hidden_act
											__a					       =						num_labels
											__a					       =						scope
											__a					       =						len(__lowercase		)





							def   UpperCamelCase_   (				self						:						List[Any]		):

											'''simple docstring'''
											__a					       =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

											__a					       =						self.get_config()

											return config, pixel_values





							def   UpperCamelCase_   (				self						:						Optional[int]		):

											'''simple docstring'''
											return ResNetConfig(
											    num_channels=self.num_channels ,			embeddings_size=self.embeddings_size ,			hidden_sizes=self.hidden_sizes ,			depths=self.depths ,			hidden_act=self.hidden_act ,			num_labels=self.num_labels ,			image_size=self.image_size ,			)





							def   UpperCamelCase_   (				self						:						List[str] ,			__lowercase						:						Union[str, Any] ,			__lowercase						:						str		):

											'''simple docstring'''
											__a					       =						FlaxResNetModel(config=__lowercase		)
											__a					       =						model(__lowercase		)

											# Output shape (b, c, h, w)
											self.parent.assertEqual(
											    result.last_hidden_state.shape ,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,			)





							def   UpperCamelCase_   (				self						:						List[str] ,			__lowercase						:						Dict ,			__lowercase						:						Optional[int]		):

											'''simple docstring'''
											__a					       =						self.num_labels
											__a					       =						FlaxResNetForImageClassification(config=__lowercase		)
											__a					       =						model(__lowercase		)
											self.parent.assertEqual(result.logits.shape ,			(self.batch_size, self.num_labels)		)







							def   UpperCamelCase_   (				self						:						List[Any]		):

											'''simple docstring'''
											__a					       =						self.prepare_config_and_inputs()
											__a       ,   __a					       =						config_and_inputs
											__a					       =						{"""pixel_values""": pixel_values}
											return config, inputs_dict






@require_flax
class 				SCREAMING_SNAKE_CASE     (							lowerCamelCase__     , unittest.TestCase   ):
							__lowerCamelCase		:		int      =(FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

							__lowerCamelCase		:		Union[str, Any]      =False
							__lowerCamelCase		:		Optional[Any]      =False
							__lowerCamelCase		:		str      =False





							def   UpperCamelCase_   (				self						:						Optional[Any]		):

											'''simple docstring'''
											__a					       =						FlaxResNetModelTester(self		)
											__a					       =						ConfigTester(self ,			config_class=__lowercase ,			has_text_modality=__lowercase		)





							def   UpperCamelCase_   (				self						:						str		):

											'''simple docstring'''
											self.create_and_test_config_common_properties()
											self.config_tester.create_and_test_config_to_json_string()
											self.config_tester.create_and_test_config_to_json_file()
											self.config_tester.create_and_test_config_from_and_save_pretrained()
											self.config_tester.create_and_test_config_with_num_labels()
											self.config_tester.check_config_can_be_init_without_params()
											self.config_tester.check_config_arguments_init()





							def   UpperCamelCase_   (				self						:						str		):

											'''simple docstring'''
											return





							def   UpperCamelCase_   (				self						:						Any		):

											'''simple docstring'''
											__a					       =						self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__lowercase		)





							def   UpperCamelCase_   (				self						:						Dict		):

											'''simple docstring'''
											__a					       =						self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__lowercase		)





							@unittest.skip(reason="""ResNet does not use inputs_embeds"""		)
							def   UpperCamelCase_   (				self						:						Optional[Any]		):

											'''simple docstring'''
											pass





							@unittest.skip(reason="""ResNet does not support input and output embeddings"""		)
							def   UpperCamelCase_   (				self						:						int		):

											'''simple docstring'''
											pass





							def   UpperCamelCase_   (				self						:						int		):

											'''simple docstring'''
											__a       ,   __a					       =						self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															__a					       =						model_class(__lowercase		)
															__a					       =						inspect.signature(model.__call__		)
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															__a					       =						[*signature.parameters.keys()]

															__a					       =						["""pixel_values"""]
															self.assertListEqual(arg_names[:1] ,			__lowercase		)





							def   UpperCamelCase_   (				self						:						Union[str, Any]		):

											'''simple docstring'''
											def check_hidden_states_output(__lowercase						:						Tuple ,			__lowercase						:						List[str] ,			__lowercase						:						str		):
															__a					       =						model_class(__lowercase		)

															__a					       =						model(**self._prepare_for_class(__lowercase ,			__lowercase		)		)

															__a					       =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															__a					       =						self.model_tester.num_stages
															self.assertEqual(len(__lowercase		) ,			expected_num_stages + 1		)





							@unittest.skip(reason="""ResNet does not use feedforward chunking"""		)
							def   UpperCamelCase_   (				self						:						Optional[Any]		):

											'''simple docstring'''
											pass







							def   UpperCamelCase_   (				self						:						List[Any]		):

											'''simple docstring'''
											__a       ,   __a					       =						self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
															with self.subTest(model_class.__name__		):
																			__a					       =						self._prepare_for_class(__lowercase ,			__lowercase		)
																			__a					       =						model_class(__lowercase		)

																			@jax.jit
																			def model_jitted(__lowercase						:						List[str] ,			**__lowercase						:						Optional[int]		):
																							return model(pixel_values=__lowercase ,			**__lowercase		)

																			with self.subTest("""JIT Enabled"""		):
																							__a					       =						model_jitted(**__lowercase		).to_tuple()

																			with self.subTest("""JIT Disabled"""		):
																							with jax.disable_jit():
																											__a					       =						model_jitted(**__lowercase		).to_tuple()

																			self.assertEqual(len(__lowercase		) ,			len(__lowercase		)		)
																			for jitted_output, output in zip(__lowercase ,			__lowercase		):
																							self.assertEqual(jitted_output.shape ,			output.shape		)



def 					lowerCAmelCase__  (							):
				"""simple docstring"""







				__a					       =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
				return image






@require_flax
class 				SCREAMING_SNAKE_CASE     (							unittest.TestCase   ):





							@cached_property
							def   UpperCamelCase_   (				self						:						Union[str, Any]		):

											'''simple docstring'''
											return AutoImageProcessor.from_pretrained("""microsoft/resnet-50"""		) if is_vision_available() else None







							@slow
							def   UpperCamelCase_   (				self						:						int		):

											'''simple docstring'''
											__a					       =						FlaxResNetForImageClassification.from_pretrained("""microsoft/resnet-50"""		)

											__a					       =						self.default_image_processor
											__a					       =						prepare_img()
											__a					       =						image_processor(images=__lowercase ,			return_tensors="""np"""		)

											__a					       =						model(**__lowercase		)

											# verify the logits
											__a					       =						(1, 1000)
											self.assertEqual(outputs.logits.shape ,			__lowercase		)

											__a					       =						jnp.array([-11.1069, -9.7877, -8.3777]		)

											self.assertTrue(jnp.allclose(outputs.logits[0, :3] ,			__lowercase ,			atol=1E-4		)		)





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

import transformers
from transformers import (
    AutoConfig,
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    DataCollatorWithPadding,
    HfArgumentParser,
    SquadDataset,
    Trainer,
    TrainingArguments,
)
from transformers import SquadDataTrainingArguments as DataTrainingArguments
from transformers.trainer_utils import is_main_process


lowerCamelCase__     =	logging.getLogger(__name__)






@dataclass
class 				SCREAMING_SNAKE_CASE     :
							__lowerCamelCase		:		str      =field(
							    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}   )
							__lowerCamelCase		:		Optional[str]      =field(
							    default=lowerCamelCase__     , metadata={'help': 'Pretrained config name or path if not the same as model_name'}   )
							__lowerCamelCase		:		Optional[str]      =field(
							    default=lowerCamelCase__     , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}   )
							__lowerCamelCase		:		bool      =field(default=lowerCamelCase__     , metadata={'help': 'Set this flag to use fast tokenization.'}   )
							# If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
							# or just modify its tokenizer_config.json.
							__lowerCamelCase		:		Optional[str]      =field(
							    default=lowerCamelCase__     , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}     , )



def 					lowerCAmelCase__  (							):
				"""simple docstring"""







				__a					       =						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					       =						parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]      )      )
				else:
								__a       ,   __a       ,   __a					       =						parser.parse_args_into_dataclasses()

				if (
				    os.path.exists(training_args.output_dir      )
				    and os.listdir(training_args.output_dir      )
				    and training_args.do_train
				    and not training_args.overwrite_output_dir
				):
								raise ValueError(
								    f"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
								    """ --overwrite_output_dir to overcome."""      )

				# Setup logging
				logging.basicConfig(
				    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""			,       datefmt="""%m/%d/%Y %H:%M:%S"""			,       level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN			,       )
				logger.warning(
				    """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"""			,       training_args.local_rank			,       training_args.device			,       training_args.n_gpu			,       bool(training_args.local_rank != -1      )			,       training_args.fpaa			,       )
				# Set the verbosity to info of the Transformers logger (on main process only):
				if is_main_process(training_args.local_rank      ):
								transformers.utils.logging.set_verbosity_info()
								transformers.utils.logging.enable_default_handler()
								transformers.utils.logging.enable_explicit_format()
				logger.info("""Training/evaluation parameters %s"""			,       _SCREAMING_SNAKE_CASE      )

				# Prepare Question-Answering task
				# Load pretrained model and tokenizer
				#
				# Distributed training:
				# The .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.

				__a					       =						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			,       )
				__a					       =						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=_SCREAMING_SNAKE_CASE			,       )
				__a					       =						AutoModelForQuestionAnswering.from_pretrained(
				    model_args.model_name_or_path			,       from_tf=bool(""".ckpt""" in model_args.model_name_or_path      )			,       config=_SCREAMING_SNAKE_CASE			,       cache_dir=model_args.cache_dir			,       )

				# Get datasets
				__a					       =						hasattr(model.config			,       """lang2id"""      )
				__a					       =						(
				    SquadDataset(
				        _SCREAMING_SNAKE_CASE			,       tokenizer=_SCREAMING_SNAKE_CASE			,       is_language_sensitive=_SCREAMING_SNAKE_CASE			,       cache_dir=model_args.cache_dir      )
				    if training_args.do_train
				    else None
				)
				__a					       =						(
				    SquadDataset(
				        _SCREAMING_SNAKE_CASE			,       tokenizer=_SCREAMING_SNAKE_CASE			,       mode="""dev"""			,       is_language_sensitive=_SCREAMING_SNAKE_CASE			,       cache_dir=model_args.cache_dir			,       )
				    if training_args.do_eval
				    else None
				)

				# Data collator
				__a					       =						DataCollatorWithPadding(_SCREAMING_SNAKE_CASE			,       pad_to_multiple_of=8      ) if training_args.fpaa else None

				# Initialize our Trainer
				__a					       =						Trainer(
				    model=_SCREAMING_SNAKE_CASE			,       args=_SCREAMING_SNAKE_CASE			,       train_dataset=_SCREAMING_SNAKE_CASE			,       eval_dataset=_SCREAMING_SNAKE_CASE			,       data_collator=_SCREAMING_SNAKE_CASE			,       )

				# Training
				if training_args.do_train:
								trainer.train(
								    model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path      ) else None      )
								trainer.save_model()
								# For convenience, we also re-save the tokenizer to the same directory,
								# so that you can share your model easily on huggingface.co/models =)
								if trainer.is_world_master():
												tokenizer.save_pretrained(training_args.output_dir      )

def 					lowerCAmelCase__  (							_SCREAMING_SNAKE_CASE    :     Optional[Any]      ):
				"""simple docstring"""







				main()


if __name__ == "__main__":
						main()
