

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




 def __init__(			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase=3  ,  _UpperCAmelCase=32  ,  _UpperCAmelCase=3  ,  _UpperCAmelCase=10  ,  _UpperCAmelCase=[10, 20, 30, 40]  ,  _UpperCAmelCase=[1, 1, 2, 1]  ,  _UpperCAmelCase=True  ,  _UpperCAmelCase=True  ,  _UpperCAmelCase="relu"  ,  _UpperCAmelCase=3  ,  _UpperCAmelCase=None  ,  _UpperCAmelCase=["stage2", "stage3", "stage4"]  ,  _UpperCAmelCase=[2, 3, 4]  ,  ):
   __UpperCAmelCase	:  Any		=     parent
   __UpperCAmelCase	:  int		=     batch_size
   __UpperCAmelCase	:  List[str]		=     image_size
   __UpperCAmelCase	:  List[str]		=     num_channels
   __UpperCAmelCase	:  List[str]		=     embeddings_size
   __UpperCAmelCase	:  str		=     hidden_sizes
   __UpperCAmelCase	:  Dict		=     depths
   __UpperCAmelCase	:  Any		=     is_training
   __UpperCAmelCase	:  Dict		=     use_labels
   __UpperCAmelCase	:  Optional[Any]		=     hidden_act
   __UpperCAmelCase	:  Optional[Any]		=     num_labels
   __UpperCAmelCase	:  str		=     scope
   __UpperCAmelCase	:  Optional[int]		=     len(_UpperCAmelCase							)
   __UpperCAmelCase	:  List[Any]		=     out_features
   __UpperCAmelCase	:  Dict		=     out_indices




 def     a       (			self							):
   __UpperCAmelCase	:  Union[str, Any]		=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

   __UpperCAmelCase	:  Tuple		=     self.get_config()

   return config, pixel_values, labels




 def     a       (			self							):
   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     a       (			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase  ,  _UpperCAmelCase							):
   __UpperCAmelCase	:  int		=     ResNetModel(config=_UpperCAmelCase							)
   model.to(_UpperCAmelCase							)
   model.eval()
   __UpperCAmelCase	:  Tuple		=     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     a       (			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase  ,  _UpperCAmelCase							):
   __UpperCAmelCase	:  int		=     self.num_labels
   __UpperCAmelCase	:  int		=     ResNetForImageClassification(_UpperCAmelCase							)
   model.to(_UpperCAmelCase							)
   model.eval()
   __UpperCAmelCase	:  Any		=     model(_UpperCAmelCase  ,  labels=_UpperCAmelCase							)
   self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.num_labels)							)




 def     a       (			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase  ,  _UpperCAmelCase							):
   __UpperCAmelCase	:  Union[str, Any]		=     ResNetBackbone(config=_UpperCAmelCase							)
   model.to(_UpperCAmelCase							)
   model.eval()
   __UpperCAmelCase	:  Dict		=     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
   __UpperCAmelCase	:  int		=     None
   __UpperCAmelCase	:  str		=     ResNetBackbone(config=_UpperCAmelCase							)
   model.to(_UpperCAmelCase							)
   model.eval()
   __UpperCAmelCase	:  Dict		=     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     a       (			self							):
   __UpperCAmelCase	:  Optional[int]		=     self.prepare_config_and_inputs()
   __UpperCAmelCase,			__UpperCAmelCase,			__UpperCAmelCase	:  Any		=     config_and_inputs
   __UpperCAmelCase	:  int		=     {'pixel_values': pixel_values}
   return config, inputs_dict



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

 _lowerCAmelCase									=	True
 _lowerCAmelCase									=	False
 _lowerCAmelCase									=	False
 _lowerCAmelCase									=	False
 _lowerCAmelCase									=	False




 def     a       (			self							):
   __UpperCAmelCase	:  List[Any]		=     ResNetModelTester(self							)
   __UpperCAmelCase	:  List[Any]		=     ConfigTester(self  ,  config_class=_UpperCAmelCase  ,  has_text_modality=_UpperCAmelCase							)




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




 @unittest.skip(reason='ResNet does not use inputs_embeds'							)
 def     a       (			self							):
   pass




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




 def     a       (			self							):
   __UpperCAmelCase,			__UpperCAmelCase	:  str		=     self.model_tester.prepare_config_and_inputs_for_common()

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

     __UpperCAmelCase	:  int		=     ['pixel_values']
     self.assertListEqual(arg_names[:1]  ,  _UpperCAmelCase							)




 def     a       (			self							):
   __UpperCAmelCase	:  Optional[Any]		=     self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*_UpperCAmelCase							)




 def     a       (			self							):
   __UpperCAmelCase	:  Any		=     self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_backbone(*_UpperCAmelCase							)




 def     a       (			self							):
   __UpperCAmelCase,			__UpperCAmelCase	:  Optional[Any]		=     self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     __UpperCAmelCase	:  List[str]		=     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     a       (			self							):
   def check_hidden_states_output(_UpperCAmelCase  ,  _UpperCAmelCase  ,  _UpperCAmelCase							):
     __UpperCAmelCase	:  int		=     model_class(_UpperCAmelCase							)
     model.to(_UpperCAmelCase							)
     model.eval()

     with torch.no_grad():
       __UpperCAmelCase	:  Dict		=     model(**self._prepare_for_class(_UpperCAmelCase  ,  _UpperCAmelCase							)							)

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

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

   __UpperCAmelCase,			__UpperCAmelCase	:  Union[str, Any]		=     self.model_tester.prepare_config_and_inputs_for_common()
   __UpperCAmelCase	:  Union[str, Any]		=     ['basic', 'bottleneck']
   for model_class in self.all_model_classes:
     for layer_type in layers_type:
       __UpperCAmelCase	:  Dict		=     layer_type
       __UpperCAmelCase	:  Dict		=     True
       check_hidden_states_output(_UpperCAmelCase  ,  _UpperCAmelCase  ,  _UpperCAmelCase							)

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

       check_hidden_states_output(_UpperCAmelCase  ,  _UpperCAmelCase  ,  _UpperCAmelCase							)




 @unittest.skip(reason='ResNet does not use feedforward chunking'							)
 def     a       (			self							):
   pass




 def     a       (			self							):
   __UpperCAmelCase	:  Optional[int]		=     self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase							)




 @slow
 def     a       (			self							):
   for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __UpperCAmelCase	:  Union[str, Any]		=     ResNetModel.from_pretrained(_UpperCAmelCase							)
     self.assertIsNotNone(_UpperCAmelCase							)





