


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






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




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






      def  lowerCamelCase (      self		:  Optional[int]				)      ->		Any:
             """simple docstring"""




             _lowerCamelCase :	Tuple						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

             _lowerCamelCase :	List[str]						=None
             if self.use_labels:
                    _lowerCamelCase :	Tuple						=ids_tensor([self.batch_size]    ,     self.num_labels				)

             _lowerCamelCase :	str						=self.get_config()

             return config, pixel_values, labels






      def  lowerCamelCase (      self		:  Tuple				)      ->		str:
             """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  lowerCamelCase (      self		:  Union[str, Any]    ,     lowercase_		:  Tuple    ,     lowercase_		:  str    ,     lowercase_		:  Optional[int]				)      ->		Tuple:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=ResNetModel(config=lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	Tuple						=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  lowerCamelCase (      self		:  Tuple    ,     lowercase_		:  Dict    ,     lowercase_		:  List[str]    ,     lowercase_		:  Any				)      ->		Dict:
             """simple docstring"""




             _lowerCamelCase :	List[Any]						=self.num_labels
             _lowerCamelCase :	Dict						=ResNetForImageClassification(lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	Tuple						=model(lowercase_    ,     labels=lowercase_				)
             self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)				)






      def  lowerCamelCase (      self		:  List[Any]    ,     lowercase_		:  Optional[int]    ,     lowercase_		:  str    ,     lowercase_		:  Optional[Any]				)      ->		List[str]:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=ResNetBackbone(config=lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	Dict						=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 :	int						=None
             _lowerCamelCase :	Optional[Any]						=ResNetBackbone(config=lowercase_				)
             model.to(lowercase_				)
             model.eval()
             _lowerCamelCase :	Tuple						=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  lowerCamelCase (      self		:  Dict				)      ->		Tuple:
             """simple docstring"""




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




@require_torch
class A						(     UpperCamelCase_					,							UpperCamelCase_					,							unittest.TestCase  ):
      UpperCamelCase__							:						Optional[int]   =(
          (
              ResNetModel,
              ResNetForImageClassification,
              ResNetBackbone,
          )
          if is_torch_available()
          else ()
      )
      UpperCamelCase__							:						Dict   =(
          {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
          if is_torch_available()
          else {}
      )

      UpperCamelCase__							:						List[Any]   =True
      UpperCamelCase__							:						int   =False
      UpperCamelCase__							:						Dict   =False
      UpperCamelCase__							:						List[Any]   =False
      UpperCamelCase__							:						Tuple   =False






      def  lowerCamelCase (      self		:  Optional[int]				)      ->		List[str]:
             """simple docstring"""




             _lowerCamelCase :	Union[str, Any]						=ResNetModelTester(self				)
             _lowerCamelCase :	Optional[int]						=ConfigTester(self    ,     config_class=lowercase_    ,     has_text_modality=lowercase_				)






      def  lowerCamelCase (      self		:  str				)      ->		Any:
             """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  lowerCamelCase (      self		:  List[str]				)      ->		str:
             """simple docstring"""




             return






      @unittest.skip(reason='ResNet does not use inputs_embeds'				)
      def  lowerCamelCase (      self		:  Optional[int]				)      ->		List[str]:
             """simple docstring"""




             pass






      @unittest.skip(reason='ResNet does not support input and output embeddings'				)
      def  lowerCamelCase (      self		:  str				)      ->		List[Any]:
             """simple docstring"""




             pass






      def  lowerCamelCase (      self		:  Dict				)      ->		Any:
             """simple docstring"""




             _lowerCamelCase			,  _lowerCamelCase :	List[str]						=self.model_tester.prepare_config_and_inputs_for_common()

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

                    _lowerCamelCase :	int						=['pixel_values']
                    self.assertListEqual(arg_names[:1]    ,     lowercase_				)






      def  lowerCamelCase (      self		:  List[Any]				)      ->		int:
             """simple docstring"""




             _lowerCamelCase :	List[Any]						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase_				)






      def  lowerCamelCase (      self		:  Union[str, Any]				)      ->		List[Any]:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_backbone(*lowercase_				)






      def  lowerCamelCase (      self		:  int				)      ->		List[Any]:
             """simple docstring"""




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

             for model_class in self.all_model_classes:
                    _lowerCamelCase :	List[Any]						=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  lowerCamelCase (      self		:  str				)      ->		Union[str, Any]:
             """simple docstring"""




             def check_hidden_states_output(lowercase_		:  List[Any]    ,     lowercase_		:  Any    ,     lowercase_		:  Union[str, Any]				):
                    _lowerCamelCase :	Optional[Any]						=model_class(lowercase_				)
                    model.to(lowercase_				)
                    model.eval()

                    with torch.no_grad():
                           _lowerCamelCase :	int						=model(**self._prepare_for_class(lowercase_    ,     lowercase_				)				)

                    _lowerCamelCase :	Union[str, Any]						=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 :	Optional[Any]						=self.model_tester.prepare_config_and_inputs_for_common()
             _lowerCamelCase :	Any						=['basic', 'bottleneck']
             for model_class in self.all_model_classes:
                    for layer_type in layers_type:
                           _lowerCamelCase :	Dict						=layer_type
                           _lowerCamelCase :	Any						=True
                           check_hidden_states_output(lowercase_    ,     lowercase_    ,     lowercase_				)

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

                           check_hidden_states_output(lowercase_    ,     lowercase_    ,     lowercase_				)






      @unittest.skip(reason='ResNet does not use feedforward chunking'				)
      def  lowerCamelCase (      self		:  Any				)      ->		Tuple:
             """simple docstring"""




             pass






      def  lowerCamelCase (      self		:  Any				)      ->		str:
             """simple docstring"""




             _lowerCamelCase :	Optional[int]						=self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*lowercase_				)






      @slow
      def  lowerCamelCase (      self		:  Optional[int]				)      ->		Any:
             """simple docstring"""




             for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _lowerCamelCase :	Optional[int]						=ResNetModel.from_pretrained(lowercase_				)
                    self.assertIsNotNone(lowercase_				)




