




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






       def __init__(   self:					Optional[int]       ,					_lowerCAmelCase:					int       ,					_lowerCAmelCase:					str=3       ,					_lowerCAmelCase:					Optional[int]=32       ,					_lowerCAmelCase:					int=3       ,					_lowerCAmelCase:					Dict=10       ,					_lowerCAmelCase:					Optional[int]=[10, 20, 30, 40]       ,					_lowerCAmelCase:					Tuple=[1, 1, 2, 1]       ,					_lowerCAmelCase:					List[Any]=True       ,					_lowerCAmelCase:					str=True       ,					_lowerCAmelCase:					Union[str, Any]="relu"       ,					_lowerCAmelCase:					Tuple=3       ,					_lowerCAmelCase:					Union[str, Any]=None       ,					):
         lowercase    :List[Any]      	=						parent
         lowercase    :List[str]      	=						batch_size
         lowercase    :Any      	=						image_size
         lowercase    :Optional[int]      	=						num_channels
         lowercase    :Optional[Any]      	=						embeddings_size
         lowercase    :Any      	=						hidden_sizes
         lowercase    :Dict      	=						depths
         lowercase    :Union[str, Any]      	=						is_training
         lowercase    :Dict      	=						use_labels
         lowercase    :List[Any]      	=						hidden_act
         lowercase    :str      	=						num_labels
         lowercase    :Tuple      	=						scope
         lowercase    :Union[str, Any]      	=						len(_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):
         lowercase    :str      	=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

         lowercase    :Any      	=						None
         if self.use_labels:
           lowercase    :Any      	=						ids_tensor([self.batch_size]       ,					self.num_labels				)

         lowercase    :str      	=						self.get_config()

         return config, pixel_values, labels






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






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         lowercase    :Optional[int]      	=						self.prepare_config_and_inputs()
         lowercase	,    lowercase	,    lowercase    :Optional[int]      	=						config_and_inputs
         lowercase    :Tuple      	=						{"pixel_values": pixel_values}
         return config, inputs_dict







@require_torch
class    __lowerCAmelCase       (							lowerCAmelCase      , lowerCAmelCase      , unittest.TestCase):
       _a 					=						(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
       _a 					=						(
           {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
           if is_torch_available()
           else {}
       )

       _a 					=						False
       _a 					=						False
       _a 					=						False
       _a 					=						False






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         lowercase    :Union[str, Any]      	=						RegNetModelTester(self				)
         lowercase    :Union[str, Any]      	=						ConfigTester(self       ,					config_class=_lowerCAmelCase       ,					has_text_modality=_lowerCAmelCase				)






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






       @unittest.skip(reason="RegNet does not use inputs_embeds"				)
       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]				):
         pass






       @unittest.skip(reason="RegNet does not support input and output embeddings"				)
       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]				):
         pass






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase	,    lowercase    :Dict      	=						self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           lowercase    :str      	=						model_class(_lowerCAmelCase				)
           lowercase    :Dict      	=						inspect.signature(model.forward				)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           lowercase    :Dict      	=						[*signature.parameters.keys()]

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






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :List[str]      	=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase	,    lowercase    :List[Any]      	=						self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           lowercase    :int      	=						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 					SCREAMING_SNAKE_CASE    (   self:					int				):
         def check_hidden_states_output(_lowerCAmelCase:					Optional[Any]       ,					_lowerCAmelCase:					Optional[int]       ,					_lowerCAmelCase:					Optional[Any]				):
           lowercase    :str      	=						model_class(_lowerCAmelCase				)
           model.to(_lowerCAmelCase				)
           model.eval()

           with torch.no_grad():
             lowercase    :str      	=						model(**self._prepare_for_class(_lowerCAmelCase       ,					_lowerCAmelCase				)				)

           lowercase    :Optional[int]      	=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           lowercase    :Dict      	=						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]       ,					)

         lowercase	,    lowercase    :Tuple      	=						self.model_tester.prepare_config_and_inputs_for_common()
         lowercase    :str      	=						["basic", "bottleneck"]
         for model_class in self.all_model_classes:
           for layer_type in layers_type:
             lowercase    :Optional[Any]      	=						layer_type
             lowercase    :Union[str, Any]      	=						True
             check_hidden_states_output(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)

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

             check_hidden_states_output(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :List[str]      	=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase				)






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase    :Any      	=						RegNetModel.from_pretrained(_lowerCAmelCase				)
           self.assertIsNotNone(_lowerCAmelCase				)







def       UpperCAmelCase__  (     ):
  lowercase    :Optional[Any]      	=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
  return image







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






       @cached_property
       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         return (
             AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				)
             if is_vision_available()
             else None
         )






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :List[str]      	=						RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(_lowerCAmelCase				)

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

         # forward pass
         with torch.no_grad():
           lowercase    :Tuple      	=						model(**_lowerCAmelCase				)

         # verify the logits
         lowercase    :Any      	=						torch.Size((1, 10_00)				)
         self.assertEqual(outputs.logits.shape       ,					_lowerCAmelCase				)

         lowercase    :int      	=						torch.tensor([-0.41_80, -1.50_51, -3.48_36]				).to(_lowerCAmelCase				)

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









