






import collections.abc
from typing import Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig


UpperCAmelCase__				   =		logging.get_logger(__name__)

# General docstring
UpperCAmelCase__				   =		"PoolFormerConfig"

# Base docstring
UpperCAmelCase__				   =		"sail/poolformer_s12"
UpperCAmelCase__				   =		[1, 512, 7, 7]

# Image classification docstring
UpperCAmelCase__				   =		"sail/poolformer_s12"
UpperCAmelCase__				   =		"tabby, tabby cat"

UpperCAmelCase__				   =		[
    "sail/poolformer_s12",
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]
def 						_a    (      a :Dict	,							a :float = 0.0	,							a :bool = False )							->			Optional[Any]:
 if drop_prob == 0.0 or not training:
  return input
 a		  =      1 - drop_prob
 a		  =      (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
 a		  =      keep_prob + torch.rand(a	,							dtype=input.dtype	,							device=input.device )
 random_tensor.floor_()  # binarize
 a		  =      input.div(a ) * random_tensor
 return output






class 		lowercase_					(	nn.Module   ):






      '''simple docstring'''




      def __init__(      self      :						int ,					__UpperCAmelCase      :						Optional[float] = None  )    ->None:




       """simple docstring"""


       super().__init__()
       a		  =      drop_prob







      def       __lowerCAmelCase					(      self      :						Optional[Any] ,					__UpperCAmelCase      :						torch.Tensor  )    ->torch.Tensor:




       """simple docstring"""


       return drop_path(__UpperCAmelCase ,					self.drop_prob ,					self.training  )







      def       __lowerCAmelCase					(      self      :						int  )    ->str:




       """simple docstring"""


       return "p={}".format(self.drop_prob  )






class 		lowercase_					(	nn.Module   ):






      '''simple docstring'''




      def __init__(      self      :						List[Any] ,					__UpperCAmelCase      :						Optional[int] ,					__UpperCAmelCase      :						Optional[int] ,					__UpperCAmelCase      :						str ,					__UpperCAmelCase      :						str ,					__UpperCAmelCase      :						int ,					__UpperCAmelCase      :						Any=None  )    ->int:




       """simple docstring"""


       super().__init__()
       a		  =      patch_size if isinstance(__UpperCAmelCase ,					collections.abc.Iterable  ) else (patch_size, patch_size)
       a		  =      stride if isinstance(__UpperCAmelCase ,					collections.abc.Iterable  ) else (stride, stride)
       a		  =      padding if isinstance(__UpperCAmelCase ,					collections.abc.Iterable  ) else (padding, padding)

       a		  =      nn.Convad(__UpperCAmelCase ,					__UpperCAmelCase ,					kernel_size=__UpperCAmelCase ,					stride=__UpperCAmelCase ,					padding=__UpperCAmelCase  )
       a		  =      norm_layer(__UpperCAmelCase  ) if norm_layer else nn.Identity()







      def       __lowerCAmelCase					(      self      :						int ,					__UpperCAmelCase      :						Optional[int]  )    ->List[str]:




       """simple docstring"""


       a		  =      self.projection(__UpperCAmelCase  )
       a		  =      self.norm(__UpperCAmelCase  )
       return embeddings






class 		lowercase_					(	nn.GroupNorm   ):






      '''simple docstring'''




      def __init__(      self      :						List[Any] ,					__UpperCAmelCase      :						Union[str, Any] ,					**__UpperCAmelCase      :						Union[str, Any]  )    ->Dict:




       """simple docstring"""


       super().__init__(1 ,					__UpperCAmelCase ,					**__UpperCAmelCase  )






class 		lowercase_					(	nn.Module   ):






      '''simple docstring'''




      def __init__(      self      :						int ,					__UpperCAmelCase      :						Optional[Any]  )    ->List[Any]:




       """simple docstring"""


       super().__init__()
       a		  =      nn.AvgPoolad(__UpperCAmelCase ,					stride=1 ,					padding=pool_size // 2 ,					count_include_pad=__UpperCAmelCase  )







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




       """simple docstring"""


       return self.pool(__UpperCAmelCase  ) - hidden_states






class 		lowercase_					(	nn.Module   ):






      '''simple docstring'''




      def __init__(      self      :						Dict ,					__UpperCAmelCase      :						Dict ,					__UpperCAmelCase      :						List[str] ,					__UpperCAmelCase      :						int ,					__UpperCAmelCase      :						Dict  )    ->List[Any]:




       """simple docstring"""


       super().__init__()
       a		  =      nn.Convad(__UpperCAmelCase ,					__UpperCAmelCase ,					1  )
       a		  =      nn.Convad(__UpperCAmelCase ,					__UpperCAmelCase ,					1  )
       a		  =      PoolFormerDropPath(__UpperCAmelCase  )
       if isinstance(config.hidden_act ,					__UpperCAmelCase  ):
        a		  =      ACTaFN[config.hidden_act]
       else:
        a		  =      config.hidden_act







      def       __lowerCAmelCase					(      self      :						int ,					__UpperCAmelCase      :						Optional[int]  )    ->List[Any]:




       """simple docstring"""


       a		  =      self.conva(__UpperCAmelCase  )
       a		  =      self.act_fn(__UpperCAmelCase  )
       a		  =      self.drop(__UpperCAmelCase  )
       a		  =      self.conva(__UpperCAmelCase  )
       a		  =      self.drop(__UpperCAmelCase  )

       return hidden_states






class 		lowercase_					(	nn.Module   ):






      '''simple docstring'''




      def __init__(      self      :						int ,					__UpperCAmelCase      :						str ,					__UpperCAmelCase      :						Dict ,					__UpperCAmelCase      :						List[str] ,					__UpperCAmelCase      :						str ,					__UpperCAmelCase      :						Tuple ,					__UpperCAmelCase      :						Tuple  )    ->int:




       """simple docstring"""


       super().__init__()
       a		  =      PoolFormerPooling(__UpperCAmelCase  )
       a		  =      PoolFormerOutput(__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase  )
       a		  =      PoolFormerGroupNorm(__UpperCAmelCase  )
       a		  =      PoolFormerGroupNorm(__UpperCAmelCase  )

       # Useful for training neural nets
       a		  =      PoolFormerDropPath(__UpperCAmelCase  ) if drop_path > 0.0 else nn.Identity()
       a		  =      config.use_layer_scale
       if config.use_layer_scale:
        a		  =      nn.Parameter(
            config.layer_scale_init_value * torch.ones((__UpperCAmelCase)  ) ,					requires_grad=__UpperCAmelCase  )
        a		  =      nn.Parameter(
            config.layer_scale_init_value * torch.ones((__UpperCAmelCase)  ) ,					requires_grad=__UpperCAmelCase  )







      def       __lowerCAmelCase					(      self      :						Any ,					__UpperCAmelCase      :						Dict  )    ->Any:




       """simple docstring"""


       if self.use_layer_scale:
        a		  =      self.pooling(self.before_norm(__UpperCAmelCase  )  )
        a		  =      self.layer_scale_a.unsqueeze(-1  ).unsqueeze(-1  ) * pooling_output
        # First residual connection
        a		  =      hidden_states + self.drop_path(__UpperCAmelCase  )
        a		  =      ()

        a		  =      self.output(self.after_norm(__UpperCAmelCase  )  )
        a		  =      self.layer_scale_a.unsqueeze(-1  ).unsqueeze(-1  ) * layer_output
        # Second residual connection
        a		  =      hidden_states + self.drop_path(__UpperCAmelCase  )

        a		  =      (output,) + outputs
        return outputs

       else:
        a		  =      self.drop_path(self.pooling(self.before_norm(__UpperCAmelCase  )  )  )
        # First residual connection
        a		  =      pooling_output + hidden_states
        a		  =      ()

        # Second residual connection inside the PoolFormerOutput block
        a		  =      self.drop_path(self.output(self.after_norm(__UpperCAmelCase  )  )  )
        a		  =      hidden_states + layer_output

        a		  =      (output,) + outputs
        return outputs






class 		lowercase_					(	nn.Module   ):






      '''simple docstring'''




      def __init__(      self      :						List[Any] ,					__UpperCAmelCase      :						Optional[int]  )    ->Dict:




       """simple docstring"""


       super().__init__()
       a		  =      config
       # stochastic depth decay rule
       a		  =      [x.item() for x in torch.linspace(0 ,					config.drop_path_rate ,					sum(config.depths  )  )]

       # patch embeddings
       a		  =      []
       for i in range(config.num_encoder_blocks  ):
        embeddings.append(
            PoolFormerEmbeddings(
                patch_size=config.patch_sizes[i] ,					stride=config.strides[i] ,					padding=config.padding[i] ,					num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] ,					hidden_size=config.hidden_sizes[i] ,					)  )
       a		  =      nn.ModuleList(__UpperCAmelCase  )

       # Transformer blocks
       a		  =      []
       a		  =      0
       for i in range(config.num_encoder_blocks  ):
        # each block consists of layers
        a		  =      []
        if i != 0:
         cur += config.depths[i - 1]
        for j in range(config.depths[i]  ):
         layers.append(
             PoolFormerLayer(
                 __UpperCAmelCase ,					num_channels=config.hidden_sizes[i] ,					pool_size=config.pool_size ,					hidden_size=config.hidden_sizes[i] ,					intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio  ) ,					drop_path=dpr[cur + j] ,					)  )
        blocks.append(nn.ModuleList(__UpperCAmelCase  )  )

       a		  =      nn.ModuleList(__UpperCAmelCase  )







      def       __lowerCAmelCase					(      self      :						List[Any] ,					__UpperCAmelCase      :						str ,					__UpperCAmelCase      :						Optional[Any]=False ,					__UpperCAmelCase      :						Tuple=True  )    ->Union[str, Any]:




       """simple docstring"""


       a		  =      () if output_hidden_states else None

       a		  =      pixel_values
       for idx, layers in enumerate(zip(self.patch_embeddings ,					self.block  )  ):
        a  ,     a		  =      layers
        # Get patch embeddings from hidden_states
        a		  =      embedding_layer(__UpperCAmelCase  )
        # Send the embeddings through the blocks
        for _, blk in enumerate(__UpperCAmelCase  ):
         a		  =      blk(__UpperCAmelCase  )
         a		  =      layer_outputs[0]

        if output_hidden_states:
         a		  =      all_hidden_states + (hidden_states,)

       if not return_dict:
        return tuple(v for v in [hidden_states, all_hidden_states] if v is not None  )

       return BaseModelOutputWithNoAttention(last_hidden_state=__UpperCAmelCase ,					hidden_states=__UpperCAmelCase  )






