





from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block







@dataclass
class     __lowerCAmelCase	(   UpperCamelCase__):
      _lowercase    : torch.FloatTensor







class     __lowerCAmelCase	(   nn.Module):







      def __init__(   self		,				lowerCAmelCase__=3		,				lowerCAmelCase__=3		,				lowerCAmelCase__=("DownEncoderBlock2D",)		,				lowerCAmelCase__=(6_4,)		,				lowerCAmelCase__=2		,				lowerCAmelCase__=3_2		,				lowerCAmelCase__="silu"		,				lowerCAmelCase__=True		,				)       ->						Any:



        '''simple docstring'''




        super().__init__()
        a__     : Optional[int]  =layers_per_block

        a__     : Tuple  =torch.nn.Convad(
            lowerCAmelCase__		,				block_out_channels[0]		,				kernel_size=3		,				stride=1		,				padding=1		,				)

        a__     : List[Any]  =None
        a__     : List[Any]  =nn.ModuleList([]							)

        # down
        a__     : Any  =block_out_channels[0]
        for i, down_block_type in enumerate(lowerCAmelCase__							):
          a__     : Tuple  =output_channel
          a__     : List[Any]  =block_out_channels[i]
          a__     : Optional[Any]  =i == len(lowerCAmelCase__							) - 1

          a__     : List[str]  =get_down_block(
              lowerCAmelCase__		,				num_layers=self.layers_per_block		,				in_channels=lowerCAmelCase__		,				out_channels=lowerCAmelCase__		,				add_downsample=not is_final_block		,				resnet_eps=1E-6		,				downsample_padding=0		,				resnet_act_fn=lowerCAmelCase__		,				resnet_groups=lowerCAmelCase__		,				attention_head_dim=lowerCAmelCase__		,				temb_channels=lowerCAmelCase__		,				)
          self.down_blocks.append(lowerCAmelCase__							)

        # mid
        a__     : Dict  =UNetMidBlockaD(
            in_channels=block_out_channels[-1]		,				resnet_eps=1E-6		,				resnet_act_fn=lowerCAmelCase__		,				output_scale_factor=1		,				resnet_time_scale_shift="default"		,				attention_head_dim=block_out_channels[-1]		,				resnet_groups=lowerCAmelCase__		,				temb_channels=lowerCAmelCase__		,				)

        # out
        a__     : str  =nn.GroupNorm(num_channels=block_out_channels[-1]		,				num_groups=lowerCAmelCase__		,				eps=1E-6							)
        a__     : Tuple  =nn.SiLU()

        a__     : Union[str, Any]  =2 * out_channels if double_z else out_channels
        a__     : Optional[Any]  =nn.Convad(block_out_channels[-1]		,				lowerCAmelCase__		,				3		,				padding=1							)

        a__     : Tuple  =False







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						Tuple:



        '''simple docstring'''




        a__     : Optional[Any]  =x
        a__     : List[str]  =self.conv_in(lowerCAmelCase__							)

        if self.training and self.gradient_checkpointing:

          def create_custom_forward(lowerCAmelCase__							):
            def custom_forward(*lowerCAmelCase__							):
              return module(*lowerCAmelCase__							)

            return custom_forward

          # down
          if is_torch_version(">="		,				"1.11.0"							):
            for down_block in self.down_blocks:
              a__     : Optional[int]  =torch.utils.checkpoint.checkpoint(
                  create_custom_forward(lowerCAmelCase__							)		,				lowerCAmelCase__		,				use_reentrant=lowerCAmelCase__							)
            # middle
            a__     : List[Any]  =torch.utils.checkpoint.checkpoint(
                create_custom_forward(self.mid_block							)		,				lowerCAmelCase__		,				use_reentrant=lowerCAmelCase__							)
          else:
            for down_block in self.down_blocks:
              a__     : str  =torch.utils.checkpoint.checkpoint(create_custom_forward(lowerCAmelCase__							)		,				lowerCAmelCase__							)
            # middle
            a__     : Dict  =torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block							)		,				lowerCAmelCase__							)

        else:
          # down
          for down_block in self.down_blocks:
            a__     : int  =down_block(lowerCAmelCase__							)

          # middle
          a__     : Optional[Any]  =self.mid_block(lowerCAmelCase__							)

        # post-process
        a__     : int  =self.conv_norm_out(lowerCAmelCase__							)
        a__     : Optional[int]  =self.conv_act(lowerCAmelCase__							)
        a__     : Optional[Any]  =self.conv_out(lowerCAmelCase__							)

        return sample







