





"""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       a							(   A_  ):
 snake_case__             =       42







class       a							(   nn.Module  ):



 def __init__(     self				,       _snake_case=3				,       _snake_case=3				,       _snake_case=("DownEncoderBlock2D",)				,       _snake_case=(64,)				,       _snake_case=2				,       _snake_case=32				,       _snake_case="silu"				,       _snake_case=True				,       ):







  """simple docstring"""






  super().__init__()
  lowerCAmelCase    				= layers_per_block

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

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

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

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

  # mid
  lowerCAmelCase    				= UNetMidBlockaD(
      in_channels=block_out_channels[-1]				,       resnet_eps=1E-6				,       resnet_act_fn=snake_case__				,       output_scale_factor=1				,       resnet_time_scale_shift='default'				,       attention_head_dim=block_out_channels[-1]				,       resnet_groups=snake_case__				,       temb_channels=snake_case__				,       )

  # out
  lowerCAmelCase    				= nn.GroupNorm(num_channels=block_out_channels[-1]				,       num_groups=snake_case__				,       eps=1E-6     )
  lowerCAmelCase    				= nn.SiLU()

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

  lowerCAmelCase    				= False



 def    UpperCamelCase__  (     self				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= x
  lowerCAmelCase    				= self.conv_in(snake_case__     )

  if self.training and self.gradient_checkpointing:

   def create_custom_forward(_snake_case     ):
    def custom_forward(*_snake_case     ):
     return module(*snake_case__     )

    return custom_forward

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

  else:
   # down
   for down_block in self.down_blocks:
    lowerCAmelCase    				= down_block(snake_case__     )

   # middle
   lowerCAmelCase    				= self.mid_block(snake_case__     )

  # post-process
  lowerCAmelCase    				= self.conv_norm_out(snake_case__     )
  lowerCAmelCase    				= self.conv_act(snake_case__     )
  lowerCAmelCase    				= self.conv_out(snake_case__     )

  return sample







class       a							(   nn.Module  ):



 def __init__(     self				,       _snake_case=3				,       _snake_case=3				,       _snake_case=("UpDecoderBlock2D",)				,       _snake_case=(64,)				,       _snake_case=2				,       _snake_case=32				,       _snake_case="silu"				,       _snake_case="group"				,       ):







  """simple docstring"""






  super().__init__()
  lowerCAmelCase    				= layers_per_block

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

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

  lowerCAmelCase    				= in_channels if norm_type == "spatial" else None

  # mid
  lowerCAmelCase    				= UNetMidBlockaD(
      in_channels=block_out_channels[-1]				,       resnet_eps=1E-6				,       resnet_act_fn=snake_case__				,       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=snake_case__				,       temb_channels=snake_case__				,       )

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

   lowerCAmelCase    				= i == len(snake_case__     ) - 1

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

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

  lowerCAmelCase    				= False



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case=None     ):







  """simple docstring"""






  lowerCAmelCase    				= z
  lowerCAmelCase    				= self.conv_in(snake_case__     )

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

   def create_custom_forward(_snake_case     ):
    def custom_forward(*_snake_case     ):
     return module(*snake_case__     )

    return custom_forward

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

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

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

   # up
   for up_block in self.up_blocks:
    lowerCAmelCase    				= up_block(snake_case__				,       snake_case__     )

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

  return sample







class       a							(   nn.Module  ):



 def __init__(     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case=None				,       _snake_case="random"				,       _snake_case=False				,       _snake_case=True     ):







  """simple docstring"""






  super().__init__()
  lowerCAmelCase    				= n_e
  lowerCAmelCase    				= vq_embed_dim
  lowerCAmelCase    				= beta
  lowerCAmelCase    				= legacy

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

  lowerCAmelCase    				= sane_index_shape



 def    UpperCamelCase__  (     self				,       _snake_case     ):







  """simple docstring"""






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



 def    UpperCamelCase__  (     self				,       _snake_case     ):







  """simple docstring"""






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



 def    UpperCamelCase__  (     self				,       _snake_case     ):







  """simple docstring"""






  lowerCAmelCase    				= z.permute(0				,       2				,       3				,       1     ).contiguous()
  lowerCAmelCase    				= 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    				= torch.argmin(torch.cdist(snake_case__				,       self.embedding.weight     )				,       dim=1     )

  lowerCAmelCase    				= self.embedding(snake_case__     ).view(z.shape     )
  lowerCAmelCase    				= None
  lowerCAmelCase    				= None

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

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

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

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

  if self.sane_index_shape:
   lowerCAmelCase    				= 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				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  if self.remap is not None:
   lowerCAmelCase    				= indices.reshape(shape[0]				,       -1     )  # add batch axis
   lowerCAmelCase    				= self.unmap_to_all(snake_case__     )
   lowerCAmelCase    				= indices.reshape(-1     )  # flatten again

  # get quantized latent vectors
  lowerCAmelCase    				= self.embedding(snake_case__     )

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

  return z_q







class       a							(   A_  ):



 def __init__(     self				,       _snake_case				,       _snake_case=False     ):







  """simple docstring"""






  lowerCAmelCase    				= parameters
  lowerCAmelCase    				= torch.chunk(snake_case__				,       2				,       dim=1     )
  lowerCAmelCase    				= torch.clamp(self.logvar				,       -30.0				,       20.0     )
  lowerCAmelCase    				= deterministic
  lowerCAmelCase    				= torch.exp(0.5 * self.logvar     )
  lowerCAmelCase    				= torch.exp(self.logvar     )
  if self.deterministic:
   lowerCAmelCase    				= torch.zeros_like(
       self.mean				,       device=self.parameters.device				,       dtype=self.parameters.dtype     )



 def    UpperCamelCase__  (     self				,       _snake_case = None     ):







  """simple docstring"""






  lowerCAmelCase    				= randn_tensor(
      self.mean.shape				,       generator=snake_case__				,       device=self.parameters.device				,       dtype=self.parameters.dtype     )
  lowerCAmelCase    				= self.mean + self.std * sample
  return x



 def    UpperCamelCase__  (     self				,       _snake_case=None     ):







  """simple docstring"""






  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				,       _snake_case				,       _snake_case=[1, 2, 3]     ):







  """simple docstring"""






  if self.deterministic:
   return torch.Tensor([0.0]     )
  lowerCAmelCase    				= np.log(2.0 * np.pi     )
  return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean				,       2     ) / self.var				,       dim=snake_case__     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return self.mean







import qiskit


def      UpperCamelCase   (       __lowerCamelCase	:					int							,   __lowerCamelCase	:					int       ):
       snake_case			:  int     							= qiskit.Aer.get_backend("aer_simulator"       )

       # Create a Quantum Circuit acting on the q register
       snake_case			:  Dict     							= qiskit.QuantumCircuit(__lowerCamelCase							,   __lowerCamelCase       )

       # Apply X (NOT) Gate to Qubits 0 & 1
       circuit.x(0       )
       circuit.x(1       )

       # Map the quantum measurement to the classical bits
       circuit.measure([0, 1]							,   [0, 1]       )

       # Execute the circuit on the qasm simulator
       snake_case			:  Dict     							= qiskit.execute(__lowerCamelCase							,   __lowerCamelCase							,   shots=1000       )

       # Return the histogram data of the results of the experiment.
       return job.result().get_counts(__lowerCamelCase       )


if __name__ == "__main__":
   __lowerCamelCase				=			single_qubit_measure(2, 2)
   print(F'Total count for various states are: {counts}')





