





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   (   _UpperCamelCase   ):

  """simple docstring"""


  def     lowercase		(    self			:		Any					)							->						str:
     __lowerCAmelCase							     =     self.config_class(**self.inputs_dict					)
     self.parent.assertTrue(hasattr(lowerCAmelCase_ ,  'tf_padding'					)					)
     self.parent.assertTrue(hasattr(lowerCAmelCase_ ,  'depth_multiplier'					)					)





class     _UpperCAmelCase   :

  """simple docstring"""


  def __init__(    self			:		Optional[Any] ,  lowerCAmelCase_			:		Any ,  lowerCAmelCase_			:		Dict=1_3 ,  lowerCAmelCase_			:		Optional[Any]=3 ,  lowerCAmelCase_			:		Optional[int]=3_2 ,  lowerCAmelCase_			:		int=0.25 ,  lowerCAmelCase_			:		Any=8 ,  lowerCAmelCase_			:		Dict=True ,  lowerCAmelCase_			:		Tuple=1_0_2_4 ,  lowerCAmelCase_			:		int=3_2 ,  lowerCAmelCase_			:		Optional[int]="relu6" ,  lowerCAmelCase_			:		List[str]=0.1 ,  lowerCAmelCase_			:		str=0.02 ,  lowerCAmelCase_			:		Optional[int]=True ,  lowerCAmelCase_			:		Optional[int]=True ,  lowerCAmelCase_			:		List[Any]=1_0 ,  lowerCAmelCase_			:		Union[str, Any]=None ,  )							->						List[Any]:
     __lowerCAmelCase							     =     parent
     __lowerCAmelCase							     =     batch_size
     __lowerCAmelCase							     =     num_channels
     __lowerCAmelCase							     =     image_size
     __lowerCAmelCase							     =     depth_multiplier
     __lowerCAmelCase							     =     min_depth
     __lowerCAmelCase							     =     tf_padding
     __lowerCAmelCase							     =     int(last_hidden_size * depth_multiplier					)
     __lowerCAmelCase							     =     output_stride
     __lowerCAmelCase							     =     hidden_act
     __lowerCAmelCase							     =     classifier_dropout_prob
     __lowerCAmelCase							     =     use_labels
     __lowerCAmelCase							     =     is_training
     __lowerCAmelCase							     =     num_labels
     __lowerCAmelCase							     =     initializer_range
     __lowerCAmelCase							     =     scope






  def     lowercase		(    self			:		List[str]					)							->						List[Any]:
     __lowerCAmelCase							     =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

     __lowerCAmelCase							     =     None
     __lowerCAmelCase							     =     None
     if self.use_labels:
        __lowerCAmelCase							     =     ids_tensor([self.batch_size] ,  self.num_labels					)
        __lowerCAmelCase							     =     ids_tensor([self.batch_size, self.image_size, self.image_size] ,  self.num_labels					)

     __lowerCAmelCase							     =     self.get_config()

     return config, pixel_values, labels, pixel_labels






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






  def     lowercase		(    self			:		int					)							->						Tuple:
     __lowerCAmelCase							     =     self.prepare_config_and_inputs()
     __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase     ,     __lowerCAmelCase							     =     config_and_inputs
     __lowerCAmelCase							     =     {'pixel_values': pixel_values}
     return config, inputs_dict





@require_torch
class     _UpperCAmelCase   (   _UpperCamelCase		,   _UpperCamelCase		,   unittest.TestCase   ):

  """simple docstring"""


  a_      =			(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
  a_      =			(
      {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
      if is_torch_available()
      else {}
  )

  a_      =			False
  a_      =			False
  a_      =			False
  a_      =			False






  def     lowercase		(    self			:		Optional[Any]					)							->						Any:
     __lowerCAmelCase							     =     MobileNetVaModelTester(self					)
     __lowerCAmelCase							     =     MobileNetVaConfigTester(self ,  config_class=lowerCAmelCase_ ,  has_text_modality=lowerCAmelCase_					)






  def     lowercase		(    self			:		Optional[Any]					)							->						int:
     self.config_tester.run_common_tests()






  @unittest.skip(reason='MobileNetV1 does not use inputs_embeds'					)
  def     lowercase		(    self			:		Dict					)							->						Dict:
     pass






  @unittest.skip(reason='MobileNetV1 does not support input and output embeddings'					)
  def     lowercase		(    self			:		Any					)							->						List[Any]:
     pass






  @unittest.skip(reason='MobileNetV1 does not output attentions'					)
  def     lowercase		(    self			:		Union[str, Any]					)							->						List[Any]:
     pass






  def     lowercase		(    self			:		Dict					)							->						Tuple:
     __lowerCAmelCase     ,     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCAmelCase							     =     ['pixel_values']
        self.assertListEqual(arg_names[:1] ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		List[Any]					)							->						Optional[Any]:
     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase_					)






  def     lowercase		(    self			:		List[Any]					)							->						Dict:
     def check_hidden_states_output(lowerCAmelCase_			:		Dict ,  lowerCAmelCase_			:		str ,  lowerCAmelCase_			:		Union[str, Any]					):
        __lowerCAmelCase							     =     model_class(lowerCAmelCase_					)
        model.to(lowerCAmelCase_					)
        model.eval()

        with torch.no_grad():
           __lowerCAmelCase							     =     model(**self._prepare_for_class(lowerCAmelCase_ ,  lowerCAmelCase_					)					)

        __lowerCAmelCase							     =     outputs.hidden_states

        __lowerCAmelCase							     =     2_6
        self.assertEqual(len(lowerCAmelCase_					) ,  lowerCAmelCase_					)

     __lowerCAmelCase     ,     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __lowerCAmelCase							     =     True
        check_hidden_states_output(lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_					)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __lowerCAmelCase							     =     True

        check_hidden_states_output(lowerCAmelCase_ ,  lowerCAmelCase_ ,  lowerCAmelCase_					)






  def     lowercase		(    self			:		Tuple					)							->						int:
     __lowerCAmelCase							     =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_					)






  @slow
  def     lowercase		(    self			:		Any					)							->						str:
     for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCAmelCase							     =     MobileNetVaModel.from_pretrained(lowerCAmelCase_					)
        self.assertIsNotNone(lowerCAmelCase_					)