class     __lowerCAmelCase	(   nn.Module):







      def __init__(   self		,				lowerCAmelCase__=3		,				lowerCAmelCase__=3		,				lowerCAmelCase__=("UpDecoderBlock2D",)		,				lowerCAmelCase__=(6_4,)		,				lowerCAmelCase__=2		,				lowerCAmelCase__=3_2		,				lowerCAmelCase__="silu"		,				lowerCAmelCase__="group"		,				)       ->						Optional[Any]:



        '''simple docstring'''




        super().__init__()
        a__     : Optional[int]  =layers_per_block

        a__     : Union[str, Any]  =nn.Convad(
            lowerCAmelCase__		,				block_out_channels[-1]		,				kernel_size=3		,				stride=1		,				padding=1		,				)

        a__     : Optional[int]  =None
        a__     : int  =nn.ModuleList([]							)

        a__     : int  =in_channels if norm_type == "spatial" else None

        # mid
        a__     : int  =UNetMidBlockaD(
            in_channels=block_out_channels[-1]		,				resnet_eps=1E-6		,				resnet_act_fn=lowerCAmelCase__		,				output_scale_factor=1		,				resnet_time_scale_shift="default" if norm_type == "group" else norm_type		,				attention_head_dim=block_out_channels[-1]		,				resnet_groups=lowerCAmelCase__		,				temb_channels=lowerCAmelCase__		,				)

        # up
        a__     : Any  =list(reversed(lowerCAmelCase__							)							)
        a__     : str  =reversed_block_out_channels[0]
        for i, up_block_type in enumerate(lowerCAmelCase__							):
          a__     : Optional[Any]  =output_channel
          a__     : str  =reversed_block_out_channels[i]

          a__     : Dict  =i == len(lowerCAmelCase__							) - 1

          a__     : Any  =get_up_block(
              lowerCAmelCase__		,				num_layers=self.layers_per_block + 1		,				in_channels=lowerCAmelCase__		,				out_channels=lowerCAmelCase__		,				prev_output_channel=lowerCAmelCase__		,				add_upsample=not is_final_block		,				resnet_eps=1E-6		,				resnet_act_fn=lowerCAmelCase__		,				resnet_groups=lowerCAmelCase__		,				attention_head_dim=lowerCAmelCase__		,				temb_channels=lowerCAmelCase__		,				resnet_time_scale_shift=lowerCAmelCase__		,				)
          self.up_blocks.append(lowerCAmelCase__							)
          a__     : Union[str, Any]  =output_channel

        # out
        if norm_type == "spatial":
          a__     : Any  =SpatialNorm(block_out_channels[0]		,				lowerCAmelCase__							)
        else:
          a__     : str  =nn.GroupNorm(num_channels=block_out_channels[0]		,				num_groups=lowerCAmelCase__		,				eps=1E-6							)
        a__     : str  =nn.SiLU()
        a__     : Union[str, Any]  =nn.Convad(block_out_channels[0]		,				lowerCAmelCase__		,				3		,				padding=1							)

        a__     : List[Any]  =False







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__=None							)       ->						List[Any]:



        '''simple docstring'''




        a__     : List[Any]  =z
        a__     : Union[str, Any]  =self.conv_in(lowerCAmelCase__							)

        a__     : Any  =next(iter(self.up_blocks.parameters()							)							).dtype
        if self.training and self.gradient_checkpointing:

          def create_custom_forward(lowerCAmelCase__							):
            def custom_forward(*lowerCAmelCase__							):
              return module(*lowerCAmelCase__							)

            return custom_forward

          if is_torch_version(">="		,				"1.11.0"							):
            # middle
            a__     : Optional[int]  =torch.utils.checkpoint.checkpoint(
                create_custom_forward(self.mid_block							)		,				lowerCAmelCase__		,				lowerCAmelCase__		,				use_reentrant=lowerCAmelCase__							)
            a__     : str  =sample.to(lowerCAmelCase__							)

            # up
            for up_block in self.up_blocks:
              a__     : Union[str, Any]  =torch.utils.checkpoint.checkpoint(
                  create_custom_forward(lowerCAmelCase__							)		,				lowerCAmelCase__		,				lowerCAmelCase__		,				use_reentrant=lowerCAmelCase__							)
          else:
            # middle
            a__     : Optional[int]  =torch.utils.checkpoint.checkpoint(
                create_custom_forward(self.mid_block							)		,				lowerCAmelCase__		,				lowerCAmelCase__							)
            a__     : List[str]  =sample.to(lowerCAmelCase__							)

            # up
            for up_block in self.up_blocks:
              a__     : Optional[int]  =torch.utils.checkpoint.checkpoint(create_custom_forward(lowerCAmelCase__							)		,				lowerCAmelCase__		,				lowerCAmelCase__							)
        else:
          # middle
          a__     : Optional[int]  =self.mid_block(lowerCAmelCase__		,				lowerCAmelCase__							)
          a__     : Dict  =sample.to(lowerCAmelCase__							)

          # up
          for up_block in self.up_blocks:
            a__     : Optional[int]  =up_block(lowerCAmelCase__		,				lowerCAmelCase__							)

        # post-process
        if latent_embeds is None:
          a__     : List[str]  =self.conv_norm_out(lowerCAmelCase__							)
        else:
          a__     : int  =self.conv_norm_out(lowerCAmelCase__		,				lowerCAmelCase__							)
        a__     : Optional[Any]  =self.conv_act(lowerCAmelCase__							)
        a__     : List[str]  =self.conv_out(lowerCAmelCase__							)

        return sample







