



'''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 	_lowerCAmelCase     :






		'''simple docstring'''
		def __init__(						self							:       Any      ,		UpperCamelCase_							:       Any      ,		UpperCamelCase_							:       Optional[Any]=3      ,		UpperCamelCase_							:       Optional[int]=32      ,		UpperCamelCase_							:       Optional[Any]=3      ,		UpperCamelCase_							:       List[str]=10      ,		UpperCamelCase_							:       List[str]=[10, 20, 30, 40]      ,		UpperCamelCase_							:       Tuple=[1, 1, 2, 1]      ,		UpperCamelCase_							:       Optional[Any]=True      ,		UpperCamelCase_							:       Any=True      ,		UpperCamelCase_							:       Tuple="relu"      ,		UpperCamelCase_							:       int=3      ,		UpperCamelCase_							:       Tuple=None      ,		UpperCamelCase_							:       Tuple=["stage2", "stage3", "stage4"]      ,		UpperCamelCase_							:       Optional[int]=[2, 3, 4]      ,		)      ->			str:







									'''simple docstring'''





									_lowercase							:		Any				=   parent
									_lowercase							:		int				=   batch_size
									_lowercase							:		List[str]				=   image_size
									_lowercase							:		List[str]				=   num_channels
									_lowercase							:		List[str]				=   embeddings_size
									_lowercase							:		str				=   hidden_sizes
									_lowercase							:		Dict				=   depths
									_lowercase							:		Any				=   is_training
									_lowercase							:		Dict				=   use_labels
									_lowercase							:		Optional[Any]				=   hidden_act
									_lowercase							:		Optional[Any]				=   num_labels
									_lowercase							:		str				=   scope
									_lowercase							:		Optional[int]				=   len(_UpperCAmelCase		)
									_lowercase							:		List[Any]				=   out_features
									_lowercase							:		Dict				=   out_indices
		def 						__lowercase      (						self							:       Optional[int]		)      ->			List[str]:







									'''simple docstring'''





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

									_lowercase							:		Any				=   None
									if self.use_labels:
																_lowercase							:		int				=   ids_tensor([self.batch_size]      ,		self.num_labels		)

									_lowercase							:		Tuple				=   self.get_config()

									return config, pixel_values, labels
		def 						__lowercase      (						self							:       List[str]		)      ->			Union[str, Any]:







									'''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							:       List[Any]      ,		UpperCamelCase_							:       str      ,		UpperCamelCase_							:       List[Any]      ,		UpperCamelCase_							:       List[str]		)      ->			Tuple:







									'''simple docstring'''





									_lowercase							:		int				=   ResNetModel(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_lowercase							:		Tuple				=   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 						__lowercase      (						self							:       List[str]      ,		UpperCamelCase_							:       Any      ,		UpperCamelCase_							:       Optional[int]      ,		UpperCamelCase_							:       Optional[int]		)      ->			Dict:







									'''simple docstring'''





									_lowercase							:		int				=   self.num_labels
									_lowercase							:		int				=   ResNetForImageClassification(_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_lowercase							:		Any				=   model(_UpperCAmelCase      ,		labels=_UpperCAmelCase		)
									self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_labels)		)
		def 						__lowercase      (						self							:       str      ,		UpperCamelCase_							:       List[Any]      ,		UpperCamelCase_							:       Any      ,		UpperCamelCase_							:       Tuple		)      ->			Any:







									'''simple docstring'''





									_lowercase							:		Union[str, Any]				=   ResNetBackbone(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_lowercase							:		Dict				=   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
									_lowercase							:		int				=   None
									_lowercase							:		str				=   ResNetBackbone(config=_UpperCAmelCase		)
									model.to(_UpperCAmelCase		)
									model.eval()
									_lowercase							:		Dict				=   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 						__lowercase      (						self							:       Dict		)      ->			Dict:







									'''simple docstring'''





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




@require_torch
class 	_lowerCAmelCase     (    _lowerCAmelCase     ,		_lowerCAmelCase     ,		unittest.TestCase       ):






		'''simple docstring'''
		snake_case_							= (
		    (
		        ResNetModel,
		        ResNetForImageClassification,
		        ResNetBackbone,
		    )
		    if is_torch_available()
		    else ()
		)
		snake_case_							= (
		    {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
		    if is_torch_available()
		    else {}
		)

		snake_case_							= True
		snake_case_							= False
		snake_case_							= False
		snake_case_							= False
		snake_case_							= False
		def 						__lowercase      (						self							:       Tuple		)      ->			Optional[int]:







									'''simple docstring'''





									_lowercase							:		List[Any]				=   ResNetModelTester(self		)
									_lowercase							:		List[Any]				=   ConfigTester(self      ,		config_class=_UpperCAmelCase      ,		has_text_modality=_UpperCAmelCase		)
		def 						__lowercase      (						self							:       Tuple		)      ->			Optional[int]:







									'''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							:       List[str]		)      ->			Optional[int]:







									'''simple docstring'''





									return
		@unittest.skip(reason='''ResNet does not use inputs_embeds'''		)
		def 						__lowercase      (						self							:       str		)      ->			Optional[int]:







									'''simple docstring'''





									pass
		@unittest.skip(reason='''ResNet does not support input and output embeddings'''		)
		def 						__lowercase      (						self							:       Union[str, Any]		)      ->			Dict:







									'''simple docstring'''





									pass
		def 						__lowercase      (						self							:       List[Any]		)      ->			Tuple:







									'''simple docstring'''





									_lowercase							:		str				=   self.model_tester.prepare_config_and_inputs_for_common()

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

																_lowercase							:		int				=   ['pixel_values']
																self.assertListEqual(arg_names[:1]      ,		_UpperCAmelCase		)
		def 						__lowercase      (						self							:       Optional[Any]		)      ->			Tuple:







									'''simple docstring'''





									_lowercase							:		Optional[Any]				=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCAmelCase		)
		def 						__lowercase      (						self							:       Any		)      ->			Tuple:







									'''simple docstring'''





									_lowercase							:		Any				=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*_UpperCAmelCase		)
		def 						__lowercase      (						self							:       Union[str, Any]		)      ->			str:







									'''simple docstring'''





									_lowercase							:		Optional[Any]				=   self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
																_lowercase							:		List[str]				=   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 						__lowercase      (						self							:       Tuple		)      ->			Any:







									'''simple docstring'''





									def check_hidden_states_output(UpperCamelCase_							:       Optional[Any]      ,		UpperCamelCase_							:       Union[str, Any]      ,		UpperCamelCase_							:       str		):
																_lowercase							:		int				=   model_class(_UpperCAmelCase		)
																model.to(_UpperCAmelCase		)
																model.eval()

																with torch.no_grad():
																							_lowercase							:		Dict				=   model(**self._prepare_for_class(_UpperCAmelCase      ,		_UpperCAmelCase		)		)

																_lowercase							:		Optional[int]				=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																_lowercase							:		List[Any]				=   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]      ,		)

									_lowercase							:		Union[str, Any]				=   self.model_tester.prepare_config_and_inputs_for_common()
									_lowercase							:		Union[str, Any]				=   ['basic', 'bottleneck']
									for model_class in self.all_model_classes:
																for layer_type in layers_type:
																							_lowercase							:		Dict				=   layer_type
																							_lowercase							:		Dict				=   True
																							check_hidden_states_output(_UpperCAmelCase      ,		_UpperCAmelCase      ,		_UpperCAmelCase		)

																							# check that output_hidden_states also work using config
																							del inputs_dict["output_hidden_states"]
																							_lowercase							:		Tuple				=   True

																							check_hidden_states_output(_UpperCAmelCase      ,		_UpperCAmelCase      ,		_UpperCAmelCase		)
		@unittest.skip(reason='''ResNet does not use feedforward chunking'''		)
		def 						__lowercase      (						self							:       Any		)      ->			List[Any]:







									'''simple docstring'''





									pass
		def 						__lowercase      (						self							:       Tuple		)      ->			Optional[int]:







									'''simple docstring'''





									_lowercase							:		Optional[int]				=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase		)





		@slow
		def 						__lowercase      (						self							:       List[str]		)      ->			Optional[int]:







									'''simple docstring'''





									for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_lowercase							:		Union[str, Any]				=   ResNetModel.from_pretrained(_UpperCAmelCase		)
																self.assertIsNotNone(_UpperCAmelCase		)





def 				_SCREAMING_SNAKE_CASE(					)		->List[str]:






							'''simple docstring'''
							_lowercase							:		Optional[Any]				=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
							return image

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






		'''simple docstring'''
		@cached_property
		def 						__lowercase      (						self							:       int		)      ->			Tuple:







									'''simple docstring'''





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





		@slow
		def 						__lowercase      (						self							:       Union[str, Any]		)      ->			List[str]:







									'''simple docstring'''





									_lowercase							:		Tuple				=   ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(_UpperCAmelCase		)

									_lowercase							:		List[Any]				=   self.default_image_processor
									_lowercase							:		List[str]				=   prepare_img()
									_lowercase							:		Union[str, Any]				=   image_processor(images=_UpperCAmelCase      ,		return_tensors='''pt'''		).to(_UpperCAmelCase		)

									# forward pass
									with torch.no_grad():
																_lowercase							:		Optional[int]				=   model(**_UpperCAmelCase		)

									# verify the logits
									_lowercase							:		List[str]				=   torch.Size((1, 1_000)		)
									self.assertEqual(outputs.logits.shape      ,		_UpperCAmelCase		)

									_lowercase							:		Dict				=   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 	_lowerCAmelCase     (    _lowerCAmelCase     ,		unittest.TestCase       ):






		'''simple docstring'''
		snake_case_							= (ResNetBackbone,) if is_torch_available() else ()
		snake_case_							= False
		snake_case_							= ResNetConfig
		def 						__lowercase      (						self							:       Optional[Any]		)      ->			List[str]:







									'''simple docstring'''





									_lowercase							:		Optional[int]				=   ResNetModelTester(self		)






import inspect
import json
import os
import tempfile
import unittest

from transformers.models.speech_to_text_a import SpeechaTextaTokenizer
from transformers.models.speech_to_text_a.tokenization_speech_to_text_a import VOCAB_FILES_NAMES

from ...test_tokenization_common import TokenizerTesterMixin


class      lowerCamelCase_ (			_lowerCAmelCase	,				unittest.TestCase):
 _lowerCAmelCase									=	SpeechaTextaTokenizer
 _lowerCAmelCase									=	False




 def     a       (			self							):
   super().setUp()

   __UpperCAmelCase	:  List[Any]		=     '<s> <pad> </s> <unk> here@@ a couple of@@ words for the he@@ re@@ vocab'.split(' '							)
   __UpperCAmelCase	:  Dict		=     ['he re</w> 123', 'here a 1456']
   __UpperCAmelCase	:  Optional[int]		=     dict(zip(_UpperCAmelCase  ,  range(len(_UpperCAmelCase							)							)							)							)

   __UpperCAmelCase	:  List[Any]		=     {'pad_token': '<pad>', 'unk_token': '<unk>', 'bos_token': '<s>', 'eos_token': '</s>'}

   __UpperCAmelCase	:  Tuple		=     tempfile.mkdtemp()
   __UpperCAmelCase	:  str		=     os.path.join(self.tmpdirname  ,  VOCAB_FILES_NAMES['vocab_file']							)
   __UpperCAmelCase	:  List[Any]		=     os.path.join(self.tmpdirname  ,  VOCAB_FILES_NAMES['merges_file']							)

   with open(self.vocab_file  ,  'w'  ,  encoding='utf-8'							) as fp:
     fp.write(json.dumps(_UpperCAmelCase							) + '\n'							)

   with open(self.merges_file  ,  'w'							) as fp:
     fp.write('\n'.join(_UpperCAmelCase							)							)




 def     a       (			self							):
   __UpperCAmelCase	:  int		=     list(self.get_tokenizer().get_vocab().keys()							)

   self.assertEqual(vocab_keys[0]  ,  '<s>'							)
   self.assertEqual(vocab_keys[1]  ,  '<pad>'							)
   self.assertEqual(vocab_keys[-1]  ,  'vocab'							)
   self.assertEqual(len(_UpperCAmelCase							)  ,  14							)




 def     a       (			self							):
   self.assertEqual(self.get_tokenizer().vocab_size  ,  14							)




 def     a       (			self							):
   __UpperCAmelCase	:  int		=     SpeechaTextaTokenizer.from_pretrained(self.tmpdirname							)

   # make sure @@ is correctly concatenated
   __UpperCAmelCase	:  int		=     [4, 6, 8, 7, 10]  # ["here@@", "couple", "words", "of@@", "the"]
   __UpperCAmelCase	:  List[str]		=     tokenizer.decode(_UpperCAmelCase							)

   self.assertTrue(output_string == 'herecouple words ofthe'							)




 def     a       (			self							):
   __UpperCAmelCase	:  Union[str, Any]		=     SpeechaTextaTokenizer.from_pretrained(self.tmpdirname							)

   with tempfile.TemporaryDirectory() as tmp_dirname:
     tokenizer.save_pretrained(_UpperCAmelCase							)
     os.remove(os.path.join(_UpperCAmelCase  ,  'merges.txt'							)							)

     # load tokenizer without merges file should not throw an error
     __UpperCAmelCase	:  Optional[int]		=     SpeechaTextaTokenizer.from_pretrained(_UpperCAmelCase							)

   with tempfile.TemporaryDirectory() as tmp_dirname:
     # save tokenizer and load again
     tokenizer.save_pretrained(_UpperCAmelCase							)
     __UpperCAmelCase	:  Optional[int]		=     SpeechaTextaTokenizer.from_pretrained(_UpperCAmelCase							)

   self.assertIsNotNone(_UpperCAmelCase							)




 def     a       (			self							):
   if not self.test_slow_tokenizer:
     return

   __UpperCAmelCase	:  List[Any]		=     inspect.signature(self.tokenizer_class.__init__							)
   __UpperCAmelCase	:  List[Any]		=     self.get_tokenizer()

   for parameter_name, parameter in signature.parameters.items():
     if parameter.default != inspect.Parameter.empty and parameter_name != "merges_file":
       self.assertIn(_UpperCAmelCase  ,  tokenizer.init_kwargs							)





