





"""simple docstring"""
from copy import deepcopy
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union

import torch
from torch import nn
from torch.utils.data import Dataset

from .deepspeed import is_deepspeed_zeroa_enabled
from .generation.configuration_utils import GenerationConfig
from .trainer import Trainer
from .utils import logging


if TYPE_CHECKING:
		from .data.data_collator import DataCollator
		from .modeling_utils import PreTrainedModel
		from .tokenization_utils_base import PreTrainedTokenizerBase
		from .trainer_callback import TrainerCallback
		from .trainer_utils import EvalPrediction, PredictionOutput
		from .training_args import TrainingArguments


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






class    _UpperCAmelCase  (      lowercase_					):


					def __init__(   self     :Union[str, Any]	,			__UpperCamelCase     :Union["PreTrainedModel", nn.Module] = None	,			__UpperCamelCase     :"TrainingArguments" = None	,			__UpperCamelCase     :Optional["DataCollator"] = None	,			__UpperCamelCase     :Optional[Dataset] = None	,			__UpperCamelCase     :Optional[Union[Dataset, Dict[str, Dataset]]] = None	,			__UpperCamelCase     :Optional["PreTrainedTokenizerBase"] = None	,			__UpperCamelCase     :Optional[Callable[[], "PreTrainedModel"]] = None	,			__UpperCamelCase     :Optional[Callable[["EvalPrediction"], Dict]] = None	,			__UpperCamelCase     :Optional[List["TrainerCallback"]] = None	,			__UpperCamelCase     :Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None)	,			__UpperCamelCase     :Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None	,			):
												super().__init__(
												    model=__UpperCamelCase	,			args=__UpperCamelCase	,			data_collator=__UpperCamelCase	,			train_dataset=__UpperCamelCase	,			eval_dataset=__UpperCamelCase	,			tokenizer=__UpperCamelCase	,			model_init=__UpperCamelCase	,			compute_metrics=__UpperCamelCase	,			callbacks=__UpperCamelCase	,			optimizers=__UpperCamelCase	,			preprocess_logits_for_metrics=__UpperCamelCase	,			)

												# Override self.model.generation_config if a GenerationConfig is specified in args.
												# Priority: args.generation_config > model.generation_config > default GenerationConfig.
												if self.args.generation_config is not None:
																			A						=    self.load_generation_config(self.args.generation_config						)
																			A						=    gen_config


					@staticmethod
					def       lowerCamelCase			(   __UpperCamelCase     :Union[str, GenerationConfig]						):

												# GenerationConfig provided, nothing to do
												if isinstance(__UpperCamelCase	,			__UpperCamelCase						):
																			return deepcopy(__UpperCamelCase						)

												# str or Path
												A						=    Path(__UpperCamelCase						) if isinstance(__UpperCamelCase	,			__UpperCamelCase						) else gen_config_arg
												A						=    None

												# Figuring if it is path pointing to a file, pointing to a directory or else a model id or URL
												# This step is required in order to determine config_file_name
												if pretrained_model_name.is_file():
																			A						=    pretrained_model_name.name
																			A						=    pretrained_model_name.parent
												# dir path
												elif pretrained_model_name.is_dir():
																			pass
												# model id or URL
												else:
																			A						=    gen_config_arg

												A						=    GenerationConfig.from_pretrained(__UpperCamelCase	,			__UpperCamelCase						)
												return gen_config


					def       lowerCamelCase			(   self     :Tuple	,			__UpperCamelCase     :Optional[Dataset] = None	,			__UpperCamelCase     :Optional[List[str]] = None	,			__UpperCamelCase     :str = "eval"	,			**__UpperCamelCase     :str	,			):
												A						=    gen_kwargs.copy()
												if gen_kwargs.get("max_length"						) is None and gen_kwargs.get("max_new_tokens"						) is None:
																			A						=    self.args.generation_max_length
												A						=    (
												    gen_kwargs["num_beams"] if gen_kwargs.get("num_beams"						) is not None else self.args.generation_num_beams
												)
												A						=    gen_kwargs

												return super().evaluate(__UpperCamelCase	,			ignore_keys=__UpperCamelCase	,			metric_key_prefix=__UpperCamelCase						)


					def       lowerCamelCase			(   self     :Optional[int]	,			__UpperCamelCase     :Dataset	,			__UpperCamelCase     :Optional[List[str]] = None	,			__UpperCamelCase     :str = "test"	,			**__UpperCamelCase     :Union[str, Any]	,			):
												A						=    gen_kwargs.copy()
												if gen_kwargs.get("max_length"						) is None and gen_kwargs.get("max_new_tokens"						) is None:
																			A						=    self.args.generation_max_length
												A						=    (
												    gen_kwargs["num_beams"] if gen_kwargs.get("num_beams"						) is not None else self.args.generation_num_beams
												)
												A						=    gen_kwargs

												return super().predict(__UpperCamelCase	,			ignore_keys=__UpperCamelCase	,			metric_key_prefix=__UpperCamelCase						)


					def       lowerCamelCase			(   self     :Tuple	,			__UpperCamelCase     :nn.Module	,			__UpperCamelCase     :Dict[str, Union[torch.Tensor, Any]]	,			__UpperCamelCase     :bool	,			__UpperCamelCase     :Optional[List[str]] = None	,			**__UpperCamelCase     :Dict	,			):

												if not self.args.predict_with_generate or prediction_loss_only:
																			return super().prediction_step(
																			    __UpperCamelCase	,			__UpperCamelCase	,			prediction_loss_only=__UpperCamelCase	,			ignore_keys=__UpperCamelCase						)

												A						=    "labels" in inputs
												A						=    self._prepare_inputs(__UpperCamelCase						)

												# XXX: adapt synced_gpus for fairscale as well
												# Priority (handled in generate):
												# gen_kwargs > model.generation_config > default GenerationConfig()

												if len(__UpperCamelCase						) == 0 and hasattr(self	,			"_gen_kwargs"						):
																			A						=    self._gen_kwargs.copy()

												if gen_kwargs.get("max_length"						) is None and gen_kwargs.get("max_new_tokens"						) is None:
																			A						=    self.model.config.max_length
												A						=    (
												    gen_kwargs["num_beams"] if gen_kwargs.get("num_beams"						) is not None else self.model.config.num_beams
												)
												A						=    True if is_deepspeed_zeroa_enabled() else False
												A						=    (
												    gen_kwargs["synced_gpus"] if gen_kwargs.get("synced_gpus"						) is not None else default_synced_gpus
												)

												# If the `decoder_input_ids` was created from `labels`, evict the former, so that the model can freely generate
												# (otherwise, it would continue generating from the padded `decoder_input_ids`)
												if (
												    "labels" in inputs
												    and "decoder_input_ids" in inputs
												    and inputs["labels"].shape == inputs["decoder_input_ids"].shape
												):
																			A						=    {k: v for k, v in inputs.items() if k != "decoder_input_ids"}
												A						=    self.model.generate(**__UpperCamelCase	,			**__UpperCamelCase						)

												# Temporary hack to ensure the generation config is not initialized for each iteration of the evaluation loop
												# TODO: remove this hack when the legacy code that initializes generation_config from a model config is
												# removed in https://github.com/huggingface/transformers/blob/98d88b23f54e5a23e741833f1e973fdf600cc2c5/src/transformers/generation/utils.py#L1183
												if self.model.generation_config._from_model_config:
																			A						=    False

												# Retrieves GenerationConfig from model.generation_config
												A						=    self.model.generation_config
												# in case the batch is shorter than max length, the output should be padded
												if generated_tokens.shape[-1] < gen_config.max_length:
																			A						=    self._pad_tensors_to_max_len(__UpperCamelCase	,			gen_config.max_length						)
												elif gen_config.max_new_tokens is not None and generated_tokens.shape[-1] < gen_config.max_new_tokens + 1:
																			A						=    self._pad_tensors_to_max_len(__UpperCamelCase	,			gen_config.max_new_tokens + 1						)

												with torch.no_grad():
																			if has_labels:
																										with self.compute_loss_context_manager():
																																	A						=    model(**__UpperCamelCase						)
																										if self.label_smoother is not None:
																																	A						=    self.label_smoother(__UpperCamelCase	,			inputs["labels"]						).mean().detach()
																										else:
																																	A						=    (outputs["loss"] if isinstance(__UpperCamelCase	,			__UpperCamelCase						) else outputs[0]).mean().detach()
																			else:
																										A						=    None

												if self.args.prediction_loss_only:
																			return loss, None, None

												if has_labels:
																			A						=    inputs["labels"]
																			if labels.shape[-1] < gen_config.max_length:
																										A						=    self._pad_tensors_to_max_len(__UpperCamelCase	,			gen_config.max_length						)
																			elif gen_config.max_new_tokens is not None and labels.shape[-1] < gen_config.max_new_tokens + 1:
																										A						=    self._pad_tensors_to_max_len(__UpperCamelCase	,			gen_config.max_new_tokens + 1						)
												else:
																			A						=    None

												return loss, generated_tokens, labels


					def       lowerCamelCase			(   self     :Any	,			__UpperCamelCase     :Tuple	,			__UpperCamelCase     :List[Any]						):
												if self.tokenizer is not None and hasattr(self.tokenizer	,			"pad_token_id"						):
																			# If PAD token is not defined at least EOS token has to be defined
																			A						=    (
																			    self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id
																			)
												else:
																			if self.model.config.pad_token_id is not None:
																										A						=    self.model.config.pad_token_id
																			else:
																										raise ValueError("Pad_token_id must be set in the configuration of the model, in order to pad tensors"						)

												A						=    pad_token_id * torch.ones(
												    (tensor.shape[0], max_length)	,			dtype=tensor.dtype	,			device=tensor.device						)
												A						=    tensor
												return padded_tensor