class     __lowerCAmelCase	(   nn.Module):







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__=None		,				lowerCAmelCase__="random"		,				lowerCAmelCase__=False		,				lowerCAmelCase__=True							)       ->						Union[str, Any]:



        '''simple docstring'''




        super().__init__()
        a__     : Optional[int]  =n_e
        a__     : Tuple  =vq_embed_dim
        a__     : int  =beta
        a__     : str  =legacy

        a__     : str  =nn.Embedding(self.n_e		,				self.vq_embed_dim							)
        self.embedding.weight.data.uniform_(-1.0 / self.n_e		,				1.0 / self.n_e							)

        a__     : Optional[int]  =remap
        if self.remap is not None:
          self.register_buffer("used"		,				torch.tensor(np.load(self.remap							)							)							)
          a__     : List[str]  =self.used.shape[0]
          a__     : List[Any]  =unknown_index  # "random" or "extra" or integer
          if self.unknown_index == "extra":
            a__     : str  =self.re_embed
            a__     : Dict  =self.re_embed + 1
          print(
              F'''Remapping {self.n_e} indices to {self.re_embed} indices. '''
              F'''Using {self.unknown_index} for unknown indices.'''							)
        else:
          a__     : Any  =n_e

        a__     : Optional[int]  =sane_index_shape







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						str:



        '''simple docstring'''




        a__     : Any  =inds.shape
        assert len(lowerCAmelCase__							) > 1
        a__     : Optional[Any]  =inds.reshape(ishape[0]		,				-1							)
        a__     : Tuple  =self.used.to(lowerCAmelCase__							)
        a__     : Union[str, Any]  =(inds[:, :, None] == used[None, None, ...]).long()
        a__     : Tuple  =match.argmax(-1							)
        a__     : Optional[Any]  =match.sum(2							) < 1
        if self.unknown_index == "random":
          a__     : Tuple  =torch.randint(0		,				self.re_embed		,				size=new[unknown].shape							).to(device=new.device							)
        else:
          a__     : str  =self.unknown_index
        return new.reshape(lowerCAmelCase__							)







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



        '''simple docstring'''




        a__     : Any  =inds.shape
        assert len(lowerCAmelCase__							) > 1
        a__     : Tuple  =inds.reshape(ishape[0]		,				-1							)
        a__     : Tuple  =self.used.to(lowerCAmelCase__							)
        if self.re_embed > self.used.shape[0]:  # extra token
          a__     : List[Any]  =0  # simply set to zero
        a__     : int  =torch.gather(used[None, :][inds.shape[0] * [0], :]		,				1		,				lowerCAmelCase__							)
        return back.reshape(lowerCAmelCase__							)







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						List[Any]:



        '''simple docstring'''




        a__     : Union[str, Any]  =z.permute(0		,				2		,				3		,				1							).contiguous()
        a__     : Tuple  =z.view(-1		,				self.vq_embed_dim							)

        # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
        a__     : Optional[Any]  =torch.argmin(torch.cdist(lowerCAmelCase__		,				self.embedding.weight							)		,				dim=1							)

        a__     : List[Any]  =self.embedding(lowerCAmelCase__							).view(z.shape							)
        a__     : List[str]  =None
        a__     : str  =None

        # compute loss for embedding
        if not self.legacy:
          a__     : Union[str, Any]  =self.beta * torch.mean((z_q.detach() - z) ** 2							) + torch.mean((z_q - z.detach()) ** 2							)
        else:
          a__     : Optional[Any]  =torch.mean((z_q.detach() - z) ** 2							) + self.beta * torch.mean((z_q - z.detach()) ** 2							)

        # preserve gradients
        a__     : List[Any]  =z + (z_q - z).detach()

        # reshape back to match original input shape
        a__     : List[str]  =z_q.permute(0		,				3		,				1		,				2							).contiguous()

        if self.remap is not None:
          a__     : Dict  =min_encoding_indices.reshape(z.shape[0]		,				-1							)  # add batch axis
          a__     : Tuple  =self.remap_to_used(lowerCAmelCase__							)
          a__     : str  =min_encoding_indices.reshape(-1		,				1							)  # flatten

        if self.sane_index_shape:
          a__     : Any  =min_encoding_indices.reshape(z_q.shape[0]		,				z_q.shape[2]		,				z_q.shape[3]							)

        return z_q, loss, (perplexity, min_encodings, min_encoding_indices)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						List[str]:



        '''simple docstring'''




        if self.remap is not None:
          a__     : Union[str, Any]  =indices.reshape(shape[0]		,				-1							)  # add batch axis
          a__     : str  =self.unmap_to_all(lowerCAmelCase__							)
          a__     : List[Any]  =indices.reshape(-1							)  # flatten again

        # get quantized latent vectors
        a__     : Optional[int]  =self.embedding(lowerCAmelCase__							)

        if shape is not None:
          a__     : Any  =z_q.view(lowerCAmelCase__							)
          # reshape back to match original input shape
          a__     : Union[str, Any]  =z_q.permute(0		,				3		,				1		,				2							).contiguous()

        return z_q







