
import inspect
import unittest

from transformers import MobileNetVaConfig
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_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 transformers import MobileNetVaForImageClassification, MobileNetVaModel
   from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import MobileNetVaImageProcessor






class   UpperCAmelCase		(						A_ ):



   def 				_SCREAMING_SNAKE_CASE   (self		:					Optional[int] )		->	List[str]:


          '''simple docstring'''


          snake_case       :   Optional[Any]							=      self.config_class(**self.inputs_dict )
          self.parent.assertTrue(hasattr(snake_case__    ,						"tf_padding" ) )
          self.parent.assertTrue(hasattr(snake_case__    ,						"depth_multiplier" ) )






class   UpperCAmelCase		:



   def __init__(self		:					List[str]    ,						snake_case__		:					Union[str, Any]    ,						snake_case__		:					Any=13    ,						snake_case__		:					int=3    ,						snake_case__		:					List[str]=32    ,						snake_case__		:					Any=0.25    ,						snake_case__		:					List[Any]=8    ,						snake_case__		:					List[str]=True    ,						snake_case__		:					Any=10_24    ,						snake_case__		:					List[Any]=32    ,						snake_case__		:					Optional[int]="relu6"    ,						snake_case__		:					List[str]=0.1    ,						snake_case__		:					Any=0.02    ,						snake_case__		:					Union[str, Any]=True    ,						snake_case__		:					Dict=True    ,						snake_case__		:					Tuple=10    ,						snake_case__		:					Tuple=None    ,						)		->	Dict:


          '''simple docstring'''


          snake_case       :   Optional[int]							=      parent
          snake_case       :   List[str]							=      batch_size
          snake_case       :   Any							=      num_channels
          snake_case       :   List[Any]							=      image_size
          snake_case       :   List[str]							=      depth_multiplier
          snake_case       :   Optional[int]							=      min_depth
          snake_case       :   Optional[Any]							=      tf_padding
          snake_case       :   Tuple							=      int(last_hidden_size * depth_multiplier )
          snake_case       :   List[Any]							=      output_stride
          snake_case       :   Union[str, Any]							=      hidden_act
          snake_case       :   Optional[Any]							=      classifier_dropout_prob
          snake_case       :   Dict							=      use_labels
          snake_case       :   Union[str, Any]							=      is_training
          snake_case       :   Optional[int]							=      num_labels
          snake_case       :   Optional[Any]							=      initializer_range
          snake_case       :   str							=      scope



   def 				_SCREAMING_SNAKE_CASE   (self		:					List[str] )		->	List[str]:


          '''simple docstring'''


          snake_case       :   Optional[int]							=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

          snake_case       :   Union[str, Any]							=      self.get_config()

          return config, pixel_values, labels, pixel_labels



   def 				_SCREAMING_SNAKE_CASE   (self		:					List[str] )		->	Optional[Any]:


          '''simple docstring'''


          return MobileNetVaConfig(
              num_channels=self.num_channels    ,						image_size=self.image_size    ,						depth_multiplier=self.depth_multiplier    ,						min_depth=self.min_depth    ,						tf_padding=self.tf_padding    ,						hidden_act=self.hidden_act    ,						classifier_dropout_prob=self.classifier_dropout_prob    ,						initializer_range=self.initializer_range    ,						)



   def 				_SCREAMING_SNAKE_CASE   (self		:					int    ,						snake_case__		:					Optional[Any]    ,						snake_case__		:					Optional[int]    ,						snake_case__		:					Optional[Any]    ,						snake_case__		:					Union[str, Any] )		->	List[str]:


          '''simple docstring'''


          snake_case       :   Optional[int]							=      MobileNetVaModel(config=snake_case__ )
          model.to(snake_case__ )
          model.eval()
          snake_case       :   int							=      model(snake_case__ )
          self.parent.assertEqual(
              result.last_hidden_state.shape    ,						(
                  self.batch_size,
                  self.last_hidden_size,
                  self.image_size // self.output_stride,
                  self.image_size // self.output_stride,
              )    ,						)



   def 				_SCREAMING_SNAKE_CASE   (self		:					List[Any]    ,						snake_case__		:					Any    ,						snake_case__		:					Any    ,						snake_case__		:					Dict    ,						snake_case__		:					Optional[int] )		->	Any:


          '''simple docstring'''


          snake_case       :   int							=      self.num_labels
          snake_case       :   Tuple							=      MobileNetVaForImageClassification(snake_case__ )
          model.to(snake_case__ )
          model.eval()
          snake_case       :   Union[str, Any]							=      model(snake_case__    ,						labels=snake_case__ )
          self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_labels) )



   def 				_SCREAMING_SNAKE_CASE   (self		:					str )		->	List[str]:


          '''simple docstring'''


          snake_case       :   str							=      self.prepare_config_and_inputs()
          snake_case				,					snake_case				,					snake_case				,					snake_case       :   List[Any]							=      config_and_inputs
          snake_case       :   Tuple							=      {"pixel_values": pixel_values}
          return config, inputs_dict






