

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      snake_case_      :


							"""simple docstring"""





							def __init__(			self       ,    _A       ,    _A=3       ,    _A=3_2       ,    _A=3       ,    _A=1_0       ,    _A=[1_0, 2_0, 3_0, 4_0]       ,    _A=[1, 1, 2, 1]       ,    _A=True       ,    _A=True       ,    _A="relu"       ,    _A=3       ,    _A=None       ,    _A=["stage2", "stage3", "stage4"]       ,    _A=[2, 3, 4]       ,    ):
												__lowerCAmelCase       =				parent
												__lowerCAmelCase       =				batch_size
												__lowerCAmelCase       =				image_size
												__lowerCAmelCase       =				num_channels
												__lowerCAmelCase       =				embeddings_size
												__lowerCAmelCase       =				hidden_sizes
												__lowerCAmelCase       =				depths
												__lowerCAmelCase       =				is_training
												__lowerCAmelCase       =				use_labels
												__lowerCAmelCase       =				hidden_act
												__lowerCAmelCase       =				num_labels
												__lowerCAmelCase       =				scope
												__lowerCAmelCase       =				len(_A				)
												__lowerCAmelCase       =				out_features
												__lowerCAmelCase       =				out_indices




							def 							A__	(			self				):
												__lowerCAmelCase       =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

												__lowerCAmelCase       =				self.get_config()

												return config, pixel_values, labels




							def 							A__	(			self				):
												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 							A__	(			self       ,    _A       ,    _A       ,    _A				):
												__lowerCAmelCase       =				ResNetModel(config=_A				)
												model.to(_A				)
												model.eval()
												__lowerCAmelCase       =				model(_A				)
												# 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 // 3_2, self.image_size // 3_2)       ,    )




							def 							A__	(			self       ,    _A       ,    _A       ,    _A				):
												__lowerCAmelCase       =				self.num_labels
												__lowerCAmelCase       =				ResNetForImageClassification(_A				)
												model.to(_A				)
												model.eval()
												__lowerCAmelCase       =				model(_A       ,    labels=_A				)
												self.parent.assertEqual(result.logits.shape       ,    (self.batch_size, self.num_labels)				)




							def 							A__	(			self       ,    _A       ,    _A       ,    _A				):
												__lowerCAmelCase       =				ResNetBackbone(config=_A				)
												model.to(_A				)
												model.eval()
												__lowerCAmelCase       =				model(_A				)

												# 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
												__lowerCAmelCase       =				None
												__lowerCAmelCase       =				ResNetBackbone(config=_A				)
												model.to(_A				)
												model.eval()
												__lowerCAmelCase       =				model(_A				)

												# 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 							A__	(			self				):
												__lowerCAmelCase       =				self.prepare_config_and_inputs()
												__lowerCAmelCase,						__lowerCAmelCase,						__lowerCAmelCase       =				config_and_inputs
												__lowerCAmelCase       =				{'pixel_values': pixel_values}
												return config, inputs_dict





