





"""simple docstring"""


import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_torch_available():
  import torch

  from transformers import (
      MraForMaskedLM,
      MraForMultipleChoice,
      MraForQuestionAnswering,
      MraForSequenceClassification,
      MraForTokenClassification,
      MraModel,
  )
  from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST



class      __SCREAMING_SNAKE_CASE    :







  '''simple docstring'''


  def __init__(		self   :       int					,   __a   :       str					,   __a   :       List[Any]=2					,   __a   :       int=8					,   __a   :       Dict=True					,   __a   :       Tuple=True					,   __a   :       List[str]=True					,   __a   :       Dict=True					,   __a   :       List[str]=99					,   __a   :       Union[str, Any]=16					,   __a   :       Any=5					,   __a   :       Any=2					,   __a   :       Any=36					,   __a   :       Tuple="gelu"					,   __a   :       Dict=0.0					,   __a   :       Optional[int]=0.0					,   __a   :       str=512					,   __a   :       Optional[int]=16					,   __a   :       Dict=2					,   __a   :       Dict=0.02					,   __a   :       Any=3					,   __a   :       List[str]=4					,   __a   :       Optional[int]=None					,   )		->				Any:
        _UpperCamelCase      :	Any						=       parent
        _UpperCamelCase      :	Union[str, Any]						=       batch_size
        _UpperCamelCase      :	Optional[int]						=       seq_length
        _UpperCamelCase      :	Union[str, Any]						=       is_training
        _UpperCamelCase      :	Optional[int]						=       use_input_mask
        _UpperCamelCase      :	Dict						=       use_token_type_ids
        _UpperCamelCase      :	int						=       use_labels
        _UpperCamelCase      :	Any						=       vocab_size
        _UpperCamelCase      :	List[str]						=       hidden_size
        _UpperCamelCase      :	Optional[int]						=       num_hidden_layers
        _UpperCamelCase      :	Any						=       num_attention_heads
        _UpperCamelCase      :	Union[str, Any]						=       intermediate_size
        _UpperCamelCase      :	Optional[Any]						=       hidden_act
        _UpperCamelCase      :	int						=       hidden_dropout_prob
        _UpperCamelCase      :	Dict						=       attention_probs_dropout_prob
        _UpperCamelCase      :	Union[str, Any]						=       max_position_embeddings
        _UpperCamelCase      :	Tuple						=       type_vocab_size
        _UpperCamelCase      :	Dict						=       type_sequence_label_size
        _UpperCamelCase      :	List[str]						=       initializer_range
        _UpperCamelCase      :	List[str]						=       num_labels
        _UpperCamelCase      :	Dict						=       num_choices
        _UpperCamelCase      :	Any						=       scope

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				Dict:
        _UpperCamelCase      :	List[str]						=       ids_tensor([self.batch_size, self.seq_length]					,   self.vocab_size	)

        _UpperCamelCase      :	List[Any]						=       None
        if self.use_input_mask:
              _UpperCamelCase      :	Optional[Any]						=       random_attention_mask([self.batch_size, self.seq_length]	)

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

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

        _UpperCamelCase      :	List[str]						=       self.get_config()

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Optional[int]:
        return MraConfig(
            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    __SCREAMING_SNAKE_CASE				(		self   :       str	)		->				Tuple:
        _UpperCamelCase      :	List[Any]						=       self.get_config()
        _UpperCamelCase      :	List[str]						=       300
        return config

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Union[str, Any]:
        (
            _UpperCamelCase  
        )      :	Union[str, Any]						=       self.prepare_config_and_inputs()

        _UpperCamelCase      :	Optional[int]						=       True
        _UpperCamelCase      :	Union[str, Any]						=       floats_tensor([self.batch_size, self.seq_length, self.hidden_size]	)
        _UpperCamelCase      :	Optional[int]						=       ids_tensor([self.batch_size, self.seq_length]					,   vocab_size=2	)

        return (
            config,
            input_ids,
            token_type_ids,
            input_mask,
            sequence_labels,
            token_labels,
            choice_labels,
            encoder_hidden_states,
            encoder_attention_mask,
        )

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]					,   __a   :       List[str]					,   __a   :       Tuple					,   __a   :       Tuple					,   __a   :       List[Any]					,   __a   :       Optional[int]					,   __a   :       List[str]					,   __a   :       Union[str, Any]	)		->				Tuple:
        _UpperCamelCase      :	Optional[Any]						=       MraModel(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Tuple						=       model(__a					,   attention_mask=__a					,   token_type_ids=__a	)
        _UpperCamelCase      :	str						=       model(__a					,   token_type_ids=__a	)
        _UpperCamelCase      :	Tuple						=       model(__a	)
        self.parent.assertEqual(result.last_hidden_state.shape					,   (self.batch_size, self.seq_length, self.hidden_size)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict					,   __a   :       Any					,   __a   :       Optional[Any]					,   __a   :       int					,   __a   :       List[str]					,   __a   :       str					,   __a   :       Tuple					,   __a   :       Optional[int]					,   __a   :       Optional[int]					,   __a   :       int					,   )		->				int:
        _UpperCamelCase      :	List[Any]						=       True
        _UpperCamelCase      :	str						=       MraModel(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	str						=       model(
            __a					,   attention_mask=__a					,   token_type_ids=__a					,   encoder_hidden_states=__a					,   encoder_attention_mask=__a					,   )
        _UpperCamelCase      :	List[str]						=       model(
            __a					,   attention_mask=__a					,   token_type_ids=__a					,   encoder_hidden_states=__a					,   )
        _UpperCamelCase      :	Dict						=       model(__a					,   attention_mask=__a					,   token_type_ids=__a	)
        self.parent.assertEqual(result.last_hidden_state.shape					,   (self.batch_size, self.seq_length, self.hidden_size)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple					,   __a   :       Union[str, Any]					,   __a   :       str					,   __a   :       Dict					,   __a   :       int					,   __a   :       List[str]					,   __a   :       int					,   __a   :       int	)		->				int:
        _UpperCamelCase      :	Tuple						=       MraForMaskedLM(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Any						=       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    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]					,   __a   :       int					,   __a   :       int					,   __a   :       int					,   __a   :       Any					,   __a   :       List[str]					,   __a   :       List[str]					,   __a   :       Dict	)		->				str:
        _UpperCamelCase      :	Union[str, Any]						=       MraForQuestionAnswering(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	List[Any]						=       model(
            __a					,   attention_mask=__a					,   token_type_ids=__a					,   start_positions=__a					,   end_positions=__a					,   )
        self.parent.assertEqual(result.start_logits.shape					,   (self.batch_size, self.seq_length)	)
        self.parent.assertEqual(result.end_logits.shape					,   (self.batch_size, self.seq_length)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]					,   __a   :       Dict					,   __a   :       Any					,   __a   :       Any					,   __a   :       Optional[Any]					,   __a   :       List[Any]					,   __a   :       Optional[int]					,   __a   :       Any	)		->				Optional[Any]:
        _UpperCamelCase      :	List[Any]						=       self.num_labels
        _UpperCamelCase      :	Optional[int]						=       MraForSequenceClassification(__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	int						=       model(__a					,   attention_mask=__a					,   token_type_ids=__a					,   labels=__a	)
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.num_labels)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]					,   __a   :       str					,   __a   :       Tuple					,   __a   :       int					,   __a   :       Any					,   __a   :       Optional[int]					,   __a   :       str					,   __a   :       str	)		->				int:
        _UpperCamelCase      :	Optional[int]						=       self.num_labels
        _UpperCamelCase      :	Tuple						=       MraForTokenClassification(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	Any						=       model(__a					,   attention_mask=__a					,   token_type_ids=__a					,   labels=__a	)
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.seq_length, self.num_labels)	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple					,   __a   :       Union[str, Any]					,   __a   :       Optional[Any]					,   __a   :       Any					,   __a   :       Optional[int]					,   __a   :       str					,   __a   :       Any					,   __a   :       Any	)		->				str:
        _UpperCamelCase      :	Tuple						=       self.num_choices
        _UpperCamelCase      :	Optional[int]						=       MraForMultipleChoice(config=__a	)
        model.to(__a	)
        model.eval()
        _UpperCamelCase      :	str						=       input_ids.unsqueeze(1	).expand(-1					,   self.num_choices					,   -1	).contiguous()
        _UpperCamelCase      :	Optional[Any]						=       token_type_ids.unsqueeze(1	).expand(-1					,   self.num_choices					,   -1	).contiguous()
        _UpperCamelCase      :	Tuple						=       input_mask.unsqueeze(1	).expand(-1					,   self.num_choices					,   -1	).contiguous()
        _UpperCamelCase      :	Optional[int]						=       model(
            __a					,   attention_mask=__a					,   token_type_ids=__a					,   labels=__a					,   )
        self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.num_choices)	)


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[Any]	)		->				Optional[Any]:
        _UpperCamelCase      :	Optional[Any]						=       self.prepare_config_and_inputs()
        (
            _UpperCamelCase  
        )      :	int						=       config_and_inputs
        _UpperCamelCase      :	str						=       {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
        return config, inputs_dict





@require_torch
class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase		,  unittest.TestCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:Any	     =					(
      (
          MraModel,
          MraForMaskedLM,
          MraForMultipleChoice,
          MraForQuestionAnswering,
          MraForSequenceClassification,
          MraForTokenClassification,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE__							:str	     =					False
  SCREAMING_SNAKE_CASE__							:int	     =					False
  SCREAMING_SNAKE_CASE__							:Optional[Any]	     =					False
  SCREAMING_SNAKE_CASE__							:Union[str, Any]	     =					False

  SCREAMING_SNAKE_CASE__							:List[Any]	     =					()

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Any:
        _UpperCamelCase      :	Optional[int]						=       MraModelTester(self	)
        _UpperCamelCase      :	Any						=       ConfigTester(self					,   config_class=__a					,   hidden_size=37	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       int	)		->				Dict:
        self.config_tester.run_common_tests()

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				List[str]:
        _UpperCamelCase      :	int						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				List[str]:
        _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    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				List[str]:
        _UpperCamelCase      :	Union[str, Any]						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				str:
        _UpperCamelCase      :	Optional[Any]						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any	)		->				Optional[int]:
        _UpperCamelCase      :	List[Any]						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]	)		->				Any:
        _UpperCamelCase      :	Union[str, Any]						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple	)		->				Optional[Any]:
        _UpperCamelCase      :	Tuple						=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*__a	)

  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]	)		->				Union[str, Any]:
        for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _UpperCamelCase      :	Tuple						=       MraModel.from_pretrained(__a	)
              self.assertIsNotNone(__a	)


  @unittest.skip(reason="MRA does not output attentions"	)
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]	)		->				Tuple:
        return





