





import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from tqdm import tqdm

from transformers import GPTaLMHeadModel


snake_case__					:							Dict													=     logging.getLogger(__name__)



def _a				(	lowerCamelCase:   Any					,				lowerCamelCase:   str )	->						Union[str, Any]:







      '''simple docstring'''






      if os.path.exists(lowerCamelCase ):
            if os.path.exists(os.path.join(lowerCamelCase					,				'''config.json''' ) ) and os.path.isfile(
                os.path.join(lowerCamelCase					,				'''config.json''' ) ):
                  os.remove(os.path.join(lowerCamelCase					,				'''config.json''' ) )
            if os.path.exists(os.path.join(lowerCamelCase					,				'''pytorch_model.bin''' ) ) and os.path.isfile(
                os.path.join(lowerCamelCase					,				'''pytorch_model.bin''' ) ):
                  os.remove(os.path.join(lowerCamelCase					,				'''pytorch_model.bin''' ) )
      else:
            os.makedirs(lowerCamelCase )
      model.save_pretrained(lowerCamelCase )



def _a				(	lowerCamelCase:   Tuple					,				lowerCamelCase:   int=False )	->						Tuple:







      '''simple docstring'''






      __A          =				2
      if unlogit:
            __A          =				torch.pow(lowerCamelCase					,				lowerCamelCase )
      __A          =				p * torch.log(lowerCamelCase )
      __A          =				0
      return -plogp.sum(dim=-1 )



def _a				(	lowerCamelCase:   Any )	->						List[str]:







      '''simple docstring'''






      logger.info('''lv, h >\t''' + '''\t'''.join(F"""{x + 1}""" for x in range(len(lowerCamelCase ) ) ) )
      for row in range(len(lowerCamelCase ) ):
            if tensor.dtype != torch.long:
                  logger.info(F"""layer {row + 1}:\t""" + '''\t'''.join(F"""{x:.5f}""" for x in tensor[row].cpu().data ) )
            else:
                  logger.info(F"""layer {row + 1}:\t""" + '''\t'''.join(F"""{x:d}""" for x in tensor[row].cpu().data ) )