class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      __snake_case       =  PoolFormerConfig
      __snake_case       =  '''poolformer'''
      __snake_case       =  '''pixel_values'''
      __snake_case       =  True







      def       __lowerCAmelCase					(      self      :						List[str] ,					__UpperCAmelCase      :						List[str]  )    ->Optional[Any]:




       """simple docstring"""


       if isinstance(__UpperCAmelCase ,					(nn.Linear, nn.Convad)  ):
        module.weight.data.normal_(mean=0.0 ,					std=self.config.initializer_range  )
        if module.bias is not None:
         module.bias.data.zero_()
       elif isinstance(__UpperCAmelCase ,					nn.LayerNorm  ):
        module.bias.data.zero_()
        module.weight.data.fill_(1.0  )







      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						Tuple ,					__UpperCAmelCase      :						Union[str, Any]=False  )    ->int:




       """simple docstring"""


       if isinstance(__UpperCAmelCase ,					__UpperCAmelCase  ):
        a		  =      value
UpperCAmelCase__				   =		R"\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

UpperCAmelCase__				   =		R"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`PoolFormerImageProcessor.__call__`] for details.\n"






@add_start_docstrings(
    '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' ,  lowercase ,  )
class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      def __init__(      self      :						str ,					__UpperCAmelCase      :						int  )    ->Optional[Any]:




       """simple docstring"""


       super().__init__(__UpperCAmelCase  )
       a		  =      config

       a		  =      PoolFormerEncoder(__UpperCAmelCase  )

       # Initialize weights and apply final processing
       self.post_init()







      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->Union[str, Any]:




       """simple docstring"""


       return self.embeddings.patch_embeddings







      @add_start_docstrings_to_model_forward(__UpperCAmelCase  )
      @add_code_sample_docstrings(
          checkpoint=_CHECKPOINT_FOR_DOC ,					output_type=__UpperCAmelCase ,					config_class=_CONFIG_FOR_DOC ,					modality='''vision''' ,					expected_output=_EXPECTED_OUTPUT_SHAPE ,					)
      def       __lowerCAmelCase					(      self      :						str ,					__UpperCAmelCase      :						Optional[torch.FloatTensor] = None ,					__UpperCAmelCase      :						Optional[bool] = None ,					__UpperCAmelCase      :						Optional[bool] = None ,					)    ->Union[Tuple, BaseModelOutputWithNoAttention]:




       """simple docstring"""


       a		  =      (
           output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
       )
       a		  =      return_dict if return_dict is not None else self.config.use_return_dict

       if pixel_values is None:
        raise ValueError('''You have to specify pixel_values'''  )

       a		  =      self.encoder(
           __UpperCAmelCase ,					output_hidden_states=__UpperCAmelCase ,					return_dict=__UpperCAmelCase ,					)
       a		  =      encoder_outputs[0]

       if not return_dict:
        return (sequence_output, None) + encoder_outputs[1:]

       return BaseModelOutputWithNoAttention(
           last_hidden_state=__UpperCAmelCase ,					hidden_states=encoder_outputs.hidden_states ,					)