@require_torch
class      __SCREAMING_SNAKE_CASE    (						unittest.TestCase   ):







  '''simple docstring'''


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict	)		->				Any:
        _UpperCamelCase      :	Tuple						=       MraModel.from_pretrained("uw-madison/mra-base-512-4"	)
        _UpperCamelCase      :	Optional[Any]						=       torch.arange(256	).unsqueeze(0	)

        with torch.no_grad():
              _UpperCamelCase      :	Dict						=       model(__a	)[0]

        _UpperCamelCase      :	Optional[Any]						=       torch.Size((1, 256, 768)	)
        self.assertEqual(output.shape					,   __a	)

        _UpperCamelCase      :	Any						=       torch.tensor(
            [[[-0.01_40, 0.08_30, -0.03_81], [0.15_46, 0.14_02, 0.02_20], [0.11_62, 0.08_51, 0.01_65]]]	)

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

  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				List[Any]:
        _UpperCamelCase      :	List[Any]						=       MraForMaskedLM.from_pretrained("uw-madison/mra-base-512-4"	)
        _UpperCamelCase      :	str						=       torch.arange(256	).unsqueeze(0	)

        with torch.no_grad():
              _UpperCamelCase      :	Optional[int]						=       model(__a	)[0]

        _UpperCamelCase      :	int						=       5_0265

        _UpperCamelCase      :	str						=       torch.Size((1, 256, vocab_size)	)
        self.assertEqual(output.shape					,   __a	)

        _UpperCamelCase      :	List[str]						=       torch.tensor(
            [[[9.25_95, -3.60_38, 11.88_19], [9.38_69, -3.26_93, 11.09_56], [11.85_24, -3.49_38, 13.12_10]]]	)

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


  @slow
  def    __SCREAMING_SNAKE_CASE				(		self   :       List[Any]	)		->				List[Any]:
        _UpperCamelCase      :	Dict						=       MraForMaskedLM.from_pretrained("uw-madison/mra-base-4096-8-d3"	)
        _UpperCamelCase      :	Any						=       torch.arange(4096	).unsqueeze(0	)

        with torch.no_grad():
              _UpperCamelCase      :	Any						=       model(__a	)[0]

        _UpperCamelCase      :	Any						=       5_0265

        _UpperCamelCase      :	str						=       torch.Size((1, 4096, vocab_size)	)
        self.assertEqual(output.shape					,   __a	)

        _UpperCamelCase      :	List[str]						=       torch.tensor(
            [[[5.47_89, -2.35_64, 7.50_64], [7.90_67, -1.33_69, 9.96_68], [9.07_12, -1.81_06, 7.03_80]]]	)

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







