



import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEmbeddings,
    BertLayer,
    BertPooler,
    BertPreTrainedModel,
)
def 		UpperCamelCase     (       snake_case__	:   List[Any]     )     ->					Union[str, Any]:
   UpperCamelCase   :  List[str]						     =     torch.exp(snake_case__     )
   UpperCamelCase   :  List[str]						     =     torch.sum(snake_case__	,					dim=1     )  # sum of exp(x_i)
   UpperCamelCase   :  str						     =     torch.sum(x * exp_x	,					dim=1     )  # sum of x_i * exp(x_i)
   return torch.log(snake_case__     ) - B / A



class     lowerCAmelCase_		(  nn.Module							):
       def __init__(      self,      SCREAMING_SNAKE_CASE_	)					->		List[Any]:
          super().__init__()
          UpperCamelCase   :  Optional[int]						     =     config.output_attentions
          UpperCamelCase   :  Union[str, Any]						     =     config.output_hidden_states
          UpperCamelCase   :  Any						     =     nn.ModuleList([BertLayer(SCREAMING_SNAKE_CASE_	) for _ in range(config.num_hidden_layers	)]	)
          UpperCamelCase   :  int						     =     nn.ModuleList([BertHighway(SCREAMING_SNAKE_CASE_	) for _ in range(config.num_hidden_layers	)]	)

          UpperCamelCase   :  str						     =     [-1 for _ in range(config.num_hidden_layers	)]
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_	)					->		Dict:
          if (type(SCREAMING_SNAKE_CASE_	) is float) or (type(SCREAMING_SNAKE_CASE_	) is int):
             for i in range(len(self.early_exit_entropy	)	):
                UpperCamelCase   :  str						     =     x
          else:
             UpperCamelCase   :  Optional[int]						     =     x
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_	)					->		Union[str, Any]:
          UpperCamelCase   :  int						     =     pooler.state_dict()
          for highway in self.highway:
             for name, param in highway.pooler.state_dict().items():
                param.copy_(loaded_model[name]	)






       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      )					->		List[Any]:
          UpperCamelCase   :  Optional[int]						     =     ()
          UpperCamelCase   :  Tuple						     =     ()
          UpperCamelCase   :  Optional[int]						     =     ()
          for i, layer_module in enumerate(self.layer	):
             if self.output_hidden_states:
                UpperCamelCase   :  Dict						     =     all_hidden_states + (hidden_states,)

             UpperCamelCase   :  List[Any]						     =     layer_module(
                 SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      head_mask[i],      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)
             UpperCamelCase   :  Union[str, Any]						     =     layer_outputs[0]

             if self.output_attentions:
                UpperCamelCase   :  Tuple						     =     all_attentions + (layer_outputs[1],)

             UpperCamelCase   :  Dict						     =     (hidden_states,)
             if self.output_hidden_states:
                UpperCamelCase   :  Dict						     =     current_outputs + (all_hidden_states,)
             if self.output_attentions:
                UpperCamelCase   :  Union[str, Any]						     =     current_outputs + (all_attentions,)

             UpperCamelCase   :  List[str]						     =     self.highway[i](SCREAMING_SNAKE_CASE_	)
             # logits, pooled_output

             if not self.training:
                UpperCamelCase   :  str						     =     highway_exit[0]
                UpperCamelCase   :  Tuple						     =     entropy(SCREAMING_SNAKE_CASE_	)
                UpperCamelCase   :  Dict						     =     highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
                UpperCamelCase   :  int						     =     all_highway_exits + (highway_exit,)

                if highway_entropy < self.early_exit_entropy[i]:
                   UpperCamelCase   :  int						     =     (highway_logits,) + current_outputs[1:] + (all_highway_exits,)
                   raise HighwayException(SCREAMING_SNAKE_CASE_,      i + 1	)
             else:
                UpperCamelCase   :  Union[str, Any]						     =     all_highway_exits + (highway_exit,)

        # Add last layer
          if self.output_hidden_states:
             UpperCamelCase   :  Optional[int]						     =     all_hidden_states + (hidden_states,)

          UpperCamelCase   :  int						     =     (hidden_states,)
          if self.output_hidden_states:
             UpperCamelCase   :  Optional[int]						     =     outputs + (all_hidden_states,)
          if self.output_attentions:
             UpperCamelCase   :  str						     =     outputs + (all_attentions,)

          UpperCamelCase   :  Optional[Any]						     =     outputs + (all_highway_exits,)
          return outputs  # last-layer hidden state, (all hidden states), (all attentions), all highway exits