class     __lowerCAmelCase	(   UpperCamelCase__):







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__=False							)       ->						Union[str, Any]:



        '''simple docstring'''




        a__     : List[Any]  =parameters
        a__ ,							a__     : str  =torch.chunk(lowerCAmelCase__		,				2		,				dim=1							)
        a__     : Any  =torch.clamp(self.logvar		,				-30.0		,				20.0							)
        a__     : Any  =deterministic
        a__     : List[Any]  =torch.exp(0.5 * self.logvar							)
        a__     : int  =torch.exp(self.logvar							)
        if self.deterministic:
          a__     : Optional[Any]  =torch.zeros_like(
              self.mean		,				device=self.parameters.device		,				dtype=self.parameters.dtype							)







      def        _lowercase  (   self		,				lowerCAmelCase__ = None							)       ->						torch.FloatTensor:



        '''simple docstring'''




        a__     : Any  =randn_tensor(
            self.mean.shape		,				generator=lowerCAmelCase__		,				device=self.parameters.device		,				dtype=self.parameters.dtype							)
        a__     : Optional[Any]  =self.mean + self.std * sample
        return x







      def        _lowercase  (   self		,				lowerCAmelCase__=None							)       ->						Tuple:



        '''simple docstring'''




        if self.deterministic:
          return torch.Tensor([0.0]							)
        else:
          if other is None:
            return 0.5 * torch.sum(torch.pow(self.mean		,				2							) + self.var - 1.0 - self.logvar		,				dim=[1, 2, 3]							)
          else:
            return 0.5 * torch.sum(
                torch.pow(self.mean - other.mean		,				2							) / other.var
                + self.var / other.var
                - 1.0
                - self.logvar
                + other.logvar		,				dim=[1, 2, 3]		,				)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__=[1, 2, 3]							)       ->						Dict:



        '''simple docstring'''




        if self.deterministic:
          return torch.Tensor([0.0]							)
        a__     : Tuple  =np.log(2.0 * np.pi							)
        return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean		,				2							) / self.var		,				dim=lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Optional[int]:



        '''simple docstring'''




        return self.mean













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     __lowerCAmelCase	(   UpperCamelCase__):







      def        _lowercase  (   self							)       ->						Any:



        '''simple docstring'''




        a__     : Optional[int]  =self.config_class(**self.inputs_dict							)
        self.parent.assertTrue(hasattr(lowerCAmelCase__		,				"tf_padding"							)							)
        self.parent.assertTrue(hasattr(lowerCAmelCase__		,				"depth_multiplier"							)							)







