





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





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





        """simple docstring"""




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





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




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

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

        lowercase_    :Any					    =				self.get_config()

        return config, pixel_values, labels





     def 							lowercase__   (				self	:      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	:      int			,   lowercase	:      Any			,   lowercase	:      int			,   lowercase	:      str		):





        """simple docstring"""




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





        """simple docstring"""




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





     def 							lowercase__   (				self	:      Any			,   lowercase	:      List[str]			,   lowercase	:      Dict			,   lowercase	:      str		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				ResNetBackbone(config=lowercase		)
        model.to(lowercase		)
        model.eval()
        lowercase_    :List[str]					    =				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
        lowercase_    :str					    =				None
        lowercase_    :List[str]					    =				ResNetBackbone(config=lowercase		)
        model.to(lowercase		)
        model.eval()
        lowercase_    :Union[str, Any]					    =				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	:      Optional[int]		):





        """simple docstring"""




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







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

     __A  				=    True
     __A  				=    False
     __A  				=    False
     __A  				=    False
     __A  				=    False





     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




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





     def 							lowercase__   (				self	:      Dict		):





        """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]		):





        """simple docstring"""




        return





     @unittest.skip(reason="ResNet does not use inputs_embeds"		)
     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        pass





     @unittest.skip(reason="ResNet does not support input and output embeddings"		)
     def 							lowercase__   (				self	:      Union[str, Any]		):





        """simple docstring"""




        pass





     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    ,							lowercase_    :int					    =				self.model_tester.prepare_config_and_inputs_for_common()

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

           lowercase_    :str					    =				["pixel_values"]
           self.assertListEqual(arg_names[:1]			,   lowercase		)





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        lowercase_    :Tuple					    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowercase		)





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :str					    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*lowercase		)





     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




        lowercase_    ,							lowercase_    :Tuple					    =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           lowercase_    :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 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        def check_hidden_states_output(lowercase	:      Any			,   lowercase	:      Any			,   lowercase	:      Tuple		):
           lowercase_    :Tuple					    =				model_class(lowercase		)
           model.to(lowercase		)
           model.eval()

           with torch.no_grad():
              lowercase_    :Any					    =				model(**self._prepare_for_class(lowercase			,   lowercase		)		)

           lowercase_    :List[str]					    =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

        lowercase_    ,							lowercase_    :Dict					    =				self.model_tester.prepare_config_and_inputs_for_common()
        lowercase_    :Optional[int]					    =				["basic", "bottleneck"]
        for model_class in self.all_model_classes:
           for layer_type in layers_type:
              lowercase_    :List[Any]					    =				layer_type
              lowercase_    :Any					    =				True
              check_hidden_states_output(lowercase			,   lowercase			,   lowercase		)

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

              check_hidden_states_output(lowercase			,   lowercase			,   lowercase		)





     @unittest.skip(reason="ResNet does not use feedforward chunking"		)
     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        pass





     def 							lowercase__   (				self	:      Any		):





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowercase		)







     @slow
     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase_    :List[Any]					    =				ResNetModel.from_pretrained(lowercase		)
           self.assertIsNotNone(lowercase		)







def 							UpperCAmelCase_						(		):
   lowercase_    :Dict					    =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
   return image
@require_torch
@require_vision
class    a_     (       unittest.TestCase							):





     @cached_property
     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




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







     @slow
     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    :Dict					    =				ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(lowercase		)

        lowercase_    :str					    =				self.default_image_processor
        lowercase_    :Any					    =				prepare_img()
        lowercase_    :List[Any]					    =				image_processor(images=lowercase			,   return_tensors="pt"		).to(lowercase		)

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

        # verify the logits
        lowercase_    :int					    =				torch.Size((1, 1_000)		)
        self.assertEqual(outputs.logits.shape			,   lowercase		)

        lowercase_    :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    a_     (       _lowerCAmelCase			,		unittest.TestCase							):
     __A  				=    (ResNetBackbone,) if is_torch_available() else ()
     __A  				=    False
     __A  				=    ResNetConfig





     def 							lowercase__   (				self	:      Optional[int]		):





        """simple docstring"""




        lowercase_    :int					    =				ResNetModelTester(self		)









'''simple docstring'''


import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Optional[int]			,__lowerCamelCase      :      Union[str, Any]			,__lowerCamelCase      :      List[Any]			,__lowerCamelCase      :      str=None				):
   lowercase_    :List[Any]					    =				None
   # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
   if str(weight.dtype				) == "torch.bfloat16":
      # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
      lowercase_    :int					    =				weight.view(torch.intaa				)
      lowercase_    :List[Any]					    =				"bfloat16"
   lowercase_    :Optional[Any]					    =				weight.cpu().numpy()
   lowercase_    :Optional[int]					    =				os.path.join(__lowerCamelCase			,F'{weight_name}.dat'				)
   if index is not None:
      if dtype is None:
         lowercase_    :str					    =				str(array.dtype				)
      lowercase_    :int					    =				{"dtype": dtype, "shape": list(array.shape				)}
   if array.ndim == 0:
      lowercase_    :int					    =				array[None]
   lowercase_    :List[Any]					    =				np.memmap(__lowerCamelCase			,dtype=array.dtype			,mode="w+"			,shape=array.shape				)
   lowercase_    :List[Any]					    =				array[:]
   file_array.flush()
   return index
def 							UpperCAmelCase_						(		__lowerCamelCase      :      int			,__lowerCamelCase      :      Dict				):
   lowercase_    :int					    =				tuple(weight_info["shape"]				)
   if shape == ():
      # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
      lowercase_    :List[str]					    =				(1,)

   lowercase_    :List[str]					    =				weight_info["dtype"]
   if dtype == "bfloat16":
      # NumPy does not support bfloat16 so this was saved as a int16
      lowercase_    :Optional[Any]					    =				"int16"

   lowercase_    :str					    =				np.memmap(__lowerCamelCase			,dtype=__lowerCamelCase			,shape=__lowerCamelCase			,mode="r"				)

   if len(weight_info["shape"]				) == 0:
      lowercase_    :Union[str, Any]					    =				weight[0]
   lowercase_    :str					    =				torch.tensor(__lowerCamelCase				)
   if weight_info["dtype"] == "bfloat16":
      lowercase_    :Any					    =				weight.view(torch.bfloataa				)

   return weight
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Dict			,__lowerCamelCase      :      List[str]				):
   if index is None or len(__lowerCamelCase				) == 0:
      # Nothing to save
      return

   lowercase_    :List[Any]					    =				os.path.join(__lowerCamelCase			,"index.json"				)
   if os.path.isfile(__lowerCamelCase				):
      with open(__lowerCamelCase			,"r"			,encoding="utf-8"				) as f:
         lowercase_    :Any					    =				json.load(__lowerCamelCase				)
   else:
      lowercase_    :Union[str, Any]					    =				{}
   current_index.update(__lowerCamelCase				)

   with open(__lowerCamelCase			,"w"			,encoding="utf-8"				) as f:
      json.dump(__lowerCamelCase			,__lowerCamelCase			,indent=2				)
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Union[str, os.PathLike]			,__lowerCamelCase      :      Dict[str, torch.Tensor]				):
   os.makedirs(__lowerCamelCase			,exist_ok=__lowerCamelCase				)
   lowercase_    :List[Any]					    =				{}
   for name, parameter in state_dict.items():
      lowercase_    :Tuple					    =				offload_weight(__lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			,index=__lowerCamelCase				)

   # Update index
   save_offload_index(__lowerCamelCase			,__lowerCamelCase				)
class    a_     (       _lowerCAmelCase							):





     def __init__(				self	:      int			,   lowercase	:      Mapping			,   lowercase	:      str		):





        """simple docstring"""




        lowercase_    :Union[str, Any]					    =				dataset
        lowercase_    :List[str]					    =				prefix





     def __getitem__(				self	:      Any			,   lowercase	:      List[str]		):





        """simple docstring"""




        return self.dataset[F'{self.prefix}{key}']





     def __iter__(				self	:      Optional[int]		):





        """simple docstring"""




        return iter([key for key in self.dataset if key.startswith(self.prefix		)]		)







     def __len__(				self	:      Any		):





        """simple docstring"""




        return len(self.dataset		)







class    a_     (       _lowerCAmelCase							):





     def __init__(				self	:      Tuple			,   lowercase	:      Dict[str, torch.Tensor] = None			,   lowercase	:      Optional[Union[str, os.PathLike]] = None			,   lowercase	:      Mapping = None			,   lowercase	:      Optional[Any]=None			,   ):





        """simple docstring"""




        if state_dict is None and save_folder is None:
           raise ValueError("Need either a `state_dict` or a `save_folder` containing offloaded weights."		)

        lowercase_    :Optional[int]					    =				{} if state_dict is None else state_dict
        lowercase_    :str					    =				save_folder
        if index is None and save_folder is not None:
           with open(os.path.join(lowercase			,   "index.json"		)		) as f:
              lowercase_    :Any					    =				json.load(lowercase		)
        lowercase_    :str					    =				{} if index is None else index
        lowercase_    :List[str]					    =				list(self.state_dict.keys()		)
        self.all_keys.extend([key for key in self.index if key not in self.all_keys]		)
        lowercase_    :List[Any]					    =				device





     def __getitem__(				self	:      Any			,   lowercase	:      str		):





        """simple docstring"""




        if key in self.state_dict:
           return self.state_dict[key]
        lowercase_    :int					    =				self.index[key]
        if weight_info.get("safetensors_file"		) is not None:
           if not is_safetensors_available():
              raise ImportError("These offloaded weights require the use of safetensors: `pip install safetensors`."		)

           from safetensors import safe_open

           lowercase_    :Dict					    =				"cpu" if self.device is None else self.device
           with safe_open(weight_info["safetensors_file"]			,   framework="pt"			,   device=lowercase		) as f:
              lowercase_    :Tuple					    =				f.get_tensor(weight_info.get("weight_name"			,   lowercase		)		)

           if "dtype" in weight_info:
              return tensor.to(getattr(lowercase			,   weight_info["dtype"]		)		)
           else:
              return tensor

        lowercase_    :str					    =				os.path.join(self.save_folder			,   F'{key}.dat'		)
        return load_offloaded_weight(lowercase			,   lowercase		)





     def __iter__(				self	:      Optional[int]		):





        """simple docstring"""




        return iter(self.all_keys		)







     def __len__(				self	:      Tuple		):





        """simple docstring"""




        return len(self.all_keys		)







def 							UpperCAmelCase_						(		__lowerCamelCase      :      Dict[str, torch.Tensor]			,__lowerCamelCase      :      List[str]				):
   lowercase_    :List[str]					    =				{}
   for module_name in submodule_names:
      # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
      # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
      result.update(
          {
              key: param
              for key, param in state_dict.items()
              if key == module_name or key.startswith(module_name + "."				)
          }				)
   return result


