




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

					def __init__(				self ,       __lowercase ,       __lowercase=3 ,       __lowercase=32 ,       __lowercase=3 ,       __lowercase=10 ,       __lowercase=[10, 20, 30, 40] ,       __lowercase=[1, 1, 2, 1] ,       __lowercase=True ,       __lowercase=True ,       __lowercase="relu" ,       __lowercase=3 ,       __lowercase=None ,       __lowercase=["stage2", "stage3", "stage4"] ,       __lowercase=[2, 3, 4] ,       ):







						'''simple docstring'''




						lowerCamelCase_							:		str							   =							parent
						lowerCamelCase_							:		Any							   =							batch_size
						lowerCamelCase_							:		Any							   =							image_size
						lowerCamelCase_							:		Optional[int]							   =							num_channels
						lowerCamelCase_							:		int							   =							embeddings_size
						lowerCamelCase_							:		Union[str, Any]							   =							hidden_sizes
						lowerCamelCase_							:		Dict							   =							depths
						lowerCamelCase_							:		Tuple							   =							is_training
						lowerCamelCase_							:		Tuple							   =							use_labels
						lowerCamelCase_							:		Dict							   =							hidden_act
						lowerCamelCase_							:		List[str]							   =							num_labels
						lowerCamelCase_							:		List[str]							   =							scope
						lowerCamelCase_							:		List[Any]							   =							len(__lowercase					)
						lowerCamelCase_							:		Optional[int]							   =							out_features
						lowerCamelCase_							:		List[str]							   =							out_indices

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Union[str, Any]							   =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

						lowerCamelCase_							:		Union[str, Any]							   =							None
						if self.use_labels:
							lowerCamelCase_							:		List[Any]							   =							ids_tensor([self.batch_size] ,       self.num_labels					)

						lowerCamelCase_							:		List[str]							   =							self.get_config()

						return config, pixel_values, labels

					def 	lowercase_							(				self					):







						'''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 ,       out_features=self.out_features ,       out_indices=self.out_indices ,       )

					def 	lowercase_							(				self ,       __lowercase ,       __lowercase ,       __lowercase					):







						'''simple docstring'''




						lowerCamelCase_							:		Optional[int]							   =							ResNetModel(config=__lowercase					)
						model.to(__lowercase					)
						model.eval()
						lowerCamelCase_							:		List[Any]							   =							model(__lowercase					)
						# 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 	lowercase_							(				self ,       __lowercase ,       __lowercase ,       __lowercase					):







						'''simple docstring'''




						lowerCamelCase_							:		Tuple							   =							self.num_labels
						lowerCamelCase_							:		List[str]							   =							ResNetForImageClassification(__lowercase					)
						model.to(__lowercase					)
						model.eval()
						lowerCamelCase_							:		Optional[int]							   =							model(__lowercase ,       labels=__lowercase					)
						self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_labels)					)

					def 	lowercase_							(				self ,       __lowercase ,       __lowercase ,       __lowercase					):







						'''simple docstring'''




						lowerCamelCase_							:		Tuple							   =							ResNetBackbone(config=__lowercase					)
						model.to(__lowercase					)
						model.eval()
						lowerCamelCase_							:		Any							   =							model(__lowercase					)

						# 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_							:		Any							   =							None
						lowerCamelCase_							:		Any							   =							ResNetBackbone(config=__lowercase					)
						model.to(__lowercase					)
						model.eval()
						lowerCamelCase_							:		Dict							   =							model(__lowercase					)

						# 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 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Dict							   =							self.prepare_config_and_inputs()
						lowerCamelCase_   ,			lowerCamelCase_   ,			lowerCamelCase_							:		Optional[Any]							   =							config_and_inputs
						lowerCamelCase_							:		str							   =							{'pixel_values': pixel_values}
						return config, inputs_dict


@require_torch
class 				__SCREAMING_SNAKE_CASE							(		lowerCamelCase   ,     lowerCamelCase   ,     unittest.TestCase  ):
					_lowerCamelCase		  = (
					    (
					        ResNetModel,
					        ResNetForImageClassification,
					        ResNetBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					_lowerCamelCase		  = (
					    {"""feature-extraction""": ResNetModel, """image-classification""": ResNetForImageClassification}
					    if is_torch_available()
					    else {}
					)

					_lowerCamelCase		  = True
					_lowerCamelCase		  = False
					_lowerCamelCase		  = False
					_lowerCamelCase		  = False
					_lowerCamelCase		  = False

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		List[Any]							   =							ResNetModelTester(self					)
						lowerCamelCase_							:		Optional[int]							   =							ConfigTester(self ,       config_class=__lowercase ,       has_text_modality=__lowercase					)

					def 	lowercase_							(				self					):







						'''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 	lowercase_							(				self					):







						'''simple docstring'''




						return

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







						'''simple docstring'''




						pass

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







						'''simple docstring'''




						pass

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_   ,			lowerCamelCase_							:		Any							   =							self.model_tester.prepare_config_and_inputs_for_common()

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

							lowerCamelCase_							:		Tuple							   =							['pixel_values']
							self.assertListEqual(arg_names[:1] ,       __lowercase					)

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Optional[int]							   =							self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowercase					)

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Union[str, Any]							   =							self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_backbone(*__lowercase					)

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_   ,			lowerCamelCase_							:		Optional[int]							   =							self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							lowerCamelCase_							:		List[str]							   =							model_class(config=__lowercase					)
							for name, module in model.named_modules():
								if isinstance(__lowercase ,       (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 	lowercase_							(				self					):







						'''simple docstring'''




						def check_hidden_states_output(__lowercase ,       __lowercase ,       __lowercase					):
							lowerCamelCase_							:		List[str]							   =							model_class(__lowercase					)
							model.to(__lowercase					)
							model.eval()

							with torch.no_grad():
								lowerCamelCase_							:		int							   =							model(**self._prepare_for_class(__lowercase ,       __lowercase					)					)

							lowerCamelCase_							:		str							   =							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

							lowerCamelCase_							:		List[str]							   =							self.model_tester.num_stages
							self.assertEqual(len(__lowercase					) ,       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_							:		Union[str, Any]							   =							self.model_tester.prepare_config_and_inputs_for_common()
						lowerCamelCase_							:		Union[str, Any]							   =							['basic', 'bottleneck']
						for model_class in self.all_model_classes:
							for layer_type in layers_type:
								lowerCamelCase_							:		List[str]							   =							layer_type
								lowerCamelCase_							:		str							   =							True
								check_hidden_states_output(__lowercase ,       __lowercase ,       __lowercase					)

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								lowerCamelCase_							:		List[Any]							   =							True

								check_hidden_states_output(__lowercase ,       __lowercase ,       __lowercase					)

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







						'''simple docstring'''




						pass

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Dict							   =							self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__lowercase					)





					@slow
					def 	lowercase_							(				self					):







						'''simple docstring'''




						for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							lowerCamelCase_							:		Dict							   =							ResNetModel.from_pretrained(__lowercase					)
							self.assertIsNotNone(__lowercase					)






def 					snake_case					(							)							->							int:




	'''simple docstring'''


	lowerCamelCase_							:		Optional[int]							   =							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
	return image


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

					@cached_property
					def 	lowercase_							(				self					):







						'''simple docstring'''




						return (
						    AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
						    if is_vision_available()
						    else None
						)





					@slow
					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Union[str, Any]							   =							ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					).to(__lowercase					)

						lowerCamelCase_							:		Dict							   =							self.default_image_processor
						lowerCamelCase_							:		Dict							   =							prepare_img()
						lowerCamelCase_							:		str							   =							image_processor(images=__lowercase ,       return_tensors='pt'					).to(__lowercase					)

						# forward pass
						with torch.no_grad():
							lowerCamelCase_							:		str							   =							model(**__lowercase					)

						# verify the logits
						lowerCamelCase_							:		Optional[Any]							   =							torch.Size((1, 1_000)					)
						self.assertEqual(outputs.logits.shape ,       __lowercase					)

						lowerCamelCase_							:		Optional[Any]							   =							torch.tensor([-11.10_69, -9.78_77, -8.37_77]					).to(__lowercase					)

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


@require_torch
class 				__SCREAMING_SNAKE_CASE							(		lowerCamelCase   ,     unittest.TestCase  ):
					_lowerCamelCase		  = (ResNetBackbone,) if is_torch_available() else ()
					_lowerCamelCase		  = False
					_lowerCamelCase		  = ResNetConfig

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		List[Any]							   =							ResNetModelTester(self					)






import json
import os
from dataclasses import dataclass

import numpy as np
import pyarrow as pa

import datasets
from utils import get_duration


UpperCamelCase__              =						1_0_0_0_0_0_0_0_0_0_0_0
UpperCamelCase__              =						1_0_0_0_0

UpperCamelCase__       , UpperCamelCase__              =						os.path.split(__file__)
UpperCamelCase__              =						os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json'))






def 					snake_case					(							A						,   A			)							->							datasets.Dataset:




	'''simple docstring'''


	lowerCamelCase_							:		int							   =							pa.Table.from_pydict({'col': [0] * chunk_size}			)
	lowerCamelCase_							:		List[str]							   =							pa.concat_tables([table] * (num_examples // chunk_size)			)
	return datasets.Dataset(A						,   fingerprint='table_100B'			)


@dataclass
class 				__SCREAMING_SNAKE_CASE							:
					_lowerCamelCase		  = 42
					_lowerCamelCase		  = 42
					_lowerCamelCase		  = 42
					_lowerCamelCase		  = 42

					def 	lowercase_							(				self					):







						'''simple docstring'''




						lowerCamelCase_							:		Optional[Any]							   =							np.random.default_rng(self.seed					)
						lowerCamelCase_							:		Any							   =							rng.integers(low=self.low ,       high=self.high ,       size=self.size					).tolist()

					def __iter__(				self					):







						'''simple docstring'''




						return iter(self._sampled_values					)





					def __len__(				self					):







						'''simple docstring'''




						return self.size






@get_duration
def 					snake_case					(							A			)							->							Optional[Any]:




	'''simple docstring'''


	lowerCamelCase_							:		Union[str, Any]							   =							dataset[0]






@get_duration
def 					snake_case					(							A			)							->							Any:




	'''simple docstring'''


	lowerCamelCase_							:		List[Any]							   =							dataset[-1]






@get_duration
def 					snake_case					(							A			)							->							Optional[Any]:




	'''simple docstring'''


	lowerCamelCase_							:		Tuple							   =							dataset[range(len(A			) // 2						,   len(A			) // 2 + 1024			)]






@get_duration
def 					snake_case					(							A			)							->							str:




	'''simple docstring'''


	lowerCamelCase_							:		List[str]							   =							dataset[RandIter(0						,   len(A			)						,   1024						,   seed=42			)]






def 					snake_case					(							)							->							List[Any]:




	'''simple docstring'''


	lowerCamelCase_							:		Tuple							   =							{'num examples': SPEED_TEST_N_EXAMPLES}
	lowerCamelCase_							:		Optional[int]							   =							(get_first_row, get_last_row, get_batch_of_aaaa_rows, get_batch_of_aaaa_random_rows)
	print('generating dataset'			)
	lowerCamelCase_							:		List[Any]							   =							generate_100B_dataset(num_examples=A						,   chunk_size=A			)
	print('Functions'			)
	for func in functions:
		print(func.__name__			)
		lowerCamelCase_							:		str							   =							func(A			)

	with open(A						,   'wb'			) as f:
		f.write(json.dumps(A			).encode('utf-8'			)			)


if __name__ == "__main__":  # useful to run the profiler
							benchmark_table_100B()
