




import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 RegNetForImageClassification, RegNetModel
		from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class     snake_case__							:
				"""simple docstring"""



				def __init__(      self				:     Optional[int]					,      __lowerCamelCase				:     str					,      __lowerCamelCase				:     Optional[Any]=3					,      __lowerCamelCase				:     Union[str, Any]=32					,      __lowerCamelCase				:     Tuple=3					,      __lowerCamelCase				:     Tuple=10					,      __lowerCamelCase				:     List[str]=[10, 20, 30, 40]					,      __lowerCamelCase				:     int=[1, 1, 2, 1]					,      __lowerCamelCase				:     Union[str, Any]=True					,      __lowerCamelCase				:     int=True					,      __lowerCamelCase				:     Union[str, Any]="relu"					,      __lowerCamelCase				:     Optional[int]=3					,      __lowerCamelCase				:     Any=None					,      )					->     Optional[Any]:
							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(__lowerCamelCase							)





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





				def 							__UpperCAmelCase							(      self				:     Optional[Any]					,      __lowerCamelCase				:     Tuple					,      __lowerCamelCase				:     Dict					,      __lowerCamelCase				:     Dict							)					->     Union[str, Any]:
							a    =			RegNetModel(config=__lowerCamelCase							)
							model.to(__lowerCamelCase							)
							model.eval()
							a    =			model(__lowerCamelCase							)
							# 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 							__UpperCAmelCase							(      self				:     int					,      __lowerCamelCase				:     str					,      __lowerCamelCase				:     int					,      __lowerCamelCase				:     Union[str, Any]							)					->     Optional[int]:
							a    =			self.num_labels
							a    =			RegNetForImageClassification(__lowerCamelCase							)
							model.to(__lowerCamelCase							)
							model.eval()
							a    =			model(__lowerCamelCase					,      labels=__lowerCamelCase							)
							self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_labels)							)





				def 							__UpperCAmelCase							(      self				:     Optional[int]							)					->     Union[str, 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     snake_case__							(_UpperCamelCase    ,       _UpperCamelCase    ,       unittest.TestCase   ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_       :							int							 =					(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
				SCREAMING_SNAKE_CASE_       :							Union[str, Any]							 =					(
				    {"""feature-extraction""": RegNetModel, """image-classification""": RegNetForImageClassification}
				    if is_torch_available()
				    else {}
				)

				SCREAMING_SNAKE_CASE_       :							Any							 =					False
				SCREAMING_SNAKE_CASE_       :							int							 =					False
				SCREAMING_SNAKE_CASE_       :							str							 =					False
				SCREAMING_SNAKE_CASE_       :							str							 =					False





				def 							__UpperCAmelCase							(      self				:     Any							)					->     Any:
							a    =			RegNetModelTester(self							)
							a    =			ConfigTester(self					,      config_class=__lowerCamelCase					,      has_text_modality=__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     Dict							)					->     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 							__UpperCAmelCase							(      self				:     List[str]							)					->     List[Any]:
							return





				@unittest.skip(reason="RegNet does not use inputs_embeds"							)
				def 							__UpperCAmelCase							(      self				:     str							)					->     Optional[Any]:
							pass





				@unittest.skip(reason="RegNet does not support input and output embeddings"							)
				def 							__UpperCAmelCase							(      self				:     Any							)					->     Union[str, Any]:
							pass





				def 							__UpperCAmelCase							(      self				:     Dict							)					->     Optional[Any]:
							a    ,		a    =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a    =			model_class(__lowerCamelCase							)
										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]					,      __lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     Optional[Any]							)					->     List[Any]:
							a    =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     int							)					->     List[str]:
							a    ,		a    =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a    =			model_class(config=__lowerCamelCase							)
										for name, module in model.named_modules():
													if isinstance(__lowerCamelCase					,      (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 							__UpperCAmelCase							(      self				:     Dict							)					->     Any:
							def check_hidden_states_output(__lowerCamelCase				:     List[Any]					,      __lowerCamelCase				:     Any					,      __lowerCamelCase				:     List[str]							):
										a    =			model_class(__lowerCamelCase							)
										model.to(__lowerCamelCase							)
										model.eval()

										with torch.no_grad():
													a    =			model(**self._prepare_for_class(__lowerCamelCase					,      __lowerCamelCase							)							)

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

										a    =			self.model_tester.num_stages
										self.assertEqual(len(__lowerCamelCase							)					,      expected_num_stages + 1							)

										# RegNet'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 // 2, self.model_tester.image_size // 2]					,      )

							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(__lowerCamelCase					,      __lowerCamelCase					,      __lowerCamelCase							)

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

													check_hidden_states_output(__lowerCamelCase					,      __lowerCamelCase					,      __lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     Any							)					->     List[str]:
							a    =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase							)





				@slow
				def 							__UpperCAmelCase							(      self				:     Optional[int]							)					->     Any:
							for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										a    =			RegNetModel.from_pretrained(__lowerCamelCase							)
										self.assertIsNotNone(__lowerCamelCase							)




def 			__magic_name__				( ):






			'''simple docstring'''







			a    =			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 							__UpperCAmelCase							(      self				:     Tuple							)					->     Union[str, Any]:
							return (
							    AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)
							    if is_vision_available()
							    else None
							)





				@slow
				def 							__UpperCAmelCase							(      self				:     Optional[Any]							)					->     Tuple:
							a    =			RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							).to(__lowerCamelCase							)

							a    =			self.default_image_processor
							a    =			prepare_img()
							a    =			image_processor(images=__lowerCamelCase					,      return_tensors="pt"							).to(__lowerCamelCase							)

							# forward pass
							with torch.no_grad():
										a    =			model(**__lowerCamelCase							)

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

							a    =			torch.tensor([-0.4_180, -1.5_051, -3.4_836]							).to(__lowerCamelCase							)

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












