import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

      if is_vision_available():
            from transformers import MaskaFormerImageProcessor

if is_vision_available():
      from PIL import Image
class     a_			:






 '''simple docstring'''






 def __init__(      self :  List[Any]      ,   lowercase__ :  str      ,   lowercase__ :  Dict=2      ,   lowercase__ :  str=True      ,   lowercase__ :  Tuple=False      ,   lowercase__ :  int=10      ,   lowercase__ :  Optional[int]=3      ,   lowercase__ :  Tuple=32 * 8      ,   lowercase__ :  List[Any]=32 * 8      ,   lowercase__ :  Optional[int]=4      ,   lowercase__ :  Optional[Any]=64      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = parent
        lowerCAmelCase__					     = batch_size
        lowerCAmelCase__					     = is_training
        lowerCAmelCase__					     = use_auxiliary_loss
        lowerCAmelCase__					     = num_queries
        lowerCAmelCase__					     = num_channels
        lowerCAmelCase__					     = min_size
        lowerCAmelCase__					     = max_size
        lowerCAmelCase__					     = num_labels
        lowerCAmelCase__					     = hidden_dim
        lowerCAmelCase__					     = hidden_dim




 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to(
            lowercase__)

        lowerCAmelCase__					     = torch.ones([self.batch_size, self.min_size, self.max_size]      ,   device=lowercase__)

        lowerCAmelCase__					     = (
            torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]      ,   device=lowercase__) > 0.5
        ).float()
        lowerCAmelCase__					     = (torch.rand((self.batch_size, self.num_labels)      ,   device=lowercase__) > 0.5).long()

        lowerCAmelCase__					     = self.get_config()
        return config, pixel_values, pixel_mask, mask_labels, class_labels




 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerConfig(
            hidden_size=self.hidden_dim      ,   )
        lowerCAmelCase__					     = self.num_queries
        lowerCAmelCase__					     = self.num_labels

        lowerCAmelCase__					     = [1, 1, 1, 1]
        lowerCAmelCase__					     = self.num_channels

        lowerCAmelCase__					     = 64
        lowerCAmelCase__					     = 128
        lowerCAmelCase__					     = self.hidden_dim
        lowerCAmelCase__					     = self.hidden_dim
        lowerCAmelCase__					     = self.hidden_dim
        return config




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







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = self.prepare_config_and_inputs()
        lowerCAmelCase__					     = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
        return config, inputs_dict




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







        '''simple docstring'''



        lowerCAmelCase__					     = output.encoder_hidden_states
        lowerCAmelCase__					     = output.pixel_decoder_hidden_states
        lowerCAmelCase__					     = output.transformer_decoder_hidden_states

        self.parent.assertTrue(len(lowercase__)      ,   len(config.backbone_config.depths))
        self.parent.assertTrue(len(lowercase__)      ,   len(config.backbone_config.depths))
        self.parent.assertTrue(len(lowercase__)      ,   config.decoder_layers)




 def 		__snake_case						(      self :  List[Any]      ,   lowercase__ :  str      ,   lowercase__ :  Dict      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  Optional[int]=False):







        '''simple docstring'''



        with torch.no_grad():
               lowerCAmelCase__					     = MaskaFormerModel(config=lowercase__)
               model.to(lowercase__)
               model.eval()

               lowerCAmelCase__					     = model(pixel_values=lowercase__      ,   pixel_mask=lowercase__)
               lowerCAmelCase__					     = model(lowercase__      ,   output_hidden_states=lowercase__)

        self.parent.assertEqual(
            output.transformer_decoder_last_hidden_state.shape      ,   (self.batch_size, self.num_queries, self.hidden_dim)      ,   )
        # let's ensure the other two hidden state exists
        self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None)
        self.parent.assertTrue(output.encoder_last_hidden_state is not None)

        if output_hidden_states:
               self.check_output_hidden_state(lowercase__      ,   lowercase__)




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  List[Any]      ,   lowercase__ :  Tuple      ,   lowercase__ :  List[Any]      ,   lowercase__ :  Optional[int]      ,   lowercase__ :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerForUniversalSegmentation(config=lowercase__)
        model.to(lowercase__)
        model.eval()

        def comm_check_on_output(lowercase__ :  str):
               # let's still check that all the required stuff is there
               self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None)
               self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None)
               self.parent.assertTrue(result.encoder_last_hidden_state is not None)
               # okay, now we need to check the logits shape
               # due to the encoder compression, masks have a //4 spatial size
               self.parent.assertEqual(
                   result.masks_queries_logits.shape      ,   (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)      ,   )
               # + 1 for null class
               self.parent.assertEqual(
                   result.class_queries_logits.shape      ,   (self.batch_size, self.num_queries, self.num_labels + 1))

        with torch.no_grad():
               lowerCAmelCase__					     = model(pixel_values=lowercase__      ,   pixel_mask=lowercase__)
               lowerCAmelCase__					     = model(lowercase__)

               comm_check_on_output(lowercase__)

               lowerCAmelCase__					     = model(
                   pixel_values=lowercase__      ,   pixel_mask=lowercase__      ,   mask_labels=lowercase__      ,   class_labels=lowercase__)

        comm_check_on_output(lowercase__)

        self.parent.assertTrue(result.loss is not None)
        self.parent.assertEqual(result.loss.shape      ,   torch.Size([1]))