from collections.abc import Generator
from math import sin



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if len(lowerCamelCase   ) != 32:
    raise ValueError("Input must be of length 32"   )

  lowercase    :Any      	=						B""
  for i in [3, 2, 1, 0]:
    little_endian += string_aa[8 * i : 8 * i + 8]
  return little_endian



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if i < 0:
    raise ValueError("Input must be non-negative"   )

  lowercase    :List[Any]      	=						format(lowerCamelCase,			"08x"   )[-8:]
  lowercase    :Tuple      	=						B""
  for i in [3, 2, 1, 0]:
    little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8"   )
  return little_endian_hex



def       UpperCAmelCase__  (     lowerCamelCase   ):
  lowercase    :Union[str, Any]      	=						B""
  for char in message:
    bit_string += format(lowerCamelCase,			"08b"   ).encode("utf-8"   )
  lowercase    :str      	=						format(len(lowerCamelCase   ),			"064b"   ).encode("utf-8"   )

  # Pad bit_string to a multiple of 512 chars
  bit_string += b"1"
  while len(lowerCamelCase   ) % 512 != 448:
    bit_string += b"0"
  bit_string += to_little_endian(start_len[32:]   ) + to_little_endian(start_len[:32]   )

  return bit_string



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if len(lowerCamelCase   ) % 512 != 0:
    raise ValueError("Input must have length that's a multiple of 512"   )

  for pos in range(0,			len(lowerCamelCase   ),			512   ):
    lowercase    :List[str]      	=						bit_string[pos : pos + 512]
    lowercase    :int      	=						[]
    for i in range(0,			512,			32   ):
      block_words.append(int(to_little_endian(block[i : i + 32]   ),			2   )   )
    yield block_words



def       UpperCAmelCase__  (     lowerCamelCase   ):
  if i < 0:
    raise ValueError("Input must be non-negative"   )

  lowercase    :List[str]      	=						format(lowerCamelCase,			"032b"   )
  lowercase    :Optional[Any]      	=						""
  for c in i_str:
    new_str += "1" if c == "0" else "0"
  return int(lowerCamelCase,			2   )



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  return (a + b) % 2**32



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  if i < 0:
    raise ValueError("Input must be non-negative"   )
  if shift < 0:
    raise ValueError("Shift must be non-negative"   )
  return ((i << shift) ^ (i >> (32 - shift))) % 2**32



def       UpperCAmelCase__  (     lowerCamelCase   ):
  lowercase    :Tuple      	=						preprocess(lowerCamelCase   )

  lowercase    :Tuple      	=						[int(2**32 * abs(sin(i + 1   )   )   ) for i in range(64   )]

  # Starting states
  lowercase    :Optional[Any]      	=						0X6745_2301
  lowercase    :Union[str, Any]      	=						0XEFCD_AB89
  lowercase    :Optional[int]      	=						0X98BA_DCFE
  lowercase    :str      	=						0X1032_5476

  lowercase    :str      	=						[
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
  ]

  # Process bit string in chunks, each with 16 32-char words
  for block_words in get_block_words(lowerCamelCase   ):
    lowercase    :str      	=						aa
    lowercase    :int      	=						ba
    lowercase    :int      	=						ca
    lowercase    :List[str]      	=						da

    # Hash current chunk
    for i in range(64   ):
      if i <= 15:
        # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
        lowercase    :Optional[int]      	=						d ^ (b & (c ^ d))
        lowercase    :Optional[Any]      	=						i
      elif i <= 31:
        # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
        lowercase    :Any      	=						c ^ (d & (b ^ c))
        lowercase    :Union[str, Any]      	=						(5 * i + 1) % 16
      elif i <= 47:
        lowercase    :Any      	=						b ^ c ^ d
        lowercase    :List[Any]      	=						(3 * i + 5) % 16
      else:
        lowercase    :List[Any]      	=						c ^ (b | not_aa(lowerCamelCase   ))
        lowercase    :Any      	=						(7 * i) % 16
      lowercase    :Dict      	=						(f + a + added_consts[i] + block_words[g]) % 2**32
      lowercase    :Any      	=						d
      lowercase    :str      	=						c
      lowercase    :Union[str, Any]      	=						b
      lowercase    :Union[str, Any]      	=						sum_aa(lowerCamelCase,			left_rotate_aa(lowerCamelCase,			shift_amounts[i]   )   )

    # Add hashed chunk to running total
    lowercase    :Optional[Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :List[Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :List[str]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )
    lowercase    :Union[str, Any]      	=						sum_aa(lowerCamelCase,			lowerCamelCase   )

  lowercase    :int      	=						reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   ) + reformat_hex(lowerCamelCase   )
  return digest


if __name__ == "__main__":
     import doctest

     doctest.testmod()



