

import gc
import unittest

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

from diffusers import PriorTransformer, UnCLIPPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel
from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
from diffusers.utils import load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()
class 					A_   (      _a ,     unittest.TestCase						):


    '''simple docstring'''






    a__     							=       UnCLIPPipeline
    a__     							=       TEXT_TO_IMAGE_PARAMS - {
        "negative_prompt",
        "height",
        "width",
        "negative_prompt_embeds",
        "guidance_scale",
        "prompt_embeds",
        "cross_attention_kwargs",
    }
    a__     							=       TEXT_TO_IMAGE_BATCH_PARAMS
    a__     							=       [
        "generator",
        "return_dict",
        "prior_num_inference_steps",
        "decoder_num_inference_steps",
        "super_res_num_inference_steps",
    ]
    a__     							=       False


    @property
    def      lowerCAmelCase_						(self  )     ->      Dict:
        return 32


    @property
    def      lowerCAmelCase_						(self  )     ->      Optional[int]:
        return 32


    @property
    def      lowerCAmelCase_						(self  )     ->      Union[str, Any]:
        return self.time_input_dim


    @property
    def      lowerCAmelCase_						(self  )     ->      Optional[int]:
        return self.time_input_dim * 4


    @property
    def      lowerCAmelCase_						(self  )     ->      Union[str, Any]:
        return 100


    @property
    def      lowerCAmelCase_						(self  )     ->      Optional[int]:
        __UpperCAmelCase									=			CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )
        return tokenizer


    @property
    def      lowerCAmelCase_						(self  )     ->      Dict:
        torch.manual_seed(0  )
        __UpperCAmelCase									=			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      lowerCAmelCase_						(self  )     ->      int:
        torch.manual_seed(0  )

        __UpperCAmelCase									=			{
            '''num_attention_heads''': 2,
            '''attention_head_dim''': 12,
            '''embedding_dim''': self.text_embedder_hidden_size,
            '''num_layers''': 1,
        }

        __UpperCAmelCase									=			PriorTransformer(**lowercase__  )
        return model


    @property
    def      lowerCAmelCase_						(self  )     ->      Union[str, Any]:
        torch.manual_seed(0  )

        __UpperCAmelCase									=			{
            '''clip_embeddings_dim''': self.text_embedder_hidden_size,
            '''time_embed_dim''': self.time_embed_dim,
            '''cross_attention_dim''': self.cross_attention_dim,
        }

        __UpperCAmelCase									=			UnCLIPTextProjModel(**lowercase__  )
        return model


    @property
    def      lowerCAmelCase_						(self  )     ->      List[Any]:
        torch.manual_seed(0  )

        __UpperCAmelCase									=			{
            '''sample_size''': 32,
            # RGB in channels
            '''in_channels''': 3,
            # Out channels is double in channels because predicts mean and variance
            '''out_channels''': 6,
            '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
            '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
            '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
            '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
            '''layers_per_block''': 1,
            '''cross_attention_dim''': self.cross_attention_dim,
            '''attention_head_dim''': 4,
            '''resnet_time_scale_shift''': '''scale_shift''',
            '''class_embed_type''': '''identity''',
        }

        __UpperCAmelCase									=			UNetaDConditionModel(**lowercase__  )
        return model


    @property
    def      lowerCAmelCase_						(self  )     ->      List[Any]:
        return {
            "sample_size": 64,
            "layers_per_block": 1,
            "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
            "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
            "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
            "in_channels": 6,
            "out_channels": 3,
        }


    @property
    def      lowerCAmelCase_						(self  )     ->      Union[str, Any]:
        torch.manual_seed(0  )

        __UpperCAmelCase									=			UNetaDModel(**self.dummy_super_res_kwargs  )
        return model


    @property
    def      lowerCAmelCase_						(self  )     ->      Any:
        # seeded differently to get different unet than `self.dummy_super_res_first`
        torch.manual_seed(1  )

        __UpperCAmelCase									=			UNetaDModel(**self.dummy_super_res_kwargs  )
        return model


    def      lowerCAmelCase_						(self  )     ->      int:
        __UpperCAmelCase									=			self.dummy_prior
        __UpperCAmelCase									=			self.dummy_decoder
        __UpperCAmelCase									=			self.dummy_text_proj
        __UpperCAmelCase									=			self.dummy_text_encoder
        __UpperCAmelCase									=			self.dummy_tokenizer
        __UpperCAmelCase									=			self.dummy_super_res_first
        __UpperCAmelCase									=			self.dummy_super_res_last

        __UpperCAmelCase									=			UnCLIPScheduler(
            variance_type='''fixed_small_log'''     ,      prediction_type='''sample'''     ,      num_train_timesteps=1_000     ,      clip_sample_range=5.0     ,      )

        __UpperCAmelCase									=			UnCLIPScheduler(
            variance_type='''learned_range'''     ,      prediction_type='''epsilon'''     ,      num_train_timesteps=1_000     ,      )

        __UpperCAmelCase									=			UnCLIPScheduler(
            variance_type='''fixed_small_log'''     ,      prediction_type='''epsilon'''     ,      num_train_timesteps=1_000     ,      )

        __UpperCAmelCase									=			{
            '''prior''': prior,
            '''decoder''': decoder,
            '''text_proj''': text_proj,
            '''text_encoder''': text_encoder,
            '''tokenizer''': tokenizer,
            '''super_res_first''': super_res_first,
            '''super_res_last''': super_res_last,
            '''prior_scheduler''': prior_scheduler,
            '''decoder_scheduler''': decoder_scheduler,
            '''super_res_scheduler''': super_res_scheduler,
        }

        return components


    def      lowerCAmelCase_						(self     ,      lowercase__     ,      lowercase__=0  )     ->      List[Any]:
        if str(lowercase__  ).startswith('''mps'''  ):
            __UpperCAmelCase									=			torch.manual_seed(lowercase__  )
        else:
            __UpperCAmelCase									=			torch.Generator(device=lowercase__  ).manual_seed(lowercase__  )
        __UpperCAmelCase									=			{
            '''prompt''': '''horse''',
            '''generator''': generator,
            '''prior_num_inference_steps''': 2,
            '''decoder_num_inference_steps''': 2,
            '''super_res_num_inference_steps''': 2,
            '''output_type''': '''numpy''',
        }
        return inputs


    def      lowerCAmelCase_						(self  )     ->      int:
        __UpperCAmelCase									=			'''cpu'''

        __UpperCAmelCase									=			self.get_dummy_components()

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

        pipe.set_progress_bar_config(disable=lowercase__  )

        __UpperCAmelCase									=			pipe(**self.get_dummy_inputs(lowercase__  )  )
        __UpperCAmelCase									=			output.images

        __UpperCAmelCase									=			pipe(
            **self.get_dummy_inputs(lowercase__  )     ,      return_dict=lowercase__     ,      )[0]

        __UpperCAmelCase									=			image[0, -3:, -3:, -1]
        __UpperCAmelCase									=			image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)

        __UpperCAmelCase									=			np.array(
            [
                0.9997,
                0.9988,
                0.0028,
                0.9997,
                0.9984,
                0.9965,
                0.0029,
                0.9986,
                0.0025,
            ]  )

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


    def      lowerCAmelCase_						(self  )     ->      Optional[Any]:
        __UpperCAmelCase									=			torch.device('''cpu'''  )
        class 					A_   :


            '''simple docstring'''






            a__     							=       1






        __UpperCAmelCase									=			self.get_dummy_components()

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

        __UpperCAmelCase									=			components['''prior''']
        __UpperCAmelCase									=			components['''decoder''']
        __UpperCAmelCase									=			components['''super_res_first''']
        __UpperCAmelCase									=			components['''tokenizer''']
        __UpperCAmelCase									=			components['''text_encoder''']

        __UpperCAmelCase									=			torch.Generator(device=lowercase__  ).manual_seed(0  )
        __UpperCAmelCase									=			prior.dtype
        __UpperCAmelCase									=			1

        __UpperCAmelCase									=			(batch_size, prior.config.embedding_dim)
        __UpperCAmelCase									=			pipe.prepare_latents(
            lowercase__     ,      dtype=lowercase__     ,      device=lowercase__     ,      generator=lowercase__     ,      latents=lowercase__     ,      scheduler=DummyScheduler()  )
        __UpperCAmelCase									=			(batch_size, decoder.config.in_channels, decoder.config.sample_size, decoder.config.sample_size)
        __UpperCAmelCase									=			pipe.prepare_latents(
            lowercase__     ,      dtype=lowercase__     ,      device=lowercase__     ,      generator=lowercase__     ,      latents=lowercase__     ,      scheduler=DummyScheduler()  )

        __UpperCAmelCase									=			(
            batch_size,
            super_res_first.config.in_channels // 2,
            super_res_first.config.sample_size,
            super_res_first.config.sample_size,
        )
        __UpperCAmelCase									=			pipe.prepare_latents(
            lowercase__     ,      dtype=lowercase__     ,      device=lowercase__     ,      generator=lowercase__     ,      latents=lowercase__     ,      scheduler=DummyScheduler()  )

        pipe.set_progress_bar_config(disable=lowercase__  )

        __UpperCAmelCase									=			'''this is a prompt example'''

        __UpperCAmelCase									=			torch.Generator(device=lowercase__  ).manual_seed(0  )
        __UpperCAmelCase									=			pipe(
            [prompt]     ,      generator=lowercase__     ,      prior_num_inference_steps=2     ,      decoder_num_inference_steps=2     ,      super_res_num_inference_steps=2     ,      prior_latents=lowercase__     ,      decoder_latents=lowercase__     ,      super_res_latents=lowercase__     ,      output_type='''np'''     ,      )
        __UpperCAmelCase									=			output.images

        __UpperCAmelCase									=			tokenizer(
            lowercase__     ,      padding='''max_length'''     ,      max_length=tokenizer.model_max_length     ,      return_tensors='''pt'''     ,      )
        __UpperCAmelCase									=			text_encoder(text_inputs.input_ids  )
        __UpperCAmelCase									=			text_inputs.attention_mask

        __UpperCAmelCase									=			torch.Generator(device=lowercase__  ).manual_seed(0  )
        __UpperCAmelCase									=			pipe(
            generator=lowercase__     ,      prior_num_inference_steps=2     ,      decoder_num_inference_steps=2     ,      super_res_num_inference_steps=2     ,      prior_latents=lowercase__     ,      decoder_latents=lowercase__     ,      super_res_latents=lowercase__     ,      text_model_output=lowercase__     ,      text_attention_mask=lowercase__     ,      output_type='''np'''     ,      )[0]

        # make sure passing text embeddings manually is identical
        assert np.abs(image - image_from_text  ).max() < 1E-4


    @skip_mps
    def      lowerCAmelCase_						(self  )     ->      str:
        __UpperCAmelCase									=			torch_device == '''cpu'''

        self._test_attention_slicing_forward_pass(test_max_difference=lowercase__     ,      expected_max_diff=0.01  )


    @skip_mps
    def      lowerCAmelCase_						(self  )     ->      str:
        __UpperCAmelCase									=			torch_device == '''cpu'''
        __UpperCAmelCase									=			True
        __UpperCAmelCase									=			[
            '''prior_num_inference_steps''',
            '''decoder_num_inference_steps''',
            '''super_res_num_inference_steps''',
        ]

        self._test_inference_batch_single_identical(
            test_max_difference=lowercase__     ,      relax_max_difference=lowercase__     ,      additional_params_copy_to_batched_inputs=lowercase__     ,      )


    def      lowerCAmelCase_						(self  )     ->      Dict:
        __UpperCAmelCase									=			[
            '''prior_num_inference_steps''',
            '''decoder_num_inference_steps''',
            '''super_res_num_inference_steps''',
        ]

        if torch_device == "mps":
            # TODO: MPS errors with larger batch sizes
            __UpperCAmelCase									=			[2, 3]
            self._test_inference_batch_consistent(
                batch_sizes=lowercase__     ,      additional_params_copy_to_batched_inputs=lowercase__     ,      )
        else:
            self._test_inference_batch_consistent(
                additional_params_copy_to_batched_inputs=lowercase__  )


    @skip_mps
    def      lowerCAmelCase_						(self  )     ->      Any:
        return super().test_dict_tuple_outputs_equivalent()


    @skip_mps
    def      lowerCAmelCase_						(self  )     ->      Optional[Any]:
        return super().test_save_load_local()






    @skip_mps
    def      lowerCAmelCase_						(self  )     ->      Optional[int]:
        return super().test_save_load_optional_components()