@require_torch
class     a_			(						SCREAMING_SNAKE_CASE	,					SCREAMING_SNAKE_CASE	,					unittest.TestCase						):






 '''simple docstring'''






 UpperCAmelCase_     			= (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
 UpperCAmelCase_     			= {'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerModelTester(self)
        lowerCAmelCase__					     = ConfigTester(self      ,   config_class=lowercase__      ,   has_text_modality=lowercase__)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        self.config_tester.run_common_tests()




 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskaformer_model(lowercase__      ,   **lowercase__      ,   output_hidden_states=lowercase__)




 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*lowercase__)




 @unittest.skip(reason='Mask2Former does not use inputs_embeds')
 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method')
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Mask2Former is not a generative model')
 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Mask2Former does not use token embeddings')
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        pass




 @require_torch_multi_gpu
 @unittest.skip(
     reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`')
 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        pass




 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        pass




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = model_class(lowercase__)
               lowerCAmelCase__					     = inspect.signature(model.forward)
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               lowerCAmelCase__					     = [*signature.parameters.keys()]

               lowerCAmelCase__					     = ['pixel_values']
               self.assertListEqual(arg_names[:1]      ,   lowercase__)




 @slow
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
               lowerCAmelCase__					     = MaskaFormerModel.from_pretrained(lowercase__)
               self.assertIsNotNone(lowercase__)




 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        lowerCAmelCase__					     = (self.model_tester.min_size,) * 2
        lowerCAmelCase__					     = {
            'pixel_values': torch.randn((2, 3, *size)      ,   device=lowercase__),
            'mask_labels': torch.randn((2, 10, *size)      ,   device=lowercase__),
            'class_labels': torch.zeros(2      ,   10      ,   device=lowercase__).long(),
        }
        lowerCAmelCase__					     = self.model_tester.get_config()

        lowerCAmelCase__					     = MaskaFormerForUniversalSegmentation(lowercase__).to(lowercase__)
        lowerCAmelCase__					     = model(**lowercase__)
        self.assertTrue(outputs.loss is not None)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskaformer_model(lowercase__      ,   **lowercase__      ,   output_hidden_states=lowercase__)




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = model_class(lowercase__).to(lowercase__)
               lowerCAmelCase__					     = model(**lowercase__      ,   output_attentions=lowercase__)
               self.assertTrue(outputs.attentions is not None)




 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        if not self.model_tester.is_training:
               return

        lowerCAmelCase__					     = self.all_model_classes[1]
        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()

        lowerCAmelCase__					     = model_class(lowercase__)
        model.to(lowercase__)
        model.train()

        lowerCAmelCase__					     = model(lowercase__      ,   mask_labels=lowercase__      ,   class_labels=lowercase__).loss
        loss.backward()




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







        '''simple docstring'''



        lowerCAmelCase__					     = self.all_model_classes[1]
        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        lowerCAmelCase__					     = True
        lowerCAmelCase__					     = True

        lowerCAmelCase__					     = model_class(lowercase__).to(lowercase__)
        model.train()

        lowerCAmelCase__					     = model(lowercase__      ,   mask_labels=lowercase__      ,   class_labels=lowercase__)

        lowerCAmelCase__					     = outputs.encoder_hidden_states[0]
        encoder_hidden_states.retain_grad()

        lowerCAmelCase__					     = outputs.pixel_decoder_hidden_states[0]
        pixel_decoder_hidden_states.retain_grad()

        lowerCAmelCase__					     = outputs.transformer_decoder_hidden_states[0]
        transformer_decoder_hidden_states.retain_grad()

        lowerCAmelCase__					     = outputs.attentions[0]
        attentions.retain_grad()

        outputs.loss.backward(retain_graph=lowercase__)

        self.assertIsNotNone(encoder_hidden_states.grad)
        self.assertIsNotNone(pixel_decoder_hidden_states.grad)
        self.assertIsNotNone(transformer_decoder_hidden_states.grad)
        self.assertIsNotNone(attentions.grad)






lowerCAmelCase__     						=			1e-4






def 				__lowerCamelCase		(						):
       lowerCAmelCase__					     = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
       return image



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






 '''simple docstring'''






 @cached_property
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        return "facebook/mask2former-swin-small-coco-instance"




 @cached_property
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None




 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(lowercase__)
        lowerCAmelCase__					     = self.default_image_processor
        lowerCAmelCase__					     = prepare_img()
        lowerCAmelCase__					     = image_processor(lowercase__      ,   return_tensors='pt').to(lowercase__)
        lowerCAmelCase__					     = inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
        # check size
        self.assertEqual(lowercase__      ,   (1, 3, 384, 384))

        with torch.no_grad():
               lowerCAmelCase__					     = model(**lowercase__)

        lowerCAmelCase__					     = torch.tensor(
            [[-0.2_790, -1.0_717, -1.1_668], [-0.5_128, -0.3_128, -0.4_987], [-0.5_832, 0.1_971, -0.0_197]]).to(lowercase__)
        self.assertTrue(
            torch.allclose(
                outputs.encoder_last_hidden_state[0, 0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))

        lowerCAmelCase__					     = torch.tensor(
            [[0.8_973, 1.1_847, 1.1_776], [1.1_934, 1.5_040, 1.5_128], [1.1_153, 1.4_486, 1.4_951]]).to(lowercase__)
        self.assertTrue(
            torch.allclose(
                outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))

        lowerCAmelCase__					     = torch.tensor(
            [[2.1_152, 1.7_000, -0.8_603], [1.5_808, 1.8_004, -0.9_353], [1.6_043, 1.7_495, -0.5_999]]).to(lowercase__)
        self.assertTrue(
            torch.allclose(
                outputs.transformer_decoder_last_hidden_state[0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))




 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(lowercase__).eval()
        lowerCAmelCase__					     = self.default_image_processor
        lowerCAmelCase__					     = prepare_img()
        lowerCAmelCase__					     = image_processor(lowercase__      ,   return_tensors='pt').to(lowercase__)
        lowerCAmelCase__					     = inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
        # check size
        self.assertEqual(lowercase__      ,   (1, 3, 384, 384))

        with torch.no_grad():
               lowerCAmelCase__					     = model(**lowercase__)
        # masks_queries_logits
        lowerCAmelCase__					     = outputs.masks_queries_logits
        self.assertEqual(
            masks_queries_logits.shape      ,   (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4))
        lowerCAmelCase__					     = [
            [-8.7_839, -9.0_056, -8.8_121],
            [-7.4_104, -7.0_313, -6.5_401],
            [-6.6_105, -6.3_427, -6.4_675],
        ]
        lowerCAmelCase__					     = torch.tensor(lowercase__).to(lowercase__)
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))
        # class_queries_logits
        lowerCAmelCase__					     = outputs.class_queries_logits
        self.assertEqual(class_queries_logits.shape      ,   (1, model.config.num_queries, model.config.num_labels + 1))
        lowerCAmelCase__					     = torch.tensor(
            [
                [1.8_324, -8.0_835, -4.1_922],
                [0.8_450, -9.0_050, -3.6_053],
                [0.3_045, -7.7_293, -3.0_275],
            ]).to(lowercase__)
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(lowercase__).eval()
        lowerCAmelCase__					     = self.default_image_processor

        lowerCAmelCase__					     = image_processor(
            [np.zeros((3, 800, 1_333)), np.zeros((3, 800, 1_333))]      ,   segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)]      ,   return_tensors='pt'      ,   )

        lowerCAmelCase__					     = inputs['pixel_values'].to(lowercase__)
        lowerCAmelCase__					     = [el.to(lowercase__) for el in inputs['mask_labels']]
        lowerCAmelCase__					     = [el.to(lowercase__) for el in inputs['class_labels']]

        with torch.no_grad():
               lowerCAmelCase__					     = model(**lowercase__)

        self.assertTrue(outputs.loss is not None)

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__)