def 			a_   (					):
       '''simple docstring'''





       _lowerCamelCase :	Union[str, Any]						=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
       return image




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






      @cached_property
      def  lowerCamelCase (      self		:  Tuple				)      ->		Dict:
             """simple docstring"""




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






      @slow
      def  lowerCamelCase (      self		:  Union[str, Any]				)      ->		List[str]:
             """simple docstring"""




             _lowerCamelCase :	str						=ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(lowercase_				)

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

             # forward pass
             with torch.no_grad():
                    _lowerCamelCase :	List[str]						=model(**lowercase_				)

             # verify the logits
             _lowerCamelCase :	Any						=torch.Size((1, 1000)				)
             self.assertEqual(outputs.logits.shape    ,     lowercase_				)

             _lowerCamelCase :	Dict						=torch.tensor([-11.1069, -9.7877, -8.3777]				).to(lowercase_				)

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




@require_torch
class A						(     UpperCamelCase_					,							unittest.TestCase  ):
      UpperCamelCase__							:						int   =(ResNetBackbone,) if is_torch_available() else ()
      UpperCamelCase__							:						Dict   =False
      UpperCamelCase__							:						int   =ResNetConfig






      def  lowerCamelCase (      self		:  List[Any]				)      ->		List[str]:
             """simple docstring"""




             _lowerCamelCase :	Optional[Any]						=ResNetModelTester(self				)






from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_clip import CLIPTokenizer


lowerCamelCase		      = logging.get_logger(__name__)

lowerCamelCase		      = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

lowerCamelCase		      = {
    'vocab_file': {
        'openai/clip-vit-base-patch32': 'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/vocab.json',
    },
    'merges_file': {
        'openai/clip-vit-base-patch32': 'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/merges.txt',
    },
    'tokenizer_file': {
        'openai/clip-vit-base-patch32': (
            'https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/tokenizer.json'
        ),
    },
}