@require_torch
class      snake_case_      (					_a      ,			_a      ,			unittest.TestCase				):


							"""simple docstring"""





							__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 							A__	(			self				):
												__lowerCAmelCase       =				ResNetModelTester(self				)
												__lowerCAmelCase       =				ConfigTester(self       ,    config_class=_A       ,    has_text_modality=_A				)




							def 							A__	(			self				):
												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 							A__	(			self				):
												return




							@unittest.skip(reason='ResNet does not use inputs_embeds'				)
							def 							A__	(			self				):
												pass




							@unittest.skip(reason='ResNet does not support input and output embeddings'				)
							def 							A__	(			self				):
												pass




							def 							A__	(			self				):
												__lowerCAmelCase,						__lowerCAmelCase       =				self.model_tester.prepare_config_and_inputs_for_common()

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

																	__lowerCAmelCase       =				['pixel_values']
																	self.assertListEqual(arg_names[:1]       ,    _A				)




							def 							A__	(			self				):
												__lowerCAmelCase       =				self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_A				)




							def 							A__	(			self				):
												__lowerCAmelCase       =				self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_backbone(*_A				)




							def 							A__	(			self				):
												__lowerCAmelCase,						__lowerCAmelCase       =				self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	__lowerCAmelCase       =				model_class(config=_A				)
																	for name, module in model.named_modules():
																						if isinstance(_A       ,    (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 							A__	(			self				):
												def check_hidden_states_output(_A       ,    _A       ,    _A				):
																	__lowerCAmelCase       =				model_class(_A				)
																	model.to(_A				)
																	model.eval()

																	with torch.no_grad():
																						__lowerCAmelCase       =				model(**self._prepare_for_class(_A       ,    _A				)				)

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

																	__lowerCAmelCase       =				self.model_tester.num_stages
																	self.assertEqual(len(_A				)       ,    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]       ,    )

												__lowerCAmelCase,						__lowerCAmelCase       =				self.model_tester.prepare_config_and_inputs_for_common()
												__lowerCAmelCase       =				['basic', 'bottleneck']
												for model_class in self.all_model_classes:
																	for layer_type in layers_type:
																						__lowerCAmelCase       =				layer_type
																						__lowerCAmelCase       =				True
																						check_hidden_states_output(_A       ,    _A       ,    _A				)

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

																						check_hidden_states_output(_A       ,    _A       ,    _A				)




							@unittest.skip(reason='ResNet does not use feedforward chunking'				)
							def 							A__	(			self				):
												pass




							def 							A__	(			self				):
												__lowerCAmelCase       =				self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*_A				)




							@slow
							def 							A__	(			self				):
												for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	__lowerCAmelCase       =				ResNetModel.from_pretrained(_A				)
																	self.assertIsNotNone(_A				)


def 							__lowercase     (	):

					"""simple docstring"""






					__lowerCAmelCase       =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
					return image





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


							"""simple docstring"""





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




							@slow
							def 							A__	(			self				):
												__lowerCAmelCase       =				ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(_A				)

												__lowerCAmelCase       =				self.default_image_processor
												__lowerCAmelCase       =				prepare_img()
												__lowerCAmelCase       =				image_processor(images=_A       ,    return_tensors='pt'				).to(_A				)

												# forward pass
												with torch.no_grad():
																	__lowerCAmelCase       =				model(**_A				)

												# verify the logits
												__lowerCAmelCase       =				torch.Size((1, 1_0_0_0)				)
												self.assertEqual(outputs.logits.shape       ,    _A				)

												__lowerCAmelCase       =				torch.tensor([-11.1069, -9.7877, -8.3777]				).to(_A				)

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





@require_torch
class      snake_case_      (					_a      ,			unittest.TestCase				):


							"""simple docstring"""





							__UpperCAmelCase      =(ResNetBackbone,) if is_torch_available() else ()
							__UpperCAmelCase      =False
							__UpperCAmelCase      =ResNetConfig




							def 							A__	(			self				):
												__lowerCAmelCase       =				ResNetModelTester(self				)









# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from typing import List


def 							__lowercase     (	UpperCAmelCase__		,       UpperCAmelCase__   ):

					"""simple docstring"""






					if name != "training_function" and name != "main":
										raise ValueError(F"""Incorrect function name passed: {name}, choose either 'main' or 'training_function'"""   )
					__lowerCAmelCase,						__lowerCAmelCase       =				[], False
					for line in lines:
										if not found_start and F"""def {name}""" in line:
															__lowerCAmelCase       =				True
															good_lines.append(UpperCAmelCase__   )
															continue
										if found_start:
															if name == "training_function" and "def main" in line:
																				return good_lines
															if name == "main" and "if __name__" in line:
																				return good_lines
															good_lines.append(UpperCAmelCase__   )


