

"""simple docstring"""

import inspect
from typing import List, Optional, Union

import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput






class  __a				(	nn.Module					):





       """simple docstring"""


       def __init__(      self ,				snake_case ,				snake_case=1.0      ):





        """simple docstring"""

        super().__init__()

        lowerCAmelCase__      :							List[Any]    =							cut_size
        lowerCAmelCase__      :							List[Any]    =							cut_power






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case      ):





        """simple docstring"""

        lowerCAmelCase__ ,	lowerCAmelCase__      :							int    =							pixel_values.shape[2:4]
        lowerCAmelCase__      :							int    =							min(snake_case ,				snake_case      )
        lowerCAmelCase__      :							Union[str, Any]    =							min(snake_case ,				snake_case ,				self.cut_size      )
        lowerCAmelCase__      :							Optional[int]    =							[]
        for _ in range(snake_case      ):
         lowerCAmelCase__      :							int    =							int(torch.rand([]      ) ** self.cut_power * (max_size - min_size) + min_size      )
         lowerCAmelCase__      :							Tuple    =							torch.randint(0 ,				sideX - size + 1 ,				()      )
         lowerCAmelCase__      :							Any    =							torch.randint(0 ,				sideY - size + 1 ,				()      )
         lowerCAmelCase__      :							int    =							pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
         cutouts.append(F.adaptive_avg_poolad(snake_case ,				self.cut_size      )      )
        return torch.cat(snake_case      )




def 			SCREAMING_SNAKE_CASE       (   lowercase__				,				lowercase__      ) ->	List[str]:
 lowerCAmelCase__      :							List[str]    =							F.normalize(lowercase__				,				dim=-1      )
 lowerCAmelCase__      :							Union[str, Any]    =							F.normalize(lowercase__				,				dim=-1      )
 return (x - y).norm(dim=-1      ).div(2      ).arcsin().pow(2      ).mul(2      )



def 			SCREAMING_SNAKE_CASE       (   lowercase__				,				lowercase__      ) ->	List[Any]:
 for param in model.parameters():
  lowerCAmelCase__      :							Optional[int]    =							value