def   a_   (			):
   __lowerCAmelCase							     =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
   return image




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

  """simple docstring"""


  @cached_property
  def     lowercase		(    self			:		Any					)							->						Optional[Any]:
     return (
         MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224'					) if is_vision_available() else None
     )






  @slow
  def     lowercase		(    self			:		Optional[int]					)							->						List[str]:
     __lowerCAmelCase							     =     MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224'					).to(lowerCAmelCase_					)

     __lowerCAmelCase							     =     self.default_image_processor
     __lowerCAmelCase							     =     prepare_img()
     __lowerCAmelCase							     =     image_processor(images=lowerCAmelCase_ ,  return_tensors='pt'					).to(lowerCAmelCase_					)

     # forward pass
     with torch.no_grad():
        __lowerCAmelCase							     =     model(**lowerCAmelCase_					)

     # verify the logits
     __lowerCAmelCase							     =     torch.Size((1, 1_0_0_1)					)
     self.assertEqual(outputs.logits.shape ,  lowerCAmelCase_					)

     __lowerCAmelCase							     =     torch.tensor([-4.17_39, -1.12_33, 3.12_05]					).to(lowerCAmelCase_					)

     self.assertTrue(torch.allclose(outputs.logits[0, :3] ,  lowerCAmelCase_ ,  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   a_   (			lowerCAmelCase_				:      Dict[str, torch.Tensor]     ):
   __lowerCAmelCase							     =     []
   __lowerCAmelCase							     =     []
   __lowerCAmelCase							     =     []

   for rt in rc.restypes:
      __lowerCAmelCase							     =     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]     )
      __lowerCAmelCase							     =     {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     )

   __lowerCAmelCase							     =     torch.tensor(
       lowerCAmelCase_,     dtype=torch.intaa,     device=protein['aatype'].device,     )
   __lowerCAmelCase							     =     torch.tensor(
       lowerCAmelCase_,     dtype=torch.intaa,     device=protein['aatype'].device,     )
   __lowerCAmelCase							     =     torch.tensor(
       lowerCAmelCase_,     dtype=torch.floataa,     device=protein['aatype'].device,     )
   __lowerCAmelCase							     =     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
   __lowerCAmelCase							     =     restype_atomaa_to_atomaa[protein_aatype]
   __lowerCAmelCase							     =     restype_atomaa_mask[protein_aatype]

   __lowerCAmelCase							     =     residx_atomaa_mask
   __lowerCAmelCase							     =     residx_atomaa_to_atomaa.long()

   # create the gather indices for mapping back
   __lowerCAmelCase							     =     restype_atomaa_to_atomaa[protein_aatype]
   __lowerCAmelCase							     =     residx_atomaa_to_atomaa.long()

   # create the corresponding mask
   __lowerCAmelCase							     =     torch.zeros([21, 37],     dtype=torch.floataa,     device=protein['aatype'].device     )
   for restype, restype_letter in enumerate(rc.restypes     ):
      __lowerCAmelCase							     =     rc.restype_atoa[restype_letter]
      __lowerCAmelCase							     =     rc.residue_atoms[restype_name]
      for atom_name in atom_names:
         __lowerCAmelCase							     =     rc.atom_order[atom_name]
         __lowerCAmelCase							     =     1

   __lowerCAmelCase							     =     restype_atomaa_mask[protein_aatype]
   __lowerCAmelCase							     =     residx_atomaa_mask

   return protein




def   a_   (			lowerCAmelCase_				:      Dict[str, torch.Tensor]     ):
   __lowerCAmelCase							     =     tree_map(lambda lowerCAmelCase_     : torch.tensor(lowerCAmelCase_,     device=batch['aatype'].device     ),     lowerCAmelCase_,     np.ndarray     )
   __lowerCAmelCase							     =     tensor_tree_map(lambda lowerCAmelCase_     : np.array(lowerCAmelCase_     ),     make_atomaa_masks(lowerCAmelCase_     )     )
   return out

