
"""simple docstring"""




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference

class 						a__		( __a,     unittest.TestCase		):
   __lowerCAmelCase				=							ShapEPipeline
   __lowerCAmelCase				=							['prompt']
   __lowerCAmelCase				=							['prompt']
   __lowerCAmelCase				=							[
       'num_images_per_prompt',
       'num_inference_steps',
       'generator',
       'latents',
       'guidance_scale',
       'frame_size',
       'output_type',
       'return_dict',
   ]
   __lowerCAmelCase				=							False
   @property
   def      __magic_name__     (     self							):
          return 32
   @property
   def      __magic_name__     (     self							):
          return 32
   @property
   def      __magic_name__     (     self							):
          return self.time_input_dim * 4
   @property
   def      __magic_name__     (     self							):
          return 8
   @property
   def      __magic_name__     (     self							):
          lowercase       :							Dict									=				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"							)
          return tokenizer
   @property
   def      __magic_name__     (     self							):
          torch.manual_seed(0							)
          lowercase       :							Optional[int]									=				CLIPTextConfig(
              bos_token_id=0      ,       eos_token_id=2      ,       hidden_size=self.text_embedder_hidden_size      ,       projection_dim=self.text_embedder_hidden_size      ,       intermediate_size=37      ,       layer_norm_eps=1E-05      ,       num_attention_heads=4      ,       num_hidden_layers=5      ,       pad_token_id=1      ,       vocab_size=1_000      ,       )
          return CLIPTextModelWithProjection(_lowerCamelCase							)
   @property
   def      __magic_name__     (     self							):
          torch.manual_seed(0							)

          lowercase       :							Optional[Any]									=				{
              "num_attention_heads": 2,
              "attention_head_dim": 16,
              "embedding_dim": self.time_input_dim,
              "num_embeddings": 32,
              "embedding_proj_dim": self.text_embedder_hidden_size,
              "time_embed_dim": self.time_embed_dim,
              "num_layers": 1,
              "clip_embed_dim": self.time_input_dim * 2,
              "additional_embeddings": 0,
              "time_embed_act_fn": "gelu",
              "norm_in_type": "layer",
              "encoder_hid_proj_type": None,
              "added_emb_type": None,
          }

          lowercase       :							Optional[Any]									=				PriorTransformer(**_lowerCamelCase							)
          return model
   @property
   def      __magic_name__     (     self							):
          torch.manual_seed(0							)

          lowercase       :							List[Any]									=				{
              "param_shapes": (
                  (self.renderer_dim, 93),
                  (self.renderer_dim, 8),
                  (self.renderer_dim, 8),
                  (self.renderer_dim, 8),
              ),
              "d_latent": self.time_input_dim,
              "d_hidden": self.renderer_dim,
              "n_output": 12,
              "background": (
                  0.1,
                  0.1,
                  0.1,
              ),
          }
          lowercase       :							List[str]									=				ShapERenderer(**_lowerCamelCase							)
          return model
   def      __magic_name__     (     self							):
          lowercase       :							str									=				self.dummy_prior
          lowercase       :							List[Any]									=				self.dummy_text_encoder
          lowercase       :							str									=				self.dummy_tokenizer
          lowercase       :							Optional[int]									=				self.dummy_renderer

          lowercase       :							List[Any]									=				HeunDiscreteScheduler(
              beta_schedule="exp"      ,       num_train_timesteps=1_024      ,       prediction_type="sample"      ,       use_karras_sigmas=_lowerCamelCase      ,       clip_sample=_lowerCamelCase      ,       clip_sample_range=1.0      ,       )
          lowercase       :							Optional[Any]									=				{
              "prior": prior,
              "text_encoder": text_encoder,
              "tokenizer": tokenizer,
              "renderer": renderer,
              "scheduler": scheduler,
          }

          return components
   def      __magic_name__     (     self      ,       _a      ,       _a=0							):
          if str(_lowerCamelCase							).startswith("mps"							):
                 lowercase       :							Dict									=				torch.manual_seed(_lowerCamelCase							)
          else:
                 lowercase       :							str									=				torch.Generator(device=_lowerCamelCase							).manual_seed(_lowerCamelCase							)
          lowercase       :							List[Any]									=				{
              "prompt": "horse",
              "generator": generator,
              "num_inference_steps": 1,
              "frame_size": 32,
              "output_type": "np",
          }
          return inputs
   def      __magic_name__     (     self							):
          lowercase       :							str									=				"cpu"

          lowercase       :							Union[str, Any]									=				self.get_dummy_components()

          lowercase       :							int									=				self.pipeline_class(**_lowerCamelCase							)
          lowercase       :							List[str]									=				pipe.to(_lowerCamelCase							)

          pipe.set_progress_bar_config(disable=_lowerCamelCase							)

          lowercase       :							int									=				pipe(**self.get_dummy_inputs(_lowerCamelCase							)							)
          lowercase       :							int									=				output.images[0]
          lowercase       :							List[str]									=				image[0, -3:, -3:, -1]

          assert image.shape == (20, 32, 32, 3)

          lowercase       :							Tuple									=				np.array(
              [
                  0.0_0_0_3_9_2_1_6,
                  0.0_0_0_3_9_2_1_6,
                  0.0_0_0_3_9_2_1_6,
                  0.0_0_0_3_9_2_1_6,
                  0.0_0_0_3_9_2_1_6,
                  0.0_0_0_3_9_2_1_6,
                  0.0_0_0_3_9_2_1_6,
                  0.0_0_0_3_9_2_1_6,
                  0.0_0_0_3_9_2_1_6,
              ]							)

          assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
   def      __magic_name__     (     self							):
          # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
          self._test_inference_batch_consistent(batch_sizes=[1, 2]							)
   def      __magic_name__     (     self							):
          lowercase       :							int									=				torch_device == "cpu"
          lowercase       :							Optional[int]									=				True

          self._test_inference_batch_single_identical(
              batch_size=2      ,       test_max_difference=_lowerCamelCase      ,       relax_max_difference=_lowerCamelCase      ,       )

   def      __magic_name__     (     self							):
          lowercase       :							Any									=				self.get_dummy_components()
          lowercase       :							Optional[Any]									=				self.pipeline_class(**_lowerCamelCase							)
          lowercase       :							str									=				pipe.to(_lowerCamelCase							)
          pipe.set_progress_bar_config(disable=_lowerCamelCase							)

          lowercase       :							List[str]									=				1
          lowercase       :							List[str]									=				2

          lowercase       :							Dict									=				self.get_dummy_inputs(_lowerCamelCase							)

          for key in inputs.keys():
                 if key in self.batch_params:
                        lowercase       :							List[Any]									=				batch_size * [inputs[key]]

          lowercase       :							int									=				pipe(**_lowerCamelCase      ,       num_images_per_prompt=_lowerCamelCase							)[0]

          assert images.shape[0] == batch_size * num_images_per_prompt