"""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      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:torch.FloatTensor





class      __SCREAMING_SNAKE_CASE    (						nn.Module   ):







  '''simple docstring'''


  def __init__(		self   :       Dict					,   __a   :       Dict=3					,   __a   :       Any=3					,   __a   :       Union[str, Any]=("DownEncoderBlock2D",)					,   __a   :       Optional[int]=(64,)					,   __a   :       int=2					,   __a   :       Tuple=32					,   __a   :       int="silu"					,   __a   :       str=True					,   )		->				Dict:
        super().__init__()
        _UpperCamelCase      :	List[str]						=       layers_per_block

        _UpperCamelCase      :	Dict						=       torch.nn.Convad(
            __a					,   block_out_channels[0]					,   kernel_size=3					,   stride=1					,   padding=1					,   )

        _UpperCamelCase      :	int						=       None
        _UpperCamelCase      :	Any						=       nn.ModuleList([]	)

        # down
        _UpperCamelCase      :	List[str]						=       block_out_channels[0]
        for i, down_block_type in enumerate(__a	):
              _UpperCamelCase      :	Tuple						=       output_channel
              _UpperCamelCase      :	int						=       block_out_channels[i]
              _UpperCamelCase      :	int						=       i == len(__a	) - 1

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

        # mid
        _UpperCamelCase      :	Union[str, Any]						=       UNetMidBlockaD(
            in_channels=block_out_channels[-1]					,   resnet_eps=1e-6					,   resnet_act_fn=__a					,   output_scale_factor=1					,   resnet_time_scale_shift="default"					,   attention_head_dim=block_out_channels[-1]					,   resnet_groups=__a					,   temb_channels=__a					,   )

        # out
        _UpperCamelCase      :	Any						=       nn.GroupNorm(num_channels=block_out_channels[-1]					,   num_groups=__a					,   eps=1e-6	)
        _UpperCamelCase      :	Any						=       nn.SiLU()

        _UpperCamelCase      :	Union[str, Any]						=       2 * out_channels if double_z else out_channels
        _UpperCamelCase      :	Tuple						=       nn.Convad(block_out_channels[-1]					,   __a					,   3					,   padding=1	)

        _UpperCamelCase      :	Optional[int]						=       False


  def    __SCREAMING_SNAKE_CASE				(		self   :       List[str]					,   __a   :       Dict	)		->				List[str]:
        _UpperCamelCase      :	int						=       x
        _UpperCamelCase      :	Optional[int]						=       self.conv_in(__a	)

        if self.training and self.gradient_checkpointing:

              def create_custom_forward(__a   :       Tuple	):
                    def custom_forward(*__a   :       Any	):
                          return module(*__a	)

                    return custom_forward

              # down
              if is_torch_version(">="					,   "1.11.0"	):
                    for down_block in self.down_blocks:
                          _UpperCamelCase      :	Optional[int]						=       torch.utils.checkpoint.checkpoint(
                              create_custom_forward(__a	)					,   __a					,   use_reentrant=__a	)
                    # middle
                    _UpperCamelCase      :	Tuple						=       torch.utils.checkpoint.checkpoint(
                        create_custom_forward(self.mid_block	)					,   __a					,   use_reentrant=__a	)
              else:
                    for down_block in self.down_blocks:
                          _UpperCamelCase      :	Any						=       torch.utils.checkpoint.checkpoint(create_custom_forward(__a	)					,   __a	)
                    # middle
                    _UpperCamelCase      :	int						=       torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block	)					,   __a	)

        else:
              # down
              for down_block in self.down_blocks:
                    _UpperCamelCase      :	int						=       down_block(__a	)

              # middle
              _UpperCamelCase      :	int						=       self.mid_block(__a	)

        # post-process
        _UpperCamelCase      :	Any						=       self.conv_norm_out(__a	)
        _UpperCamelCase      :	Any						=       self.conv_act(__a	)
        _UpperCamelCase      :	Optional[Any]						=       self.conv_out(__a	)

        return sample





class      __SCREAMING_SNAKE_CASE    (						nn.Module   ):







  '''simple docstring'''


  def __init__(		self   :       Dict					,   __a   :       int=3					,   __a   :       Any=3					,   __a   :       str=("UpDecoderBlock2D",)					,   __a   :       Optional[int]=(64,)					,   __a   :       int=2					,   __a   :       Optional[int]=32					,   __a   :       Tuple="silu"					,   __a   :       Union[str, Any]="group"					,   )		->				str:
        super().__init__()
        _UpperCamelCase      :	List[Any]						=       layers_per_block

        _UpperCamelCase      :	Tuple						=       nn.Convad(
            __a					,   block_out_channels[-1]					,   kernel_size=3					,   stride=1					,   padding=1					,   )

        _UpperCamelCase      :	List[str]						=       None
        _UpperCamelCase      :	Dict						=       nn.ModuleList([]	)

        _UpperCamelCase      :	List[Any]						=       in_channels if norm_type == "spatial" else None

        # mid
        _UpperCamelCase      :	Optional[Any]						=       UNetMidBlockaD(
            in_channels=block_out_channels[-1]					,   resnet_eps=1e-6					,   resnet_act_fn=__a					,   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=__a					,   temb_channels=__a					,   )

        # up
        _UpperCamelCase      :	List[str]						=       list(reversed(__a	)	)
        _UpperCamelCase      :	int						=       reversed_block_out_channels[0]
        for i, up_block_type in enumerate(__a	):
              _UpperCamelCase      :	int						=       output_channel
              _UpperCamelCase      :	Union[str, Any]						=       reversed_block_out_channels[i]

              _UpperCamelCase      :	Optional[Any]						=       i == len(__a	) - 1

              _UpperCamelCase      :	Union[str, Any]						=       get_up_block(
                  __a					,   num_layers=self.layers_per_block + 1					,   in_channels=__a					,   out_channels=__a					,   prev_output_channel=__a					,   add_upsample=not is_final_block					,   resnet_eps=1e-6					,   resnet_act_fn=__a					,   resnet_groups=__a					,   attention_head_dim=__a					,   temb_channels=__a					,   resnet_time_scale_shift=__a					,   )
              self.up_blocks.append(__a	)
              _UpperCamelCase      :	Optional[Any]						=       output_channel

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

        _UpperCamelCase      :	Dict						=       False


  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       List[Any]					,   __a   :       Union[str, Any]=None	)		->				Tuple:
        _UpperCamelCase      :	List[str]						=       z
        _UpperCamelCase      :	Dict						=       self.conv_in(__a	)

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

              def create_custom_forward(__a   :       Any	):
                    def custom_forward(*__a   :       Tuple	):
                          return module(*__a	)

                    return custom_forward

              if is_torch_version(">="					,   "1.11.0"	):
                    # middle
                    _UpperCamelCase      :	str						=       torch.utils.checkpoint.checkpoint(
                        create_custom_forward(self.mid_block	)					,   __a					,   __a					,   use_reentrant=__a	)
                    _UpperCamelCase      :	Optional[int]						=       sample.to(__a	)

                    # up
                    for up_block in self.up_blocks:
                          _UpperCamelCase      :	List[Any]						=       torch.utils.checkpoint.checkpoint(
                              create_custom_forward(__a	)					,   __a					,   __a					,   use_reentrant=__a	)
              else:
                    # middle
                    _UpperCamelCase      :	Optional[int]						=       torch.utils.checkpoint.checkpoint(
                        create_custom_forward(self.mid_block	)					,   __a					,   __a	)
                    _UpperCamelCase      :	Union[str, Any]						=       sample.to(__a	)

                    # up
                    for up_block in self.up_blocks:
                          _UpperCamelCase      :	str						=       torch.utils.checkpoint.checkpoint(create_custom_forward(__a	)					,   __a					,   __a	)
        else:
              # middle
              _UpperCamelCase      :	str						=       self.mid_block(__a					,   __a	)
              _UpperCamelCase      :	int						=       sample.to(__a	)

              # up
              for up_block in self.up_blocks:
                    _UpperCamelCase      :	Any						=       up_block(__a					,   __a	)

        # post-process
        if latent_embeds is None:
              _UpperCamelCase      :	List[str]						=       self.conv_norm_out(__a	)
        else:
              _UpperCamelCase      :	Optional[int]						=       self.conv_norm_out(__a					,   __a	)
        _UpperCamelCase      :	Tuple						=       self.conv_act(__a	)
        _UpperCamelCase      :	List[Any]						=       self.conv_out(__a	)

        return sample





class      __SCREAMING_SNAKE_CASE    (						nn.Module   ):







  '''simple docstring'''


  def __init__(		self   :       Dict					,   __a   :       Tuple					,   __a   :       List[str]					,   __a   :       List[str]					,   __a   :       str=None					,   __a   :       Optional[int]="random"					,   __a   :       Any=False					,   __a   :       Optional[Any]=True	)		->				List[Any]:
        super().__init__()
        _UpperCamelCase      :	Tuple						=       n_e
        _UpperCamelCase      :	Tuple						=       vq_embed_dim
        _UpperCamelCase      :	Union[str, Any]						=       beta
        _UpperCamelCase      :	str						=       legacy

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

        _UpperCamelCase      :	Any						=       remap
        if self.remap is not None:
              self.register_buffer("used"					,   torch.tensor(np.load(self.remap	)	)	)
              _UpperCamelCase      :	Dict						=       self.used.shape[0]
              _UpperCamelCase      :	Optional[int]						=       unknown_index  # "random" or "extra" or integer
              if self.unknown_index == "extra":
                    _UpperCamelCase      :	Optional[int]						=       self.re_embed
                    _UpperCamelCase      :	Any						=       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:
              _UpperCamelCase      :	Union[str, Any]						=       n_e

        _UpperCamelCase      :	List[str]						=       sane_index_shape

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

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict					,   __a   :       Optional[int]	)		->				Optional[int]:
        _UpperCamelCase      :	int						=       inds.shape
        assert len(__a	) > 1
        _UpperCamelCase      :	List[Any]						=       inds.reshape(ishape[0]					,   -1	)
        _UpperCamelCase      :	Optional[int]						=       self.used.to(__a	)
        if self.re_embed > self.used.shape[0]:  # extra token
              _UpperCamelCase      :	int						=       0  # simply set to zero
        _UpperCamelCase      :	Union[str, Any]						=       torch.gather(used[None, :][inds.shape[0] * [0], :]					,   1					,   __a	)
        return back.reshape(__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       str	)		->				Optional[int]:
        # reshape z -> (batch, height, width, channel) and flatten
        _UpperCamelCase      :	List[str]						=       z.permute(0					,   2					,   3					,   1	).contiguous()
        _UpperCamelCase      :	int						=       z.view(-1					,   self.vq_embed_dim	)

        # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
        _UpperCamelCase      :	Optional[int]						=       torch.argmin(torch.cdist(__a					,   self.embedding.weight	)					,   dim=1	)

        _UpperCamelCase      :	int						=       self.embedding(__a	).view(z.shape	)
        _UpperCamelCase      :	str						=       None
        _UpperCamelCase      :	Any						=       None

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

        # preserve gradients
        _UpperCamelCase      :	List[str]						=       z + (z_q - z).detach()

        # reshape back to match original input shape
        _UpperCamelCase      :	Optional[Any]						=       z_q.permute(0					,   3					,   1					,   2	).contiguous()

        if self.remap is not None:
              _UpperCamelCase      :	Tuple						=       min_encoding_indices.reshape(z.shape[0]					,   -1	)  # add batch axis
              _UpperCamelCase      :	Dict						=       self.remap_to_used(__a	)
              _UpperCamelCase      :	List[str]						=       min_encoding_indices.reshape(-1					,   1	)  # flatten

        if self.sane_index_shape:
              _UpperCamelCase      :	str						=       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    __SCREAMING_SNAKE_CASE				(		self   :       List[str]					,   __a   :       List[str]					,   __a   :       str	)		->				Any:
        # shape specifying (batch, height, width, channel)
        if self.remap is not None:
              _UpperCamelCase      :	str						=       indices.reshape(shape[0]					,   -1	)  # add batch axis
              _UpperCamelCase      :	str						=       self.unmap_to_all(__a	)
              _UpperCamelCase      :	int						=       indices.reshape(-1	)  # flatten again

        # get quantized latent vectors
        _UpperCamelCase      :	Optional[int]						=       self.embedding(__a	)

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

        return z_q





class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase   ):







  '''simple docstring'''


  def __init__(		self   :       Optional[int]					,   __a   :       List[str]					,   __a   :       Optional[Any]=False	)		->				int:
        _UpperCamelCase      :	Dict						=       parameters
        _UpperCamelCase,  _UpperCamelCase      :	str						=       torch.chunk(__a					,   2					,   dim=1	)
        _UpperCamelCase      :	Tuple						=       torch.clamp(self.logvar					,   -30.0					,   20.0	)
        _UpperCamelCase      :	Union[str, Any]						=       deterministic
        _UpperCamelCase      :	Dict						=       torch.exp(0.5 * self.logvar	)
        _UpperCamelCase      :	Any						=       torch.exp(self.logvar	)
        if self.deterministic:
              _UpperCamelCase      :	List[Any]						=       torch.zeros_like(
                  self.mean					,   device=self.parameters.device					,   dtype=self.parameters.dtype	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Optional[int]					,   __a   :       Optional[torch.Generator] = None	)		->				torch.FloatTensor:
        # make sure sample is on the same device as the parameters and has same dtype
        _UpperCamelCase      :	List[Any]						=       randn_tensor(
            self.mean.shape					,   generator=__a					,   device=self.parameters.device					,   dtype=self.parameters.dtype	)
        _UpperCamelCase      :	List[Any]						=       self.mean + self.std * sample
        return x

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       List[str]=None	)		->				List[Any]:
        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    __SCREAMING_SNAKE_CASE				(		self   :       str					,   __a   :       Tuple					,   __a   :       List[str]=[1, 2, 3]	)		->				int:
        if self.deterministic:
              return torch.Tensor([0.0]	)
        _UpperCamelCase      :	List[str]						=       np.log(2.0 * np.pi	)
        return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean					,   2	) / self.var					,   dim=__a	)


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