@require_torch
class   UpperCAmelCase		(						A_       ,A_       ,unittest.TestCase ):
   A__					:		str						     =     (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
   A__					:		str						     =     (
       {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification}
       if is_torch_available()
       else {}
   )

   A__					:		List[str]						     =     False
   A__					:		List[str]						     =     False
   A__					:		Union[str, Any]						     =     False
   A__					:		Optional[int]						     =     False



   def 				_SCREAMING_SNAKE_CASE   (self		:					List[Any] )		->	Any:


          '''simple docstring'''


          snake_case       :   List[Any]							=      MobileNetVaModelTester(self )
          snake_case       :   int							=      MobileNetVaConfigTester(self    ,						config_class=snake_case__    ,						has_text_modality=snake_case__ )



   def 				_SCREAMING_SNAKE_CASE   (self		:					List[str] )		->	Tuple:


          '''simple docstring'''


          self.config_tester.run_common_tests()



   @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" )
   def 				_SCREAMING_SNAKE_CASE   (self		:					int )		->	Dict:


          '''simple docstring'''


          pass



   @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" )
   def 				_SCREAMING_SNAKE_CASE   (self		:					List[str] )		->	Tuple:


          '''simple docstring'''


          pass



   @unittest.skip(reason="MobileNetV1 does not output attentions" )
   def 				_SCREAMING_SNAKE_CASE   (self		:					Any )		->	Dict:


          '''simple docstring'''


          pass



   def 				_SCREAMING_SNAKE_CASE   (self		:					Dict )		->	Any:


          '''simple docstring'''


          snake_case				,					snake_case       :   Any							=      self.model_tester.prepare_config_and_inputs_for_common()

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

                 snake_case       :   Optional[int]							=      ["pixel_values"]
                 self.assertListEqual(arg_names[:1]    ,						snake_case__ )



   def 				_SCREAMING_SNAKE_CASE   (self		:					Optional[Any] )		->	List[Any]:


          '''simple docstring'''


          snake_case       :   Tuple							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case__ )



   def 				_SCREAMING_SNAKE_CASE   (self		:					Union[str, Any] )		->	str:


          '''simple docstring'''


          def check_hidden_states_output(snake_case__		:					str    ,						snake_case__		:					Dict    ,						snake_case__		:					int ):
                 snake_case       :   Optional[Any]							=      model_class(snake_case__ )
                 model.to(snake_case__ )
                 model.eval()

                 with torch.no_grad():
                        snake_case       :   Any							=      model(**self._prepare_for_class(snake_case__    ,						snake_case__ ) )

                 snake_case       :   Optional[int]							=      outputs.hidden_states

                 snake_case       :   int							=      26
                 self.assertEqual(len(snake_case__ )    ,						snake_case__ )

          snake_case				,					snake_case       :   Any							=      self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 snake_case       :   List[str]							=      True
                 check_hidden_states_output(snake_case__    ,						snake_case__    ,						snake_case__ )

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 snake_case       :   Union[str, Any]							=      True

                 check_hidden_states_output(snake_case__    ,						snake_case__    ,						snake_case__ )



   def 				_SCREAMING_SNAKE_CASE   (self		:					List[str] )		->	Any:


          '''simple docstring'''


          snake_case       :   List[Any]							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case__ )



   @slow
   def 				_SCREAMING_SNAKE_CASE   (self		:					Any )		->	Union[str, Any]:


          '''simple docstring'''


          for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 snake_case       :   str							=      MobileNetVaModel.from_pretrained(snake_case__ )
                 self.assertIsNotNone(snake_case__ )