@slow
@require_torch_gpu
class 						a__		( unittest.TestCase		):
   def      __magic_name__     (     self							):
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()

   def      __magic_name__     (     self							):
          lowercase       :							List[str]									=				load_numpy(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
              "/shap_e/test_shap_e_np_out.npy"							)
          lowercase       :							Any									=				ShapEPipeline.from_pretrained("openai/shap-e"							)
          lowercase       :							Any									=				pipe.to(_lowerCamelCase							)
          pipe.set_progress_bar_config(disable=_lowerCamelCase							)

          lowercase       :							Dict									=				torch.Generator(device=_lowerCamelCase							).manual_seed(0							)

          lowercase       :							Union[str, Any]									=				pipe(
              "a shark"      ,       generator=_lowerCamelCase      ,       guidance_scale=1_5.0      ,       num_inference_steps=64      ,       frame_size=64      ,       output_type="np"      ,       ).images[0]

          assert images.shape == (20, 64, 64, 3)

          assert_mean_pixel_difference(_lowerCamelCase      ,       _lowerCamelCase							)



'''simple docstring'''

from collections import OrderedDict
from typing import List, Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A_     :						Tuple    							=logging.get_logger(__name__)

A_     :						Dict    							={
    '''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''',
}


class     __UpperCAmelCase       ( __a		):
  __A :				Union[str, Any]											= 'efficientnet'





  def __init__(	self    ,     _lowerCamelCase = 3    ,     _lowerCamelCase = 600    ,     _lowerCamelCase = 2.0    ,     _lowerCamelCase = 3.1    ,     _lowerCamelCase = 8    ,     _lowerCamelCase = [3, 3, 5, 3, 5, 5, 3]    ,     _lowerCamelCase = [32, 16, 24, 40, 80, 112, 192]    ,     _lowerCamelCase = [16, 24, 40, 80, 112, 192, 320]    ,     _lowerCamelCase = []    ,     _lowerCamelCase = [1, 2, 2, 2, 1, 2, 1]    ,     _lowerCamelCase = [1, 2, 2, 3, 3, 4, 1]    ,     _lowerCamelCase = [1, 6, 6, 6, 6, 6, 6]    ,     _lowerCamelCase = 0.25    ,     _lowerCamelCase = "swish"    ,     _lowerCamelCase = 2560    ,     _lowerCamelCase = "mean"    ,     _lowerCamelCase = 0.02    ,     _lowerCamelCase = 0.0_01    ,     _lowerCamelCase = 0.99    ,     _lowerCamelCase = 0.5    ,     _lowerCamelCase = 0.2    ,     **_lowerCamelCase    ,     ):
     super().__init__(**_lowerCamelCase )

     lowerCAmelCase_			=      num_channels
     lowerCAmelCase_			=      image_size
     lowerCAmelCase_			=      width_coefficient
     lowerCAmelCase_			=      depth_coefficient
     lowerCAmelCase_			=      depth_divisor
     lowerCAmelCase_			=      kernel_sizes
     lowerCAmelCase_			=      in_channels
     lowerCAmelCase_			=      out_channels
     lowerCAmelCase_			=      depthwise_padding
     lowerCAmelCase_			=      strides
     lowerCAmelCase_			=      num_block_repeats
     lowerCAmelCase_			=      expand_ratios
     lowerCAmelCase_			=      squeeze_expansion_ratio
     lowerCAmelCase_			=      hidden_act
     lowerCAmelCase_			=      hidden_dim
     lowerCAmelCase_			=      pooling_type
     lowerCAmelCase_			=      initializer_range
     lowerCAmelCase_			=      batch_norm_eps
     lowerCAmelCase_			=      batch_norm_momentum
     lowerCAmelCase_			=      dropout_rate
     lowerCAmelCase_			=      drop_connect_rate
     lowerCAmelCase_			=      sum(_lowerCamelCase ) * 4






class     __UpperCAmelCase       ( __a		):
  __A :				str											= version.parse('1.11'		)





  @property
  def 						UpperCAmelCase_	(	self ):
     return OrderedDict(
         [
             ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
         ] )







  @property
  def 						UpperCAmelCase_	(	self ):
     return 1E-5