class  __a				(	__magic_name__					):





       """simple docstring"""


       def __init__(      self ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				):





        """simple docstring"""

        super().__init__()
        self.register_modules(
            vae=snake_case ,				text_encoder=snake_case ,				clip_model=snake_case ,				tokenizer=snake_case ,				unet=snake_case ,				scheduler=snake_case ,				feature_extractor=snake_case ,				)

        lowerCAmelCase__      :							List[Any]    =							transforms.Normalize(mean=feature_extractor.image_mean ,				std=feature_extractor.image_std      )
        lowerCAmelCase__      :							str    =							(
            feature_extractor.size
            if isinstance(feature_extractor.size ,				snake_case      )
            else feature_extractor.size["shortest_edge"]
        )
        lowerCAmelCase__      :							Tuple    =							MakeCutouts(self.cut_out_size      )

        set_requires_grad(self.text_encoder ,				snake_case      )
        set_requires_grad(self.clip_model ,				snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case = "auto"      ):





        """simple docstring"""

        if slice_size == "auto":
         # half the attention head size is usually a good trade-off between
         # speed and memory
         lowerCAmelCase__      :							int    =							self.unet.config.attention_head_dim // 2
        self.unet.set_attention_slice(snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        self.enable_attention_slicing(snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        set_requires_grad(self.vae ,				snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        set_requires_grad(self.vae ,				snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        set_requires_grad(self.unet ,				snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        set_requires_grad(self.unet ,				snake_case      )






       @torch.enable_grad()
       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case=True ,				):





        """simple docstring"""

        lowerCAmelCase__      :							int    =							latents.detach().requires_grad_()

        lowerCAmelCase__      :							List[Any]    =							self.scheduler.scale_model_input(snake_case ,				snake_case      )

        # predict the noise residual
        lowerCAmelCase__      :							int    =							self.unet(snake_case ,				snake_case ,				encoder_hidden_states=snake_case      ).sample

        if isinstance(self.scheduler ,				(PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)      ):
         lowerCAmelCase__      :							List[str]    =							self.scheduler.alphas_cumprod[timestep]
         lowerCAmelCase__      :							Union[str, Any]    =							1 - alpha_prod_t
         # compute predicted original sample from predicted noise also called
         # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
         lowerCAmelCase__      :							Union[str, Any]    =							(latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

         lowerCAmelCase__      :							str    =							torch.sqrt(snake_case      )
         lowerCAmelCase__      :							Optional[int]    =							pred_original_sample * (fac) + latents * (1 - fac)
        elif isinstance(self.scheduler ,				snake_case      ):
         lowerCAmelCase__      :							Optional[int]    =							self.scheduler.sigmas[index]
         lowerCAmelCase__      :							Optional[int]    =							latents - sigma * noise_pred
        else:
         raise ValueError(F"""scheduler type {type(self.scheduler      )} not supported"""      )

        lowerCAmelCase__      :							str    =							1 / self.vae.config.scaling_factor * sample
        lowerCAmelCase__      :							Any    =							self.vae.decode(snake_case      ).sample
        lowerCAmelCase__      :							Tuple    =							(image / 2 + 0.5).clamp(0 ,				1      )

        if use_cutouts:
         lowerCAmelCase__      :							List[str]    =							self.make_cutouts(snake_case ,				snake_case      )
        else:
         lowerCAmelCase__      :							List[str]    =							transforms.Resize(self.cut_out_size      )(snake_case      )
        lowerCAmelCase__      :							Dict    =							self.normalize(snake_case      ).to(latents.dtype      )

        lowerCAmelCase__      :							Any    =							self.clip_model.get_image_features(snake_case      )
        lowerCAmelCase__      :							List[Any]    =							image_embeddings_clip / image_embeddings_clip.norm(p=2 ,				dim=-1 ,				keepdim=snake_case      )

        if use_cutouts:
         lowerCAmelCase__      :							Union[str, Any]    =							spherical_dist_loss(snake_case ,				snake_case      )
         lowerCAmelCase__      :							Union[str, Any]    =							dists.view([num_cutouts, sample.shape[0], -1]      )
         lowerCAmelCase__      :							Optional[int]    =							dists.sum(2      ).mean(0      ).sum() * clip_guidance_scale
        else:
         lowerCAmelCase__      :							Optional[int]    =							spherical_dist_loss(snake_case ,				snake_case      ).mean() * clip_guidance_scale

        lowerCAmelCase__      :							int    =							-torch.autograd.grad(snake_case ,				snake_case      )[0]

        if isinstance(self.scheduler ,				snake_case      ):
         lowerCAmelCase__      :							Dict    =							latents.detach() + grads * (sigma**2)
         lowerCAmelCase__      :							Optional[Any]    =							noise_pred_original
        else:
         lowerCAmelCase__      :							str    =							noise_pred_original - torch.sqrt(snake_case      ) * grads
        return noise_pred, latents






       @torch.no_grad()
       def __call__(      self ,				snake_case ,				snake_case = 512 ,				snake_case = 512 ,				snake_case = 50 ,				snake_case = 7.5 ,				snake_case = 1 ,				snake_case = 0.0 ,				snake_case = 100 ,				snake_case = None ,				snake_case = 4 ,				snake_case = True ,				snake_case = None ,				snake_case = None ,				snake_case = "pil" ,				snake_case = True ,				):





        """simple docstring"""

        if isinstance(snake_case ,				snake_case      ):
         lowerCAmelCase__      :							List[str]    =							1
        elif isinstance(snake_case ,				snake_case      ):
         lowerCAmelCase__      :							List[str]    =							len(snake_case      )
        else:
         raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(snake_case      )}"""      )

        if height % 8 != 0 or width % 8 != 0:
         raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}."""      )

        # get prompt text embeddings
        lowerCAmelCase__      :							str    =							self.tokenizer(
            snake_case ,				padding="max_length" ,				max_length=self.tokenizer.model_max_length ,				truncation=snake_case ,				return_tensors="pt" ,				)
        lowerCAmelCase__      :							Optional[Any]    =							self.text_encoder(text_input.input_ids.to(self.device      )      )[0]
        # duplicate text embeddings for each generation per prompt
        lowerCAmelCase__      :							List[Any]    =							text_embeddings.repeat_interleave(snake_case ,				dim=0      )

        if clip_guidance_scale > 0:
         if clip_prompt is not None:
          lowerCAmelCase__      :							str    =							self.tokenizer(
              snake_case ,				padding="max_length" ,				max_length=self.tokenizer.model_max_length ,				truncation=snake_case ,				return_tensors="pt" ,				).input_ids.to(self.device      )
         else:
          lowerCAmelCase__      :							str    =							text_input.input_ids.to(self.device      )
         lowerCAmelCase__      :							Optional[Any]    =							self.clip_model.get_text_features(snake_case      )
         lowerCAmelCase__      :							List[str]    =							text_embeddings_clip / text_embeddings_clip.norm(p=2 ,				dim=-1 ,				keepdim=snake_case      )
         # duplicate text embeddings clip for each generation per prompt
         lowerCAmelCase__      :							Optional[Any]    =							text_embeddings_clip.repeat_interleave(snake_case ,				dim=0      )

        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
        # corresponds to doing no classifier free guidance.
        lowerCAmelCase__      :							int    =							guidance_scale > 1.0
        # get unconditional embeddings for classifier free guidance
        if do_classifier_free_guidance:
         lowerCAmelCase__      :							Union[str, Any]    =							text_input.input_ids.shape[-1]
         lowerCAmelCase__      :							Dict    =							self.tokenizer([""] ,				padding="max_length" ,				max_length=snake_case ,				return_tensors="pt"      )
         lowerCAmelCase__      :							List[str]    =							self.text_encoder(uncond_input.input_ids.to(self.device      )      )[0]
         # duplicate unconditional embeddings for each generation per prompt
         lowerCAmelCase__      :							List[str]    =							uncond_embeddings.repeat_interleave(snake_case ,				dim=0      )

         # For classifier free guidance, we need to do two forward passes.
         # Here we concatenate the unconditional and text embeddings into a single batch
         # to avoid doing two forward passes
         lowerCAmelCase__      :							Dict    =							torch.cat([uncond_embeddings, text_embeddings]      )

        # get the initial random noise unless the user supplied it

        # Unlike in other pipelines, latents need to be generated in the target device
        # for 1-to-1 results reproducibility with the CompVis implementation.
        # However this currently doesn't work in `mps`.
        lowerCAmelCase__      :							Any    =							(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
        lowerCAmelCase__      :							Dict    =							text_embeddings.dtype
        if latents is None:
         if self.device.type == "mps":
          # randn does not work reproducibly on mps
          lowerCAmelCase__      :							Tuple    =							torch.randn(snake_case ,				generator=snake_case ,				device="cpu" ,				dtype=snake_case      ).to(
              self.device      )
         else:
          lowerCAmelCase__      :							Any    =							torch.randn(snake_case ,				generator=snake_case ,				device=self.device ,				dtype=snake_case      )
        else:
         if latents.shape != latents_shape:
          raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""      )
         lowerCAmelCase__      :							Union[str, Any]    =							latents.to(self.device      )

        # set timesteps
        lowerCAmelCase__      :							Union[str, Any]    =							"offset" in set(inspect.signature(self.scheduler.set_timesteps      ).parameters.keys()      )
        lowerCAmelCase__      :							Dict    =							{}
        if accepts_offset:
         lowerCAmelCase__      :							List[str]    =							1

        self.scheduler.set_timesteps(snake_case ,				**snake_case      )

        # Some schedulers like PNDM have timesteps as arrays
        # It's more optimized to move all timesteps to correct device beforehand
        lowerCAmelCase__      :							Dict    =							self.scheduler.timesteps.to(self.device      )

        # scale the initial noise by the standard deviation required by the scheduler
        lowerCAmelCase__      :							Union[str, Any]    =							latents * self.scheduler.init_noise_sigma

        # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
        # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
        # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
        # and should be between [0, 1]
        lowerCAmelCase__      :							Optional[int]    =							"eta" in set(inspect.signature(self.scheduler.step      ).parameters.keys()      )
        lowerCAmelCase__      :							List[str]    =							{}
        if accepts_eta:
         lowerCAmelCase__      :							Dict    =							eta

        # check if the scheduler accepts generator
        lowerCAmelCase__      :							Any    =							"generator" in set(inspect.signature(self.scheduler.step      ).parameters.keys()      )
        if accepts_generator:
         lowerCAmelCase__      :							Tuple    =							generator

        for i, t in enumerate(self.progress_bar(snake_case      )      ):
         # expand the latents if we are doing classifier free guidance
         lowerCAmelCase__      :							str    =							torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
         lowerCAmelCase__      :							Tuple    =							self.scheduler.scale_model_input(snake_case ,				snake_case      )

         # predict the noise residual
         lowerCAmelCase__      :							Tuple    =							self.unet(snake_case ,				snake_case ,				encoder_hidden_states=snake_case      ).sample

         # perform classifier free guidance
         if do_classifier_free_guidance:
          lowerCAmelCase__ ,	lowerCAmelCase__      :							Optional[Any]    =							noise_pred.chunk(2      )
          lowerCAmelCase__      :							int    =							noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

         # perform clip guidance
         if clip_guidance_scale > 0:
          lowerCAmelCase__      :							Optional[Any]    =							(
              text_embeddings.chunk(2      )[1] if do_classifier_free_guidance else text_embeddings
          )
          lowerCAmelCase__ ,	lowerCAmelCase__      :							Optional[Any]    =							self.cond_fn(
              snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				snake_case ,				)

         # compute the previous noisy sample x_t -> x_t-1
         lowerCAmelCase__      :							str    =							self.scheduler.step(snake_case ,				snake_case ,				snake_case ,				**snake_case      ).prev_sample

        # scale and decode the image latents with vae
        lowerCAmelCase__      :							Tuple    =							1 / self.vae.config.scaling_factor * latents
        lowerCAmelCase__      :							int    =							self.vae.decode(snake_case      ).sample

        lowerCAmelCase__      :							int    =							(image / 2 + 0.5).clamp(0 ,				1      )
        lowerCAmelCase__      :							List[str]    =							image.cpu().permute(0 ,				2 ,				3 ,				1      ).numpy()

        if output_type == "pil":
         lowerCAmelCase__      :							Dict    =							self.numpy_to_pil(snake_case      )

        if not return_dict:
         return (image, None)

        return StableDiffusionPipelineOutput(images=snake_case ,				nsfw_content_detected=snake_case      )









"""simple docstring"""

import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, 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 EfficientNetForImageClassification, EfficientNetModel
    from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor






class  __a				:





       """simple docstring"""


       def __init__(      self ,				snake_case ,				snake_case=13 ,				snake_case=32 ,				snake_case=3 ,				snake_case=[3, 3, 5] ,				snake_case=[32, 16, 24] ,				snake_case=[16, 24, 40] ,				snake_case=[1, 1, 2] ,				snake_case=[1, 1, 2] ,				snake_case=[1, 6, 6] ,				snake_case=True ,				snake_case=True ,				snake_case=37 ,				snake_case="gelu" ,				snake_case=10 ,				):





        """simple docstring"""

        lowerCAmelCase__      :							str    =							parent
        lowerCAmelCase__      :							int    =							batch_size
        lowerCAmelCase__      :							Dict    =							image_size
        lowerCAmelCase__      :							str    =							num_channels
        lowerCAmelCase__      :							Union[str, Any]    =							kernel_sizes
        lowerCAmelCase__      :							int    =							in_channels
        lowerCAmelCase__      :							Dict    =							out_channels
        lowerCAmelCase__      :							str    =							strides
        lowerCAmelCase__      :							int    =							num_block_repeats
        lowerCAmelCase__      :							str    =							expand_ratios
        lowerCAmelCase__      :							List[Any]    =							is_training
        lowerCAmelCase__      :							Any    =							hidden_act
        lowerCAmelCase__      :							Any    =							num_labels
        lowerCAmelCase__      :							int    =							use_labels






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Dict    =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

        lowerCAmelCase__      :							List[str]    =							None
        if self.use_labels:
         lowerCAmelCase__      :							int    =							ids_tensor([self.batch_size] ,				self.num_labels      )

        lowerCAmelCase__      :							List[str]    =							self.get_config()
        return config, pixel_values, labels






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        return EfficientNetConfig(
            num_channels=self.num_channels ,				kernel_sizes=self.kernel_sizes ,				in_channels=self.in_channels ,				out_channels=self.out_channels ,				strides=self.strides ,				num_block_repeats=self.num_block_repeats ,				expand_ratios=self.expand_ratios ,				hidden_act=self.hidden_act ,				num_labels=self.num_labels ,				)






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case ,				snake_case      ):





        """simple docstring"""

        lowerCAmelCase__      :							Union[str, Any]    =							EfficientNetModel(config=snake_case      )
        model.to(snake_case      )
        model.eval()
        lowerCAmelCase__      :							Tuple    =							model(snake_case      )
        # expected last hidden states: B, C, H // 4, W // 4
        self.parent.assertEqual(
            result.last_hidden_state.shape ,				(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4) ,				)






       def  SCREAMING_SNAKE_CASE_  (      self ,				snake_case ,				snake_case ,				snake_case      ):





        """simple docstring"""

        lowerCAmelCase__      :							int    =							EfficientNetForImageClassification(snake_case      )
        model.to(snake_case      )
        model.eval()
        lowerCAmelCase__      :							str    =							model(snake_case ,				labels=snake_case      )
        self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							str    =							self.prepare_config_and_inputs()
        lowerCAmelCase__ ,	lowerCAmelCase__ ,	lowerCAmelCase__      :							Dict    =							config_and_inputs
        lowerCAmelCase__      :							Dict    =							{"pixel_values": pixel_values}
        return config, inputs_dict






@require_torch
class  __a				(	__magic_name__					,  __magic_name__					,  unittest.TestCase					):





       """simple docstring"""


       __UpperCamelCase				:			Any          =	(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
       __UpperCamelCase				:			Dict          =	(
           {'feature-extraction': EfficientNetModel, 'image-classification': EfficientNetForImageClassification}
           if is_torch_available()
           else {}
       )

       __UpperCamelCase				:			str          =	False
       __UpperCamelCase				:			List[Any]          =	False
       __UpperCamelCase				:			Dict          =	False
       __UpperCamelCase				:			Optional[int]          =	False
       __UpperCamelCase				:			List[Any]          =	False






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							List[str]    =							EfficientNetModelTester(self      )
        lowerCAmelCase__      :							Tuple    =							ConfigTester(
            self ,				config_class=snake_case ,				has_text_modality=snake_case ,				hidden_size=37      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

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





        """simple docstring"""

        return






       @unittest.skip(reason="EfficientNet does not use inputs_embeds"      )
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        pass






       @unittest.skip(reason="EfficientNet does not support input and output embeddings"      )
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        pass






       @unittest.skip(reason="EfficientNet does not use feedforward chunking"      )
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        pass






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__ ,	lowerCAmelCase__      :							List[Any]    =							self.model_tester.prepare_config_and_inputs_for_common()

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

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






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							List[Any]    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        def check_hidden_states_output(snake_case ,				snake_case ,				snake_case      ):
         lowerCAmelCase__      :							Tuple    =							model_class(snake_case      )
         model.to(snake_case      )
         model.eval()

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

         lowerCAmelCase__      :							Tuple    =							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
         lowerCAmelCase__      :							Any    =							sum(config.num_block_repeats      ) * 4
         self.assertEqual(len(snake_case      ) ,				snake_case      )

         # EfficientNet'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] ,				)

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

        for model_class in self.all_model_classes:
         lowerCAmelCase__      :							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"]
         lowerCAmelCase__      :							Tuple    =							True

         check_hidden_states_output(snake_case ,				snake_case ,				snake_case      )






       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Optional[Any]    =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*snake_case      )






       @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."      )
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        pass






       @slow
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCAmelCase__      :							str    =							EfficientNetModel.from_pretrained(snake_case      )
         self.assertIsNotNone(snake_case      )






       @is_pipeline_test
       @require_vision
       @slow
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        super().test_pipeline_image_classification()




def 			SCREAMING_SNAKE_CASE       (   ) ->	Dict:
 lowerCAmelCase__      :							List[Any]    =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
 return image






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





       """simple docstring"""


       @cached_property
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        return AutoImageProcessor.from_pretrained("google/efficientnet-b7"      ) if is_vision_available() else None






       @slow
       def  SCREAMING_SNAKE_CASE_  (      self      ):





        """simple docstring"""

        lowerCAmelCase__      :							Optional[Any]    =							EfficientNetForImageClassification.from_pretrained("google/efficientnet-b7"      ).to(snake_case      )

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

        # forward pass
        with torch.no_grad():
         lowerCAmelCase__      :							str    =							model(**snake_case      )

        # verify the logits
        lowerCAmelCase__      :							Any    =							torch.Size((1, 1_000)      )
        self.assertEqual(outputs.logits.shape ,				snake_case      )

        lowerCAmelCase__      :							Union[str, Any]    =							torch.tensor([0.0_001, 0.0_002, 0.0_002]      ).to(snake_case      )
        self.assertTrue(torch.allclose(outputs.logits[0, :3] ,				snake_case ,				atol=1e-4      )      )