"""simple docstring"""
import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
		from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor






class    _UpperCAmelCase  :


					def __init__(   self     :Optional[Any]	,			__UpperCamelCase     :Dict	,			__UpperCamelCase     :Optional[Any]=3	,			__UpperCamelCase     :Optional[int]=32	,			__UpperCamelCase     :str=3	,			__UpperCamelCase     :Union[str, Any]=10	,			__UpperCamelCase     :Union[str, Any]=[10, 20, 30, 40]	,			__UpperCamelCase     :int=[1, 1, 2, 1]	,			__UpperCamelCase     :Dict=True	,			__UpperCamelCase     :Optional[Any]=True	,			__UpperCamelCase     :Any="relu"	,			__UpperCamelCase     :Optional[Any]=3	,			__UpperCamelCase     :int=None	,			__UpperCamelCase     :str=["stage2", "stage3", "stage4"]	,			__UpperCamelCase     :str=[2, 3, 4]	,			):
												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(__UpperCamelCase						)
												A						=    out_features
												A						=    out_indices


					def       lowerCamelCase			(   self     :List[Any]						):
												A						=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

												A						=    None
												if self.use_labels:
																			A						=    ids_tensor([self.batch_size]	,			self.num_labels						)

												A						=    self.get_config()

												return config, pixel_values, labels


					def       lowerCamelCase			(   self     :Optional[Any]						):
												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	,			out_features=self.out_features	,			out_indices=self.out_indices	,			)


					def       lowerCamelCase			(   self     :int	,			__UpperCamelCase     :Optional[Any]	,			__UpperCamelCase     :str	,			__UpperCamelCase     :List[Any]						):
												A						=    ResNetModel(config=__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												A						=    model(__UpperCamelCase						)
												# expected last hidden states: B, C, H // 32, W // 32
												self.parent.assertEqual(
												    result.last_hidden_state.shape	,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)	,			)


					def       lowerCamelCase			(   self     :int	,			__UpperCamelCase     :Optional[Any]	,			__UpperCamelCase     :str	,			__UpperCamelCase     :str						):
												A						=    self.num_labels
												A						=    ResNetForImageClassification(__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												A						=    model(__UpperCamelCase	,			labels=__UpperCamelCase						)
												self.parent.assertEqual(result.logits.shape	,			(self.batch_size, self.num_labels)						)


					def       lowerCamelCase			(   self     :Dict	,			__UpperCamelCase     :Optional[Any]	,			__UpperCamelCase     :Optional[int]	,			__UpperCamelCase     :str						):
												A						=    ResNetBackbone(config=__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												A						=    model(__UpperCamelCase						)

												# verify feature maps
												self.parent.assertEqual(len(result.feature_maps						)	,			len(config.out_features						)						)
												self.parent.assertListEqual(list(result.feature_maps[0].shape						)	,			[self.batch_size, self.hidden_sizes[1], 4, 4]						)

												# verify channels
												self.parent.assertEqual(len(model.channels						)	,			len(config.out_features						)						)
												self.parent.assertListEqual(model.channels	,			config.hidden_sizes[1:]						)

												# verify backbone works with out_features=None
												A						=    None
												A						=    ResNetBackbone(config=__UpperCamelCase						)
												model.to(__UpperCamelCase						)
												model.eval()
												A						=    model(__UpperCamelCase						)

												# verify feature maps
												self.parent.assertEqual(len(result.feature_maps						)	,			1						)
												self.parent.assertListEqual(list(result.feature_maps[0].shape						)	,			[self.batch_size, self.hidden_sizes[-1], 1, 1]						)

												# verify channels
												self.parent.assertEqual(len(model.channels						)	,			1						)
												self.parent.assertListEqual(model.channels	,			[config.hidden_sizes[-1]]						)


					def       lowerCamelCase			(   self     :List[Any]						):
												A						=    self.prepare_config_and_inputs()
												A,      A,      A						=    config_and_inputs
												A						=    {"pixel_values": pixel_values}
												return config, inputs_dict







@require_torch
class    _UpperCAmelCase  (      lowercase_	,				lowercase_	,				unittest.TestCase					):
					UpperCamelCase						=				(
					    (
					        ResNetModel,
					        ResNetForImageClassification,
					        ResNetBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					UpperCamelCase						=				(
					    {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
					    if is_torch_available()
					    else {}
					)

					UpperCamelCase						=				True
					UpperCamelCase						=				False
					UpperCamelCase						=				False
					UpperCamelCase						=				False
					UpperCamelCase						=				False


					def       lowerCamelCase			(   self     :List[Any]						):
												A						=    ResNetModelTester(self						)
												A						=    ConfigTester(self	,			config_class=__UpperCamelCase	,			has_text_modality=__UpperCamelCase						)


					def       lowerCamelCase			(   self     :List[Any]						):
												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       lowerCamelCase			(   self     :Union[str, Any]						):
												return


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


					@unittest.skip(reason="ResNet does not support input and output embeddings"						)
					def       lowerCamelCase			(   self     :Optional[Any]						):
												pass


					def       lowerCamelCase			(   self     :List[Any]						):
												A,      A						=    self.model_tester.prepare_config_and_inputs_for_common()

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

																			A						=    ["pixel_values"]
																			self.assertListEqual(arg_names[:1]	,			__UpperCamelCase						)


					def       lowerCamelCase			(   self     :Tuple						):
												A						=    self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__UpperCamelCase						)


					def       lowerCamelCase			(   self     :Union[str, Any]						):
												A						=    self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_backbone(*__UpperCamelCase						)


					def       lowerCamelCase			(   self     :Optional[Any]						):
												A,      A						=    self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																			A						=    model_class(config=__UpperCamelCase						)
																			for name, module in model.named_modules():
																										if isinstance(__UpperCamelCase	,			(nn.BatchNormad, nn.GroupNorm)						):
																																	self.assertTrue(
																																	    torch.all(module.weight == 1						)	,			msg=f"Parameter {name} of model {model_class} seems not properly initialized"	,			)
																																	self.assertTrue(
																																	    torch.all(module.bias == 0						)	,			msg=f"Parameter {name} of model {model_class} seems not properly initialized"	,			)


					def       lowerCamelCase			(   self     :Optional[Any]						):
												def check_hidden_states_output(__UpperCamelCase     :int	,			__UpperCamelCase     :Any	,			__UpperCamelCase     :Union[str, Any]						):
																			A						=    model_class(__UpperCamelCase						)
																			model.to(__UpperCamelCase						)
																			model.eval()

																			with torch.no_grad():
																										A						=    model(**self._prepare_for_class(__UpperCamelCase	,			__UpperCamelCase						)						)

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

																			A						=    self.model_tester.num_stages
																			self.assertEqual(len(__UpperCamelCase						)	,			expected_num_stages + 1						)

																			# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
																			self.assertListEqual(
																			    list(hidden_states[0].shape[-2:]						)	,			[self.model_tester.image_size // 4, self.model_tester.image_size // 4]	,			)

												A,      A						=    self.model_tester.prepare_config_and_inputs_for_common()
												A						=    ["basic", "bottleneck"]
												for model_class in self.all_model_classes:
																			for layer_type in layers_type:
																										A						=    layer_type
																										A						=    True
																										check_hidden_states_output(__UpperCamelCase	,			__UpperCamelCase	,			__UpperCamelCase						)

																										# check that output_hidden_states also work using config
																										del inputs_dict["output_hidden_states"]
																										A						=    True

																										check_hidden_states_output(__UpperCamelCase	,			__UpperCamelCase	,			__UpperCamelCase						)


					@unittest.skip(reason="ResNet does not use feedforward chunking"						)
					def       lowerCamelCase			(   self     :Tuple						):
												pass


					def       lowerCamelCase			(   self     :Optional[int]						):
												A						=    self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase						)


					@slow
					def       lowerCamelCase			(   self     :Union[str, Any]						):
												for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			A						=    ResNetModel.from_pretrained(__UpperCamelCase						)
																			self.assertIsNotNone(__UpperCamelCase						)







def    A__							(     ):
							A						=    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
							return image






@require_torch
@require_vision
class    _UpperCAmelCase  (      unittest.TestCase					):


					@cached_property
					def       lowerCamelCase			(   self     :List[Any]						):
												return (
												    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
												    if is_vision_available()
												    else None
												)


					@slow
					def       lowerCamelCase			(   self     :Dict						):
												A						=    ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(__UpperCamelCase						)

												A						=    self.default_image_processor
												A						=    prepare_img()
												A						=    image_processor(images=__UpperCamelCase	,			return_tensors="pt"						).to(__UpperCamelCase						)

												# forward pass
												with torch.no_grad():
																			A						=    model(**__UpperCamelCase						)

												# verify the logits
												A						=    torch.Size((1, 10_00)						)
												self.assertEqual(outputs.logits.shape	,			__UpperCamelCase						)

												A						=    torch.tensor([-11.1_069, -9.7_877, -8.3_777]						).to(__UpperCamelCase						)

												self.assertTrue(torch.allclose(outputs.logits[0, :3]	,			__UpperCamelCase	,			atol=1e-4						)						)







@require_torch
class    _UpperCAmelCase  (      lowercase_	,				unittest.TestCase					):
					UpperCamelCase						=				(ResNetBackbone,) if is_torch_available() else ()
					UpperCamelCase						=				False
					UpperCamelCase						=				ResNetConfig


					def       lowerCamelCase			(   self     :Dict						):
												A						=    ResNetModelTester(self						)


