

"""simple docstring"""





import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


_a				   =							logging.getLogger(__name__)

require_version('pytorch_lightning>=1.0.4')

_a				   =							{
    'base': AutoModel,
    'sequence-classification': AutoModelForSequenceClassification,
    'question-answering': AutoModelForQuestionAnswering,
    'pretraining': AutoModelForPreTraining,
    'token-classification': AutoModelForTokenClassification,
    'language-modeling': AutoModelWithLMHead,
    'summarization': AutoModelForSeqaSeqLM,
    'translation': AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
_a				   =							{
    'linear': get_linear_schedule_with_warmup,
    'cosine': get_cosine_schedule_with_warmup,
    'cosine_w_restarts': get_cosine_with_hard_restarts_schedule_with_warmup,
    'polynomial': get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
_a				   =							sorted(arg_to_scheduler.keys())
_a				   =							'{' + ', '.join(arg_to_scheduler_choices) + '}'




class       _lowerCAmelCase						(			pl.LightningModule     ):







 """simple docstring"""







 def __init__(    self							:    Optional[Any],      UpperCAmelCase__							:    argparse.Namespace,      UpperCAmelCase__							:    List[str]=None,      UpperCAmelCase__							:    Dict="base",      UpperCAmelCase__							:    Tuple=None,      UpperCAmelCase__							:    Optional[int]=None,      UpperCAmelCase__							:    Optional[int]=None,      **UpperCAmelCase__							:    int,      ):
    super().__init__()
    # TODO: move to self.save_hyperparameters()
    # self.save_hyperparameters()
    # can also expand arguments into trainer signature for easier reading

    self.save_hyperparameters(UpperCAmelCase__			)
    __lowercase			=		0
    __lowercase			=		Path(self.hparams.output_dir			)
    __lowercase			=		self.hparams.cache_dir if self.hparams.cache_dir else None
    if config is None:
       __lowercase			=		AutoConfig.from_pretrained(
           self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path,      **({"num_labels": num_labels} if num_labels is not None else {}),      cache_dir=UpperCAmelCase__,      **UpperCAmelCase__,      )
    else:
       __lowercase			=		config

    __lowercase			=		("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout")
    for p in extra_model_params:
       if getattr(self.hparams,      UpperCAmelCase__,      UpperCAmelCase__			):
          assert hasattr(self.config,      UpperCAmelCase__			), F"""model config doesn't have a `{p}` attribute"""
          setattr(self.config,      UpperCAmelCase__,      getattr(self.hparams,      UpperCAmelCase__			)			)

    if tokenizer is None:
       __lowercase			=		AutoTokenizer.from_pretrained(
           self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path,      cache_dir=UpperCAmelCase__,      )
    else:
       __lowercase			=		tokenizer
    __lowercase			=		MODEL_MODES[mode]
    if model is None:
       __lowercase			=		self.model_type.from_pretrained(
           self.hparams.model_name_or_path,      from_tf=bool(".ckpt" in self.hparams.model_name_or_path			),      config=self.config,      cache_dir=UpperCAmelCase__,      )
    else:
       __lowercase			=		model


 def       _lowercase				(    self							:    Tuple,      *UpperCAmelCase__							:    Optional[int],      **UpperCAmelCase__							:    Tuple			):
    __lowercase			=		self.model_type.from_pretrained(*UpperCAmelCase__,      **UpperCAmelCase__			)


 def       _lowercase				(    self							:    List[Any]			):
    __lowercase			=		arg_to_scheduler[self.hparams.lr_scheduler]
    __lowercase			=		get_schedule_func(
        self.opt,      num_warmup_steps=self.hparams.warmup_steps,      num_training_steps=self.total_steps()			)
    __lowercase			=		{"scheduler": scheduler, "interval": "step", "frequency": 1}
    return scheduler


 def       _lowercase				(    self							:    Optional[int]			):
    __lowercase			=		self.model
    __lowercase			=		["bias", "LayerNorm.weight"]
    __lowercase			=		[
        {
            "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay			)],
            "weight_decay": self.hparams.weight_decay,
        },
        {
            "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay			)],
            "weight_decay": 0.0,
        },
    ]
    if self.hparams.adafactor:
       __lowercase			=		Adafactor(
           UpperCAmelCase__,      lr=self.hparams.learning_rate,      scale_parameter=UpperCAmelCase__,      relative_step=UpperCAmelCase__			)

    else:
       __lowercase			=		AdamW(
           UpperCAmelCase__,      lr=self.hparams.learning_rate,      eps=self.hparams.adam_epsilon			)
    __lowercase			=		optimizer

    __lowercase			=		self.get_lr_scheduler()

    return [optimizer], [scheduler]


 def       _lowercase				(    self							:    List[Any],      UpperCAmelCase__							:    Any,      UpperCAmelCase__							:    str			):
    return self.validation_step(UpperCAmelCase__,      UpperCAmelCase__			)


 def       _lowercase				(    self							:    Union[str, Any],      UpperCAmelCase__							:    Optional[Any]			):
    return self.validation_end(UpperCAmelCase__			)


 def       _lowercase				(    self							:    str			):
    __lowercase			=		max(1,      self.hparams.gpus			)  # TODO: consider num_tpu_cores
    __lowercase			=		self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
    return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs


 def       _lowercase				(    self							:    str,      UpperCAmelCase__							:    List[Any]			):
    if mode == "test":
       __lowercase			=		len(self.test_dataloader().dataset			)
    else:
       __lowercase			=		self.get_dataloader("train",      self.hparams.train_batch_size,      shuffle=UpperCAmelCase__			)
       __lowercase			=		len(self.train_dataloader().dataset			)


 def       _lowercase				(    self							:    Optional[int],      UpperCAmelCase__							:    str,      UpperCAmelCase__							:    int,      UpperCAmelCase__							:    bool = False			):
    raise NotImplementedError("You must implement this for your task"			)


 def       _lowercase				(    self							:    List[str]			):
    return self.train_loader


 def       _lowercase				(    self							:    str			):
    return self.get_dataloader("dev",      self.hparams.eval_batch_size,      shuffle=UpperCAmelCase__			)


 def       _lowercase				(    self							:    Optional[int]			):
    return self.get_dataloader("test",      self.hparams.eval_batch_size,      shuffle=UpperCAmelCase__			)


 def       _lowercase				(    self							:    str,      UpperCAmelCase__							:    Tuple			):
    return os.path.join(
        self.hparams.data_dir,      "cached_{}_{}_{}".format(
            UpperCAmelCase__,      list(filter(UpperCAmelCase__,      self.hparams.model_name_or_path.split("/"			)			)			).pop(),      str(self.hparams.max_seq_length			),      ),      )


 @pl.utilities.rank_zero_only
 def       _lowercase				(    self							:    str,      UpperCAmelCase__							:    Dict[str, Any]			):
    __lowercase			=		self.output_dir.joinpath("best_tfmr"			)
    __lowercase			=		self.step_count
    self.model.save_pretrained(UpperCAmelCase__			)
    self.tokenizer.save_pretrained(UpperCAmelCase__			)



 @staticmethod
 def       _lowercase				(    UpperCAmelCase__							:    int,      UpperCAmelCase__							:    Tuple			):
    parser.add_argument(
        "--model_name_or_path",      default=UpperCAmelCase__,      type=UpperCAmelCase__,      required=UpperCAmelCase__,      help="Path to pretrained model or model identifier from huggingface.co/models",      )
    parser.add_argument(
        "--config_name",      default="",      type=UpperCAmelCase__,      help="Pretrained config name or path if not the same as model_name"			)
    parser.add_argument(
        "--tokenizer_name",      default=UpperCAmelCase__,      type=UpperCAmelCase__,      help="Pretrained tokenizer name or path if not the same as model_name",      )
    parser.add_argument(
        "--cache_dir",      default="",      type=UpperCAmelCase__,      help="Where do you want to store the pre-trained models downloaded from huggingface.co",      )
    parser.add_argument(
        "--encoder_layerdrop",      type=UpperCAmelCase__,      help="Encoder layer dropout probability (Optional). Goes into model.config",      )
    parser.add_argument(
        "--decoder_layerdrop",      type=UpperCAmelCase__,      help="Decoder layer dropout probability (Optional). Goes into model.config",      )
    parser.add_argument(
        "--dropout",      type=UpperCAmelCase__,      help="Dropout probability (Optional). Goes into model.config",      )
    parser.add_argument(
        "--attention_dropout",      type=UpperCAmelCase__,      help="Attention dropout probability (Optional). Goes into model.config",      )
    parser.add_argument("--learning_rate",      default=5E-5,      type=UpperCAmelCase__,      help="The initial learning rate for Adam."			)
    parser.add_argument(
        "--lr_scheduler",      default="linear",      choices=UpperCAmelCase__,      metavar=UpperCAmelCase__,      type=UpperCAmelCase__,      help="Learning rate scheduler",      )
    parser.add_argument("--weight_decay",      default=0.0,      type=UpperCAmelCase__,      help="Weight decay if we apply some."			)
    parser.add_argument("--adam_epsilon",      default=1E-8,      type=UpperCAmelCase__,      help="Epsilon for Adam optimizer."			)
    parser.add_argument("--warmup_steps",      default=0,      type=UpperCAmelCase__,      help="Linear warmup over warmup_steps."			)
    parser.add_argument("--num_workers",      default=4,      type=UpperCAmelCase__,      help="kwarg passed to DataLoader"			)
    parser.add_argument("--num_train_epochs",      dest="max_epochs",      default=3,      type=UpperCAmelCase__			)
    parser.add_argument("--train_batch_size",      default=3_2,      type=UpperCAmelCase__			)
    parser.add_argument("--eval_batch_size",      default=3_2,      type=UpperCAmelCase__			)
    parser.add_argument("--adafactor",      action="store_true"			)







class       _lowerCAmelCase						(			pl.Callback     ):







 """simple docstring"""







 def       _lowercase				(    self							:    Any,      UpperCAmelCase__							:    int,      UpperCAmelCase__							:    int			):
    __lowercase			=		trainer.lr_schedulers[0]["scheduler"]
    __lowercase			=		{F"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr()			)}
    pl_module.logger.log_metrics(UpperCAmelCase__			)


 def       _lowercase				(    self							:    int,      UpperCAmelCase__							:    pl.Trainer,      UpperCAmelCase__							:    pl.LightningModule			):
    rank_zero_info("***** Validation results *****"			)
    __lowercase			=		trainer.callback_metrics
    # Log results
    for key in sorted(UpperCAmelCase__			):
       if key not in ["log", "progress_bar"]:
          rank_zero_info("{} = {}\n".format(UpperCAmelCase__,      str(metrics[key]			)			)			)



 def       _lowercase				(    self							:    Dict,      UpperCAmelCase__							:    pl.Trainer,      UpperCAmelCase__							:    pl.LightningModule			):
    rank_zero_info("***** Test results *****"			)
    __lowercase			=		trainer.callback_metrics
    # Log and save results to file
    __lowercase			=		os.path.join(pl_module.hparams.output_dir,      "test_results.txt"			)
    with open(UpperCAmelCase__,      "w"			) as writer:
       for key in sorted(UpperCAmelCase__			):
          if key not in ["log", "progress_bar"]:
             rank_zero_info("{} = {}\n".format(UpperCAmelCase__,      str(metrics[key]			)			)			)
             writer.write("{} = {}\n".format(UpperCAmelCase__,      str(metrics[key]			)			)			)







def 						_A						(						UpperCamelCase_  : Union[str, Any],    UpperCamelCase_  : Dict)			->		None:
   '''simple docstring'''


   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(
       "--fp16",    action="store_true",    help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",    )

   parser.add_argument(
       "--fp16_opt_level",    type=UpperCamelCase_,    default="O2",    help=(
           "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
           "See details at https://nvidia.github.io/apex/amp.html"
       ),    )
   parser.add_argument("--n_tpu_cores",    dest="tpu_cores",    type=UpperCamelCase_)
   parser.add_argument("--max_grad_norm",    dest="gradient_clip_val",    default=1.0,    type=UpperCamelCase_,    help="Max gradient norm")
   parser.add_argument("--do_train",    action="store_true",    help="Whether to run training.")
   parser.add_argument("--do_predict",    action="store_true",    help="Whether to run predictions on the test set.")
   parser.add_argument(
       "--gradient_accumulation_steps",    dest="accumulate_grad_batches",    type=UpperCamelCase_,    default=1,    help="Number of updates steps to accumulate before performing a backward/update pass.",    )
   parser.add_argument("--seed",    type=UpperCamelCase_,    default=42,    help="random seed for initialization")
   parser.add_argument(
       "--data_dir",    default=UpperCamelCase_,    type=UpperCamelCase_,    required=UpperCamelCase_,    help="The input data dir. Should contain the training files for the CoNLL-2003 NER task.",    )




def 						_A						(						UpperCamelCase_  : BaseTransformer,    UpperCamelCase_  : argparse.Namespace,    UpperCamelCase_  : Optional[Any]=None,    UpperCamelCase_  : List[str]=True,    UpperCamelCase_  : Optional[int]=[],    UpperCamelCase_  : str=None,    UpperCamelCase_  : Optional[int]=None,    **UpperCamelCase_  : int,    )			->		Optional[Any]:
   '''simple docstring'''


   pl.seed_everything(args.seed)

   # init model
   __lowercase			=		Path(model.hparams.output_dir)
   odir.mkdir(exist_ok=UpperCamelCase_)

   # add custom checkpoints
   if checkpoint_callback is None:
      __lowercase			=		pl.callbacks.ModelCheckpoint(
          filepath=args.output_dir,    prefix="checkpoint",    monitor="val_loss",    mode="min",    save_top_k=1)
   if early_stopping_callback:
      extra_callbacks.append(UpperCamelCase_)
   if logging_callback is None:
      __lowercase			=		LoggingCallback()

   __lowercase			=		{}

   # TODO: remove with PyTorch 1.6 since pl uses native amp
   if args.fpaa:
      __lowercase			=		16
      __lowercase			=		args.fpaa_opt_level

   if args.gpus > 1:
      __lowercase			=		"ddp"

   __lowercase			=		args.accumulate_grad_batches
   __lowercase			=		extra_train_kwargs.get("accelerator",    UpperCamelCase_)
   __lowercase			=		extra_train_kwargs.get("profiler",    UpperCamelCase_)

   __lowercase			=		pl.Trainer.from_argparse_args(
       UpperCamelCase_,    weights_summary=UpperCamelCase_,    callbacks=[logging_callback] + extra_callbacks,    logger=UpperCamelCase_,    checkpoint_callback=UpperCamelCase_,    **UpperCamelCase_,    )

   if args.do_train:
      trainer.fit(UpperCamelCase_)

   return trainer



"""simple docstring"""





import functools
import math

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




def 						_A						(						UpperCamelCase_  : int,    UpperCamelCase_  : Union[str, Any],    UpperCamelCase_  : List[Any],    UpperCamelCase_  : Dict,    UpperCamelCase_  : int = 4096)			->		Optional[Any]:
   '''simple docstring'''


   __lowercase	,__lowercase	,__lowercase			=		key.shape[-3:]
   __lowercase			=		value.shape[-1]
   __lowercase			=		min(UpperCamelCase_,    UpperCamelCase_)
   __lowercase			=		query / jnp.sqrt(UpperCamelCase_)

   @functools.partial(jax.checkpoint,    prevent_cse=UpperCamelCase_)
   def summarize_chunk(UpperCamelCase_  : int,    UpperCamelCase_  : Union[str, Any],    UpperCamelCase_  : Any):
      __lowercase			=		jnp.einsum("...qhd,...khd->...qhk",    UpperCamelCase_,    UpperCamelCase_,    precision=UpperCamelCase_)

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

      __lowercase			=		jnp.einsum("...vhf,...qhv->...qhf",    UpperCamelCase_,    UpperCamelCase_,    precision=UpperCamelCase_)
      __lowercase			=		jnp.einsum("...qhk->...qh",    UpperCamelCase_)

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

   def chunk_scanner(UpperCamelCase_  : int):
      # julienne key array
      __lowercase			=		jax.lax.dynamic_slice(
          operand=UpperCamelCase_,    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
      __lowercase			=		jax.lax.dynamic_slice(
          operand=UpperCamelCase_,    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(UpperCamelCase_,    UpperCamelCase_,    UpperCamelCase_)

   __lowercase	,__lowercase	,__lowercase			=		jax.lax.map(f=UpperCamelCase_,    xs=jnp.arange(0,    UpperCamelCase_,    UpperCamelCase_))

   __lowercase			=		jnp.max(UpperCamelCase_,    axis=0,    keepdims=UpperCamelCase_)
   __lowercase			=		jnp.exp(chunk_max - global_max)

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

   __lowercase			=		chunk_values.sum(axis=0)
   __lowercase			=		jnp.expand_dims(UpperCamelCase_,    -1).sum(axis=0)

   return all_values / all_weights




def 						_A						(						UpperCamelCase_  : Optional[Any],    UpperCamelCase_  : Optional[int],    UpperCamelCase_  : List[str],    UpperCamelCase_  : Union[str, Any]=jax.lax.Precision.HIGHEST,    UpperCamelCase_  : int = 1024,    UpperCamelCase_  : int = 4096)			->		str:
   '''simple docstring'''


   __lowercase	,__lowercase	,__lowercase			=		query.shape[-3:]

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

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

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

   return jnp.concatenate(UpperCamelCase_,    axis=-3)  # fuse the chunked result back




class       _lowerCAmelCase						(			nn.Module     ):







 """simple docstring"""







 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      int     	=			8
 __UpperCAmelCase			:      int     	=			6_4
 __UpperCAmelCase			:      float     	=			0.0
 __UpperCAmelCase			:      bool     	=			False
 __UpperCAmelCase			:      jnp.dtype     	=			jnp.floataa


 def       _lowercase				(    self							:    List[Any]			):
    __lowercase			=		self.dim_head * self.heads
    __lowercase			=		self.dim_head**-0.5

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

    __lowercase			=		nn.Dense(self.query_dim,      dtype=self.dtype,      name="to_out_0"			)
    __lowercase			=		nn.Dropout(rate=self.dropout			)


 def       _lowercase				(    self							:    Any,      UpperCAmelCase__							:    Union[str, Any]			):
    __lowercase	,__lowercase	,__lowercase			=		tensor.shape
    __lowercase			=		self.heads
    __lowercase			=		tensor.reshape(UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__,      dim // head_size			)
    __lowercase			=		jnp.transpose(UpperCAmelCase__,      (0, 2, 1, 3)			)
    __lowercase			=		tensor.reshape(batch_size * head_size,      UpperCAmelCase__,      dim // head_size			)
    return tensor


 def       _lowercase				(    self							:    Union[str, Any],      UpperCAmelCase__							:    int			):
    __lowercase	,__lowercase	,__lowercase			=		tensor.shape
    __lowercase			=		self.heads
    __lowercase			=		tensor.reshape(batch_size // head_size,      UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__			)
    __lowercase			=		jnp.transpose(UpperCAmelCase__,      (0, 2, 1, 3)			)
    __lowercase			=		tensor.reshape(batch_size // head_size,      UpperCAmelCase__,      dim * head_size			)
    return tensor



 def __call__(    self							:    List[Any],      UpperCAmelCase__							:    str,      UpperCAmelCase__							:    Union[str, Any]=None,      UpperCAmelCase__							:    Optional[Any]=True			):
    __lowercase			=		hidden_states if context is None else context

    __lowercase			=		self.query(UpperCAmelCase__			)
    __lowercase			=		self.key(UpperCAmelCase__			)
    __lowercase			=		self.value(UpperCAmelCase__			)

    __lowercase			=		self.reshape_heads_to_batch_dim(UpperCAmelCase__			)
    __lowercase			=		self.reshape_heads_to_batch_dim(UpperCAmelCase__			)
    __lowercase			=		self.reshape_heads_to_batch_dim(UpperCAmelCase__			)

    if self.use_memory_efficient_attention:
       __lowercase			=		query_states.transpose(1,      0,      2			)
       __lowercase			=		key_states.transpose(1,      0,      2			)
       __lowercase			=		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

       __lowercase			=		query_states.shape[-3]
       if flatten_latent_dim % 6_4 == 0:
          __lowercase			=		int(flatten_latent_dim / 6_4			)
       elif flatten_latent_dim % 1_6 == 0:
          __lowercase			=		int(flatten_latent_dim / 1_6			)
       elif flatten_latent_dim % 4 == 0:
          __lowercase			=		int(flatten_latent_dim / 4			)
       else:
          __lowercase			=		int(UpperCAmelCase__			)

       __lowercase			=		jax_memory_efficient_attention(
           UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__,      query_chunk_size=UpperCAmelCase__,      key_chunk_size=4_0_9_6 * 4			)

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

       # attend to values
       __lowercase			=		jnp.einsum("b i j, b j d -> b i d",      UpperCAmelCase__,      UpperCAmelCase__			)

    __lowercase			=		self.reshape_batch_dim_to_heads(UpperCAmelCase__			)
    __lowercase			=		self.proj_attn(UpperCAmelCase__			)
    return self.dropout_layer(UpperCAmelCase__,      deterministic=UpperCAmelCase__			)







class       _lowerCAmelCase						(			nn.Module     ):







 """simple docstring"""







 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      float     	=			0.0
 __UpperCAmelCase			:      bool     	=			False
 __UpperCAmelCase			:      jnp.dtype     	=			jnp.floataa
 __UpperCAmelCase			:      bool     	=			False


 def       _lowercase				(    self							:    Tuple			):
    # self attention (or cross_attention if only_cross_attention is True)
    __lowercase			=		FlaxAttention(
        self.dim,      self.n_heads,      self.d_head,      self.dropout,      self.use_memory_efficient_attention,      dtype=self.dtype			)
    # cross attention
    __lowercase			=		FlaxAttention(
        self.dim,      self.n_heads,      self.d_head,      self.dropout,      self.use_memory_efficient_attention,      dtype=self.dtype			)
    __lowercase			=		FlaxFeedForward(dim=self.dim,      dropout=self.dropout,      dtype=self.dtype			)
    __lowercase			=		nn.LayerNorm(epsilon=1E-5,      dtype=self.dtype			)
    __lowercase			=		nn.LayerNorm(epsilon=1E-5,      dtype=self.dtype			)
    __lowercase			=		nn.LayerNorm(epsilon=1E-5,      dtype=self.dtype			)
    __lowercase			=		nn.Dropout(rate=self.dropout			)



 def __call__(    self							:    str,      UpperCAmelCase__							:    Union[str, Any],      UpperCAmelCase__							:    Optional[Any],      UpperCAmelCase__							:    Dict=True			):
    # self attention
    __lowercase			=		hidden_states
    if self.only_cross_attention:
       __lowercase			=		self.attna(self.norma(UpperCAmelCase__			),      UpperCAmelCase__,      deterministic=UpperCAmelCase__			)
    else:
       __lowercase			=		self.attna(self.norma(UpperCAmelCase__			),      deterministic=UpperCAmelCase__			)
    __lowercase			=		hidden_states + residual

    # cross attention
    __lowercase			=		hidden_states
    __lowercase			=		self.attna(self.norma(UpperCAmelCase__			),      UpperCAmelCase__,      deterministic=UpperCAmelCase__			)
    __lowercase			=		hidden_states + residual

    # feed forward
    __lowercase			=		hidden_states
    __lowercase			=		self.ff(self.norma(UpperCAmelCase__			),      deterministic=UpperCAmelCase__			)
    __lowercase			=		hidden_states + residual

    return self.dropout_layer(UpperCAmelCase__,      deterministic=UpperCAmelCase__			)







class       _lowerCAmelCase						(			nn.Module     ):







 """simple docstring"""







 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      int     	=			1
 __UpperCAmelCase			:      float     	=			0.0
 __UpperCAmelCase			:      bool     	=			False
 __UpperCAmelCase			:      bool     	=			False
 __UpperCAmelCase			:      jnp.dtype     	=			jnp.floataa
 __UpperCAmelCase			:      bool     	=			False


 def       _lowercase				(    self							:    Dict			):
    __lowercase			=		nn.GroupNorm(num_groups=3_2,      epsilon=1E-5			)

    __lowercase			=		self.n_heads * self.d_head
    if self.use_linear_projection:
       __lowercase			=		nn.Dense(UpperCAmelCase__,      dtype=self.dtype			)
    else:
       __lowercase			=		nn.Conv(
           UpperCAmelCase__,      kernel_size=(1, 1),      strides=(1, 1),      padding="VALID",      dtype=self.dtype,      )

    __lowercase			=		[
        FlaxBasicTransformerBlock(
            UpperCAmelCase__,      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:
       __lowercase			=		nn.Dense(UpperCAmelCase__,      dtype=self.dtype			)
    else:
       __lowercase			=		nn.Conv(
           UpperCAmelCase__,      kernel_size=(1, 1),      strides=(1, 1),      padding="VALID",      dtype=self.dtype,      )

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



 def __call__(    self							:    Dict,      UpperCAmelCase__							:    Union[str, Any],      UpperCAmelCase__							:    Tuple,      UpperCAmelCase__							:    List[str]=True			):
    __lowercase	,__lowercase	,__lowercase	,__lowercase			=		hidden_states.shape
    __lowercase			=		hidden_states
    __lowercase			=		self.norm(UpperCAmelCase__			)
    if self.use_linear_projection:
       __lowercase			=		hidden_states.reshape(UpperCAmelCase__,      height * width,      UpperCAmelCase__			)
       __lowercase			=		self.proj_in(UpperCAmelCase__			)
    else:
       __lowercase			=		self.proj_in(UpperCAmelCase__			)
       __lowercase			=		hidden_states.reshape(UpperCAmelCase__,      height * width,      UpperCAmelCase__			)

    for transformer_block in self.transformer_blocks:
       __lowercase			=		transformer_block(UpperCAmelCase__,      UpperCAmelCase__,      deterministic=UpperCAmelCase__			)

    if self.use_linear_projection:
       __lowercase			=		self.proj_out(UpperCAmelCase__			)
       __lowercase			=		hidden_states.reshape(UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__			)
    else:
       __lowercase			=		hidden_states.reshape(UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__,      UpperCAmelCase__			)
       __lowercase			=		self.proj_out(UpperCAmelCase__			)

    __lowercase			=		hidden_states + residual
    return self.dropout_layer(UpperCAmelCase__,      deterministic=UpperCAmelCase__			)







class       _lowerCAmelCase						(			nn.Module     ):







 """simple docstring"""







 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      float     	=			0.0
 __UpperCAmelCase			:      jnp.dtype     	=			jnp.floataa


 def       _lowercase				(    self							:    List[str]			):
    # The second linear layer needs to be called
    # net_2 for now to match the index of the Sequential layer
    __lowercase			=		FlaxGEGLU(self.dim,      self.dropout,      self.dtype			)
    __lowercase			=		nn.Dense(self.dim,      dtype=self.dtype			)



 def __call__(    self							:    int,      UpperCAmelCase__							:    List[str],      UpperCAmelCase__							:    Union[str, Any]=True			):
    __lowercase			=		self.net_a(UpperCAmelCase__,      deterministic=UpperCAmelCase__			)
    __lowercase			=		self.net_a(UpperCAmelCase__			)
    return hidden_states







class       _lowerCAmelCase						(			nn.Module     ):







 """simple docstring"""







 __UpperCAmelCase			:      int
 __UpperCAmelCase			:      float     	=			0.0
 __UpperCAmelCase			:      jnp.dtype     	=			jnp.floataa


 def       _lowercase				(    self							:    int			):
    __lowercase			=		self.dim * 4
    __lowercase			=		nn.Dense(inner_dim * 2,      dtype=self.dtype			)
    __lowercase			=		nn.Dropout(rate=self.dropout			)



 def __call__(    self							:    Optional[Any],      UpperCAmelCase__							:    str,      UpperCAmelCase__							:    int=True			):
    __lowercase			=		self.proj(UpperCAmelCase__			)
    __lowercase	,__lowercase			=		jnp.split(UpperCAmelCase__,      2,      axis=2			)
    return self.dropout_layer(hidden_linear * nn.gelu(UpperCAmelCase__			),      deterministic=UpperCAmelCase__			)