@add_start_docstrings(
    "The Bert Model transformer with early exiting (DeeBERT). "	,   a__	,   )
class     lowerCAmelCase_		(  a__							):
       def __init__(      self,      SCREAMING_SNAKE_CASE_	)					->		List[str]:
          super().__init__(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Tuple						     =     config

          UpperCamelCase   :  Optional[int]						     =     BertEmbeddings(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Any						     =     DeeBertEncoder(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Any						     =     BertPooler(SCREAMING_SNAKE_CASE_	)

          self.init_weights()
       def  snake_case_	(      self	)					->		Optional[Any]:
          self.encoder.init_highway_pooler(self.pooler	)
       def  snake_case_	(      self	)					->		Any:
          return self.embeddings.word_embeddings
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_	)					->		int:
          UpperCamelCase   :  Tuple						     =     value
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_	)					->		Dict:
          for layer, heads in heads_to_prune.items():
             self.encoder.layer[layer].attention.prune_heads(SCREAMING_SNAKE_CASE_	)






       @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_	)
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      )					->		int:
          if input_ids is not None and inputs_embeds is not None:
             raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time'	)
          elif input_ids is not None:
             UpperCamelCase   :  List[Any]						     =     input_ids.size()
          elif inputs_embeds is not None:
             UpperCamelCase   :  Optional[Any]						     =     inputs_embeds.size()[:-1]
          else:
             raise ValueError('You have to specify either input_ids or inputs_embeds'	)

          UpperCamelCase   :  List[str]						     =     input_ids.device if input_ids is not None else inputs_embeds.device

          if attention_mask is None:
             UpperCamelCase   :  Tuple						     =     torch.ones(SCREAMING_SNAKE_CASE_,      device=SCREAMING_SNAKE_CASE_	)
          if encoder_attention_mask is None:
             UpperCamelCase   :  Tuple						     =     torch.ones(SCREAMING_SNAKE_CASE_,      device=SCREAMING_SNAKE_CASE_	)
          if token_type_ids is None:
             UpperCamelCase   :  str						     =     torch.zeros(SCREAMING_SNAKE_CASE_,      dtype=torch.long,      device=SCREAMING_SNAKE_CASE_	)

          # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
          # ourselves in which case we just need to make it broadcastable to all heads.
          UpperCamelCase   :  torch.Tensor						     =     self.get_extended_attention_mask(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)

          # If a 2D ou 3D attention mask is provided for the cross-attention
          # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
          if encoder_attention_mask.dim() == 3:
             UpperCamelCase   :  int						     =     encoder_attention_mask[:, None, :, :]
          if encoder_attention_mask.dim() == 2:
             UpperCamelCase   :  str						     =     encoder_attention_mask[:, None, None, :]

          UpperCamelCase   :  Any						     =     encoder_extended_attention_mask.to(
              dtype=next(self.parameters()	).dtype	)  # fp16 compatibility
          UpperCamelCase   :  List[str]						     =     (1.0 - encoder_extended_attention_mask) * -1_00_00.0

          # Prepare head mask if needed
          # 1.0 in head_mask indicate we keep the head
          # attention_probs has shape bsz x n_heads x N x N
          # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
          # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
          UpperCamelCase   :  Optional[int]						     =     self.get_head_mask(SCREAMING_SNAKE_CASE_,      self.config.num_hidden_layers	)

          UpperCamelCase   :  Optional[int]						     =     self.embeddings(
              input_ids=SCREAMING_SNAKE_CASE_,      position_ids=SCREAMING_SNAKE_CASE_,      token_type_ids=SCREAMING_SNAKE_CASE_,      inputs_embeds=SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Optional[Any]						     =     self.encoder(
              SCREAMING_SNAKE_CASE_,      attention_mask=SCREAMING_SNAKE_CASE_,      head_mask=SCREAMING_SNAKE_CASE_,      encoder_hidden_states=SCREAMING_SNAKE_CASE_,      encoder_attention_mask=SCREAMING_SNAKE_CASE_,      )
          UpperCamelCase   :  Dict						     =     encoder_outputs[0]
          UpperCamelCase   :  Union[str, Any]						     =     self.pooler(SCREAMING_SNAKE_CASE_	)

          UpperCamelCase   :  List[str]						     =     (
              sequence_output,
              pooled_output,
          ) + encoder_outputs[
              1:
          ]  # add hidden_states and attentions if they are here
          return outputs  # sequence_output, pooled_output, (hidden_states), (attentions), highway exits






class     lowerCAmelCase_		(  a__							):
       def __init__(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)					->		Tuple:
          UpperCamelCase   :  Dict						     =     message
          UpperCamelCase   :  int						     =     exit_layer  # start from 1!






class     lowerCAmelCase_		(  nn.Module							):
       def __init__(      self,      SCREAMING_SNAKE_CASE_	)					->		Dict:
          super().__init__()
          UpperCamelCase   :  Union[str, Any]						     =     BertPooler(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Optional[int]						     =     nn.Dropout(config.hidden_dropout_prob	)
          UpperCamelCase   :  Union[str, Any]						     =     nn.Linear(config.hidden_size,      config.num_labels	)






       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_	)					->		Dict:
          # Pooler
          UpperCamelCase   :  Dict						     =     encoder_outputs[0]
          UpperCamelCase   :  List[Any]						     =     self.pooler(SCREAMING_SNAKE_CASE_	)
          # "return" pooler_output

          # BertModel
          UpperCamelCase   :  Any						     =     (pooler_input, pooler_output) + encoder_outputs[1:]
          # "return" bmodel_output

          # Dropout and classification
          UpperCamelCase   :  List[str]						     =     bmodel_output[1]

          UpperCamelCase   :  Optional[Any]						     =     self.dropout(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Tuple						     =     self.classifier(SCREAMING_SNAKE_CASE_	)

          return logits, pooled_output






@add_start_docstrings(
    "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n    also takes care of multi-layer training. "	,   a__	,   )
class     lowerCAmelCase_		(  a__							):
       def __init__(      self,      SCREAMING_SNAKE_CASE_	)					->		Any:
          super().__init__(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  str						     =     config.num_labels
          UpperCamelCase   :  Dict						     =     config.num_hidden_layers

          UpperCamelCase   :  Optional[Any]						     =     DeeBertModel(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Dict						     =     nn.Dropout(config.hidden_dropout_prob	)
          UpperCamelCase   :  Optional[int]						     =     nn.Linear(config.hidden_size,      self.config.num_labels	)

          self.init_weights()






       @add_start_docstrings_to_model_forward(SCREAMING_SNAKE_CASE_	)
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=None,      SCREAMING_SNAKE_CASE_=-1,      SCREAMING_SNAKE_CASE_=False,      )					->		Optional[int]:
          UpperCamelCase   :  str						     =     self.num_layers
          try:
             UpperCamelCase   :  Tuple						     =     self.bert(
                 SCREAMING_SNAKE_CASE_,      attention_mask=SCREAMING_SNAKE_CASE_,      token_type_ids=SCREAMING_SNAKE_CASE_,      position_ids=SCREAMING_SNAKE_CASE_,      head_mask=SCREAMING_SNAKE_CASE_,      inputs_embeds=SCREAMING_SNAKE_CASE_,      )
             # sequence_output, pooled_output, (hidden_states), (attentions), highway exits

             UpperCamelCase   :  Optional[Any]						     =     outputs[1]

             UpperCamelCase   :  Union[str, Any]						     =     self.dropout(SCREAMING_SNAKE_CASE_	)
             UpperCamelCase   :  int						     =     self.classifier(SCREAMING_SNAKE_CASE_	)
             UpperCamelCase   :  Dict						     =     (logits,) + outputs[2:]  # add hidden states and attention if they are here
          except HighwayException as e:
             UpperCamelCase   :  Optional[int]						     =     e.message
             UpperCamelCase   :  List[Any]						     =     e.exit_layer
             UpperCamelCase   :  Optional[int]						     =     outputs[0]

          if not self.training:
             UpperCamelCase   :  List[Any]						     =     entropy(SCREAMING_SNAKE_CASE_	)
             UpperCamelCase   :  Any						     =     []
             UpperCamelCase   :  Any						     =     []
          if labels is not None:
             if self.num_labels == 1:
                #  We are doing regression
                UpperCamelCase   :  str						     =     MSELoss()
                UpperCamelCase   :  int						     =     loss_fct(logits.view(-1	),      labels.view(-1	)	)
             else:
                UpperCamelCase   :  List[Any]						     =     CrossEntropyLoss()
                UpperCamelCase   :  Optional[Any]						     =     loss_fct(logits.view(-1,      self.num_labels	),      labels.view(-1	)	)

             # work with highway exits
             UpperCamelCase   :  List[Any]						     =     []
             for highway_exit in outputs[-1]:
                UpperCamelCase   :  Tuple						     =     highway_exit[0]
                if not self.training:
                   highway_logits_all.append(SCREAMING_SNAKE_CASE_	)
                   highway_entropy.append(highway_exit[2]	)
                if self.num_labels == 1:
                   #  We are doing regression
                   UpperCamelCase   :  Optional[Any]						     =     MSELoss()
                   UpperCamelCase   :  Optional[int]						     =     loss_fct(highway_logits.view(-1	),      labels.view(-1	)	)
                else:
                   UpperCamelCase   :  Tuple						     =     CrossEntropyLoss()
                   UpperCamelCase   :  Tuple						     =     loss_fct(highway_logits.view(-1,      self.num_labels	),      labels.view(-1	)	)
                highway_losses.append(SCREAMING_SNAKE_CASE_	)

             if train_highway:
                UpperCamelCase   :  Tuple						     =     (sum(highway_losses[:-1]	),) + outputs
                # exclude the final highway, of course
             else:
                UpperCamelCase   :  Optional[int]						     =     (loss,) + outputs
          if not self.training:
             UpperCamelCase   :  Optional[int]						     =     outputs + ((original_entropy, highway_entropy), exit_layer)
             if output_layer >= 0:
                UpperCamelCase   :  str						     =     (
                    (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
                )  # use the highway of the last layer

          return outputs  # (loss), logits, (hidden_states), (attentions), (highway_exits)








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     lowerCAmelCase_		(  a__	,   unittest.TestCase							):
       UpperCAmelCase__    : Union[str, Any]       					=  ShapEPipeline
       UpperCAmelCase__    : List[Any]       					=  ["prompt"]
       UpperCAmelCase__    : List[str]       					=  ["prompt"]
       UpperCAmelCase__    : int       					=  [
           "num_images_per_prompt",
           "num_inference_steps",
           "generator",
           "latents",
           "guidance_scale",
           "frame_size",
           "output_type",
           "return_dict",
       ]
       UpperCAmelCase__    : Union[str, Any]       					=  False
       @property
       def  snake_case_	(      self	)					->		Union[str, Any]:
          return 32
       @property
       def  snake_case_	(      self	)					->		List[str]:
          return 32
       @property
       def  snake_case_	(      self	)					->		int:
          return self.time_input_dim * 4
       @property
       def  snake_case_	(      self	)					->		Optional[int]:
          return 8
       @property
       def  snake_case_	(      self	)					->		str:
          UpperCamelCase   :  Union[str, Any]						     =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'	)
          return tokenizer
       @property
       def  snake_case_	(      self	)					->		Optional[Any]:
          torch.manual_seed(0	)
          UpperCamelCase   :  Dict						     =     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=1000,      )
          return CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE_	)
       @property
       def  snake_case_	(      self	)					->		Dict:
          torch.manual_seed(0	)

          UpperCamelCase   :  int						     =     {
              '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,
          }

          UpperCamelCase   :  Any						     =     PriorTransformer(**SCREAMING_SNAKE_CASE_	)
          return model
       @property
       def  snake_case_	(      self	)					->		Tuple:
          torch.manual_seed(0	)

          UpperCamelCase   :  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,
              ),
          }
          UpperCamelCase   :  Dict						     =     ShapERenderer(**SCREAMING_SNAKE_CASE_	)
          return model
       def  snake_case_	(      self	)					->		Tuple:
          UpperCamelCase   :  List[Any]						     =     self.dummy_prior
          UpperCamelCase   :  int						     =     self.dummy_text_encoder
          UpperCamelCase   :  Dict						     =     self.dummy_tokenizer
          UpperCamelCase   :  List[str]						     =     self.dummy_renderer

          UpperCamelCase   :  str						     =     HeunDiscreteScheduler(
              beta_schedule='exp',      num_train_timesteps=1024,      prediction_type='sample',      use_karras_sigmas=SCREAMING_SNAKE_CASE_,      clip_sample=SCREAMING_SNAKE_CASE_,      clip_sample_range=1.0,      )
          UpperCamelCase   :  List[str]						     =     {
              'prior': prior,
              'text_encoder': text_encoder,
              'tokenizer': tokenizer,
              'renderer': renderer,
              'scheduler': scheduler,
          }

          return components
       def  snake_case_	(      self,      SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_=0	)					->		Any:
          if str(SCREAMING_SNAKE_CASE_	).startswith('mps'	):
             UpperCamelCase   :  Optional[int]						     =     torch.manual_seed(SCREAMING_SNAKE_CASE_	)
          else:
             UpperCamelCase   :  Any						     =     torch.Generator(device=SCREAMING_SNAKE_CASE_	).manual_seed(SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  str						     =     {
              'prompt': 'horse',
              'generator': generator,
              'num_inference_steps': 1,
              'frame_size': 32,
              'output_type': 'np',
          }
          return inputs
       def  snake_case_	(      self	)					->		int:
          UpperCamelCase   :  str						     =     'cpu'

          UpperCamelCase   :  Optional[int]						     =     self.get_dummy_components()

          UpperCamelCase   :  int						     =     self.pipeline_class(**SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Optional[Any]						     =     pipe.to(SCREAMING_SNAKE_CASE_	)

          pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_	)

          UpperCamelCase   :  str						     =     pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_	)	)
          UpperCamelCase   :  Optional[int]						     =     output.images[0]
          UpperCamelCase   :  Union[str, Any]						     =     image[0, -3:, -3:, -1]

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

          UpperCamelCase   :  List[str]						     =     np.array(
              [
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
                  0.00_03_92_16,
              ]	)

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

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






       def  snake_case_	(      self	)					->		List[Any]:
          UpperCamelCase   :  List[Any]						     =     self.get_dummy_components()
          UpperCamelCase   :  str						     =     self.pipeline_class(**SCREAMING_SNAKE_CASE_	)
          UpperCamelCase   :  Optional[int]						     =     pipe.to(SCREAMING_SNAKE_CASE_	)
          pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_	)

          UpperCamelCase   :  Optional[Any]						     =     1
          UpperCamelCase   :  Union[str, Any]						     =     2

          UpperCamelCase   :  Union[str, Any]						     =     self.get_dummy_inputs(SCREAMING_SNAKE_CASE_	)

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

          UpperCamelCase   :  int						     =     pipe(**SCREAMING_SNAKE_CASE_,      num_images_per_prompt=SCREAMING_SNAKE_CASE_	)[0]

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






@slow
@require_torch_gpu
class     lowerCAmelCase_		(  unittest.TestCase							):
       def  snake_case_	(      self	)					->		str:
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






       def  snake_case_	(      self	)					->		Tuple:
          UpperCamelCase   :  Optional[int]						     =     load_numpy(
              'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
              '/shap_e/test_shap_e_np_out.npy'	)
          UpperCamelCase   :  Optional[int]						     =     ShapEPipeline.from_pretrained('openai/shap-e'	)
          UpperCamelCase   :  Optional[int]						     =     pipe.to(SCREAMING_SNAKE_CASE_	)
          pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_	)

          UpperCamelCase   :  str						     =     torch.Generator(device=SCREAMING_SNAKE_CASE_	).manual_seed(0	)

          UpperCamelCase   :  Dict						     =     pipe(
              'a shark',      generator=SCREAMING_SNAKE_CASE_,      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(SCREAMING_SNAKE_CASE_,      SCREAMING_SNAKE_CASE_	)



