




'''simple docstring'''





import argparse
import csv
import logging
import os
import random

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

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO
)
lowerCAmelCase_					    = logging.getLogger(__name__)



def      __lowerCAmelCase			(					UpperCamelCase	,      UpperCamelCase      )     ->	Dict:
  lowerCAmelCase__				:  Any		       =     np.argmax(UpperCamelCase	,      axis=1      )
  return np.sum(outputs == labels      )



def      __lowerCAmelCase			(					UpperCamelCase      )     ->	Union[str, Any]:
  with open(UpperCamelCase	,      encoding='''utf_8'''      ) as f:
    lowerCAmelCase__				:  str		       =     csv.reader(UpperCamelCase      )
    lowerCAmelCase__				:  str		       =     []
    next(UpperCamelCase      )  # skip the first line
    for line in tqdm(UpperCamelCase      ):
      output.append((''' '''.join(line[1:5]      ), line[5], line[6], int(line[-1]      ) - 1)      )
  return output



def      __lowerCAmelCase			(					UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase      )     ->	Any:
  lowerCAmelCase__				:  Tuple		       =     []
  for dataset in encoded_datasets:
    lowerCAmelCase__				:  Any		       =     len(UpperCamelCase      )
    lowerCAmelCase__				:  Any		       =     np.zeros((n_batch, 2, input_len)	,      dtype=np.intaa      )
    lowerCAmelCase__				:  List[Any]		       =     np.zeros((n_batch, 2)	,      dtype=np.intaa      )
    lowerCAmelCase__				:  Optional[int]		       =     np.full((n_batch, 2, input_len)	,      fill_value=-100	,      dtype=np.intaa      )
    lowerCAmelCase__				:  Union[str, Any]		       =     np.zeros((n_batch,)	,      dtype=np.intaa      )
    for (
        i,
        (story, conta, conta, mc_label),
    ) in enumerate(UpperCamelCase      ):
      lowerCAmelCase__				:  Optional[Any]		       =     [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
      lowerCAmelCase__				:  str		       =     [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
      lowerCAmelCase__				:  Any		       =     with_conta
      lowerCAmelCase__				:  Optional[int]		       =     with_conta
      lowerCAmelCase__				:  List[Any]		       =     len(UpperCamelCase      ) - 1
      lowerCAmelCase__				:  str		       =     len(UpperCamelCase      ) - 1
      lowerCAmelCase__				:  Union[str, Any]		       =     with_conta
      lowerCAmelCase__				:  Dict		       =     with_conta
      lowerCAmelCase__				:  List[Any]		       =     mc_label
    lowerCAmelCase__				:  int		       =     (input_ids, mc_token_ids, lm_labels, mc_labels)
    tensor_datasets.append(tuple(torch.tensor(UpperCamelCase      ) for t in all_inputs      )      )
  return tensor_datasets



def      __lowerCAmelCase			(					)     ->	str:
  lowerCAmelCase__				:  str		       =     argparse.ArgumentParser()
  parser.add_argument('''--model_name'''	,      type=UpperCamelCase	,      default='''openai-gpt'''	,      help='''pretrained model name'''      )
  parser.add_argument('''--do_train'''	,      action='''store_true'''	,      help='''Whether to run training.'''      )
  parser.add_argument('''--do_eval'''	,      action='''store_true'''	,      help='''Whether to run eval on the dev set.'''      )
  parser.add_argument(
      '''--output_dir'''	,      default=UpperCamelCase	,      type=UpperCamelCase	,      required=UpperCamelCase	,      help='''The output directory where the model predictions and checkpoints will be written.'''	,      )
  parser.add_argument('''--train_dataset'''	,      type=UpperCamelCase	,      default=''''''      )
  parser.add_argument('''--eval_dataset'''	,      type=UpperCamelCase	,      default=''''''      )
  parser.add_argument('''--seed'''	,      type=UpperCamelCase	,      default=42      )
  parser.add_argument('''--num_train_epochs'''	,      type=UpperCamelCase	,      default=3      )
  parser.add_argument('''--train_batch_size'''	,      type=UpperCamelCase	,      default=8      )
  parser.add_argument('''--eval_batch_size'''	,      type=UpperCamelCase	,      default=16      )
  parser.add_argument('''--adam_epsilon'''	,      default=1E-8	,      type=UpperCamelCase	,      help='''Epsilon for Adam optimizer.'''      )
  parser.add_argument('''--max_grad_norm'''	,      type=UpperCamelCase	,      default=1      )
  parser.add_argument(
      '''--max_steps'''	,      default=-1	,      type=UpperCamelCase	,      help=(
          '''If > 0: set total number of training                         steps to perform. Override num_train_epochs.'''
      )	,      )
  parser.add_argument(
      '''--gradient_accumulation_steps'''	,      type=UpperCamelCase	,      default=1	,      help='''Number of updates steps to accumulate before                        performing a backward/update pass.'''	,      )
  parser.add_argument('''--learning_rate'''	,      type=UpperCamelCase	,      default=6.25E-5      )
  parser.add_argument('''--warmup_steps'''	,      default=0	,      type=UpperCamelCase	,      help='''Linear warmup over warmup_steps.'''      )
  parser.add_argument('''--lr_schedule'''	,      type=UpperCamelCase	,      default='''warmup_linear'''      )
  parser.add_argument('''--weight_decay'''	,      type=UpperCamelCase	,      default=0.01      )
  parser.add_argument('''--lm_coef'''	,      type=UpperCamelCase	,      default=0.9      )
  parser.add_argument('''--n_valid'''	,      type=UpperCamelCase	,      default=374      )

  parser.add_argument('''--server_ip'''	,      type=UpperCamelCase	,      default=''''''	,      help='''Can be used for distant debugging.'''      )
  parser.add_argument('''--server_port'''	,      type=UpperCamelCase	,      default=''''''	,      help='''Can be used for distant debugging.'''      )
  lowerCAmelCase__				:  Tuple		       =     parser.parse_args()
  print(UpperCamelCase      )

  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=UpperCamelCase      )
    ptvsd.wait_for_attach()

  random.seed(args.seed      )
  np.random.seed(args.seed      )
  torch.manual_seed(args.seed      )
  torch.cuda.manual_seed_all(args.seed      )

  lowerCAmelCase__				:  Dict		       =     torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''      )
  lowerCAmelCase__				:  List[str]		       =     torch.cuda.device_count()
  logger.info('''device: {}, n_gpu {}'''.format(UpperCamelCase	,      UpperCamelCase      )      )

  if not args.do_train and not args.do_eval:
    raise ValueError('''At least one of `do_train` or `do_eval` must be True.'''      )

  if not os.path.exists(args.output_dir      ):
    os.makedirs(args.output_dir      )

  # Load tokenizer and model
  # This loading functions also add new tokens and embeddings called `special tokens`
  # These new embeddings will be fine-tuned on the RocStories dataset
  lowerCAmelCase__				:  Any		       =     ['''_start_''', '''_delimiter_''', '''_classify_''']
  lowerCAmelCase__				:  Optional[Any]		       =     OpenAIGPTTokenizer.from_pretrained(args.model_name      )
  tokenizer.add_tokens(UpperCamelCase      )
  lowerCAmelCase__				:  Optional[int]		       =     tokenizer.convert_tokens_to_ids(UpperCamelCase      )
  lowerCAmelCase__				:  Optional[Any]		       =     OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name      )
  model.resize_token_embeddings(len(UpperCamelCase      )      )
  model.to(UpperCamelCase      )

  # Load and encode the datasets
  def tokenize_and_encode(UpperCamelCase      ):
    if isinstance(UpperCamelCase	,      UpperCamelCase      ):
      return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(UpperCamelCase      )      )
    elif isinstance(UpperCamelCase	,      UpperCamelCase      ):
      return obj
    return [tokenize_and_encode(UpperCamelCase      ) for o in obj]

  logger.info('''Encoding dataset...'''      )
  lowerCAmelCase__				:  Any		       =     load_rocstories_dataset(args.train_dataset      )
  lowerCAmelCase__				:  Any		       =     load_rocstories_dataset(args.eval_dataset      )
  lowerCAmelCase__				:  Optional[int]		       =     (train_dataset, eval_dataset)
  lowerCAmelCase__				:  Union[str, Any]		       =     tokenize_and_encode(UpperCamelCase      )

  # Compute the max input length for the Transformer
  lowerCAmelCase__				:  List[str]		       =     model.config.n_positions // 2 - 2
  lowerCAmelCase__				:  Dict		       =     max(
      len(story[:max_length]      ) + max(len(conta[:max_length]      )	,      len(conta[:max_length]      )      ) + 3
      for dataset in encoded_datasets
      for story, conta, conta, _ in dataset      )
  lowerCAmelCase__				:  Optional[Any]		       =     min(UpperCamelCase	,      model.config.n_positions      )  # Max size of input for the pre-trained model

  # Prepare inputs tensors and dataloaders
  lowerCAmelCase__				:  Optional[Any]		       =     pre_process_datasets(UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase	,      *UpperCamelCase      )
  lowerCAmelCase__				:  Tuple		       =     tensor_datasets[0], tensor_datasets[1]

  lowerCAmelCase__				:  Tuple		       =     TensorDataset(*UpperCamelCase      )
  lowerCAmelCase__				:  Optional[int]		       =     RandomSampler(UpperCamelCase      )
  lowerCAmelCase__				:  int		       =     DataLoader(UpperCamelCase	,      sampler=UpperCamelCase	,      batch_size=args.train_batch_size      )

  lowerCAmelCase__				:  Optional[int]		       =     TensorDataset(*UpperCamelCase      )
  lowerCAmelCase__				:  Dict		       =     SequentialSampler(UpperCamelCase      )
  lowerCAmelCase__				:  Any		       =     DataLoader(UpperCamelCase	,      sampler=UpperCamelCase	,      batch_size=args.eval_batch_size      )

  # Prepare optimizer
  if args.do_train:
    if args.max_steps > 0:
      lowerCAmelCase__				:  Dict		       =     args.max_steps
      lowerCAmelCase__				:  Optional[int]		       =     args.max_steps // (len(UpperCamelCase      ) // args.gradient_accumulation_steps) + 1
    else:
      lowerCAmelCase__				:  Dict		       =     len(UpperCamelCase      ) // args.gradient_accumulation_steps * args.num_train_epochs

    lowerCAmelCase__				:  Tuple		       =     list(model.named_parameters()      )
    lowerCAmelCase__				:  List[str]		       =     ['''bias''', '''LayerNorm.bias''', '''LayerNorm.weight''']
    lowerCAmelCase__				:  Optional[Any]		       =     [
        {
            '''params''': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay      )],
            '''weight_decay''': args.weight_decay,
        },
        {'''params''': [p for n, p in param_optimizer if any(nd in n for nd in no_decay      )], '''weight_decay''': 0.0},
    ]
    lowerCAmelCase__				:  Optional[int]		       =     AdamW(UpperCamelCase	,      lr=args.learning_rate	,      eps=args.adam_epsilon      )
    lowerCAmelCase__				:  str		       =     get_linear_schedule_with_warmup(
        UpperCamelCase	,      num_warmup_steps=args.warmup_steps	,      num_training_steps=UpperCamelCase      )

  if args.do_train:
    lowerCAmelCase__				:  Any		       =     0, 0, None
    model.train()
    for _ in trange(int(args.num_train_epochs      )	,      desc='''Epoch'''      ):
      lowerCAmelCase__				:  str		       =     0
      lowerCAmelCase__				:  List[str]		       =     0
      lowerCAmelCase__				:  Any		       =     tqdm(UpperCamelCase	,      desc='''Training'''      )
      for step, batch in enumerate(UpperCamelCase      ):
        lowerCAmelCase__				:  Union[str, Any]		       =     tuple(t.to(UpperCamelCase      ) for t in batch      )
        lowerCAmelCase__				:  Optional[int]		       =     batch
        lowerCAmelCase__				:  Optional[Any]		       =     model(UpperCamelCase	,      mc_token_ids=UpperCamelCase	,      lm_labels=UpperCamelCase	,      mc_labels=UpperCamelCase      )
        lowerCAmelCase__				:  int		       =     args.lm_coef * losses[0] + losses[1]
        loss.backward()
        optimizer.step()
        scheduler.step()
        optimizer.zero_grad()
        tr_loss += loss.item()
        lowerCAmelCase__				:  List[str]		       =     (
            loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
        )
        nb_tr_steps += 1
        lowerCAmelCase__				:  Dict		       =     '''Training loss: {:.2e} lr: {:.2e}'''.format(UpperCamelCase	,      scheduler.get_lr()[0]      )

    # Save a trained model
  if args.do_train:
    # Save a trained model, configuration and tokenizer
    lowerCAmelCase__				:  Dict		       =     model.module if hasattr(UpperCamelCase	,      '''module'''      ) else model  # Only save the model itself

    # If we save using the predefined names, we can load using `from_pretrained`
    lowerCAmelCase__				:  Optional[Any]		       =     os.path.join(args.output_dir	,      UpperCamelCase      )
    lowerCAmelCase__				:  int		       =     os.path.join(args.output_dir	,      UpperCamelCase      )

    torch.save(model_to_save.state_dict()	,      UpperCamelCase      )
    model_to_save.config.to_json_file(UpperCamelCase      )
    tokenizer.save_vocabulary(args.output_dir      )

    # Load a trained model and vocabulary that you have fine-tuned
    lowerCAmelCase__				:  str		       =     OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir      )
    lowerCAmelCase__				:  List[Any]		       =     OpenAIGPTTokenizer.from_pretrained(args.output_dir      )
    model.to(UpperCamelCase      )

  if args.do_eval:
    model.eval()
    lowerCAmelCase__				:  List[str]		       =     0, 0
    lowerCAmelCase__				:  Any		       =     0, 0
    for batch in tqdm(UpperCamelCase	,      desc='''Evaluating'''      ):
      lowerCAmelCase__				:  str		       =     tuple(t.to(UpperCamelCase      ) for t in batch      )
      lowerCAmelCase__				:  str		       =     batch
      with torch.no_grad():
        lowerCAmelCase__				:  Optional[Any]		       =     model(
            UpperCamelCase	,      mc_token_ids=UpperCamelCase	,      lm_labels=UpperCamelCase	,      mc_labels=UpperCamelCase      )

      lowerCAmelCase__				:  Optional[int]		       =     mc_logits.detach().cpu().numpy()
      lowerCAmelCase__				:  List[Any]		       =     mc_labels.to('''cpu'''      ).numpy()
      lowerCAmelCase__				:  List[Any]		       =     accuracy(UpperCamelCase	,      UpperCamelCase      )

      eval_loss += mc_loss.mean().item()
      eval_accuracy += tmp_eval_accuracy

      nb_eval_examples += input_ids.size(0      )
      nb_eval_steps += 1

    lowerCAmelCase__				:  Union[str, Any]		       =     eval_loss / nb_eval_steps
    lowerCAmelCase__				:  Optional[Any]		       =     eval_accuracy / nb_eval_examples
    lowerCAmelCase__				:  List[str]		       =     tr_loss / nb_tr_steps if args.do_train else None
    lowerCAmelCase__				:  Optional[int]		       =     {'''eval_loss''': eval_loss, '''eval_accuracy''': eval_accuracy, '''train_loss''': train_loss}

    lowerCAmelCase__				:  Dict		       =     os.path.join(args.output_dir	,      '''eval_results.txt'''      )
    with open(UpperCamelCase	,      '''w'''      ) as writer:
      logger.info('''***** Eval results *****'''      )
      for key in sorted(result.keys()      ):
        logger.info('''  %s = %s'''	,      UpperCamelCase	,      str(result[key]      )      )
        writer.write('''%s = %s\n''' % (key, str(result[key]      ))      )