lowerCamelCase		      = {
    'openai/clip-vit-base-patch32': 77,
}




class A						(     UpperCamelCase_  ):
      UpperCamelCase__							:						Dict   =VOCAB_FILES_NAMES
      UpperCamelCase__							:						Optional[int]   =PRETRAINED_VOCAB_FILES_MAP
      UpperCamelCase__							:						Optional[int]   =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      UpperCamelCase__							:						Optional[Any]   =['input_ids', 'attention_mask']
      UpperCamelCase__							:						str   =CLIPTokenizer






      def __init__(      self		:  str    ,     lowercase_		:  Optional[Any]=None    ,     lowercase_		:  Optional[int]=None    ,     lowercase_		:  int=None    ,     lowercase_		:  Optional[int]="<|endoftext|>"    ,     lowercase_		:  Union[str, Any]="<|startoftext|>"    ,     lowercase_		:  Tuple="<|endoftext|>"    ,     lowercase_		:  int="<|endoftext|>"    ,     **lowercase_		:  Optional[Any]    ,     )      ->		Any:
             """simple docstring"""




             super().__init__(
                 lowercase_    ,     lowercase_    ,     tokenizer_file=lowercase_    ,     unk_token=lowercase_    ,     bos_token=lowercase_    ,     eos_token=lowercase_    ,     pad_token=lowercase_    ,     **lowercase_    ,     )

             if not isinstance(self.backend_tokenizer.pre_tokenizer    ,     pre_tokenizers.Sequence				):
                    raise ValueError(
                        'The `backend_tokenizer` provided does not match the expected format. The CLIP tokenizer has been'
                        ' heavily modified from transformers version 4.17.0. You need to convert the tokenizer you are using'
                        ' to be compatible with this version.The easiest way to do so is'
                        ' `CLIPTokenizerFast.from_pretrained("path_to_local_folder_or_hub_repo, from_slow=True)`. If you want'
                        ' to use your existing tokenizer, you will have to revert to a version prior to 4.17.0 of'
                        ' transformers.'				)

             self._wrap_decode_method_backend_tokenizer()






      def  lowerCamelCase (      self		:  Any				)      ->		Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase :	int						=self.backend_tokenizer.decode

             def new_decode_method(*lowercase_		:  List[str]    ,     **lowercase_		:  int				):
                    _lowerCamelCase :	Tuple						=orig_decode_method(*lowercase_    ,     **lowercase_				)
                    _lowerCamelCase :	Dict						=text.replace(self.backend_tokenizer.model.end_of_word_suffix    ,     ' '				).strip()
                    return text

             _lowerCamelCase :	List[Any]						=new_decode_method






      def  lowerCamelCase (      self		:  Dict    ,     lowercase_		:  List[int]    ,     lowercase_		:  Optional[List[int]] = None				)      ->		List[int]:
             """simple docstring"""




             _lowerCamelCase :	Union[str, Any]						=[self.bos_token_id]
             _lowerCamelCase :	str						=[self.eos_token_id]

             if token_ids_a is None:
                    return bos_token + token_ids_a + eos_token
             return bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token






      def  lowerCamelCase (      self		:  Any    ,     lowercase_		:  List[int]    ,     lowercase_		:  Optional[List[int]] = None				)      ->		List[int]:
             """simple docstring"""




             _lowerCamelCase :	int						=[self.bos_token_id]
             _lowerCamelCase :	Any						=[self.eos_token_id]

             if token_ids_a is None:
                    return len(bos_token + token_ids_a + eos_token				) * [0]
             return len(bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token				) * [0]






      def  lowerCamelCase (      self		:  str    ,     lowercase_		:  str    ,     lowercase_		:  Optional[str] = None				)      ->		Tuple[str]:
             """simple docstring"""




             _lowerCamelCase :	str						=self._tokenizer.model.save(lowercase_    ,     name=lowercase_				)
             return tuple(lowercase_				)