def  _snake_case		()							->		List[str]:
  __UpperCAmelCase	:  Optional[Any]		=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
  return image


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




 @cached_property
 def     a       (			self							):
   return (
       AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)
       if is_vision_available()
       else None
   )




 @slow
 def     a       (			self							):
   __UpperCAmelCase	:  Tuple		=     ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							).to(_UpperCAmelCase							)

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

   # forward pass
   with torch.no_grad():
     __UpperCAmelCase	:  Optional[int]		=     model(**_UpperCAmelCase							)

   # verify the logits
   __UpperCAmelCase	:  List[str]		=     torch.Size((1, 1_000)							)
   self.assertEqual(outputs.logits.shape  ,  _UpperCAmelCase							)

   __UpperCAmelCase	:  Dict		=     torch.tensor([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]							).to(_UpperCAmelCase							)

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



@require_torch
class      lowerCamelCase_ (			_lowerCAmelCase	,				unittest.TestCase):
 _lowerCAmelCase									=	(ResNetBackbone,) if is_torch_available() else ()
 _lowerCAmelCase									=	False
 _lowerCAmelCase									=	ResNetConfig




 def     a       (			self							):
   __UpperCAmelCase	:  Optional[int]		=     ResNetModelTester(self							)








from __future__ import annotations





def  _snake_case		(snake_case_					:     int  )							->		int | None:
  for r in range(1    ,       snake_case_  ):
    __UpperCAmelCase	:  List[str]		=     []
    for x in range(n - 1  ):
      __UpperCAmelCase	:  Union[str, Any]		=     pow(snake_case_    ,       snake_case_    ,       snake_case_  )
      if val in li:
        break
      li.append(snake_case_  )
    else:
      return r
  return None


if __name__ == "__main__":
      _SCREAMING_SNAKE_CASE							 =			int(input('''Enter a prime number q: '''))
      _SCREAMING_SNAKE_CASE							 =			find_primitive(q)
      if a is None:
            print(F'''Cannot find the primitive for the value: {a!r}''')
      else:
            _SCREAMING_SNAKE_CASE							 =			int(input('''Enter private key of A: '''))
            _SCREAMING_SNAKE_CASE							 =			pow(a, a_private, q)
            _SCREAMING_SNAKE_CASE							 =			int(input('''Enter private key of B: '''))
            _SCREAMING_SNAKE_CASE							 =			pow(a, b_private, q)

            _SCREAMING_SNAKE_CASE							 =			pow(b_public, a_private, q)
            _SCREAMING_SNAKE_CASE							 =			pow(a_public, b_private, q)

            print('''The key value generated by A is: ''', a_secret)
            print('''The key value generated by B is: ''', b_secret)





