code: 
  
  
  """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 __snake_case		:
  
  
  
  
  
  
  
     """simple docstring"""
  
  
  
  
     def __init__(		self							:str				,  UpperCamelCase__							:Dict				,  UpperCamelCase__							:Optional[Any]=3				,  UpperCamelCase__							:int=32				,  UpperCamelCase__							:str=3				,  UpperCamelCase__							:str=10				,  UpperCamelCase__							:Optional[int]=[10, 20, 30, 40]				,  UpperCamelCase__							:Optional[int]=[1, 1, 2, 1]				,  UpperCamelCase__							:str=True				,  UpperCamelCase__							:Any=True				,  UpperCamelCase__							:int="relu"				,  UpperCamelCase__							:Union[str, Any]=3				,  UpperCamelCase__							:Tuple=None				,  UpperCamelCase__							:int=["stage2", "stage3", "stage4"]				,  UpperCamelCase__							:List[str]=[2, 3, 4]				,  ):
            _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(UpperCamelCase__       )
            _a          =				out_features
            _a          =				out_indices
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:Tuple       ):
            _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 SCREAMING_SNAKE_CASE_      (		self							:Optional[int]       ):
            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 SCREAMING_SNAKE_CASE_      (		self							:Optional[int]				,  UpperCamelCase__							:Union[str, Any]				,  UpperCamelCase__							:Dict				,  UpperCamelCase__							:Any       ):
            _a          =				ResNetModel(config=UpperCamelCase__       )
            model.to(UpperCamelCase__       )
            model.eval()
            _a          =				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 SCREAMING_SNAKE_CASE_      (		self							:Optional[Any]				,  UpperCamelCase__							:str				,  UpperCamelCase__							:Any				,  UpperCamelCase__							:Any       ):
            _a          =				self.num_labels
            _a          =				ResNetForImageClassification(UpperCamelCase__       )
            model.to(UpperCamelCase__       )
            model.eval()
            _a          =				model(UpperCamelCase__				,  labels=UpperCamelCase__       )
            self.parent.assertEqual(result.logits.shape				,  (self.batch_size, self.num_labels)       )
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:Any				,  UpperCamelCase__							:List[str]				,  UpperCamelCase__							:Any				,  UpperCamelCase__							:str       ):
            _a          =				ResNetBackbone(config=UpperCamelCase__       )
            model.to(UpperCamelCase__       )
            model.eval()
            _a          =				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
            _a          =				None
            _a          =				ResNetBackbone(config=UpperCamelCase__       )
            model.to(UpperCamelCase__       )
            model.eval()
            _a          =				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 SCREAMING_SNAKE_CASE_      (		self							:int       ):
            _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"""
  
  
  
  
     lowerCAmelCase_				:   Dict     	=			(
         (
             ResNetModel,
             ResNetForImageClassification,
             ResNetBackbone,
         )
         if is_torch_available()
         else ()
     )
     lowerCAmelCase_				:   List[str]     	=			(
         {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
         if is_torch_available()
         else {}
     )
  
     lowerCAmelCase_				:   Tuple     	=			True
     lowerCAmelCase_				:   List[str]     	=			False
     lowerCAmelCase_				:   Optional[int]     	=			False
     lowerCAmelCase_				:   Tuple     	=			False
     lowerCAmelCase_				:   Tuple     	=			False
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:List[str]       ):
            _a          =				ResNetModelTester(self       )
            _a          =				ConfigTester(self				,  config_class=UpperCamelCase__				,  has_text_modality=UpperCamelCase__       )
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:Union[str, 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 SCREAMING_SNAKE_CASE_      (		self							:Tuple       ):
            return
  
  
  
  
     @unittest.skip(reason="ResNet does not use inputs_embeds"       )
     def SCREAMING_SNAKE_CASE_      (		self							:Optional[Any]       ):
            pass
  
  
  
  
     @unittest.skip(reason="ResNet does not support input and output embeddings"       )
     def SCREAMING_SNAKE_CASE_      (		self							:Optional[int]       ):
            pass
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:str       ):
            _a   , _a          =				self.model_tester.prepare_config_and_inputs_for_common()
  
            for model_class in self.all_model_classes:
                   _a          =				model_class(UpperCamelCase__       )
                   _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]				,  UpperCamelCase__       )
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:Optional[int]       ):
            _a          =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*UpperCamelCase__       )
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:Dict       ):
            _a          =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_backbone(*UpperCamelCase__       )
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:Optional[Any]       ):
            _a   , _a          =				self.model_tester.prepare_config_and_inputs_for_common()
  
            for model_class in self.all_model_classes:
                   _a          =				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 SCREAMING_SNAKE_CASE_      (		self							:Any       ):
            def check_hidden_states_output(UpperCamelCase__							:int				,  UpperCamelCase__							:Tuple				,  UpperCamelCase__							:int       ):
                   _a          =				model_class(UpperCamelCase__       )
                   model.to(UpperCamelCase__       )
                   model.eval()
  
                   with torch.no_grad():
                          _a          =				model(**self._prepare_for_class(UpperCamelCase__				,  UpperCamelCase__       )       )
  
                   _a          =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
  
                   _a          =				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]				,  )
  
            _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(UpperCamelCase__				,  UpperCamelCase__				,  UpperCamelCase__       )
  
                          # check that output_hidden_states also work using config
                          del inputs_dict["output_hidden_states"]
                          _a          =				True
  
                          check_hidden_states_output(UpperCamelCase__				,  UpperCamelCase__				,  UpperCamelCase__       )
  
  
  
  
     @unittest.skip(reason="ResNet does not use feedforward chunking"       )
     def SCREAMING_SNAKE_CASE_      (		self							:Dict       ):
            pass
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:Any       ):
            _a          =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__       )
  
  
  
  
     @slow
     def SCREAMING_SNAKE_CASE_      (		self							:Optional[int]       ):
            for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _a          =				ResNetModel.from_pretrained(UpperCamelCase__       )
                   self.assertIsNotNone(UpperCamelCase__       )
  
  
  
  
  
  
  def 						__a			(  ):
  
  
  
  
  
         """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 SCREAMING_SNAKE_CASE_      (		self							:Union[str, Any]       ):
            return (
                AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
                if is_vision_available()
                else None
            )
  
  
  
  
     @slow
     def SCREAMING_SNAKE_CASE_      (		self							:int       ):
            _a          =				ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(UpperCamelCase__       )
  
            _a          =				self.default_image_processor
            _a          =				prepare_img()
            _a          =				image_processor(images=UpperCamelCase__				,  return_tensors="pt"       ).to(UpperCamelCase__       )
  
            # forward pass
            with torch.no_grad():
                   _a          =				model(**UpperCamelCase__       )
  
            # verify the logits
            _a          =				torch.Size((1, 1_000)       )
            self.assertEqual(outputs.logits.shape				,  UpperCamelCase__       )
  
            _a          =				torch.tensor([-11.1069, -9.7877, -8.3777]       ).to(UpperCamelCase__       )
  
            self.assertTrue(torch.allclose(outputs.logits[0, :3]				,  UpperCamelCase__				,  atol=1E-4       )       )
  
  
  
  
  
  
  @require_torch
  class __snake_case		(					UpperCAmelCase_				,       unittest.TestCase      ):
  
  
  
  
  
  
  
     """simple docstring"""
  
  
  
  
     lowerCAmelCase_				:   Optional[Any]     	=			(ResNetBackbone,) if is_torch_available() else ()
     lowerCAmelCase_				:   int     	=			False
     lowerCAmelCase_				:   Dict     	=			ResNetConfig
  
  
  
  
     def SCREAMING_SNAKE_CASE_      (		self							:List[str]       ):
            _a          =				ResNetModelTester(self       )
  
style_context: 
  
  
  """simple docstring"""
  
  
  
  
  from __future__ import annotations
  
  __SCREAMING_SNAKE_CASE					=						[2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7]
  
  
  
  
  
  class __snake_case		:
  
  
  
  
  
  
  
     """simple docstring"""
  
  
  
  
     def __init__(		self							:Optional[Any]				,  UpperCamelCase__							:int       ):
            _a          =				-1
            _a          =				-1
            _a          =				[-1] * length
            _a          =				None
            _a          =				None
  
  
  
  
     def __repr__(		self							:Optional[Any]       ):
            return f'Node(min_value={self.minn} max_value={self.maxx})'
  
  
  
  
  
  
  def 						__a      (  a					):
  
  
  
  
  
         """simple docstring"""
  
  
  
  
  
  
  
         _a          =				Node(len(a					)					)
         _a   , _a          =				min(a					), max(a					)
         # Leaf node case where the node contains only one unique value
         if root.minn == root.maxx:
                return root
         _a          =				(root.minn + root.maxx) // 2
  
         _a          =				[]
         _a          =				[]
  
         for index, num in enumerate(a					):
                if num <= pivot:
                       left_arr.append(a					)
                else:
                       right_arr.append(a					)
                _a          =				len(a					)
         _a          =				build_tree(a					)
         _a          =				build_tree(a					)
         return root
  
  
  
  def 						__a      (  a,		a,		a					):
  
  
  
  
  
         """simple docstring"""
  
  
  
  
  
  
  
         if index < 0 or node is None:
                return 0
         # Leaf node cases
         if node.minn == node.maxx:
                return index + 1 if node.minn == num else 0
         _a          =				(node.minn + node.maxx) // 2
         if num <= pivot:
                # go the left subtree and map index to the left subtree
                return rank_till_index(node.left,		a,		node.map_left[index] - 1					)
         else:
                # go to the right subtree and map index to the right subtree
                return rank_till_index(node.right,		a,		index - node.map_left[index]					)
  
  
  
  def 						__a      (  a,		a,		a,		a					):
  
  
  
  
  
         """simple docstring"""
  
  
  
  
  
  
  
         if start > end:
                return 0
         _a          =				rank_till_index(a,		a,		a					)
         _a          =				rank_till_index(a,		a,		start - 1					)
         return rank_till_end - rank_before_start
  
  
  
  def 						__a      (  a,		a,		a,		a					):
  
  
  
  
  
         """simple docstring"""
  
  
  
  
  
  
  
         if index > (end - start) or start > end or node is None:
                return -1
         # Leaf node case
         if node.minn == node.maxx:
                return node.minn
         # Number of elements in the left subtree in interval [start, end]
         _a          =				node.map_left[end] - (
             node.map_left[start - 1] if start else 0
         )
         if num_elements_in_left_tree > index:
                return quantile(
                    node.left,		a,		(node.map_left[start - 1] if start else 0),		node.map_left[end] - 1,		)
         else:
                return quantile(
                    node.right,		index - num_elements_in_left_tree,		start - (node.map_left[start - 1] if start else 0),		end - node.map_left[end],		)
  
  
  
  def 						__a      (  a,		a,		a,		a,		a					):
  
  
  
  
  
         """simple docstring"""
  
  
  
  
  
  
  
         if (
             start > end
             or node is None
             or start_num > end_num
             or node.minn > end_num
             or node.maxx < start_num
         ):
                return 0
         if start_num <= node.minn and node.maxx <= end_num:
                return end - start + 1
         _a          =				range_counting(
             node.left,		(node.map_left[start - 1] if start else 0),		node.map_left[end] - 1,		a,		a,		)
         _a          =				range_counting(
             node.right,		start - (node.map_left[start - 1] if start else 0),		end - node.map_left[end],		a,		a,		)
         return left + right
  
  
  if __name__ == "__main__":
     import doctest
  
     doctest.testmod()
  