def 			UpperCamelCase					(    ):
       snake_case       :   Union[str, Any]							=      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
       return image






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



   @cached_property
   def 				_SCREAMING_SNAKE_CASE   (self		:					Optional[int] )		->	Tuple:


          '''simple docstring'''


          return (
              MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None
          )



   @slow
   def 				_SCREAMING_SNAKE_CASE   (self		:					Union[str, Any] )		->	Union[str, Any]:


          '''simple docstring'''


          snake_case       :   List[str]							=      MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(snake_case__ )

          snake_case       :   Union[str, Any]							=      self.default_image_processor
          snake_case       :   Dict							=      prepare_img()
          snake_case       :   Tuple							=      image_processor(images=snake_case__    ,						return_tensors="pt" ).to(snake_case__ )

          # forward pass
          with torch.no_grad():
                 snake_case       :   List[Any]							=      model(**snake_case__ )

          # verify the logits
          snake_case       :   Optional[int]							=      torch.Size((1, 10_01) )
          self.assertEqual(outputs.logits.shape    ,						snake_case__ )

          snake_case       :   List[Any]							=      torch.tensor([-4.1739, -1.1233, 3.1205] ).to(snake_case__ )

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







from typing import Dict

import numpy as np
import torch

from . import residue_constants as rc
from .tensor_utils import tensor_tree_map, tree_map


def 			UpperCamelCase					(    __lowerCamelCase     : Dict[str, torch.Tensor]    ):
       snake_case       :   List[str]							=      []
       snake_case       :   Optional[int]							=      []
       snake_case       :   Any							=      []

       for rt in rc.restypes:
              snake_case       :   List[Any]							=      rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]
              restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names]    )
              snake_case       :   str							=      {name: i for i, name in enumerate(__lowerCamelCase    )}
              restype_atomaa_to_atomaa_list.append(
                  [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types]    )

              restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names]    )

       # Add dummy mapping for restype 'UNK'
       restype_atomaa_to_atomaa_list.append([0] * 14    )
       restype_atomaa_to_atomaa_list.append([0] * 37    )
       restype_atomaa_mask_list.append([0.0] * 14    )

       snake_case       :   Optional[Any]							=      torch.tensor(
           __lowerCamelCase				,					dtype=torch.intaa				,					device=protein["aatype"].device				,					)
       snake_case       :   List[Any]							=      torch.tensor(
           __lowerCamelCase				,					dtype=torch.intaa				,					device=protein["aatype"].device				,					)
       snake_case       :   int							=      torch.tensor(
           __lowerCamelCase				,					dtype=torch.floataa				,					device=protein["aatype"].device				,					)
       snake_case       :   int							=      protein["aatype"].to(torch.long    )

       # create the mapping for (residx, atom14) --> atom37, i.e. an array
       # with shape (num_res, 14) containing the atom37 indices for this protein
       snake_case       :   List[Any]							=      restype_atomaa_to_atomaa[protein_aatype]
       snake_case       :   str							=      restype_atomaa_mask[protein_aatype]

       snake_case       :   str							=      residx_atomaa_mask
       snake_case       :   Any							=      residx_atomaa_to_atomaa.long()

       # create the gather indices for mapping back
       snake_case       :   List[str]							=      restype_atomaa_to_atomaa[protein_aatype]
       snake_case       :   List[Any]							=      residx_atomaa_to_atomaa.long()

       # create the corresponding mask
       snake_case       :   Union[str, Any]							=      torch.zeros([21, 37]				,					dtype=torch.floataa				,					device=protein["aatype"].device    )
       for restype, restype_letter in enumerate(rc.restypes    ):
              snake_case       :   Optional[int]							=      rc.restype_atoa[restype_letter]
              snake_case       :   Any							=      rc.residue_atoms[restype_name]
              for atom_name in atom_names:
                     snake_case       :   List[Any]							=      rc.atom_order[atom_name]
                     snake_case       :   Optional[Any]							=      1

       snake_case       :   List[Any]							=      restype_atomaa_mask[protein_aatype]
       snake_case       :   int							=      residx_atomaa_mask

       return protein




def 			UpperCamelCase					(    __lowerCamelCase     : Dict[str, torch.Tensor]    ):
       snake_case       :   Dict							=      tree_map(lambda __lowerCamelCase    : torch.tensor(__lowerCamelCase				,					device=batch["aatype"].device    )				,					__lowerCamelCase				,					np.ndarray    )
       snake_case       :   List[str]							=      tensor_tree_map(lambda __lowerCamelCase    : np.array(__lowerCamelCase    )				,					make_atomaa_masks(__lowerCamelCase    )    )
       return out





