'''simple docstring'''




import math
import unittest

from transformers import BioGptConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import (
      BioGptForCausalLM,
      BioGptForSequenceClassification,
      BioGptForTokenClassification,
      BioGptModel,
      BioGptTokenizer,
  )
  from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST

class 	lowerCamelCase_	:
      '''simple docstring'''

      def __init__(       self						:				List[Any]						,					A						:				Dict						,					A						:				Optional[Any]=13						,					A						:				Optional[Any]=7						,					A						:				Union[str, Any]=True						,					A						:				Optional[Any]=True						,					A						:				int=False						,					A						:				str=True						,					A						:				Optional[Any]=99						,					A						:				Union[str, Any]=32						,					A						:				int=5						,					A						:				Tuple=4						,					A						:				Union[str, Any]=37						,					A						:				Dict="gelu"						,					A						:				Union[str, Any]=0.1						,					A						:				str=0.1						,					A						:				Union[str, Any]=512						,					A						:				int=16						,					A						:				List[str]=2						,					A						:				Tuple=0.02						,					A						:				int=3						,					A						:				List[str]=4						,					A						:				str=None						,					):
             _UpperCAmelCase     :  List[Any]							      =    parent
             _UpperCAmelCase     :  Any							      =    batch_size
             _UpperCAmelCase     :  int							      =    seq_length
             _UpperCAmelCase     :  Union[str, Any]							      =    is_training
             _UpperCAmelCase     :  Any							      =    use_input_mask
             _UpperCAmelCase     :  Optional[Any]							      =    use_token_type_ids
             _UpperCAmelCase     :  str							      =    use_labels
             _UpperCAmelCase     :  Union[str, Any]							      =    vocab_size
             _UpperCAmelCase     :  Tuple							      =    hidden_size
             _UpperCAmelCase     :  Union[str, Any]							      =    num_hidden_layers
             _UpperCAmelCase     :  Optional[Any]							      =    num_attention_heads
             _UpperCAmelCase     :  Union[str, Any]							      =    intermediate_size
             _UpperCAmelCase     :  Union[str, Any]							      =    hidden_act
             _UpperCAmelCase     :  List[Any]							      =    hidden_dropout_prob
             _UpperCAmelCase     :  List[Any]							      =    attention_probs_dropout_prob
             _UpperCAmelCase     :  Optional[int]							      =    max_position_embeddings
             _UpperCAmelCase     :  str							      =    type_vocab_size
             _UpperCAmelCase     :  str							      =    type_sequence_label_size
             _UpperCAmelCase     :  int							      =    initializer_range
             _UpperCAmelCase     :  Optional[Any]							      =    num_labels
             _UpperCAmelCase     :  List[str]							      =    num_choices
             _UpperCAmelCase     :  List[str]							      =    scope




      def      _A	(       self						:				Optional[int]       ):
             _UpperCAmelCase     :  Dict							      =    ids_tensor([self.batch_size, self.seq_length]						,					self.vocab_size       )

             _UpperCAmelCase     :  Union[str, Any]							      =    None
             if self.use_input_mask:
                    _UpperCAmelCase     :  List[Any]							      =    random_attention_mask([self.batch_size, self.seq_length]       )

             _UpperCAmelCase     :  Any							      =    None
             if self.use_token_type_ids:
                    _UpperCAmelCase     :  List[str]							      =    ids_tensor([self.batch_size, self.seq_length]						,					self.type_vocab_size       )

             _UpperCAmelCase     :  Optional[int]							      =    None
             _UpperCAmelCase     :  Any							      =    None
             _UpperCAmelCase     :  Optional[int]							      =    None
             if self.use_labels:
                    _UpperCAmelCase     :  Optional[Any]							      =    ids_tensor([self.batch_size]						,					self.type_sequence_label_size       )
                    _UpperCAmelCase     :  Tuple							      =    ids_tensor([self.batch_size, self.seq_length]						,					self.num_labels       )
                    _UpperCAmelCase     :  List[str]							      =    ids_tensor([self.batch_size]						,					self.num_choices       )

             _UpperCAmelCase     :  List[Any]							      =    self.get_config()

             return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




      def      _A	(       self						:				Dict       ):
             return BioGptConfig(
                 vocab_size=self.vocab_size						,					hidden_size=self.hidden_size						,					num_hidden_layers=self.num_hidden_layers						,					num_attention_heads=self.num_attention_heads						,					intermediate_size=self.intermediate_size						,					hidden_act=self.hidden_act						,					hidden_dropout_prob=self.hidden_dropout_prob						,					attention_probs_dropout_prob=self.attention_probs_dropout_prob						,					max_position_embeddings=self.max_position_embeddings						,					type_vocab_size=self.type_vocab_size						,					is_decoder=A						,					initializer_range=self.initializer_range						,					)




      def      _A	(       self						:				int						,					A						:				List[Any]						,					A						:				Any						,					A						:				int						,					A						:				Union[str, Any]						,					A						:				Dict						,					A						:				List[Any]						,					A						:				Dict       ):
             _UpperCAmelCase     :  List[str]							      =    BioGptModel(config=A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  Tuple							      =    model(A						,					attention_mask=A       )
             _UpperCAmelCase     :  int							      =    model(A       )
             self.parent.assertEqual(result.last_hidden_state.shape						,					(self.batch_size, self.seq_length, self.hidden_size)       )




      def      _A	(       self						:				List[Any]						,					A						:				str						,					A						:				List[Any]						,					A						:				Dict						,					A						:				List[Any]						,					A						:				List[str]						,					A						:				Union[str, Any]						,					A						:				int						,					A						:				List[str]						,					A						:				Dict						,					):
             _UpperCAmelCase     :  Optional[int]							      =    BioGptForCausalLM(config=A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  Optional[int]							      =    model(A						,					attention_mask=A						,					token_type_ids=A						,					labels=A       )
             self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.seq_length, self.vocab_size)       )




      def      _A	(       self						:				List[Any]						,					A						:				str						,					A						:				str						,					A						:				str						,					A						:				Any						,					A						:				List[str]						,					*A						:				Optional[int]       ):
             _UpperCAmelCase     :  str							      =    BioGptModel(config=A       )
             model.to(A       )
             model.eval()

             # create attention mask
             _UpperCAmelCase     :  List[Any]							      =    torch.ones(input_ids.shape						,					dtype=torch.long						,					device=A       )
             _UpperCAmelCase     :  Optional[int]							      =    self.seq_length // 2
             _UpperCAmelCase     :  List[Any]							      =    0

             # first forward pass
             _UpperCAmelCase      ,  _UpperCAmelCase     :  List[str]							      =    model(A						,					attention_mask=A       ).to_tuple()

             # create hypothetical next token and extent to next_input_ids
             _UpperCAmelCase     :  List[str]							      =    ids_tensor((self.batch_size, 1)						,					config.vocab_size       )

             # change a random masked slice from input_ids
             _UpperCAmelCase     :  List[str]							      =    ids_tensor((1,)						,					A       ).item() + 1
             _UpperCAmelCase     :  str							      =    ids_tensor((self.batch_size, 1)						,					config.vocab_size       ).squeeze(-1       )
             _UpperCAmelCase     :  Any							      =    random_other_next_tokens

             # append to next input_ids and attn_mask
             _UpperCAmelCase     :  List[Any]							      =    torch.cat([input_ids, next_tokens]						,					dim=-1       )
             _UpperCAmelCase     :  Optional[int]							      =    torch.cat(
                 [attn_mask, torch.ones((attn_mask.shape[0], 1)						,					dtype=torch.long						,					device=A       )]						,					dim=1						,					)

             # get two different outputs
             _UpperCAmelCase     :  List[Any]							      =    model(A						,					attention_mask=A       )["last_hidden_state"]
             _UpperCAmelCase     :  Optional[Any]							      =    model(A						,					past_key_values=A						,					attention_mask=A       )["last_hidden_state"]

             # select random slice
             _UpperCAmelCase     :  Any							      =    ids_tensor((1,)						,					output_from_past.shape[-1]       ).item()
             _UpperCAmelCase     :  Optional[Any]							      =    output_from_no_past[:, -1, random_slice_idx].detach()
             _UpperCAmelCase     :  Any							      =    output_from_past[:, 0, random_slice_idx].detach()

             # test that outputs are equal for slice
             self.parent.assertTrue(torch.allclose(A						,					A						,					atol=1E-3       )       )




      def      _A	(       self						:				int						,					A						:				Dict						,					A						:				str						,					A						:				Dict						,					A						:				Union[str, Any]						,					A						:				Any						,					*A						:				Union[str, Any]       ):
             _UpperCAmelCase     :  Optional[Any]							      =    BioGptModel(config=A       ).to(A       ).eval()

             _UpperCAmelCase     :  List[Any]							      =    torch.ones(input_ids.shape						,					dtype=torch.long						,					device=A       )

             # first forward pass
             _UpperCAmelCase     :  Union[str, Any]							      =    model(A						,					attention_mask=A						,					use_cache=A       )

             _UpperCAmelCase      ,  _UpperCAmelCase     :  Dict							      =    outputs.to_tuple()

             # create hypothetical multiple next token and extent to next_input_ids
             _UpperCAmelCase     :  str							      =    ids_tensor((self.batch_size, 3)						,					config.vocab_size       )
             _UpperCAmelCase     :  Any							      =    ids_tensor((self.batch_size, 3)						,					2       )

             # append to next input_ids and
             _UpperCAmelCase     :  Optional[Any]							      =    torch.cat([input_ids, next_tokens]						,					dim=-1       )
             _UpperCAmelCase     :  Dict							      =    torch.cat([attention_mask, next_attn_mask]						,					dim=-1       )

             _UpperCAmelCase     :  Any							      =    model(A						,					attention_mask=A       )["last_hidden_state"]
             _UpperCAmelCase     :  Dict							      =    model(A						,					attention_mask=A						,					past_key_values=A       )[
                 "last_hidden_state"
             ]

             # select random slice
             _UpperCAmelCase     :  Dict							      =    ids_tensor((1,)						,					output_from_past.shape[-1]       ).item()
             _UpperCAmelCase     :  Dict							      =    output_from_no_past[:, -3:, random_slice_idx].detach()
             _UpperCAmelCase     :  Any							      =    output_from_past[:, :, random_slice_idx].detach()

             self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]       )

             # test that outputs are equal for slice
             self.parent.assertTrue(torch.allclose(A						,					A						,					atol=1E-3       )       )




      def      _A	(       self						:				Optional[Any]						,					A						:				Tuple						,					A						:				List[str]						,					A						:				Tuple						,					A						:				Dict						,					A						:				List[Any]						,					*A						:				Tuple						,					A						:				List[str]=False       ):
             _UpperCAmelCase     :  Optional[int]							      =    BioGptForCausalLM(A       )
             model.to(A       )
             if gradient_checkpointing:
                    model.gradient_checkpointing_enable()

             _UpperCAmelCase     :  Union[str, Any]							      =    model(A						,					labels=A       )
             self.parent.assertEqual(result.loss.shape						,					()       )
             self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.seq_length, self.vocab_size)       )
             result.loss.backward()




      def      _A	(       self						:				Optional[Any]						,					A						:				Any						,					*A						:				Optional[Any]       ):
             _UpperCAmelCase     :  Tuple							      =    BioGptModel(A       )
             _UpperCAmelCase     :  int							      =    model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers       )
             for key in model.state_dict().keys():
                    if "c_proj" in key and "weight" in key:
                           self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]       ) - model_std       )						,					0.001       )
                           self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]       ) - 0.0       )						,					0.01       )




      def      _A	(       self						:				Optional[int]						,					A						:				Dict						,					A						:				Tuple						,					A						:				Optional[int]						,					A						:				int						,					A						:				List[str]						,					*A						:				Dict       ):
             _UpperCAmelCase     :  Any							      =    self.num_labels
             _UpperCAmelCase     :  Any							      =    BioGptForTokenClassification(A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  Optional[int]							      =    model(A						,					attention_mask=A						,					token_type_ids=A       )
             self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.seq_length, self.num_labels)       )





      def      _A	(       self						:				int       ):
             _UpperCAmelCase     :  Dict							      =    self.prepare_config_and_inputs()
             (
                 (
                 _UpperCAmelCase
             )      ,  (
                 _UpperCAmelCase
             )      ,  (
                 _UpperCAmelCase
             )      ,  (
                 _UpperCAmelCase
             )      ,  (
                 _UpperCAmelCase
             )      ,  (
                 _UpperCAmelCase
             )      ,  (
                 _UpperCAmelCase
             )      ,  
             )     :  List[str]							      =    config_and_inputs
             _UpperCAmelCase     :  Optional[int]							      =    {"input_ids": input_ids, "attention_mask": input_mask}
             return config, inputs_dict

