






'''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   ,   _A   ,   _A=3   ,   _A=32   ,   _A=3   ,   _A=10   ,   _A=[10, 20, 30, 40]   ,   _A=[1, 1, 2, 1]   ,   _A=True   ,   _A=True   ,   _A="relu"   ,   _A=3   ,   _A=None   ,   _A=["stage2", "stage3", "stage4"]   ,   _A=[2, 3, 4]   ,   )    ->   Tuple:
    __a    :	List[str]									=						parent
    __a    :	int									=						batch_size
    __a    :	Optional[int]									=						image_size
    __a    :	Union[str, Any]									=						num_channels
    __a    :	Any									=						embeddings_size
    __a    :	Any									=						hidden_sizes
    __a    :	str									=						depths
    __a    :	str									=						is_training
    __a    :	Tuple									=						use_labels
    __a    :	List[Any]									=						hidden_act
    __a    :	Tuple									=						num_labels
    __a    :	Union[str, Any]									=						scope
    __a    :	str									=						len(_A			)
    __a    :	List[Any]									=						out_features
    __a    :	str									=						out_indices



   def    __magic_name__    ( self			)    ->   List[Any]:
    __a    :	Tuple									=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

    __a    :	Optional[int]									=						None
    if self.use_labels:
     __a    :	Union[str, Any]									=						ids_tensor([self.batch_size]   ,   self.num_labels			)

    __a    :	Any									=						self.get_config()

    return config, pixel_values, labels



   def    __magic_name__    ( self			)    ->   Optional[Any]:
    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    __magic_name__    ( self   ,   _A   ,   _A   ,   _A			)    ->   str:
    __a    :	Optional[int]									=						ResNetModel(config=_A			)
    model.to(_A			)
    model.eval()
    __a    :	List[str]									=						model(_A			)
    # 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    __magic_name__    ( self   ,   _A   ,   _A   ,   _A			)    ->   List[Any]:
    __a    :	Optional[int]									=						self.num_labels
    __a    :	Optional[int]									=						ResNetForImageClassification(_A			)
    model.to(_A			)
    model.eval()
    __a    :	Tuple									=						model(_A   ,   labels=_A			)
    self.parent.assertEqual(result.logits.shape   ,   (self.batch_size, self.num_labels)			)



   def    __magic_name__    ( self   ,   _A   ,   _A   ,   _A			)    ->   int:
    __a    :	str									=						ResNetBackbone(config=_A			)
    model.to(_A			)
    model.eval()
    __a    :	List[str]									=						model(_A			)

    # 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    :	Tuple									=						None
    __a    :	Union[str, Any]									=						ResNetBackbone(config=_A			)
    model.to(_A			)
    model.eval()
    __a    :	str									=						model(_A			)

    # 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    __magic_name__    ( self			)    ->   Dict:
    __a    :	Union[str, Any]									=						self.prepare_config_and_inputs()
    __a			,    __a			,    __a    :	List[Any]									=						config_and_inputs
    __a    :	Union[str, Any]									=						{'pixel_values': pixel_values}
    return config, inputs_dict




@require_torch
class 							lowerCAmelCase					(							lowerCamelCase__							,      lowerCamelCase__							,      unittest.TestCase   ):







   """simple docstring"""







   _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    __magic_name__    ( self			)    ->   List[str]:
    __a    :	Dict									=						ResNetModelTester(self			)
    __a    :	List[str]									=						ConfigTester(self   ,   config_class=_A   ,   has_text_modality=_A			)



   def    __magic_name__    ( 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    __magic_name__    ( self			)    ->   str:
    return



   @unittest.skip(reason='ResNet does not use inputs_embeds'			)
   def    __magic_name__    ( self			)    ->   str:
    pass



   @unittest.skip(reason='ResNet does not support input and output embeddings'			)
   def    __magic_name__    ( self			)    ->   str:
    pass



   def    __magic_name__    ( self			)    ->   Any:
    __a			,    __a    :	Tuple									=						self.model_tester.prepare_config_and_inputs_for_common()

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

     __a    :	Union[str, Any]									=						['pixel_values']
     self.assertListEqual(arg_names[:1]   ,   _A			)



   def    __magic_name__    ( self			)    ->   List[str]:
    __a    :	Any									=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*_A			)



   def    __magic_name__    ( self			)    ->   str:
    __a    :	Optional[int]									=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_backbone(*_A			)



   def    __magic_name__    ( self			)    ->   int:
    __a			,    __a    :	List[Any]									=						self.model_tester.prepare_config_and_inputs_for_common()

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

     with torch.no_grad():
      __a    :	List[str]									=						model(**self._prepare_for_class(_A   ,   _A			)			)

     __a    :	Union[str, Any]									=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     __a    :	Tuple									=						self.model_tester.num_stages
     self.assertEqual(len(_A			)   ,   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    :	Optional[Any]									=						self.model_tester.prepare_config_and_inputs_for_common()
    __a    :	Tuple									=						['basic', 'bottleneck']
    for model_class in self.all_model_classes:
     for layer_type in layers_type:
      __a    :	List[Any]									=						layer_type
      __a    :	int									=						True
      check_hidden_states_output(_A   ,   _A   ,   _A			)

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

      check_hidden_states_output(_A   ,   _A   ,   _A			)



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



   def    __magic_name__    ( self			)    ->   int:
    __a    :	Optional[int]									=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*_A			)



   @slow
   def    __magic_name__    ( self			)    ->   Union[str, Any]:
    for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a    :	str									=						ResNetModel.from_pretrained(_A			)
     self.assertIsNotNone(_A			)






def   lowerCAmelCase__			(					):
 __a    :	List[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    __magic_name__    ( self			)    ->   Dict:
    return (
        AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)
        if is_vision_available()
        else None
    )



   @slow
   def    __magic_name__    ( self			)    ->   List[Any]:
    __a    :	Dict									=						ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			).to(_A			)

    __a    :	Optional[int]									=						self.default_image_processor
    __a    :	Dict									=						prepare_img()
    __a    :	List[Any]									=						image_processor(images=_A   ,   return_tensors='pt'			).to(_A			)

    # forward pass
    with torch.no_grad():
     __a    :	Union[str, Any]									=						model(**_A			)

    # verify the logits
    __a    :	Optional[int]									=						torch.Size((1, 1000)			)
    self.assertEqual(outputs.logits.shape   ,   _A			)

    __a    :	str									=						torch.tensor([-11.1_069, -9.7_877, -8.3_777]			).to(_A			)

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




@require_torch
class 							lowerCAmelCase					(							lowerCamelCase__							,      unittest.TestCase   ):







   """simple docstring"""







   _A						=   (ResNetBackbone,) if is_torch_available() else ()
   _A						=   False
   _A						=   ResNetConfig



   def    __magic_name__    ( self			)    ->   List[Any]:
    __a    :	int									=						ResNetModelTester(self			)












'''simple docstring'''


import math
from timeit import timeit






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__		):
 __a    :	Any									=						0
 __a    :	List[Any]									=						abs(SCREAMING_SNAKE_CASE__		)
 while True:
  __a    :	int									=						n // 10
  digits += 1
  if n == 0:
   break
 return digits






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__		):
 return 1 if n == 0 else math.floor(math.log(abs(SCREAMING_SNAKE_CASE__		)       ,		10		) + 1		)






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__		):
 return len(str(abs(SCREAMING_SNAKE_CASE__		)		)		)






def   lowerCAmelCase__			(					):
 from collections.abc import Callable

 def benchmark_a_function(SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		) -> None:
  __a    :	Tuple									=						f'''{func.__name__}({value})'''
  __a    :	List[Any]									=						timeit(f'''__main__.{call}'''       ,		setup='import __main__'		)
  print(f'''{call}: {func(SCREAMING_SNAKE_CASE__		)} -- {timing} seconds'''		)

 for value in (262144, 1125899906842624, 1267650600228229401496703205376):
  for func in (num_digits, num_digits_fast, num_digits_faster):
   benchmark_a_function(SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		)
  print()


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  benchmark()