class     __lowerCAmelCase	:







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__=1_3		,				lowerCAmelCase__=3		,				lowerCAmelCase__=3_2		,				lowerCAmelCase__=0.25		,				lowerCAmelCase__=8		,				lowerCAmelCase__=True		,				lowerCAmelCase__=1_0_2_4		,				lowerCAmelCase__=3_2		,				lowerCAmelCase__="relu6"		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=0.02		,				lowerCAmelCase__=True		,				lowerCAmelCase__=True		,				lowerCAmelCase__=1_0		,				lowerCAmelCase__=None		,				)       ->						Dict:



        '''simple docstring'''




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







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



        '''simple docstring'''




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

        a__     : Any  =None
        a__     : List[Any]  =None
        if self.use_labels:
          a__     : Dict  =ids_tensor([self.batch_size]		,				self.num_labels							)
          a__     : Tuple  =ids_tensor([self.batch_size, self.image_size, self.image_size]		,				self.num_labels							)

        a__     : Optional[Any]  =self.get_config()

        return config, pixel_values, labels, pixel_labels







      def        _lowercase  (   self							)       ->						str:



        '''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        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						Union[str, Any]:



        '''simple docstring'''




        a__     : Union[str, Any]  =MobileNetVaModel(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : str  =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		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						str:



        '''simple docstring'''




        a__     : Any  =self.num_labels
        a__     : Dict  =MobileNetVaForImageClassification(lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : Optional[int]  =model(lowerCAmelCase__		,				labels=lowerCAmelCase__							)
        self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)							)







      def        _lowercase  (   self							)       ->						str:



        '''simple docstring'''




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







@require_torch
class     __lowerCAmelCase	(   UpperCamelCase__						,    UpperCamelCase__						,    unittest.TestCase):
      _lowercase    : List[str]            =      (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
      _lowercase    : Optional[int]            =      (
          {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
          if is_torch_available()
          else {}
      )

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







      def        _lowercase  (   self							)       ->						Optional[int]:



        '''simple docstring'''




        a__     : Optional[Any]  =MobileNetVaModelTester(self							)
        a__     : Optional[Any]  =MobileNetVaConfigTester(self		,				config_class=lowerCAmelCase__		,				has_text_modality=lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Dict:



        '''simple docstring'''




        self.config_tester.run_common_tests()







      @unittest.skip(reason="MobileNetV1 does not use inputs_embeds"							)
      def        _lowercase  (   self							)       ->						Union[str, Any]:



        '''simple docstring'''




        pass







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



        '''simple docstring'''




        pass







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



        '''simple docstring'''




        pass







      def        _lowercase  (   self							)       ->						str:



        '''simple docstring'''




        a__ ,							a__     : Optional[int]  =self.model_tester.prepare_config_and_inputs_for_common()

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

          a__     : Union[str, Any]  =["pixel_values"]
          self.assertListEqual(arg_names[:1]		,				lowerCAmelCase__							)







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



        '''simple docstring'''




        a__     : Optional[Any]  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase__							)







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



        '''simple docstring'''




        def check_hidden_states_output(lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							):
          a__     : int  =model_class(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()

          with torch.no_grad():
            a__     : List[Any]  =model(**self._prepare_for_class(lowerCAmelCase__		,				lowerCAmelCase__							)							)

          a__     : Optional[int]  =outputs.hidden_states

          a__     : Optional[int]  =2_6
          self.assertEqual(len(lowerCAmelCase__							)		,				lowerCAmelCase__							)

        a__ ,							a__     : Optional[Any]  =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          a__     : Optional[int]  =True
          check_hidden_states_output(lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)

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

          check_hidden_states_output(lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Any:



        '''simple docstring'''




        a__     : Dict  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__							)







      @slow
      def        _lowercase  (   self							)       ->						Any:



        '''simple docstring'''




        for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          a__     : List[str]  =MobileNetVaModel.from_pretrained(lowerCAmelCase__							)
          self.assertIsNotNone(lowerCAmelCase__							)
def 					_A	(		):





  """simple docstring"""



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







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







      @cached_property
      def        _lowercase  (   self							)       ->						Optional[Any]:



        '''simple docstring'''




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







      @slow
      def        _lowercase  (   self							)       ->						Optional[int]:



        '''simple docstring'''




        a__     : str  =MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224"							).to(lowerCAmelCase__							)

        a__     : Optional[Any]  =self.default_image_processor
        a__     : Optional[int]  =prepare_img()
        a__     : Optional[int]  =image_processor(images=lowerCAmelCase__		,				return_tensors="pt"							).to(lowerCAmelCase__							)

        # forward pass
        with torch.no_grad():
          a__     : int  =model(**lowerCAmelCase__							)

        # verify the logits
        a__     : str  =torch.Size((1, 1_0_0_1)							)
        self.assertEqual(outputs.logits.shape		,				lowerCAmelCase__							)

        a__     : int  =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							)							)