@require_torch
class 	lowerCamelCase_	(snake_case__							, snake_case__							, snake_case__							, unittest.TestCase    ):
      '''simple docstring'''

      __UpperCamelCase:  List[str]						=						(
          (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
          if is_torch_available()
          else ()
      )
      __UpperCamelCase:  List[str]						=						(BioGptForCausalLM,) if is_torch_available() else ()
      __UpperCamelCase:  str						=						(
          {
              "feature-extraction": BioGptModel,
              "text-classification": BioGptForSequenceClassification,
              "text-generation": BioGptForCausalLM,
              "token-classification": BioGptForTokenClassification,
              "zero-shot": BioGptForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      __UpperCamelCase:  Union[str, Any]						=						False




      def      _A	(       self						:				Optional[Any]       ):
             _UpperCAmelCase     :  List[Any]							      =    BioGptModelTester(self       )
             _UpperCAmelCase     :  str							      =    ConfigTester(self						,					config_class=A						,					hidden_size=37       )




      def      _A	(       self						:				Union[str, Any]       ):
             self.config_tester.run_common_tests()




      def      _A	(       self						:				Any       ):
             _UpperCAmelCase     :  Any							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*A       )




      def      _A	(       self						:				Any       ):
             _UpperCAmelCase     :  Optional[int]							      =    self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                    _UpperCAmelCase     :  Tuple							      =    type
                    self.model_tester.create_and_check_model(*A       )




      def      _A	(       self						:				int       ):
             _UpperCAmelCase     :  Optional[int]							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_biogpt_model_attention_mask_past(*A       )




      def      _A	(       self						:				Union[str, Any]       ):
             _UpperCAmelCase     :  List[Any]							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_forward_and_backwards(*A						,					gradient_checkpointing=A       )




      def      _A	(       self						:				Union[str, Any]       ):
             _UpperCAmelCase     :  Dict							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_biogpt_model_past_large_inputs(*A       )




      def      _A	(       self						:				Dict       ):
             _UpperCAmelCase     :  Dict							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_biogpt_weight_initialization(*A       )




      def      _A	(       self						:				Dict       ):
             _UpperCAmelCase     :  Dict							      =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_biogpt_for_token_classification(*A       )




      @slow
      def      _A	(       self						:				List[str]       ):
             _UpperCAmelCase     :  Optional[Any]							      =    BioGptForCausalLM.from_pretrained("microsoft/biogpt"       )
             model.to(A       )
             _UpperCAmelCase     :  Tuple							      =    BioGptTokenizer.from_pretrained("microsoft/biogpt"       )

             _UpperCAmelCase     :  str							      =    "left"

             # Define PAD Token = EOS Token = 50256
             _UpperCAmelCase     :  Any							      =    tokenizer.eos_token
             _UpperCAmelCase     :  int							      =    model.config.eos_token_id

             # use different length sentences to test batching
             _UpperCAmelCase     :  Any							      =    [
                 "Hello, my dog is a little",
                 "Today, I",
             ]

             _UpperCAmelCase     :  Tuple							      =    tokenizer(A						,					return_tensors="pt"						,					padding=A       )
             _UpperCAmelCase     :  Optional[Any]							      =    inputs["input_ids"].to(A       )

             _UpperCAmelCase     :  Any							      =    model.generate(
                 input_ids=A						,					attention_mask=inputs["attention_mask"].to(A       )						,					)

             _UpperCAmelCase     :  int							      =    tokenizer(sentences[0]						,					return_tensors="pt"       ).input_ids.to(A       )
             _UpperCAmelCase     :  List[Any]							      =    model.generate(input_ids=A       )

             _UpperCAmelCase     :  List[Any]							      =    inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
             _UpperCAmelCase     :  int							      =    tokenizer(sentences[1]						,					return_tensors="pt"       ).input_ids.to(A       )
             _UpperCAmelCase     :  int							      =    model.generate(input_ids=A						,					max_length=model.config.max_length - num_paddings       )

             _UpperCAmelCase     :  Dict							      =    tokenizer.batch_decode(A						,					skip_special_tokens=A       )
             _UpperCAmelCase     :  Any							      =    tokenizer.decode(output_non_padded[0]						,					skip_special_tokens=A       )
             _UpperCAmelCase     :  Optional[int]							      =    tokenizer.decode(output_padded[0]						,					skip_special_tokens=A       )

             _UpperCAmelCase     :  str							      =    [
                 "Hello, my dog is a little bit bigger than a little bit.",
                 "Today, I have a good idea of how to use the information",
             ]
             self.assertListEqual(A						,					A       )
             self.assertListEqual(A						,					[non_padded_sentence, padded_sentence]       )




      @slow
      def      _A	(       self						:				str       ):
             for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _UpperCAmelCase     :  Optional[Any]							      =    BioGptModel.from_pretrained(A       )
                    self.assertIsNotNone(A       )




      def      _A	(       self						:				List[str]       ):
             _UpperCAmelCase      ,  _UpperCAmelCase     :  int							      =    self.model_tester.prepare_config_and_inputs_for_common()
             _UpperCAmelCase     :  str							      =    3
             _UpperCAmelCase     :  List[str]							      =    input_dict["input_ids"]
             _UpperCAmelCase     :  Dict							      =    input_ids.ne(1       ).to(A       )
             _UpperCAmelCase     :  List[Any]							      =    ids_tensor([self.model_tester.batch_size]						,					self.model_tester.type_sequence_label_size       )
             _UpperCAmelCase     :  List[str]							      =    BioGptForSequenceClassification(A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  List[str]							      =    model(A						,					attention_mask=A						,					labels=A       )
             self.assertEqual(result.logits.shape						,					(self.model_tester.batch_size, self.model_tester.num_labels)       )





      def      _A	(       self						:				int       ):
             _UpperCAmelCase      ,  _UpperCAmelCase     :  Optional[Any]							      =    self.model_tester.prepare_config_and_inputs_for_common()
             _UpperCAmelCase     :  int							      =    3
             _UpperCAmelCase     :  Dict							      =    "multi_label_classification"
             _UpperCAmelCase     :  Optional[Any]							      =    input_dict["input_ids"]
             _UpperCAmelCase     :  Optional[int]							      =    input_ids.ne(1       ).to(A       )
             _UpperCAmelCase     :  Tuple							      =    ids_tensor(
                 [self.model_tester.batch_size, config.num_labels]						,					self.model_tester.type_sequence_label_size       ).to(torch.float       )
             _UpperCAmelCase     :  Optional[Any]							      =    BioGptForSequenceClassification(A       )
             model.to(A       )
             model.eval()
             _UpperCAmelCase     :  Tuple							      =    model(A						,					attention_mask=A						,					labels=A       )
             self.assertEqual(result.logits.shape						,					(self.model_tester.batch_size, self.model_tester.num_labels)       )

@require_torch
class 	lowerCamelCase_	(unittest.TestCase    ):
      '''simple docstring'''

      @slow
      def      _A	(       self						:				List[Any]       ):
             _UpperCAmelCase     :  Optional[Any]							      =    BioGptForCausalLM.from_pretrained("microsoft/biogpt"       )
             _UpperCAmelCase     :  List[str]							      =    torch.tensor([[2, 4805, 9, 656, 21]]       )
             _UpperCAmelCase     :  List[Any]							      =    model(A       )[0]

             _UpperCAmelCase     :  int							      =    42384

             _UpperCAmelCase     :  int							      =    torch.Size((1, 5, vocab_size)       )
             self.assertEqual(output.shape						,					A       )

             _UpperCAmelCase     :  Any							      =    torch.tensor(
                 [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]]       )

             self.assertTrue(torch.allclose(output[:, :3, :3]						,					A						,					atol=1E-4       )       )





      @slow
      def      _A	(       self						:				Any       ):
             _UpperCAmelCase     :  str							      =    BioGptTokenizer.from_pretrained("microsoft/biogpt"       )
             _UpperCAmelCase     :  Tuple							      =    BioGptForCausalLM.from_pretrained("microsoft/biogpt"       )
             model.to(A       )

             torch.manual_seed(0       )
             _UpperCAmelCase     :  Optional[Any]							      =    tokenizer("COVID-19 is"						,					return_tensors="pt"       ).to(A       )
             _UpperCAmelCase     :  Dict							      =    model.generate(
                 **A						,					min_length=100						,					max_length=1024						,					num_beams=5						,					early_stopping=A						,					)
             _UpperCAmelCase     :  Optional[Any]							      =    tokenizer.decode(output_ids[0]						,					skip_special_tokens=A       )

             _UpperCAmelCase     :  List[str]							      =    (
                 "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the"
                 " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and"
                 " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),"
                 " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and"
                 " more than 800,000 deaths."
             )
             self.assertEqual(A						,					A       )


"""simple docstring"""




from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block
@dataclass
class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  torch.FloatTensor






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase=3						,__UpperCAmelCase=3						,__UpperCAmelCase=("DownEncoderBlock2D",)						,__UpperCAmelCase=(64,)						,__UpperCAmelCase=2						,__UpperCAmelCase=32						,__UpperCAmelCase="silu"						,__UpperCAmelCase=True						,)    -> Union[str, Any]:
													super().__init__()
													A__		   =							layers_per_block

													A__		   =							torch.nn.Convad(
													    __UpperCAmelCase						,block_out_channels[0]						,kernel_size=3						,stride=1						,padding=1						,)

													A__		   =							None
													A__		   =							nn.ModuleList([]   )

													# down
													A__		   =							block_out_channels[0]
													for i, down_block_type in enumerate(__UpperCAmelCase   ):
																				A__		   =							output_channel
																				A__		   =							block_out_channels[i]
																				A__		   =							i == len(__UpperCAmelCase   ) - 1

																				A__		   =							get_down_block(
																				    __UpperCAmelCase						,num_layers=self.layers_per_block						,in_channels=__UpperCAmelCase						,out_channels=__UpperCAmelCase						,add_downsample=not is_final_block						,resnet_eps=1e-6						,downsample_padding=0						,resnet_act_fn=__UpperCAmelCase						,resnet_groups=__UpperCAmelCase						,attention_head_dim=__UpperCAmelCase						,temb_channels=__UpperCAmelCase						,)
																				self.down_blocks.append(__UpperCAmelCase   )

													# mid
													A__		   =							UNetMidBlockaD(
													    in_channels=block_out_channels[-1]						,resnet_eps=1e-6						,resnet_act_fn=__UpperCAmelCase						,output_scale_factor=1						,resnet_time_scale_shift='default'						,attention_head_dim=block_out_channels[-1]						,resnet_groups=__UpperCAmelCase						,temb_channels=__UpperCAmelCase						,)

													# out
													A__		   =							nn.GroupNorm(num_channels=block_out_channels[-1]						,num_groups=__UpperCAmelCase						,eps=1e-6   )
													A__		   =							nn.SiLU()

													A__		   =							2 * out_channels if double_z else out_channels
													A__		   =							nn.Convad(block_out_channels[-1]						,__UpperCAmelCase						,3						,padding=1   )

													A__		   =							False





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Optional[int]:
													A__		   =							x
													A__		   =							self.conv_in(__UpperCAmelCase   )

													if self.training and self.gradient_checkpointing:

																				def create_custom_forward(__UpperCAmelCase   ):
																											def custom_forward(*__UpperCAmelCase   ):
																																		return module(*__UpperCAmelCase   )

																											return custom_forward

																				# down
																				if is_torch_version('>='						,'1.11.0'   ):
																											for down_block in self.down_blocks:
																																		A__		   =							torch.utils.checkpoint.checkpoint(
																																		    create_custom_forward(__UpperCAmelCase   )						,__UpperCAmelCase						,use_reentrant=__UpperCAmelCase   )
																											# middle
																											A__		   =							torch.utils.checkpoint.checkpoint(
																											    create_custom_forward(self.mid_block   )						,__UpperCAmelCase						,use_reentrant=__UpperCAmelCase   )
																				else:
																											for down_block in self.down_blocks:
																																		A__		   =							torch.utils.checkpoint.checkpoint(create_custom_forward(__UpperCAmelCase   )						,__UpperCAmelCase   )
																											# middle
																											A__		   =							torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block   )						,__UpperCAmelCase   )

													else:
																				# down
																				for down_block in self.down_blocks:
																											A__		   =							down_block(__UpperCAmelCase   )

																				# middle
																				A__		   =							self.mid_block(__UpperCAmelCase   )

													# post-process
													A__		   =							self.conv_norm_out(__UpperCAmelCase   )
													A__		   =							self.conv_act(__UpperCAmelCase   )
													A__		   =							self.conv_out(__UpperCAmelCase   )

													return sample






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase=3						,__UpperCAmelCase=3						,__UpperCAmelCase=("UpDecoderBlock2D",)						,__UpperCAmelCase=(64,)						,__UpperCAmelCase=2						,__UpperCAmelCase=32						,__UpperCAmelCase="silu"						,__UpperCAmelCase="group"						,)    -> Any:
													super().__init__()
													A__		   =							layers_per_block

													A__		   =							nn.Convad(
													    __UpperCAmelCase						,block_out_channels[-1]						,kernel_size=3						,stride=1						,padding=1						,)

													A__		   =							None
													A__		   =							nn.ModuleList([]   )

													A__		   =							in_channels if norm_type == 'spatial' else None

													# mid
													A__		   =							UNetMidBlockaD(
													    in_channels=block_out_channels[-1]						,resnet_eps=1e-6						,resnet_act_fn=__UpperCAmelCase						,output_scale_factor=1						,resnet_time_scale_shift='default' if norm_type == 'group' else norm_type						,attention_head_dim=block_out_channels[-1]						,resnet_groups=__UpperCAmelCase						,temb_channels=__UpperCAmelCase						,)

													# up
													A__		   =							list(reversed(__UpperCAmelCase   )   )
													A__		   =							reversed_block_out_channels[0]
													for i, up_block_type in enumerate(__UpperCAmelCase   ):
																				A__		   =							output_channel
																				A__		   =							reversed_block_out_channels[i]

																				A__		   =							i == len(__UpperCAmelCase   ) - 1

																				A__		   =							get_up_block(
																				    __UpperCAmelCase						,num_layers=self.layers_per_block + 1						,in_channels=__UpperCAmelCase						,out_channels=__UpperCAmelCase						,prev_output_channel=__UpperCAmelCase						,add_upsample=not is_final_block						,resnet_eps=1e-6						,resnet_act_fn=__UpperCAmelCase						,resnet_groups=__UpperCAmelCase						,attention_head_dim=__UpperCAmelCase						,temb_channels=__UpperCAmelCase						,resnet_time_scale_shift=__UpperCAmelCase						,)
																				self.up_blocks.append(__UpperCAmelCase   )
																				A__		   =							output_channel

													# out
													if norm_type == "spatial":
																				A__		   =							SpatialNorm(block_out_channels[0]						,__UpperCAmelCase   )
													else:
																				A__		   =							nn.GroupNorm(num_channels=block_out_channels[0]						,num_groups=__UpperCAmelCase						,eps=1e-6   )
													A__		   =							nn.SiLU()
													A__		   =							nn.Convad(block_out_channels[0]						,__UpperCAmelCase						,3						,padding=1   )

													A__		   =							False





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=None   )    -> Dict:
													A__		   =							z
													A__		   =							self.conv_in(__UpperCAmelCase   )

													A__		   =							next(iter(self.up_blocks.parameters()   )   ).dtype
													if self.training and self.gradient_checkpointing:

																				def create_custom_forward(__UpperCAmelCase   ):
																											def custom_forward(*__UpperCAmelCase   ):
																																		return module(*__UpperCAmelCase   )

																											return custom_forward

																				if is_torch_version('>='						,'1.11.0'   ):
																											# middle
																											A__		   =							torch.utils.checkpoint.checkpoint(
																											    create_custom_forward(self.mid_block   )						,__UpperCAmelCase						,__UpperCAmelCase						,use_reentrant=__UpperCAmelCase   )
																											A__		   =							sample.to(__UpperCAmelCase   )

																											# up
																											for up_block in self.up_blocks:
																																		A__		   =							torch.utils.checkpoint.checkpoint(
																																		    create_custom_forward(__UpperCAmelCase   )						,__UpperCAmelCase						,__UpperCAmelCase						,use_reentrant=__UpperCAmelCase   )
																				else:
																											# middle
																											A__		   =							torch.utils.checkpoint.checkpoint(
																											    create_custom_forward(self.mid_block   )						,__UpperCAmelCase						,__UpperCAmelCase   )
																											A__		   =							sample.to(__UpperCAmelCase   )

																											# up
																											for up_block in self.up_blocks:
																																		A__		   =							torch.utils.checkpoint.checkpoint(create_custom_forward(__UpperCAmelCase   )						,__UpperCAmelCase						,__UpperCAmelCase   )
													else:
																				# middle
																				A__		   =							self.mid_block(__UpperCAmelCase						,__UpperCAmelCase   )
																				A__		   =							sample.to(__UpperCAmelCase   )

																				# up
																				for up_block in self.up_blocks:
																											A__		   =							up_block(__UpperCAmelCase						,__UpperCAmelCase   )

        # post-process
													if latent_embeds is None:
																				A__		   =							self.conv_norm_out(__UpperCAmelCase   )
													else:
																				A__		   =							self.conv_norm_out(__UpperCAmelCase						,__UpperCAmelCase   )
													A__		   =							self.conv_act(__UpperCAmelCase   )
													A__		   =							self.conv_out(__UpperCAmelCase   )

													return sample






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase=None						,__UpperCAmelCase="random"						,__UpperCAmelCase=False						,__UpperCAmelCase=True   )    -> Tuple:
													super().__init__()
													A__		   =							n_e
													A__		   =							vq_embed_dim
													A__		   =							beta
													A__		   =							legacy

													A__		   =							nn.Embedding(self.n_e						,self.vq_embed_dim   )
													self.embedding.weight.data.uniform_(-1.0 / self.n_e						,1.0 / self.n_e   )

													A__		   =							remap
													if self.remap is not None:
																				self.register_buffer('used'						,torch.tensor(np.load(self.remap   )   )   )
																				A__		   =							self.used.shape[0]
																				A__		   =							unknown_index  # "random" or "extra" or integer
																				if self.unknown_index == "extra":
																											A__		   =							self.re_embed
																											A__		   =							self.re_embed + 1
																				print(
																				    f'''Remapping {self.n_e} indices to {self.re_embed} indices. '''
																				    f'''Using {self.unknown_index} for unknown indices.'''   )
													else:
																				A__		   =							n_e

													A__		   =							sane_index_shape





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> List[str]:
													A__		   =							inds.shape
													assert len(__UpperCAmelCase   ) > 1
													A__		   =							inds.reshape(ishape[0]						,-1   )
													A__		   =							self.used.to(__UpperCAmelCase   )
													A__		   =							(inds[:, :, None] == used[None, None, ...]).long()
													A__		   =							match.argmax(-1   )
													A__		   =							match.sum(2   ) < 1
													if self.unknown_index == "random":
																				A__		   =							torch.randint(0						,self.re_embed						,size=new[unknown].shape   ).to(device=new.device   )
													else:
																				A__		   =							self.unknown_index
													return new.reshape(__UpperCAmelCase   )





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Optional[Any]:
													A__		   =							inds.shape
													assert len(__UpperCAmelCase   ) > 1
													A__		   =							inds.reshape(ishape[0]						,-1   )
													A__		   =							self.used.to(__UpperCAmelCase   )
													if self.re_embed > self.used.shape[0]:  # extra token
																				A__		   =							0  # simply set to zero
													A__		   =							torch.gather(used[None, :][inds.shape[0] * [0], :]						,1						,__UpperCAmelCase   )
													return back.reshape(__UpperCAmelCase   )





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Dict:
													# reshape z -> (batch, height, width, channel) and flatten
													A__		   =							z.permute(0						,2						,3						,1   ).contiguous()
													A__		   =							z.view(-1						,self.vq_embed_dim   )

													# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
													A__		   =							torch.argmin(torch.cdist(__UpperCAmelCase						,self.embedding.weight   )						,dim=1   )

													A__		   =							self.embedding(__UpperCAmelCase   ).view(z.shape   )
													A__		   =							None
													A__		   =							None

													# compute loss for embedding
													if not self.legacy:
																				A__		   =							self.beta * torch.mean((z_q.detach() - z) ** 2   ) + torch.mean((z_q - z.detach()) ** 2   )
													else:
																				A__		   =							torch.mean((z_q.detach() - z) ** 2   ) + self.beta * torch.mean((z_q - z.detach()) ** 2   )

													# preserve gradients
													A__		   =							z + (z_q - z).detach()

													# reshape back to match original input shape
													A__		   =							z_q.permute(0						,3						,1						,2   ).contiguous()

													if self.remap is not None:
																				A__		   =							min_encoding_indices.reshape(z.shape[0]						,-1   )  # add batch axis
																				A__		   =							self.remap_to_used(__UpperCAmelCase   )
																				A__		   =							min_encoding_indices.reshape(-1						,1   )  # flatten

													if self.sane_index_shape:
																				A__		   =							min_encoding_indices.reshape(z_q.shape[0]						,z_q.shape[2]						,z_q.shape[3]   )

													return z_q, loss, (perplexity, min_encodings, min_encoding_indices)





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase   )    -> str:
													# shape specifying (batch, height, width, channel)
													if self.remap is not None:
																				A__		   =							indices.reshape(shape[0]						,-1   )  # add batch axis
																				A__		   =							self.unmap_to_all(__UpperCAmelCase   )
																				A__		   =							indices.reshape(-1   )  # flatten again

													# get quantized latent vectors
													A__		   =							self.embedding(__UpperCAmelCase   )

													if shape is not None:
																				A__		   =							z_q.view(__UpperCAmelCase   )
																				# reshape back to match original input shape
																				A__		   =							z_q.permute(0						,3						,1						,2   ).contiguous()

													return z_q