def _a				(	lowerCamelCase:   Tuple					,				lowerCamelCase:   List[str]					,				lowerCamelCase:   Optional[int]					,				lowerCamelCase:   List[Any]=True					,				lowerCamelCase:   Union[str, Any]=True					,				lowerCamelCase:   Union[str, Any]=None					,				lowerCamelCase:   Any=False )	->						Optional[int]:







      '''simple docstring'''






      __A   ,						__A          =				model.config.num_hidden_layers, model.config.num_attention_heads
      __A          =				torch.zeros(lowerCamelCase					,				lowerCamelCase ).to(args.device )
      __A          =				torch.zeros(lowerCamelCase					,				lowerCamelCase ).to(args.device )

      if head_mask is None:
            __A          =				torch.ones(lowerCamelCase					,				lowerCamelCase ).to(args.device )

      head_mask.requires_grad_(requires_grad=lowerCamelCase )
      # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
      if actually_pruned:
            __A          =				None

      __A          =				0.0
      __A          =				0.0
      for step, inputs in enumerate(tqdm(lowerCamelCase					,				desc='''Iteration'''					,				disable=args.local_rank not in [-1, 0] ) ):
            __A          =				tuple(t.to(args.device ) for t in inputs )
            ((__A)   ,						)          =				inputs

            # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
            __A          =				model(lowerCamelCase					,				labels=lowerCamelCase					,				head_mask=lowerCamelCase )
            #  (loss), lm_logits, presents, (all hidden_states), (attentions)
            __A   ,						__A   ,						__A          =				(
                outputs[0],
                outputs[1],
                outputs[-1],
            )  # Loss and logits are the first, attention the last
            loss.backward()  # Backpropagate to populate the gradients in the head mask
            total_loss += loss.detach().cpu().numpy()
            if compute_entropy:
                  for layer, attn in enumerate(lowerCamelCase ):
                        __A          =				entropy(attn.detach()					,				lowerCamelCase )
                        attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach()

            if compute_importance:
                  head_importance += head_mask.grad.abs().detach()
            tot_tokens += torch.ones_like(lowerCamelCase ).float().detach().sum().data

      # Normalize
      attn_entropy /= tot_tokens
      head_importance /= tot_tokens
      # Layerwise importance normalization
      if not args.dont_normalize_importance_by_layer:
            __A          =				2
            __A          =				torch.pow(torch.pow(lowerCamelCase					,				lowerCamelCase ).sum(-1 )					,				1 / exponent )
            head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20

      if not args.dont_normalize_global_importance:
            __A          =				(head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

      # Print matrices
      if compute_entropy:
            logger.info('''Attention entropies''' )
            print_ad_tensor(lowerCamelCase )
      if compute_importance:
            logger.info('''Head importance scores''' )
            print_ad_tensor(lowerCamelCase )
      logger.info('''Head ranked by importance scores''' )
      __A          =				torch.zeros(head_importance.numel()					,				dtype=torch.long					,				device=args.device )
      __A          =				torch.arange(
          head_importance.numel()					,				device=args.device )
      __A          =				head_ranks.view_as(lowerCamelCase )
      print_ad_tensor(lowerCamelCase )
      return attn_entropy, head_importance, total_loss



def _a				(	lowerCamelCase:   Tuple					,				lowerCamelCase:   Union[str, Any]					,				lowerCamelCase:   Dict )	->						List[str]:







      '''simple docstring'''






      __A   ,						__A   ,						__A          =				compute_heads_importance(lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				compute_entropy=lowerCamelCase )
      __A          =				1 / loss  # instead of downsteam score use the LM loss
      logger.info('''Pruning: original score: %f, threshold: %f'''					,				lowerCamelCase					,				original_score * args.masking_threshold )

      __A          =				torch.ones_like(lowerCamelCase )
      __A          =				max(1					,				int(new_head_mask.numel() * args.masking_amount ) )

      __A          =				original_score
      while current_score >= original_score * args.masking_threshold:
            __A          =				new_head_mask.clone().detach()  # save current head mask
            # heads from least important to most - keep only not-masked heads
            __A          =				float('''Inf''' )
            __A          =				head_importance.view(-1 ).sort()[1]

            if len(lowerCamelCase ) <= num_to_mask:
                  print('''BREAK BY num_to_mask''' )
                  break

            # mask heads
            __A          =				current_heads_to_mask[:num_to_mask]
            logger.info('''Heads to mask: %s'''					,				str(current_heads_to_mask.tolist() ) )
            __A          =				new_head_mask.view(-1 )
            __A          =				0.0
            __A          =				new_head_mask.view_as(lowerCamelCase )
            __A          =				new_head_mask.clone().detach()
            print_ad_tensor(lowerCamelCase )

            # Compute metric and head importance again
            __A   ,						__A   ,						__A          =				compute_heads_importance(
                lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				compute_entropy=lowerCamelCase					,				head_mask=lowerCamelCase )
            __A          =				1 / loss
            logger.info(
                '''Masking: current score: %f, remaining heads %d (%.1f percents)'''					,				lowerCamelCase					,				new_head_mask.sum()					,				new_head_mask.sum() / new_head_mask.numel() * 1_00					,				)

      logger.info('''Final head mask''' )
      print_ad_tensor(lowerCamelCase )
      np.save(os.path.join(args.output_dir					,				'''head_mask.npy''' )					,				head_mask.detach().cpu().numpy() )

      return head_mask



def _a				(	lowerCamelCase:   Optional[int]					,				lowerCamelCase:   Optional[Any]					,				lowerCamelCase:   Optional[Any]					,				lowerCamelCase:   int )	->						Any:







      '''simple docstring'''






      __A          =				datetime.now()
      __A   ,						__A   ,						__A          =				compute_heads_importance(
          lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				compute_entropy=lowerCamelCase					,				compute_importance=lowerCamelCase					,				head_mask=lowerCamelCase )
      __A          =				1 / loss
      __A          =				datetime.now() - before_time

      __A          =				sum(p.numel() for p in model.parameters() )
      __A          =				{
          layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCamelCase ) )
      }

      for k, v in heads_to_prune.items():
            if isinstance(lowerCamelCase					,				lowerCamelCase ):
                  __A          =				[
                      v,
                  ]

      assert sum(len(lowerCamelCase ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item()
      model.prune_heads(lowerCamelCase )
      __A          =				sum(p.numel() for p in model.parameters() )

      __A          =				datetime.now()
      __A   ,						__A   ,						__A          =				compute_heads_importance(
          lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				compute_entropy=lowerCamelCase					,				compute_importance=lowerCamelCase					,				head_mask=lowerCamelCase					,				actually_pruned=lowerCamelCase					,				)

      __A          =				1 / loss
      __A          =				datetime.now() - before_time

      logger.info(
          '''Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)'''					,				lowerCamelCase					,				lowerCamelCase					,				pruned_num_params / original_num_params * 1_00					,				)
      logger.info('''Pruning: score with masking: %f score with pruning: %f'''					,				lowerCamelCase					,				lowerCamelCase )
      logger.info('''Pruning: speed ratio (original timing / new timing): %f percents'''					,				original_time / new_time * 1_00 )
      save_model(lowerCamelCase					,				args.output_dir )



def _a				(	)	->						Tuple:







      '''simple docstring'''






      __A          =				argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          '''--data_dir'''					,				default=lowerCamelCase					,				type=lowerCamelCase					,				required=lowerCamelCase					,				help='''The input data dir. Should contain the .tsv files (or other data files) for the task.'''					,				)
      parser.add_argument(
          '''--model_name_or_path'''					,				default=lowerCamelCase					,				type=lowerCamelCase					,				required=lowerCamelCase					,				help='''Path to pretrained model or model identifier from huggingface.co/models'''					,				)
      parser.add_argument(
          '''--output_dir'''					,				default=lowerCamelCase					,				type=lowerCamelCase					,				required=lowerCamelCase					,				help='''The output directory where the model predictions and checkpoints will be written.'''					,				)

      # Other parameters
      parser.add_argument(
          '''--config_name'''					,				default=''''''					,				type=lowerCamelCase					,				help='''Pretrained config name or path if not the same as model_name_or_path'''					,				)
      parser.add_argument(
          '''--tokenizer_name'''					,				default=''''''					,				type=lowerCamelCase					,				help='''Pretrained tokenizer name or path if not the same as model_name_or_path'''					,				)
      parser.add_argument(
          '''--cache_dir'''					,				default=lowerCamelCase					,				type=lowerCamelCase					,				help='''Where do you want to store the pre-trained models downloaded from s3'''					,				)
      parser.add_argument(
          '''--data_subset'''					,				type=lowerCamelCase					,				default=-1					,				help='''If > 0: limit the data to a subset of data_subset instances.''' )
      parser.add_argument(
          '''--overwrite_output_dir'''					,				action='''store_true'''					,				help='''Whether to overwrite data in output directory''' )
      parser.add_argument(
          '''--overwrite_cache'''					,				action='''store_true'''					,				help='''Overwrite the cached training and evaluation sets''' )

      parser.add_argument(
          '''--dont_normalize_importance_by_layer'''					,				action='''store_true'''					,				help='''Don\'t normalize importance score by layers''' )
      parser.add_argument(
          '''--dont_normalize_global_importance'''					,				action='''store_true'''					,				help='''Don\'t normalize all importance scores between 0 and 1'''					,				)

      parser.add_argument(
          '''--try_masking'''					,				action='''store_true'''					,				help='''Whether to try to mask head until a threshold of accuracy.''' )
      parser.add_argument(
          '''--masking_threshold'''					,				default=0.9					,				type=lowerCamelCase					,				help='''masking threshold in term of metrics (stop masking when metric < threshold * original metric value).'''					,				)
      parser.add_argument(
          '''--masking_amount'''					,				default=0.1					,				type=lowerCamelCase					,				help='''Amount to heads to masking at each masking step.''' )
      parser.add_argument('''--metric_name'''					,				default='''acc'''					,				type=lowerCamelCase					,				help='''Metric to use for head masking.''' )

      parser.add_argument(
          '''--max_seq_length'''					,				default=1_28					,				type=lowerCamelCase					,				help=(
              '''The maximum total input sequence length after WordPiece tokenization. \n'''
              '''Sequences longer than this will be truncated, sequences shorter padded.'''
          )					,				)
      parser.add_argument('''--batch_size'''					,				default=1					,				type=lowerCamelCase					,				help='''Batch size.''' )

      parser.add_argument('''--seed'''					,				type=lowerCamelCase					,				default=42 )
      parser.add_argument('''--local_rank'''					,				type=lowerCamelCase					,				default=-1					,				help='''local_rank for distributed training on gpus''' )
      parser.add_argument('''--no_cuda'''					,				action='''store_true'''					,				help='''Whether not to use CUDA when available''' )
      parser.add_argument('''--server_ip'''					,				type=lowerCamelCase					,				default=''''''					,				help='''Can be used for distant debugging.''' )
      parser.add_argument('''--server_port'''					,				type=lowerCamelCase					,				default=''''''					,				help='''Can be used for distant debugging.''' )
      __A          =				parser.parse_args()

      if args.server_ip and args.server_port:
            # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
            import ptvsd

            print('''Waiting for debugger attach''' )
            ptvsd.enable_attach(address=(args.server_ip, args.server_port)					,				redirect_output=lowerCamelCase )
            ptvsd.wait_for_attach()

      # Setup devices and distributed training
      if args.local_rank == -1 or args.no_cuda:
            __A          =				torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu''' )
            __A          =				0 if args.no_cuda else torch.cuda.device_count()
      else:
            torch.cuda.set_device(args.local_rank )
            __A          =				torch.device('''cuda'''					,				args.local_rank )
            __A          =				1
            torch.distributed.init_process_group(backend='''nccl''' )  # Initializes the distributed backend

      # Setup logging
      logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN )
      logger.info('''device: {} n_gpu: {}, distributed: {}'''.format(args.device					,				args.n_gpu					,				bool(args.local_rank != -1 ) ) )

      __A          =				GPTaLMHeadModel.from_pretrained(args.model_name_or_path )

      # Distributed and parallel training
      model.to(args.device )
      if args.local_rank != -1:
            __A          =				nn.parallel.DistributedDataParallel(
                lowerCamelCase					,				device_ids=[args.local_rank]					,				output_device=args.local_rank					,				find_unused_parameters=lowerCamelCase )
      elif args.n_gpu > 1:
            __A          =				nn.DataParallel(lowerCamelCase )

      # Print/save training arguments
      os.makedirs(args.output_dir					,				exist_ok=lowerCamelCase )
      torch.save(lowerCamelCase					,				os.path.join(args.output_dir					,				'''run_args.bin''' ) )
      logger.info('''Training/evaluation parameters %s'''					,				lowerCamelCase )

      # Prepare dataset
      __A          =				np.concatenate(
          [
              np.loadtxt(args.data_dir					,				dtype=np.intaa ),
          ] )
      __A          =				(torch.from_numpy(lowerCamelCase ),)
      __A          =				TensorDataset(*lowerCamelCase )
      __A          =				RandomSampler(lowerCamelCase )
      __A          =				DataLoader(lowerCamelCase					,				sampler=lowerCamelCase					,				batch_size=args.batch_size )

      # Compute head entropy and importance score
      compute_heads_importance(lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase )

      # Try head masking (set heads to zero until the score goes under a threshole)
      # and head pruning (remove masked heads and see the effect on the network)
      if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
            __A          =				mask_heads(lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase )
            prune_heads(lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase )


if __name__ == "__main__":
       main()












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_					(			_lowerCamelCase   ):
   lowerCAmelCase__        = 42





@flax_register_to_config
class A_					(			nn.Module ,      _lowerCamelCase ,      _lowerCamelCase   ):
   lowerCAmelCase__        = 32
   lowerCAmelCase__        = 4
   lowerCAmelCase__        = 4
   lowerCAmelCase__        = (
       "CrossAttnDownBlock2D",
       "CrossAttnDownBlock2D",
       "CrossAttnDownBlock2D",
       "DownBlock2D",
   )
   lowerCAmelCase__        = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")
   lowerCAmelCase__        = False
   lowerCAmelCase__        = (320, 640, 1280, 1280)
   lowerCAmelCase__        = 2
   lowerCAmelCase__        = 8
   lowerCAmelCase__        = None
   lowerCAmelCase__        = 1280
   lowerCAmelCase__        = 0.0
   lowerCAmelCase__        = False
   lowerCAmelCase__        = jnp.floataa
   lowerCAmelCase__        = True
   lowerCAmelCase__        = 0
   lowerCAmelCase__        = False




   def _lowerCAmelCase      (self	:Tuple    ,   _UpperCamelCase	:jax.random.KeyArray )->					FrozenDict:
         # init input tensors
         __A          =				(1, self.in_channels, self.sample_size, self.sample_size)
         __A          =				jnp.zeros(_UpperCamelCase    ,   dtype=jnp.floataa )
         __A          =				jnp.ones((1,)    ,   dtype=jnp.intaa )
         __A          =				jnp.zeros((1, 1, self.cross_attention_dim)    ,   dtype=jnp.floataa )

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

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




   def _lowerCAmelCase      (self	:Tuple )->					Optional[int]:
         __A          =				self.block_out_channels
         __A          =				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.
         __A          =				self.num_attention_heads or self.attention_head_dim

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

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

         __A          =				self.only_cross_attention
         if isinstance(_UpperCamelCase    ,   _UpperCamelCase ):
               __A          =				(only_cross_attention,) * len(self.down_block_types )

         if isinstance(_UpperCamelCase    ,   _UpperCamelCase ):
               __A          =				(num_attention_heads,) * len(self.down_block_types )

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

               if down_block_type == "CrossAttnDownBlock2D":
                     __A          =				FlaxCrossAttnDownBlockaD(
                         in_channels=_UpperCamelCase    ,   out_channels=_UpperCamelCase    ,   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:
                     __A          =				FlaxDownBlockaD(
                         in_channels=_UpperCamelCase    ,   out_channels=_UpperCamelCase    ,   dropout=self.dropout    ,   num_layers=self.layers_per_block    ,   add_downsample=not is_final_block    ,   dtype=self.dtype    ,   )

               down_blocks.append(_UpperCamelCase )
         __A          =				down_blocks

         # mid
         __A          =				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
         __A          =				[]
         __A          =				list(reversed(_UpperCamelCase ) )
         __A          =				list(reversed(_UpperCamelCase ) )
         __A          =				list(reversed(_UpperCamelCase ) )
         __A          =				reversed_block_out_channels[0]
         for i, up_block_type in enumerate(self.up_block_types ):
               __A          =				output_channel
               __A          =				reversed_block_out_channels[i]
               __A          =				reversed_block_out_channels[min(i + 1    ,   len(_UpperCamelCase ) - 1 )]

               __A          =				i == len(_UpperCamelCase ) - 1

               if up_block_type == "CrossAttnUpBlock2D":
                     __A          =				FlaxCrossAttnUpBlockaD(
                         in_channels=_UpperCamelCase    ,   out_channels=_UpperCamelCase    ,   prev_output_channel=_UpperCamelCase    ,   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:
                     __A          =				FlaxUpBlockaD(
                         in_channels=_UpperCamelCase    ,   out_channels=_UpperCamelCase    ,   prev_output_channel=_UpperCamelCase    ,   num_layers=self.layers_per_block + 1    ,   add_upsample=not is_final_block    ,   dropout=self.dropout    ,   dtype=self.dtype    ,   )

               up_blocks.append(_UpperCamelCase )
               __A          =				output_channel
         __A          =				up_blocks

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






   def __call__(self	:Union[str, Any]    ,   _UpperCamelCase	:Any    ,   _UpperCamelCase	:List[str]    ,   _UpperCamelCase	:str    ,   _UpperCamelCase	:int=None    ,   _UpperCamelCase	:Optional[int]=None    ,   _UpperCamelCase	:bool = True    ,   _UpperCamelCase	:bool = False    ,   )->					Union[FlaxUNetaDConditionOutput, Tuple]:
         # 1. time
         if not isinstance(_UpperCamelCase    ,   jnp.ndarray ):
               __A          =				jnp.array([timesteps]    ,   dtype=jnp.intaa )
         elif isinstance(_UpperCamelCase    ,   jnp.ndarray ) and len(timesteps.shape ) == 0:
               __A          =				timesteps.astype(dtype=jnp.floataa )
               __A          =				jnp.expand_dims(_UpperCamelCase    ,   0 )

         __A          =				self.time_proj(_UpperCamelCase )
         __A          =				self.time_embedding(_UpperCamelCase )

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

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

         if down_block_additional_residuals is not None:
               __A          =				()

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

               __A          =				new_down_block_res_samples

         # 4. mid
         __A          =				self.mid_block(_UpperCamelCase    ,   _UpperCamelCase    ,   _UpperCamelCase    ,   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:
               __A          =				down_block_res_samples[-(self.layers_per_block + 1) :]
               __A          =				down_block_res_samples[: -(self.layers_per_block + 1)]
               if isinstance(_UpperCamelCase    ,   _UpperCamelCase ):
                     __A          =				up_block(
                         _UpperCamelCase    ,   temb=_UpperCamelCase    ,   encoder_hidden_states=_UpperCamelCase    ,   res_hidden_states_tuple=_UpperCamelCase    ,   deterministic=not train    ,   )
               else:
                     __A          =				up_block(_UpperCamelCase    ,   temb=_UpperCamelCase    ,   res_hidden_states_tuple=_UpperCamelCase    ,   deterministic=not train )

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

         if not return_dict:
               return (sample,)

         return FlaxUNetaDConditionOutput(sample=_UpperCamelCase )