@nightly
class 					A_   (      unittest.TestCase						):


    '''simple docstring'''






    def      lowerCAmelCase_						(self  )     ->      Union[str, Any]:
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()






    def      lowerCAmelCase_						(self  )     ->      Any:
        __UpperCAmelCase									=			load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/unclip/karlo_v1_alpha_horse_cpu.npy'''  )

        __UpperCAmelCase									=			UnCLIPPipeline.from_pretrained('''kakaobrain/karlo-v1-alpha'''  )
        pipeline.set_progress_bar_config(disable=lowercase__  )

        __UpperCAmelCase									=			torch.manual_seed(0  )
        __UpperCAmelCase									=			pipeline(
            '''horse'''     ,      num_images_per_prompt=1     ,      generator=lowercase__     ,      output_type='''np'''     ,      )

        __UpperCAmelCase									=			output.images[0]

        assert image.shape == (256, 256, 3)
        assert np.abs(expected_image - image  ).max() < 1E-1






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


    '''simple docstring'''






    def      lowerCAmelCase_						(self  )     ->      List[Any]:
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()


    def      lowerCAmelCase_						(self  )     ->      List[str]:
        __UpperCAmelCase									=			load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
            '''/unclip/karlo_v1_alpha_horse_fp16.npy'''  )

        __UpperCAmelCase									=			UnCLIPPipeline.from_pretrained('''kakaobrain/karlo-v1-alpha'''     ,      torch_dtype=torch.floataa  )
        __UpperCAmelCase									=			pipeline.to(lowercase__  )
        pipeline.set_progress_bar_config(disable=lowercase__  )

        __UpperCAmelCase									=			torch.Generator(device='''cpu'''  ).manual_seed(0  )
        __UpperCAmelCase									=			pipeline(
            '''horse'''     ,      generator=lowercase__     ,      output_type='''np'''     ,      )

        __UpperCAmelCase									=			output.images[0]

        assert image.shape == (256, 256, 3)

        assert_mean_pixel_difference(lowercase__     ,      lowercase__  )






    def      lowerCAmelCase_						(self  )     ->      Dict:
        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

        __UpperCAmelCase									=			UnCLIPPipeline.from_pretrained('''kakaobrain/karlo-v1-alpha'''     ,      torch_dtype=torch.floataa  )
        __UpperCAmelCase									=			pipe.to(lowercase__  )
        pipe.set_progress_bar_config(disable=lowercase__  )
        pipe.enable_attention_slicing()
        pipe.enable_sequential_cpu_offload()

        __UpperCAmelCase									=			pipe(
            '''horse'''     ,      num_images_per_prompt=1     ,      prior_num_inference_steps=2     ,      decoder_num_inference_steps=2     ,      super_res_num_inference_steps=2     ,      output_type='''np'''     ,      )

        __UpperCAmelCase									=			torch.cuda.max_memory_allocated()
        # make sure that less than 7 GB is allocated
        assert mem_bytes < 7 * 10**9







import functools
import math

import flax.linen as nn
import jax
import jax.numpy as jnp


def       __a       (   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE = 4_0_9_6      )      ->     Any:






    '''simple docstring'''
    __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase									=			key.shape[-3:]
    __UpperCAmelCase									=			value.shape[-1]
    __UpperCAmelCase									=			min(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      )
    __UpperCAmelCase									=			query / jnp.sqrt(SCREAMING_SNAKE_CASE      )

    @functools.partial(jax.checkpoint       ,   prevent_cse=SCREAMING_SNAKE_CASE      )
    def summarize_chunk(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      ):
        __UpperCAmelCase									=			jnp.einsum('''...qhd,...khd->...qhk'''       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   precision=SCREAMING_SNAKE_CASE      )

        __UpperCAmelCase									=			jnp.max(SCREAMING_SNAKE_CASE       ,   axis=-1       ,   keepdims=SCREAMING_SNAKE_CASE      )
        __UpperCAmelCase									=			jax.lax.stop_gradient(SCREAMING_SNAKE_CASE      )
        __UpperCAmelCase									=			jnp.exp(attn_weights - max_score      )

        __UpperCAmelCase									=			jnp.einsum('''...vhf,...qhv->...qhf'''       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   precision=SCREAMING_SNAKE_CASE      )
        __UpperCAmelCase									=			jnp.einsum('''...qhk->...qh'''       ,   SCREAMING_SNAKE_CASE      )

        return (exp_values, exp_weights.sum(axis=-1      ), max_score)

    def chunk_scanner(SCREAMING_SNAKE_CASE      ):
        # julienne key array
        __UpperCAmelCase									=			jax.lax.dynamic_slice(
            operand=SCREAMING_SNAKE_CASE       ,   start_indices=[0] * (key.ndim - 3) + [chunk_idx, 0, 0]       ,   slice_sizes=list(key.shape[:-3]      ) + [key_chunk_size, num_heads, k_features]       ,   )

        # julienne value array
        __UpperCAmelCase									=			jax.lax.dynamic_slice(
            operand=SCREAMING_SNAKE_CASE       ,   start_indices=[0] * (value.ndim - 3) + [chunk_idx, 0, 0]       ,   slice_sizes=list(value.shape[:-3]      ) + [key_chunk_size, num_heads, v_features]       ,   )

        return summarize_chunk(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      )

    __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase									=			jax.lax.map(f=SCREAMING_SNAKE_CASE       ,   xs=jnp.arange(0       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      )      )

    __UpperCAmelCase									=			jnp.max(SCREAMING_SNAKE_CASE       ,   axis=0       ,   keepdims=SCREAMING_SNAKE_CASE      )
    __UpperCAmelCase									=			jnp.exp(chunk_max - global_max      )

    chunk_values *= jnp.expand_dims(SCREAMING_SNAKE_CASE       ,   axis=-1      )
    chunk_weights *= max_diffs

    __UpperCAmelCase									=			chunk_values.sum(axis=0      )
    __UpperCAmelCase									=			jnp.expand_dims(SCREAMING_SNAKE_CASE       ,   -1      ).sum(axis=0      )

    return all_values / all_weights


def       __a       (   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE=jax.lax.Precision.HIGHEST       ,   SCREAMING_SNAKE_CASE = 1_0_2_4       ,   SCREAMING_SNAKE_CASE = 4_0_9_6      )      ->     int:






    '''simple docstring'''
    __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase									=			query.shape[-3:]

    def chunk_scanner(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      ):
        # julienne query array
        __UpperCAmelCase									=			jax.lax.dynamic_slice(
            operand=SCREAMING_SNAKE_CASE       ,   start_indices=([0] * (query.ndim - 3)) + [chunk_idx, 0, 0]       ,   slice_sizes=list(query.shape[:-3]      ) + [min(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      ), num_heads, q_features]       ,   )

        return (
            chunk_idx + query_chunk_size,  # unused ignore it
            _query_chunk_attention(
                query=SCREAMING_SNAKE_CASE       ,   key=SCREAMING_SNAKE_CASE       ,   value=SCREAMING_SNAKE_CASE       ,   precision=SCREAMING_SNAKE_CASE       ,   key_chunk_size=SCREAMING_SNAKE_CASE      ),
        )

    __UpperCAmelCase					,     __UpperCAmelCase									=			jax.lax.scan(
        f=SCREAMING_SNAKE_CASE       ,   init=0       ,   xs=SCREAMING_SNAKE_CASE       ,   length=math.ceil(num_q / query_chunk_size      )      )

    return jnp.concatenate(SCREAMING_SNAKE_CASE       ,   axis=-3      )  # fuse the chunked result back
class 					A_   (      nn.Module						):


    '''simple docstring'''






    a__     							=       42
    a__     							=       8
    a__     							=       64
    a__     							=       0.0
    a__     							=       False
    a__     							=       jnp.floataa


    def      lowerCAmelCase_						(self  )     ->      Tuple:
        __UpperCAmelCase									=			self.dim_head * self.heads
        __UpperCAmelCase									=			self.dim_head**-0.5

        # Weights were exported with old names {to_q, to_k, to_v, to_out}
        __UpperCAmelCase									=			nn.Dense(lowercase__     ,      use_bias=lowercase__     ,      dtype=self.dtype     ,      name='''to_q'''  )
        __UpperCAmelCase									=			nn.Dense(lowercase__     ,      use_bias=lowercase__     ,      dtype=self.dtype     ,      name='''to_k'''  )
        __UpperCAmelCase									=			nn.Dense(lowercase__     ,      use_bias=lowercase__     ,      dtype=self.dtype     ,      name='''to_v'''  )

        __UpperCAmelCase									=			nn.Dense(self.query_dim     ,      dtype=self.dtype     ,      name='''to_out_0'''  )
        __UpperCAmelCase									=			nn.Dropout(rate=self.dropout  )


    def      lowerCAmelCase_						(self     ,      lowercase__  )     ->      Optional[int]:
        __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase									=			tensor.shape
        __UpperCAmelCase									=			self.heads
        __UpperCAmelCase									=			tensor.reshape(lowercase__     ,      lowercase__     ,      lowercase__     ,      dim // head_size  )
        __UpperCAmelCase									=			jnp.transpose(lowercase__     ,      (0, 2, 1, 3)  )
        __UpperCAmelCase									=			tensor.reshape(batch_size * head_size     ,      lowercase__     ,      dim // head_size  )
        return tensor


    def      lowerCAmelCase_						(self     ,      lowercase__  )     ->      Any:
        __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase									=			tensor.shape
        __UpperCAmelCase									=			self.heads
        __UpperCAmelCase									=			tensor.reshape(batch_size // head_size     ,      lowercase__     ,      lowercase__     ,      lowercase__  )
        __UpperCAmelCase									=			jnp.transpose(lowercase__     ,      (0, 2, 1, 3)  )
        __UpperCAmelCase									=			tensor.reshape(batch_size // head_size     ,      lowercase__     ,      dim * head_size  )
        return tensor






    def __call__(self     ,      lowercase__     ,      lowercase__=None     ,      lowercase__=True  )     ->      Optional[Any]:
        __UpperCAmelCase									=			hidden_states if context is None else context

        __UpperCAmelCase									=			self.query(lowercase__  )
        __UpperCAmelCase									=			self.key(lowercase__  )
        __UpperCAmelCase									=			self.value(lowercase__  )

        __UpperCAmelCase									=			self.reshape_heads_to_batch_dim(lowercase__  )
        __UpperCAmelCase									=			self.reshape_heads_to_batch_dim(lowercase__  )
        __UpperCAmelCase									=			self.reshape_heads_to_batch_dim(lowercase__  )

        if self.use_memory_efficient_attention:
            __UpperCAmelCase									=			query_states.transpose(1     ,      0     ,      2  )
            __UpperCAmelCase									=			key_states.transpose(1     ,      0     ,      2  )
            __UpperCAmelCase									=			value_states.transpose(1     ,      0     ,      2  )

            # this if statement create a chunk size for each layer of the unet
            # the chunk size is equal to the query_length dimension of the deepest layer of the unet

            __UpperCAmelCase									=			query_states.shape[-3]
            if flatten_latent_dim % 64 == 0:
                __UpperCAmelCase									=			int(flatten_latent_dim / 64  )
            elif flatten_latent_dim % 16 == 0:
                __UpperCAmelCase									=			int(flatten_latent_dim / 16  )
            elif flatten_latent_dim % 4 == 0:
                __UpperCAmelCase									=			int(flatten_latent_dim / 4  )
            else:
                __UpperCAmelCase									=			int(lowercase__  )

            __UpperCAmelCase									=			jax_memory_efficient_attention(
                lowercase__     ,      lowercase__     ,      lowercase__     ,      query_chunk_size=lowercase__     ,      key_chunk_size=4_096 * 4  )

            __UpperCAmelCase									=			hidden_states.transpose(1     ,      0     ,      2  )
        else:
            # compute attentions
            __UpperCAmelCase									=			jnp.einsum('''b i d, b j d->b i j'''     ,      lowercase__     ,      lowercase__  )
            __UpperCAmelCase									=			attention_scores * self.scale
            __UpperCAmelCase									=			nn.softmax(lowercase__     ,      axis=2  )

            # attend to values
            __UpperCAmelCase									=			jnp.einsum('''b i j, b j d -> b i d'''     ,      lowercase__     ,      lowercase__  )

        __UpperCAmelCase									=			self.reshape_batch_dim_to_heads(lowercase__  )
        __UpperCAmelCase									=			self.proj_attn(lowercase__  )
        return self.dropout_layer(lowercase__     ,      deterministic=lowercase__  )






class 					A_   (      nn.Module						):


    '''simple docstring'''






    a__     							=       42
    a__     							=       42
    a__     							=       42
    a__     							=       0.0
    a__     							=       False
    a__     							=       jnp.floataa
    a__     							=       False


    def      lowerCAmelCase_						(self  )     ->      Union[str, Any]:
        # self attention (or cross_attention if only_cross_attention is True)
        __UpperCAmelCase									=			FlaxAttention(
            self.dim     ,      self.n_heads     ,      self.d_head     ,      self.dropout     ,      self.use_memory_efficient_attention     ,      dtype=self.dtype  )
        # cross attention
        __UpperCAmelCase									=			FlaxAttention(
            self.dim     ,      self.n_heads     ,      self.d_head     ,      self.dropout     ,      self.use_memory_efficient_attention     ,      dtype=self.dtype  )
        __UpperCAmelCase									=			FlaxFeedForward(dim=self.dim     ,      dropout=self.dropout     ,      dtype=self.dtype  )
        __UpperCAmelCase									=			nn.LayerNorm(epsilon=1E-5     ,      dtype=self.dtype  )
        __UpperCAmelCase									=			nn.LayerNorm(epsilon=1E-5     ,      dtype=self.dtype  )
        __UpperCAmelCase									=			nn.LayerNorm(epsilon=1E-5     ,      dtype=self.dtype  )
        __UpperCAmelCase									=			nn.Dropout(rate=self.dropout  )






    def __call__(self     ,      lowercase__     ,      lowercase__     ,      lowercase__=True  )     ->      Optional[int]:
        # self attention
        __UpperCAmelCase									=			hidden_states
        if self.only_cross_attention:
            __UpperCAmelCase									=			self.attna(self.norma(lowercase__  )     ,      lowercase__     ,      deterministic=lowercase__  )
        else:
            __UpperCAmelCase									=			self.attna(self.norma(lowercase__  )     ,      deterministic=lowercase__  )
        __UpperCAmelCase									=			hidden_states + residual

        # cross attention
        __UpperCAmelCase									=			hidden_states
        __UpperCAmelCase									=			self.attna(self.norma(lowercase__  )     ,      lowercase__     ,      deterministic=lowercase__  )
        __UpperCAmelCase									=			hidden_states + residual

        # feed forward
        __UpperCAmelCase									=			hidden_states
        __UpperCAmelCase									=			self.ff(self.norma(lowercase__  )     ,      deterministic=lowercase__  )
        __UpperCAmelCase									=			hidden_states + residual

        return self.dropout_layer(lowercase__     ,      deterministic=lowercase__  )






class 					A_   (      nn.Module						):


    '''simple docstring'''






    a__     							=       42
    a__     							=       42
    a__     							=       42
    a__     							=       1
    a__     							=       0.0
    a__     							=       False
    a__     							=       False
    a__     							=       jnp.floataa
    a__     							=       False


    def      lowerCAmelCase_						(self  )     ->      int:
        __UpperCAmelCase									=			nn.GroupNorm(num_groups=32     ,      epsilon=1E-5  )

        __UpperCAmelCase									=			self.n_heads * self.d_head
        if self.use_linear_projection:
            __UpperCAmelCase									=			nn.Dense(lowercase__     ,      dtype=self.dtype  )
        else:
            __UpperCAmelCase									=			nn.Conv(
                lowercase__     ,      kernel_size=(1, 1)     ,      strides=(1, 1)     ,      padding='''VALID'''     ,      dtype=self.dtype     ,      )

        __UpperCAmelCase									=			[
            FlaxBasicTransformerBlock(
                lowercase__     ,      self.n_heads     ,      self.d_head     ,      dropout=self.dropout     ,      only_cross_attention=self.only_cross_attention     ,      dtype=self.dtype     ,      use_memory_efficient_attention=self.use_memory_efficient_attention     ,      )
            for _ in range(self.depth  )
        ]

        if self.use_linear_projection:
            __UpperCAmelCase									=			nn.Dense(lowercase__     ,      dtype=self.dtype  )
        else:
            __UpperCAmelCase									=			nn.Conv(
                lowercase__     ,      kernel_size=(1, 1)     ,      strides=(1, 1)     ,      padding='''VALID'''     ,      dtype=self.dtype     ,      )

        __UpperCAmelCase									=			nn.Dropout(rate=self.dropout  )






    def __call__(self     ,      lowercase__     ,      lowercase__     ,      lowercase__=True  )     ->      Dict:
        __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase									=			hidden_states.shape
        __UpperCAmelCase									=			hidden_states
        __UpperCAmelCase									=			self.norm(lowercase__  )
        if self.use_linear_projection:
            __UpperCAmelCase									=			hidden_states.reshape(lowercase__     ,      height * width     ,      lowercase__  )
            __UpperCAmelCase									=			self.proj_in(lowercase__  )
        else:
            __UpperCAmelCase									=			self.proj_in(lowercase__  )
            __UpperCAmelCase									=			hidden_states.reshape(lowercase__     ,      height * width     ,      lowercase__  )

        for transformer_block in self.transformer_blocks:
            __UpperCAmelCase									=			transformer_block(lowercase__     ,      lowercase__     ,      deterministic=lowercase__  )

        if self.use_linear_projection:
            __UpperCAmelCase									=			self.proj_out(lowercase__  )
            __UpperCAmelCase									=			hidden_states.reshape(lowercase__     ,      lowercase__     ,      lowercase__     ,      lowercase__  )
        else:
            __UpperCAmelCase									=			hidden_states.reshape(lowercase__     ,      lowercase__     ,      lowercase__     ,      lowercase__  )
            __UpperCAmelCase									=			self.proj_out(lowercase__  )

        __UpperCAmelCase									=			hidden_states + residual
        return self.dropout_layer(lowercase__     ,      deterministic=lowercase__  )






class 					A_   (      nn.Module						):


    '''simple docstring'''






    a__     							=       42
    a__     							=       0.0
    a__     							=       jnp.floataa


    def      lowerCAmelCase_						(self  )     ->      int:
        # The second linear layer needs to be called
        # net_2 for now to match the index of the Sequential layer
        __UpperCAmelCase									=			FlaxGEGLU(self.dim     ,      self.dropout     ,      self.dtype  )
        __UpperCAmelCase									=			nn.Dense(self.dim     ,      dtype=self.dtype  )






    def __call__(self     ,      lowercase__     ,      lowercase__=True  )     ->      Dict:
        __UpperCAmelCase									=			self.net_a(lowercase__     ,      deterministic=lowercase__  )
        __UpperCAmelCase									=			self.net_a(lowercase__  )
        return hidden_states






class 					A_   (      nn.Module						):


    '''simple docstring'''






    a__     							=       42
    a__     							=       0.0
    a__     							=       jnp.floataa


    def      lowerCAmelCase_						(self  )     ->      Optional[int]:
        __UpperCAmelCase									=			self.dim * 4
        __UpperCAmelCase									=			nn.Dense(inner_dim * 2     ,      dtype=self.dtype  )
        __UpperCAmelCase									=			nn.Dropout(rate=self.dropout  )






    def __call__(self     ,      lowercase__     ,      lowercase__=True  )     ->      Union[str, Any]:
        __UpperCAmelCase									=			self.proj(lowercase__  )
        __UpperCAmelCase					,     __UpperCAmelCase									=			jnp.split(lowercase__     ,      2     ,      axis=2  )
        return self.dropout_layer(hidden_linear * nn.gelu(lowercase__  )     ,      deterministic=lowercase__  )