class 			UpperCamelCase__(	__A       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase=False   )    -> Any:
													A__		   =							parameters
													A__   ,     A__		   =							torch.chunk(__UpperCAmelCase						,2						,dim=1   )
													A__		   =							torch.clamp(self.logvar						,-3_0.0						,2_0.0   )
													A__		   =							deterministic
													A__		   =							torch.exp(0.5 * self.logvar   )
													A__		   =							torch.exp(self.logvar   )
													if self.deterministic:
																				A__		   =							A__		   =							torch.zeros_like(
																				    self.mean						,device=self.parameters.device						,dtype=self.parameters.dtype   )





						def  snake_case__		(				self						,__UpperCAmelCase = None   )    -> torch.FloatTensor:
													# make sure sample is on the same device as the parameters and has same dtype
													A__		   =							randn_tensor(
													    self.mean.shape						,generator=__UpperCAmelCase						,device=self.parameters.device						,dtype=self.parameters.dtype   )
													A__		   =							self.mean + self.std * sample
													return x





						def  snake_case__		(				self						,__UpperCAmelCase=None   )    -> int:
													if self.deterministic:
																				return torch.Tensor([0.0]   )
													else:
																				if other is None:
																											return 0.5 * torch.sum(torch.pow(self.mean						,2   ) + self.var - 1.0 - self.logvar						,dim=[1, 2, 3]   )
																				else:
																											return 0.5 * torch.sum(
																											    torch.pow(self.mean - other.mean						,2   ) / other.var
																											    + self.var / other.var
																											    - 1.0
																											    - self.logvar
																											    + other.logvar						,dim=[1, 2, 3]						,)





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=[1, 2, 3]   )    -> List[Any]:
													if self.deterministic:
																				return torch.Tensor([0.0]   )
													A__		   =							np.log(2.0 * np.pi   )
													return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean						,2   ) / self.var						,dim=__UpperCAmelCase   )





						def  snake_case__		(				self   )    -> Optional[Any]:
													return self.mean