import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__lowerCAmelCase		:				str       			=		logging.get_logger(__name__)

__lowerCAmelCase		:				Dict       			=		{'vocab_file': 'spiece.model'}

__lowerCAmelCase		:				Optional[int]       			=		{
    'vocab_file': {
        'bert_for_seq_generation': (
            'https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model'
        ),
    }
}

__lowerCAmelCase		:				Dict       			=		{'bert_for_seq_generation': 512}




class     snake_case__							(_UpperCamelCase   ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_       :							Any							 =					VOCAB_FILES_NAMES
				SCREAMING_SNAKE_CASE_       :							Union[str, Any]							 =					PRETRAINED_VOCAB_FILES_MAP
				SCREAMING_SNAKE_CASE_       :							int							 =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				SCREAMING_SNAKE_CASE_       :							List[int]							 =					[]
				SCREAMING_SNAKE_CASE_       :							Optional[Any]							 =					["""input_ids""", """attention_mask"""]





				def __init__(      self				:     List[Any]					,      __lowerCamelCase				:     Tuple					,      __lowerCamelCase				:     str="<s>"					,      __lowerCamelCase				:     Optional[int]="</s>"					,      __lowerCamelCase				:     int="<unk>"					,      __lowerCamelCase				:     List[str]="<pad>"					,      __lowerCamelCase				:     Union[str, Any]="<::::>"					,      __lowerCamelCase				:     Optional[Dict[str, Any]] = None					,      **__lowerCamelCase				:     List[str]					,      )					->     None:
							a    =			{} if sp_model_kwargs is None else sp_model_kwargs

							# Add extra_ids to the special token list
							super().__init__(
							    bos_token=__lowerCamelCase					,      eos_token=__lowerCamelCase					,      unk_token=__lowerCamelCase					,      pad_token=__lowerCamelCase					,      sep_token=__lowerCamelCase					,      sp_model_kwargs=self.sp_model_kwargs					,      **__lowerCamelCase					,      )

							a    =			vocab_file

							a    =			spm.SentencePieceProcessor(**self.sp_model_kwargs							)
							self.sp_model.Load(__lowerCamelCase							)





				@property
				def 							__UpperCAmelCase							(      self				:     Dict							)					->     Dict:
							return self.sp_model.get_piece_size()





				def 							__UpperCAmelCase							(      self				:     Tuple							)					->     Optional[int]:
							a    =			{self.convert_ids_to_tokens(__lowerCamelCase							): i for i in range(self.vocab_size							)}
							vocab.update(self.added_tokens_encoder							)
							return vocab





				def __getstate__(      self				:     Dict							)					->     Optional[Any]:
							a    =			self.__dict__.copy()
							a    =			None
							return state





				def __setstate__(      self				:     Optional[Any]					,      __lowerCamelCase				:     Dict							)					->     Optional[Any]:
							a    =			d

							# for backward compatibility
							if not hasattr(self					,      "sp_model_kwargs"							):
										a    =			{}

							a    =			spm.SentencePieceProcessor(**self.sp_model_kwargs							)
							self.sp_model.Load(self.vocab_file							)





				def 							__UpperCAmelCase							(      self				:     Union[str, Any]					,      __lowerCamelCase				:     str							)					->     List[str]:
							return self.sp_model.encode(__lowerCamelCase					,      out_type=__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     str					,      __lowerCamelCase				:     Union[str, Any]							)					->     int:
							return self.sp_model.piece_to_id(__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     Tuple					,      __lowerCamelCase				:     List[str]							)					->     Any:
							a    =			self.sp_model.IdToPiece(__lowerCamelCase							)
							return token





				def 							__UpperCAmelCase							(      self				:     Any					,      __lowerCamelCase				:     Dict							)					->     Any:
							a    =			[]
							a    =			""
							for token in tokens:
										# make sure that special tokens are not decoded using sentencepiece model
										if token in self.all_special_tokens:
													out_string += self.sp_model.decode(__lowerCamelCase							) + token
													a    =			[]
										else:
													current_sub_tokens.append(__lowerCamelCase							)
							out_string += self.sp_model.decode(__lowerCamelCase							)
							return out_string.strip()





				def 							__UpperCAmelCase							(      self				:     Dict					,      __lowerCamelCase				:     str					,      __lowerCamelCase				:     Optional[str] = None							)					->     Tuple[str]:
							if not os.path.isdir(__lowerCamelCase							):
										logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""							)
										return
							a    =			os.path.join(
							    __lowerCamelCase					,      (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]							)

							if os.path.abspath(self.vocab_file							) != os.path.abspath(__lowerCamelCase							) and os.path.isfile(self.vocab_file							):
										copyfile(self.vocab_file					,      __lowerCamelCase							)
							elif not os.path.isfile(self.vocab_file							):
										with open(__lowerCamelCase					,      "wb"							) as fi:
													a    =			self.sp_model.serialized_model_proto()
													fi.write(__lowerCamelCase							)

							return (out_vocab_file,)