def 							__lowercase     (	UpperCAmelCase__   ):

					"""simple docstring"""






					return [line for line in lines if not line.lstrip().startswith('#'   ) and line != "\n"]


def 							__lowercase     (	UpperCAmelCase__		,       UpperCAmelCase__		,       UpperCAmelCase__		,       UpperCAmelCase__ = None   ):

					"""simple docstring"""






					with open(UpperCAmelCase__		,       'r'   ) as f:
										__lowerCAmelCase       =				f.readlines()
					with open(os.path.abspath(os.path.join('examples'		,       'nlp_example.py'   )   )		,       'r'   ) as f:
										__lowerCAmelCase       =				f.readlines()
					with open(UpperCAmelCase__		,       'r'   ) as f:
										__lowerCAmelCase       =				f.readlines()
					if secondary_filename is not None:
										with open(UpperCAmelCase__		,       'r'   ) as f:
															__lowerCAmelCase       =				f.readlines()

    # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content
					if parser_only:
										__lowerCAmelCase       =				clean_lines(get_function_contents_by_name(UpperCAmelCase__		,       'main'   )   )
										__lowerCAmelCase       =				clean_lines(get_function_contents_by_name(UpperCAmelCase__		,       'main'   )   )
										__lowerCAmelCase       =				clean_lines(get_function_contents_by_name(UpperCAmelCase__		,       'main'   )   )
										if secondary_filename is not None:
															__lowerCAmelCase       =				clean_lines(get_function_contents_by_name(UpperCAmelCase__		,       'main'   )   )
					else:
										__lowerCAmelCase       =				clean_lines(get_function_contents_by_name(UpperCAmelCase__		,       'training_function'   )   )
										__lowerCAmelCase       =				clean_lines(get_function_contents_by_name(UpperCAmelCase__		,       'training_function'   )   )
										__lowerCAmelCase       =				clean_lines(get_function_contents_by_name(UpperCAmelCase__		,       'training_function'   )   )
										if secondary_filename is not None:
															__lowerCAmelCase       =				clean_lines(
															    get_function_contents_by_name(UpperCAmelCase__		,       'training_function'   )   )

					__lowerCAmelCase       =				'train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n'

					# Specific code in our script that differs from the full version, aka what is new
					__lowerCAmelCase       =				[]
					__lowerCAmelCase       =				[]  # We keep track of the idxs just in case it's a repeated statement
					__lowerCAmelCase       =				iter(UpperCAmelCase__   )
					for i in range(len(UpperCAmelCase__   ) - 1   ):
										if i not in passed_idxs:
															__lowerCAmelCase       =				next(UpperCAmelCase__   )
															if (line not in full_file_func) and (line.lstrip() != _dl_line):
																				if "TESTING_MOCKED_DATALOADERS" not in line:
																									new_feature_code.append(UpperCAmelCase__   )
																									passed_idxs.append(UpperCAmelCase__   )
																				else:
																									# Skip over the `config['num_epochs'] = 2` statement
																									__lowerCAmelCase       =				next(UpperCAmelCase__   )

    # Extract out just the new parts from the full_file_training_func
					__lowerCAmelCase       =				[]
					__lowerCAmelCase       =				[]  # We keep track of the idxs just in case it's a repeated statement
					for i, line in enumerate(UpperCAmelCase__   ):
										if i not in passed_idxs:
															if (line not in full_file_func) and (line.lstrip() != _dl_line):
																				if "TESTING_MOCKED_DATALOADERS" not in line:
																									new_full_example_parts.append(UpperCAmelCase__   )
																									passed_idxs.append(UpperCAmelCase__   )

    # Finally, get the overall diff
					__lowerCAmelCase       =				[line for line in new_feature_code if line not in new_full_example_parts]
					if secondary_filename is not None:
										__lowerCAmelCase       =				[line for line in full_file_contents if line not in secondary_file_func]
										__lowerCAmelCase       =				[line for line in diff_from_example if line not in diff_from_two]

					return diff_from_example