class 		lowercase_					(	nn.Module   ):






      '''simple docstring'''




      def __init__(      self      :						Optional[int] ,					__UpperCAmelCase      :						Dict  )    ->List[str]:




       """simple docstring"""


       super().__init__()
       a		  =      nn.Linear(config.hidden_size ,					config.hidden_size  )







      def       __lowerCAmelCase					(      self      :						int ,					__UpperCAmelCase      :						Optional[Any]  )    ->Union[str, Any]:




       """simple docstring"""


       a		  =      self.dense(__UpperCAmelCase  )
       return output






@add_start_docstrings(
    '''
    PoolFormer Model transformer with an image classification head on top
    ''' ,  lowercase ,  )
class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      def __init__(      self      :						Union[str, Any] ,					__UpperCAmelCase      :						List[str]  )    ->Any:




       """simple docstring"""


       super().__init__(__UpperCAmelCase  )
       a		  =      config.num_labels
       a		  =      PoolFormerModel(__UpperCAmelCase  )

       # Final norm
       a		  =      PoolFormerGroupNorm(config.hidden_sizes[-1]  )
       # Classifier head
       a		  =      (
           nn.Linear(config.hidden_sizes[-1] ,					config.num_labels  ) if config.num_labels > 0 else nn.Identity()
       )

       # Initialize weights and apply final processing
       self.post_init()







      @add_start_docstrings_to_model_forward(__UpperCAmelCase  )
      @add_code_sample_docstrings(
          checkpoint=_IMAGE_CLASS_CHECKPOINT ,					output_type=__UpperCAmelCase ,					config_class=_CONFIG_FOR_DOC ,					expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,					)
      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						Optional[torch.FloatTensor] = None ,					__UpperCAmelCase      :						Optional[torch.LongTensor] = None ,					__UpperCAmelCase      :						Optional[bool] = None ,					__UpperCAmelCase      :						Optional[bool] = None ,					)    ->Union[Tuple, ImageClassifierOutputWithNoAttention]:




       """simple docstring"""


       a		  =      return_dict if return_dict is not None else self.config.use_return_dict

       a		  =      self.poolformer(
           __UpperCAmelCase ,					output_hidden_states=__UpperCAmelCase ,					return_dict=__UpperCAmelCase ,					)

       a		  =      outputs[0]

       a		  =      self.classifier(self.norm(__UpperCAmelCase  ).mean([-2, -1]  )  )

       a		  =      None
       if labels is not None:
        if self.config.problem_type is None:
         if self.num_labels == 1:
          a		  =      '''regression'''
         elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
          a		  =      '''single_label_classification'''
         else:
          a		  =      '''multi_label_classification'''

        if self.config.problem_type == "regression":
         a		  =      MSELoss()
         if self.num_labels == 1:
          a		  =      loss_fct(logits.squeeze() ,					labels.squeeze()  )
         else:
          a		  =      loss_fct(__UpperCAmelCase ,					__UpperCAmelCase  )
        elif self.config.problem_type == "single_label_classification":
         a		  =      CrossEntropyLoss()
         a		  =      loss_fct(logits.view(-1 ,					self.num_labels  ) ,					labels.view(-1  )  )
        elif self.config.problem_type == "multi_label_classification":
         a		  =      BCEWithLogitsLoss()
         a		  =      loss_fct(__UpperCAmelCase ,					__UpperCAmelCase  )

       if not return_dict:
        a		  =      (logits,) + outputs[2:]
        return ((loss,) + output) if loss is not None else output

       return ImageClassifierOutputWithNoAttention(loss=__UpperCAmelCase ,					logits=__UpperCAmelCase ,					hidden_states=outputs.hidden_states  )










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 		lowercase_					(	lowercase ,  unittest.TestCase   ):






      '''simple docstring'''




      __snake_case       =  ShapEPipeline
      __snake_case       =  ['''prompt''']
      __snake_case       =  ['''prompt''']
      __snake_case       =  [
          '''num_images_per_prompt''',
          '''num_inference_steps''',
          '''generator''',
          '''latents''',
          '''guidance_scale''',
          '''frame_size''',
          '''output_type''',
          '''return_dict''',
      ]
      __snake_case       =  False







      @property
      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->Union[str, Any]:




       """simple docstring"""


       return 32







      @property
      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->List[str]:




       """simple docstring"""


       return 32







      @property
      def       __lowerCAmelCase					(      self      :						Any  )    ->Tuple:




       """simple docstring"""


       return self.time_input_dim * 4







      @property
      def       __lowerCAmelCase					(      self      :						Tuple  )    ->Optional[Any]:




       """simple docstring"""


       return 8







      @property
      def       __lowerCAmelCase					(      self      :						Tuple  )    ->str:




       """simple docstring"""


       a		  =      CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )
       return tokenizer







      @property
      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->List[Any]:




       """simple docstring"""


       torch.manual_seed(0  )
       a		  =      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-0_5 ,					num_attention_heads=4 ,					num_hidden_layers=5 ,					pad_token_id=1 ,					vocab_size=1_000 ,					)
       return CLIPTextModelWithProjection(__UpperCAmelCase  )







      @property
      def       __lowerCAmelCase					(      self      :						Dict  )    ->Union[str, Any]:




       """simple docstring"""


       torch.manual_seed(0  )

       a		  =      {
           '''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,
       }

       a		  =      PriorTransformer(**__UpperCAmelCase  )
       return model







      @property
      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->List[str]:




       """simple docstring"""


       torch.manual_seed(0  )

       a		  =      {
           '''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,
           ),
       }
       a		  =      ShapERenderer(**__UpperCAmelCase  )
       return model







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




       """simple docstring"""


       a		  =      self.dummy_prior
       a		  =      self.dummy_text_encoder
       a		  =      self.dummy_tokenizer
       a		  =      self.dummy_renderer

       a		  =      HeunDiscreteScheduler(
           beta_schedule='''exp''' ,					num_train_timesteps=1_024 ,					prediction_type='''sample''' ,					use_karras_sigmas=__UpperCAmelCase ,					clip_sample=__UpperCAmelCase ,					clip_sample_range=1.0 ,					)
       a		  =      {
           '''prior''': prior,
           '''text_encoder''': text_encoder,
           '''tokenizer''': tokenizer,
           '''renderer''': renderer,
           '''scheduler''': scheduler,
       }

       return components







      def       __lowerCAmelCase					(      self      :						Tuple ,					__UpperCAmelCase      :						Optional[Any] ,					__UpperCAmelCase      :						str=0  )    ->Optional[int]:




       """simple docstring"""


       if str(__UpperCAmelCase  ).startswith('''mps'''  ):
        a		  =      torch.manual_seed(__UpperCAmelCase  )
       else:
        a		  =      torch.Generator(device=__UpperCAmelCase  ).manual_seed(__UpperCAmelCase  )
       a		  =      {
           '''prompt''': '''horse''',
           '''generator''': generator,
           '''num_inference_steps''': 1,
           '''frame_size''': 32,
           '''output_type''': '''np''',
       }
       return inputs







      def       __lowerCAmelCase					(      self      :						Dict  )    ->Optional[int]:




       """simple docstring"""


       a		  =      '''cpu'''

       a		  =      self.get_dummy_components()

       a		  =      self.pipeline_class(**__UpperCAmelCase  )
       a		  =      pipe.to(__UpperCAmelCase  )

       pipe.set_progress_bar_config(disable=__UpperCAmelCase  )

       a		  =      pipe(**self.get_dummy_inputs(__UpperCAmelCase  )  )
       a		  =      output.images[0]
       a		  =      image[0, -3:, -3:, -1]

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

       a		  =      np.array(
           [
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
               0.00039216,
           ]  )

       assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2







      def       __lowerCAmelCase					(      self      :						Dict  )    ->Optional[Any]:




       """simple docstring"""


       self._test_inference_batch_consistent(batch_sizes=[1, 2]  )







      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->Tuple:




       """simple docstring"""


       a		  =      torch_device == '''cpu'''
       a		  =      True

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







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




       """simple docstring"""


       a		  =      self.get_dummy_components()
       a		  =      self.pipeline_class(**__UpperCAmelCase  )
       a		  =      pipe.to(__UpperCAmelCase  )
       pipe.set_progress_bar_config(disable=__UpperCAmelCase  )

       a		  =      1
       a		  =      2

       a		  =      self.get_dummy_inputs(__UpperCAmelCase  )

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

       a		  =      pipe(**__UpperCAmelCase ,					num_images_per_prompt=__UpperCAmelCase  )[0]

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






@slow
@require_torch_gpu
class 		lowercase_					(	unittest.TestCase   ):






      '''simple docstring'''




      def       __lowerCAmelCase					(      self      :						int  )    ->Any:




       """simple docstring"""


       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()







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




       """simple docstring"""


       a		  =      load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/shap_e/test_shap_e_np_out.npy'''  )
       a		  =      ShapEPipeline.from_pretrained('''openai/shap-e'''  )
       a		  =      pipe.to(__UpperCAmelCase  )
       pipe.set_progress_bar_config(disable=__UpperCAmelCase  )

       a		  =      torch.Generator(device=__UpperCAmelCase  ).manual_seed(0  )

       a		  =      pipe(
           '''a shark''' ,					generator=__UpperCAmelCase ,					guidance_scale=15.0 ,					num_inference_steps=64 ,					frame_size=64 ,					output_type='''np''' ,					).images[0]

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

       assert_mean_pixel_difference(__UpperCAmelCase ,					__UpperCAmelCase  )


