



'''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        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  __lowercase							:      torch.FloatTensor







class        lowerCAmelCase_(				nn.Module     ):
  '''simple docstring'''




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

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

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

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

          lowerCAmelCase__ :  Tuple							      =					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
      lowerCAmelCase__ :  Any							      =					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
      lowerCAmelCase__ :  List[str]							      =					nn.GroupNorm(num_channels=block_out_channels[-1]  ,num_groups=__UpperCAmelCase  ,eps=1E-6      )
      lowerCAmelCase__ :  List[str]							      =					nn.SiLU()

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

      lowerCAmelCase__ :  Optional[int]							      =					False






  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Optional[Any]:
      lowerCAmelCase__ :  Any							      =					x
      lowerCAmelCase__ :  Optional[Any]							      =					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:
                  lowerCAmelCase__ :  Tuple							      =					torch.utils.checkpoint.checkpoint(
                      create_custom_forward(__UpperCAmelCase      )  ,__UpperCAmelCase  ,use_reentrant=__UpperCAmelCase      )
              # middle
              lowerCAmelCase__ :  List[Any]							      =					torch.utils.checkpoint.checkpoint(
                  create_custom_forward(self.mid_block      )  ,__UpperCAmelCase  ,use_reentrant=__UpperCAmelCase      )
          else:
              for down_block in self.down_blocks:
                  lowerCAmelCase__ :  Union[str, Any]							      =					torch.utils.checkpoint.checkpoint(create_custom_forward(__UpperCAmelCase      )  ,__UpperCAmelCase      )
              # middle
              lowerCAmelCase__ :  List[str]							      =					torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block      )  ,__UpperCAmelCase      )

      else:
          # down
          for down_block in self.down_blocks:
              lowerCAmelCase__ :  Union[str, Any]							      =					down_block(__UpperCAmelCase      )

          # middle
          lowerCAmelCase__ :  Optional[int]							      =					self.mid_block(__UpperCAmelCase      )

      # post-process
      lowerCAmelCase__ :  str							      =					self.conv_norm_out(__UpperCAmelCase      )
      lowerCAmelCase__ :  Optional[int]							      =					self.conv_act(__UpperCAmelCase      )
      lowerCAmelCase__ :  int							      =					self.conv_out(__UpperCAmelCase      )

      return sample







class        lowerCAmelCase_(				nn.Module     ):
  '''simple docstring'''




  def __init__(    self  ,__UpperCAmelCase=3  ,__UpperCAmelCase=3  ,__UpperCAmelCase=("UpDecoderBlock2D",)  ,__UpperCAmelCase=(64,)  ,__UpperCAmelCase=2  ,__UpperCAmelCase=32  ,__UpperCAmelCase="silu"  ,__UpperCAmelCase="group"  ,)    ->		List[Any]:
      super().__init__()
      lowerCAmelCase__ :  Dict							      =					layers_per_block

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

      lowerCAmelCase__ :  Union[str, Any]							      =					None
      lowerCAmelCase__ :  Dict							      =					nn.ModuleList([]      )

      lowerCAmelCase__ :  Tuple							      =					in_channels if norm_type == """spatial""" else None

      # mid
      lowerCAmelCase__ :  Optional[Any]							      =					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
      lowerCAmelCase__ :  Optional[int]							      =					list(reversed(__UpperCAmelCase      )      )
      lowerCAmelCase__ :  Tuple							      =					reversed_block_out_channels[0]
      for i, up_block_type in enumerate(__UpperCAmelCase      ):
          lowerCAmelCase__ :  Optional[Any]							      =					output_channel
          lowerCAmelCase__ :  int							      =					reversed_block_out_channels[i]

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

          lowerCAmelCase__ :  Union[str, Any]							      =					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      )
          lowerCAmelCase__ :  Union[str, Any]							      =					output_channel

      # out
      if norm_type == "spatial":
          lowerCAmelCase__ :  Optional[Any]							      =					SpatialNorm(block_out_channels[0]  ,__UpperCAmelCase      )
      else:
          lowerCAmelCase__ :  List[Any]							      =					nn.GroupNorm(num_channels=block_out_channels[0]  ,num_groups=__UpperCAmelCase  ,eps=1E-6      )
      lowerCAmelCase__ :  int							      =					nn.SiLU()
      lowerCAmelCase__ :  Dict							      =					nn.Convad(block_out_channels[0]  ,__UpperCAmelCase  ,3  ,padding=1      )

      lowerCAmelCase__ :  Optional[Any]							      =					False






  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=None      )    ->		Optional[Any]:
      lowerCAmelCase__ :  Optional[Any]							      =					z
      lowerCAmelCase__ :  List[Any]							      =					self.conv_in(__UpperCAmelCase      )

      lowerCAmelCase__ :  Dict							      =					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
              lowerCAmelCase__ :  Union[str, Any]							      =					torch.utils.checkpoint.checkpoint(
                  create_custom_forward(self.mid_block      )  ,__UpperCAmelCase  ,__UpperCAmelCase  ,use_reentrant=__UpperCAmelCase      )
              lowerCAmelCase__ :  List[Any]							      =					sample.to(__UpperCAmelCase      )

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

              # up
              for up_block in self.up_blocks:
                  lowerCAmelCase__ :  List[Any]							      =					torch.utils.checkpoint.checkpoint(create_custom_forward(__UpperCAmelCase      )  ,__UpperCAmelCase  ,__UpperCAmelCase      )
      else:
          # middle
          lowerCAmelCase__ :  Any							      =					self.mid_block(__UpperCAmelCase  ,__UpperCAmelCase      )
          lowerCAmelCase__ :  int							      =					sample.to(__UpperCAmelCase      )

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

        # post-process
      if latent_embeds is None:
          lowerCAmelCase__ :  Union[str, Any]							      =					self.conv_norm_out(__UpperCAmelCase      )
      else:
          lowerCAmelCase__ :  List[Any]							      =					self.conv_norm_out(__UpperCAmelCase  ,__UpperCAmelCase      )
      lowerCAmelCase__ :  Dict							      =					self.conv_act(__UpperCAmelCase      )
      lowerCAmelCase__ :  Optional[int]							      =					self.conv_out(__UpperCAmelCase      )

      return sample







class        lowerCAmelCase_(				nn.Module     ):
  '''simple docstring'''




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

      lowerCAmelCase__ :  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      )

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

      lowerCAmelCase__ :  Tuple							      =					sane_index_shape




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




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




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase      )    ->		Union[str, Any]:
      # reshape z -> (batch, height, width, channel) and flatten
      lowerCAmelCase__ :  Optional[int]							      =					z.permute(0  ,2  ,3  ,1      ).contiguous()
      lowerCAmelCase__ :  Tuple							      =					z.view(-1  ,self.vq_embed_dim      )

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

      lowerCAmelCase__ :  Dict							      =					self.embedding(__UpperCAmelCase      ).view(z.shape      )
      lowerCAmelCase__ :  Tuple							      =					None
      lowerCAmelCase__ :  int							      =					None

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

      # preserve gradients
      lowerCAmelCase__ :  Optional[Any]							      =					z + (z_q - z).detach()

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

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

      if self.sane_index_shape:
          lowerCAmelCase__ :  Union[str, Any]							      =					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 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase      )    ->		Tuple:
      # shape specifying (batch, height, width, channel)
      if self.remap is not None:
          lowerCAmelCase__ :  str							      =					indices.reshape(shape[0]  ,-1      )  # add batch axis
          lowerCAmelCase__ :  Dict							      =					self.unmap_to_all(__UpperCAmelCase      )
          lowerCAmelCase__ :  Dict							      =					indices.reshape(-1      )  # flatten again

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

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

      return z_q







class        lowerCAmelCase_(				SCREAMING_SNAKE_CASE_     ):
  '''simple docstring'''




  def __init__(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=False      )    ->		Dict:
      lowerCAmelCase__ :  int							      =					parameters
      lowerCAmelCase__      ,   lowerCAmelCase__ :  List[Any]							      =					torch.chunk(__UpperCAmelCase  ,2  ,dim=1      )
      lowerCAmelCase__ :  Optional[Any]							      =					torch.clamp(self.logvar  ,-3_0.0  ,2_0.0      )
      lowerCAmelCase__ :  List[Any]							      =					deterministic
      lowerCAmelCase__ :  str							      =					torch.exp(0.5 * self.logvar      )
      lowerCAmelCase__ :  str							      =					torch.exp(self.logvar      )
      if self.deterministic:
          lowerCAmelCase__ :  Optional[int]							      =					torch.zeros_like(
              self.mean  ,device=self.parameters.device  ,dtype=self.parameters.dtype      )




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




  def 							UpperCAmelCase_	(    self  ,__UpperCAmelCase=None      )    ->		str:
      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 							UpperCAmelCase_	(    self  ,__UpperCAmelCase  ,__UpperCAmelCase=[1, 2, 3]      )    ->		Optional[Any]:
      if self.deterministic:
          return torch.Tensor([0.0]      )
      lowerCAmelCase__ :  str							      =					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 							UpperCAmelCase_	(    self      )    ->		Optional[int]:
      return self.mean





import math
import sys







def 			A_      (    _UpperCAmelCase    ):
						if number != int(_UpperCAmelCase    ):
												raise ValueError("the value of input must be a natural number"    )
						if number < 0:
												raise ValueError("the value of input must not be a negative number"    )
						if number == 0:
												return 1
						SCREAMING_SNAKE_CASE_: List[str]  		=       [-1] * (number + 1)
						SCREAMING_SNAKE_CASE_: str  		=       0
						for i in range(1				,	number + 1    ):
												SCREAMING_SNAKE_CASE_: str  		=       sys.maxsize
												SCREAMING_SNAKE_CASE_: List[Any]  		=       int(math.sqrt(_UpperCAmelCase    )    )
												for j in range(1				,	root + 1    ):
																		SCREAMING_SNAKE_CASE_: List[str]  		=       1 + answers[i - (j**2)]
																		SCREAMING_SNAKE_CASE_: Optional[Any]  		=       min(_UpperCAmelCase				,	_UpperCAmelCase    )
												SCREAMING_SNAKE_CASE_: Dict  		=       answer
						return answers[number]


if __name__ == "__main__":
						import doctest

						doctest.testmod()






