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_			(						SCREAMING_SNAKE_CASE	,					unittest.TestCase						):






 '''simple docstring'''






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




 @property
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        return 32




 @property
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        return 32




 @property
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        return self.time_input_dim * 4




 @property
 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        return 8




 @property
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



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




 @property
 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        torch.manual_seed(0)
        lowerCAmelCase__					     = 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(lowercase__)




 @property
 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        torch.manual_seed(0)

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

        lowerCAmelCase__					     = PriorTransformer(**lowercase__)
        return model




 @property
 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        torch.manual_seed(0)

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




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.dummy_prior
        lowerCAmelCase__					     = self.dummy_text_encoder
        lowerCAmelCase__					     = self.dummy_tokenizer
        lowerCAmelCase__					     = self.dummy_renderer

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

        return components




 def 		__snake_case						(      self :  Tuple      ,   lowercase__ :  str      ,   lowercase__ :  Any=0):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        lowerCAmelCase__					     = 'cpu'

        lowerCAmelCase__					     = self.get_dummy_components()

        lowerCAmelCase__					     = self.pipeline_class(**lowercase__)
        lowerCAmelCase__					     = pipe.to(lowercase__)

        pipe.set_progress_bar_config(disable=lowercase__)

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

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

        lowerCAmelCase__					     = np.array(
            [
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
                0.00_039_216,
            ])

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




 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = torch_device == 'cpu'
        lowerCAmelCase__					     = True

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




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.get_dummy_components()
        lowerCAmelCase__					     = self.pipeline_class(**lowercase__)
        lowerCAmelCase__					     = pipe.to(lowercase__)
        pipe.set_progress_bar_config(disable=lowercase__)

        lowerCAmelCase__					     = 1
        lowerCAmelCase__					     = 2

        lowerCAmelCase__					     = self.get_dummy_inputs(lowercase__)

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

        lowerCAmelCase__					     = pipe(**lowercase__      ,   num_images_per_prompt=lowercase__)[0]

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






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






 '''simple docstring'''






 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



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




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



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

        lowerCAmelCase__					     = torch.Generator(device=lowercase__).manual_seed(0)

        lowerCAmelCase__					     = pipe(
            'a shark'      ,   generator=lowercase__      ,   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(lowercase__      ,   lowercase__)

from typing import Optional, Tuple, Union

import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict

from ..configuration_utils import ConfigMixin, flax_register_to_config
from ..utils import BaseOutput
from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
from .modeling_flax_utils import FlaxModelMixin
from .unet_ad_blocks_flax import (
    FlaxCrossAttnDownBlockaD,
    FlaxCrossAttnUpBlockaD,
    FlaxDownBlockaD,
    FlaxUNetMidBlockaDCrossAttn,
    FlaxUpBlockaD,
)
@flax.struct.dataclass
class     a_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= 42






@flax_register_to_config
class     a_			(						nn.Module	,					SCREAMING_SNAKE_CASE	,					SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= 32
 UpperCAmelCase_     			= 4
 UpperCAmelCase_     			= 4
 UpperCAmelCase_     			= (
     "CrossAttnDownBlock2D",
     "CrossAttnDownBlock2D",
     "CrossAttnDownBlock2D",
     "DownBlock2D",
 )
 UpperCAmelCase_     			= ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= (320, 640, 1_280, 1_280)
 UpperCAmelCase_     			= 2
 UpperCAmelCase_     			= 8
 UpperCAmelCase_     			= None
 UpperCAmelCase_     			= 1_280
 UpperCAmelCase_     			= 0.0
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= jnp.floataa
 UpperCAmelCase_     			= True
 UpperCAmelCase_     			= 0
 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  Optional[int]      ,   lowercase__ :  jax.random.KeyArray):







        '''simple docstring'''



        lowerCAmelCase__					     = (1, self.in_channels, self.sample_size, self.sample_size)
        lowerCAmelCase__					     = jnp.zeros(lowercase__      ,   dtype=jnp.floataa)
        lowerCAmelCase__					     = jnp.ones((1,)      ,   dtype=jnp.intaa)
        lowerCAmelCase__					     = jnp.zeros((1, 1, self.cross_attention_dim)      ,   dtype=jnp.floataa)

        lowerCAmelCase__     , lowerCAmelCase__					     = jax.random.split(lowercase__)
        lowerCAmelCase__					     = {'params': params_rng, 'dropout': dropout_rng}

        return self.init(lowercase__      ,   lowercase__      ,   lowercase__      ,   lowercase__)["params"]




 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.block_out_channels
        lowerCAmelCase__					     = block_out_channels[0] * 4

        if self.num_attention_heads is not None:
               raise ValueError(
                   'At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.')

        # If `num_attention_heads` is not defined (which is the case for most models)
        # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
        # The reason for this behavior is to correct for incorrectly named variables that were introduced
        # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
        # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
        # which is why we correct for the naming here.
        lowerCAmelCase__					     = self.num_attention_heads or self.attention_head_dim

        # input
        lowerCAmelCase__					     = nn.Conv(
            block_out_channels[0]      ,   kernel_size=(3, 3)      ,   strides=(1, 1)      ,   padding=((1, 1), (1, 1))      ,   dtype=self.dtype      ,   )

        # time
        lowerCAmelCase__					     = FlaxTimesteps(
            block_out_channels[0]      ,   flip_sin_to_cos=self.flip_sin_to_cos      ,   freq_shift=self.config.freq_shift)
        lowerCAmelCase__					     = FlaxTimestepEmbedding(lowercase__      ,   dtype=self.dtype)

        lowerCAmelCase__					     = self.only_cross_attention
        if isinstance(lowercase__      ,   lowercase__):
               lowerCAmelCase__					     = (only_cross_attention,) * len(self.down_block_types)

        if isinstance(lowercase__      ,   lowercase__):
               lowerCAmelCase__					     = (num_attention_heads,) * len(self.down_block_types)

        # down
        lowerCAmelCase__					     = []
        lowerCAmelCase__					     = block_out_channels[0]
        for i, down_block_type in enumerate(self.down_block_types):
               lowerCAmelCase__					     = output_channel
               lowerCAmelCase__					     = block_out_channels[i]
               lowerCAmelCase__					     = i == len(lowercase__) - 1

               if down_block_type == "CrossAttnDownBlock2D":
                      lowerCAmelCase__					     = FlaxCrossAttnDownBlockaD(
                          in_channels=lowercase__      ,   out_channels=lowercase__      ,   dropout=self.dropout      ,   num_layers=self.layers_per_block      ,   num_attention_heads=num_attention_heads[i]      ,   add_downsample=not is_final_block      ,   use_linear_projection=self.use_linear_projection      ,   only_cross_attention=only_cross_attention[i]      ,   use_memory_efficient_attention=self.use_memory_efficient_attention      ,   dtype=self.dtype      ,   )
               else:
                      lowerCAmelCase__					     = FlaxDownBlockaD(
                          in_channels=lowercase__      ,   out_channels=lowercase__      ,   dropout=self.dropout      ,   num_layers=self.layers_per_block      ,   add_downsample=not is_final_block      ,   dtype=self.dtype      ,   )

               down_blocks.append(lowercase__)
        lowerCAmelCase__					     = down_blocks

        # mid
        lowerCAmelCase__					     = FlaxUNetMidBlockaDCrossAttn(
            in_channels=block_out_channels[-1]      ,   dropout=self.dropout      ,   num_attention_heads=num_attention_heads[-1]      ,   use_linear_projection=self.use_linear_projection      ,   use_memory_efficient_attention=self.use_memory_efficient_attention      ,   dtype=self.dtype      ,   )

        # up
        lowerCAmelCase__					     = []
        lowerCAmelCase__					     = list(reversed(lowercase__))
        lowerCAmelCase__					     = list(reversed(lowercase__))
        lowerCAmelCase__					     = list(reversed(lowercase__))
        lowerCAmelCase__					     = reversed_block_out_channels[0]
        for i, up_block_type in enumerate(self.up_block_types):
               lowerCAmelCase__					     = output_channel
               lowerCAmelCase__					     = reversed_block_out_channels[i]
               lowerCAmelCase__					     = reversed_block_out_channels[min(i + 1      ,   len(lowercase__) - 1)]

               lowerCAmelCase__					     = i == len(lowercase__) - 1

               if up_block_type == "CrossAttnUpBlock2D":
                      lowerCAmelCase__					     = FlaxCrossAttnUpBlockaD(
                          in_channels=lowercase__      ,   out_channels=lowercase__      ,   prev_output_channel=lowercase__      ,   num_layers=self.layers_per_block + 1      ,   num_attention_heads=reversed_num_attention_heads[i]      ,   add_upsample=not is_final_block      ,   dropout=self.dropout      ,   use_linear_projection=self.use_linear_projection      ,   only_cross_attention=only_cross_attention[i]      ,   use_memory_efficient_attention=self.use_memory_efficient_attention      ,   dtype=self.dtype      ,   )
               else:
                      lowerCAmelCase__					     = FlaxUpBlockaD(
                          in_channels=lowercase__      ,   out_channels=lowercase__      ,   prev_output_channel=lowercase__      ,   num_layers=self.layers_per_block + 1      ,   add_upsample=not is_final_block      ,   dropout=self.dropout      ,   dtype=self.dtype      ,   )

               up_blocks.append(lowercase__)
               lowerCAmelCase__					     = output_channel
        lowerCAmelCase__					     = up_blocks

        # out
        lowerCAmelCase__					     = nn.GroupNorm(num_groups=32      ,   epsilon=1e-5)
        lowerCAmelCase__					     = nn.Conv(
            self.out_channels      ,   kernel_size=(3, 3)      ,   strides=(1, 1)      ,   padding=((1, 1), (1, 1))      ,   dtype=self.dtype      ,   )




 def __call__(      self :  Optional[Any]      ,   lowercase__ :  Optional[int]      ,   lowercase__ :  List[str]      ,   lowercase__ :  int      ,   lowercase__ :  List[Any]=None      ,   lowercase__ :  Union[str, Any]=None      ,   lowercase__ :  bool = True      ,   lowercase__ :  bool = False      ,   ):







        '''simple docstring'''



        if not isinstance(lowercase__      ,   jnp.ndarray):
               lowerCAmelCase__					     = jnp.array([timesteps]      ,   dtype=jnp.intaa)
        elif isinstance(lowercase__      ,   jnp.ndarray) and len(timesteps.shape) == 0:
               lowerCAmelCase__					     = timesteps.astype(dtype=jnp.floataa)
               lowerCAmelCase__					     = jnp.expand_dims(lowercase__      ,   0)

        lowerCAmelCase__					     = self.time_proj(lowercase__)
        lowerCAmelCase__					     = self.time_embedding(lowercase__)

        # 2. pre-process
        lowerCAmelCase__					     = jnp.transpose(lowercase__      ,   (0, 2, 3, 1))
        lowerCAmelCase__					     = self.conv_in(lowercase__)

        # 3. down
        lowerCAmelCase__					     = (sample,)
        for down_block in self.down_blocks:
               if isinstance(lowercase__      ,   lowercase__):
                      lowerCAmelCase__     , lowerCAmelCase__					     = down_block(lowercase__      ,   lowercase__      ,   lowercase__      ,   deterministic=not train)
               else:
                      lowerCAmelCase__     , lowerCAmelCase__					     = down_block(lowercase__      ,   lowercase__      ,   deterministic=not train)
               down_block_res_samples += res_samples

        if down_block_additional_residuals is not None:
               lowerCAmelCase__					     = ()

               for down_block_res_sample, down_block_additional_residual in zip(
                   lowercase__      ,   lowercase__):
                      down_block_res_sample += down_block_additional_residual
                      new_down_block_res_samples += (down_block_res_sample,)

               lowerCAmelCase__					     = new_down_block_res_samples

        # 4. mid
        lowerCAmelCase__					     = self.mid_block(lowercase__      ,   lowercase__      ,   lowercase__      ,   deterministic=not train)

        if mid_block_additional_residual is not None:
               sample += mid_block_additional_residual

        # 5. up
        for up_block in self.up_blocks:
               lowerCAmelCase__					     = down_block_res_samples[-(self.layers_per_block + 1) :]
               lowerCAmelCase__					     = down_block_res_samples[: -(self.layers_per_block + 1)]
               if isinstance(lowercase__      ,   lowercase__):
                      lowerCAmelCase__					     = up_block(
                          lowercase__      ,   temb=lowercase__      ,   encoder_hidden_states=lowercase__      ,   res_hidden_states_tuple=lowercase__      ,   deterministic=not train      ,   )
               else:
                      lowerCAmelCase__					     = up_block(lowercase__      ,   temb=lowercase__      ,   res_hidden_states_tuple=lowercase__      ,   deterministic=not train)

        # 6. post-process
        lowerCAmelCase__					     = self.conv_norm_out(lowercase__)
        lowerCAmelCase__					     = nn.silu(lowercase__)
        lowerCAmelCase__					     = self.conv_out(lowercase__)
        lowerCAmelCase__					     = jnp.transpose(lowercase__      ,   (0, 3, 1, 2))

        if not return_dict:
               return (sample,)

        return FlaxUNetaDConditionOutput(sample=lowercase__)