if __name__ == "__main__":
     main()







from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block






@dataclass
class  _lowerCAmelCase     (  _lowercase	):
      A__		     =		42






class  _lowerCAmelCase     (  _lowercase    ,			_lowercase	):

      @register_to_config
      def __init__(   self      ,				__UpperCAmelCase = 6_5536      ,				__UpperCAmelCase = None      ,				__UpperCAmelCase = 2      ,				__UpperCAmelCase = 2      ,				__UpperCAmelCase = 0      ,				__UpperCAmelCase = "fourier"      ,				__UpperCAmelCase = True      ,				__UpperCAmelCase = False      ,				__UpperCAmelCase = 0.0      ,				__UpperCAmelCase = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")      ,				__UpperCAmelCase = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")      ,				__UpperCAmelCase = "UNetMidBlock1D"      ,				__UpperCAmelCase = None      ,				__UpperCAmelCase = (32, 32, 64)      ,				__UpperCAmelCase = None      ,				__UpperCAmelCase = 8      ,				__UpperCAmelCase = 1      ,				__UpperCAmelCase = False      ,				):
        super().__init__()
        lowerCAmelCase__				:  Dict		       =     sample_size

        # time
        if time_embedding_type == "fourier":
          lowerCAmelCase__				:  str		       =     GaussianFourierProjection(
              embedding_size=8      ,				set_W_to_weight=__UpperCAmelCase      ,				log=__UpperCAmelCase      ,				flip_sin_to_cos=__UpperCAmelCase		)
          lowerCAmelCase__				:  int		       =     2 * block_out_channels[0]
        elif time_embedding_type == "positional":
          lowerCAmelCase__				:  int		       =     Timesteps(
              block_out_channels[0]      ,				flip_sin_to_cos=__UpperCAmelCase      ,				downscale_freq_shift=__UpperCAmelCase		)
          lowerCAmelCase__				:  str		       =     block_out_channels[0]

        if use_timestep_embedding:
          lowerCAmelCase__				:  str		       =     block_out_channels[0] * 4
          lowerCAmelCase__				:  Dict		       =     TimestepEmbedding(
              in_channels=__UpperCAmelCase      ,				time_embed_dim=__UpperCAmelCase      ,				act_fn=__UpperCAmelCase      ,				out_dim=block_out_channels[0]      ,				)

        lowerCAmelCase__				:  str		       =     nn.ModuleList([]		)
        lowerCAmelCase__				:  Optional[Any]		       =     None
        lowerCAmelCase__				:  Optional[int]		       =     nn.ModuleList([]		)
        lowerCAmelCase__				:  Optional[Any]		       =     None

        # down
        lowerCAmelCase__				:  List[Any]		       =     in_channels
        for i, down_block_type in enumerate(__UpperCAmelCase		):
          lowerCAmelCase__				:  List[str]		       =     output_channel
          lowerCAmelCase__				:  Any		       =     block_out_channels[i]

          if i == 0:
            input_channel += extra_in_channels

          lowerCAmelCase__				:  Any		       =     i == len(__UpperCAmelCase		) - 1

          lowerCAmelCase__				:  Any		       =     get_down_block(
              __UpperCAmelCase      ,				num_layers=__UpperCAmelCase      ,				in_channels=__UpperCAmelCase      ,				out_channels=__UpperCAmelCase      ,				temb_channels=block_out_channels[0]      ,				add_downsample=not is_final_block or downsample_each_block      ,				)
          self.down_blocks.append(__UpperCAmelCase		)

        # mid
        lowerCAmelCase__				:  Optional[int]		       =     get_mid_block(
            __UpperCAmelCase      ,				in_channels=block_out_channels[-1]      ,				mid_channels=block_out_channels[-1]      ,				out_channels=block_out_channels[-1]      ,				embed_dim=block_out_channels[0]      ,				num_layers=__UpperCAmelCase      ,				add_downsample=__UpperCAmelCase      ,				)

        # up
        lowerCAmelCase__				:  Union[str, Any]		       =     list(reversed(__UpperCAmelCase		)		)
        lowerCAmelCase__				:  List[str]		       =     reversed_block_out_channels[0]
        if out_block_type is None:
          lowerCAmelCase__				:  Optional[int]		       =     out_channels
        else:
          lowerCAmelCase__				:  int		       =     block_out_channels[0]

        for i, up_block_type in enumerate(__UpperCAmelCase		):
          lowerCAmelCase__				:  Optional[int]		       =     output_channel
          lowerCAmelCase__				:  Any		       =     (
              reversed_block_out_channels[i + 1] if i < len(__UpperCAmelCase		) - 1 else final_upsample_channels
          )

          lowerCAmelCase__				:  Optional[int]		       =     i == len(__UpperCAmelCase		) - 1

          lowerCAmelCase__				:  Optional[int]		       =     get_up_block(
              __UpperCAmelCase      ,				num_layers=__UpperCAmelCase      ,				in_channels=__UpperCAmelCase      ,				out_channels=__UpperCAmelCase      ,				temb_channels=block_out_channels[0]      ,				add_upsample=not is_final_block      ,				)
          self.up_blocks.append(__UpperCAmelCase		)
          lowerCAmelCase__				:  int		       =     output_channel

        # out
        lowerCAmelCase__				:  Union[str, Any]		       =     norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4      ,				32		)
        lowerCAmelCase__				:  Dict		       =     get_out_block(
            out_block_type=__UpperCAmelCase      ,				num_groups_out=__UpperCAmelCase      ,				embed_dim=block_out_channels[0]      ,				out_channels=__UpperCAmelCase      ,				act_fn=__UpperCAmelCase      ,				fc_dim=block_out_channels[-1] // 4      ,				)







      def 	__magic_name__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase      ,				__UpperCAmelCase = True      ,				):
        lowerCAmelCase__				:  int		       =     timestep
        if not torch.is_tensor(__UpperCAmelCase		):
          lowerCAmelCase__				:  Any		       =     torch.tensor([timesteps]      ,				dtype=torch.long      ,				device=sample.device		)
        elif torch.is_tensor(__UpperCAmelCase		) and len(timesteps.shape		) == 0:
          lowerCAmelCase__				:  Any		       =     timesteps[None].to(sample.device		)

        lowerCAmelCase__				:  int		       =     self.time_proj(__UpperCAmelCase		)
        if self.config.use_timestep_embedding:
          lowerCAmelCase__				:  str		       =     self.time_mlp(__UpperCAmelCase		)
        else:
          lowerCAmelCase__				:  Tuple		       =     timestep_embed[..., None]
          lowerCAmelCase__				:  Union[str, Any]		       =     timestep_embed.repeat([1, 1, sample.shape[2]]		).to(sample.dtype		)
          lowerCAmelCase__				:  Any		       =     timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:])		)

        # 2. down
        lowerCAmelCase__				:  int		       =     ()
        for downsample_block in self.down_blocks:
          lowerCAmelCase__       ,			lowerCAmelCase__				:  int		       =     downsample_block(hidden_states=__UpperCAmelCase      ,				temb=__UpperCAmelCase		)
          down_block_res_samples += res_samples

        # 3. mid
        if self.mid_block:
          lowerCAmelCase__				:  Dict		       =     self.mid_block(__UpperCAmelCase      ,				__UpperCAmelCase		)

        # 4. up
        for i, upsample_block in enumerate(self.up_blocks		):
          lowerCAmelCase__				:  Tuple		       =     down_block_res_samples[-1:]
          lowerCAmelCase__				:  int		       =     down_block_res_samples[:-1]
          lowerCAmelCase__				:  Optional[int]		       =     upsample_block(__UpperCAmelCase      ,				res_hidden_states_tuple=__UpperCAmelCase      ,				temb=__UpperCAmelCase		)

        # 5. post-process
        if self.out_block:
          lowerCAmelCase__				:  Any		       =     self.out_block(__UpperCAmelCase      ,				__UpperCAmelCase		)

        if not return_dict:
          return (sample,)

        return UNetaDOutput(sample=__UpperCAmelCase		)

