





"""simple docstring"""


import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import cached_download, hf_hub_download, hf_hub_url
from PIL import Image

from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig
from transformers.utils import logging


logging.set_verbosity_info()
lowerCamelCase__				  =   logging.get_logger(__name__)




def 					lowercase__    (					lowercase_			)					->		List[Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[str]						=       SwinConfig(
          embed_dim=192		,depths=(2, 2, 18, 2)		,num_heads=(6, 12, 24, 48)		,window_size=12		,out_features=["stage2", "stage3", "stage4"]		,)

      _UpperCamelCase      :	List[Any]						=       DetaConfig(
          backbone_config=lowercase_		,num_queries=900		,encoder_ffn_dim=2_048		,decoder_ffn_dim=2_048		,num_feature_levels=5		,assign_first_stage=lowercase_		,with_box_refine=lowercase_		,two_stage=lowercase_		,)

      # set labels
      _UpperCamelCase      :	int						=       "huggingface/label-files"
      if "o365" in model_name:
            _UpperCamelCase      :	Optional[Any]						=       366
            _UpperCamelCase      :	List[str]						=       "object365-id2label.json"
      else:
            _UpperCamelCase      :	List[str]						=       91
            _UpperCamelCase      :	List[str]						=       "coco-detection-id2label.json"

      _UpperCamelCase      :	Union[str, Any]						=       num_labels
      _UpperCamelCase      :	Optional[Any]						=       json.load(open(cached_download(hf_hub_url(lowercase_		,lowercase_		,repo_type="dataset"			)			)		,"r"			)			)
      _UpperCamelCase      :	Any						=       {int(lowercase_			): v for k, v in idalabel.items()}
      _UpperCamelCase      :	Tuple						=       idalabel
      _UpperCamelCase      :	List[Any]						=       {v: k for k, v in idalabel.items()}

      return config




def 					lowercase__    (					lowercase_			)					->		str:




      """simple docstring"""

      _UpperCamelCase      :	List[str]						=       []

      # stem
      # fmt: off
      rename_keys.append(("backbone.0.body.patch_embed.proj.weight", "model.backbone.model.embeddings.patch_embeddings.projection.weight")			)
      rename_keys.append(("backbone.0.body.patch_embed.proj.bias", "model.backbone.model.embeddings.patch_embeddings.projection.bias")			)
      rename_keys.append(("backbone.0.body.patch_embed.norm.weight", "model.backbone.model.embeddings.norm.weight")			)
      rename_keys.append(("backbone.0.body.patch_embed.norm.bias", "model.backbone.model.embeddings.norm.bias")			)
      # stages
      for i in range(len(config.backbone_config.depths			)			):
            for j in range(config.backbone_config.depths[i]			):
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''')			)

            if i < 3:
                  rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.reduction.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.reduction.weight''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.weight''')			)
                  rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.bias''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.bias''')			)

      rename_keys.append(("backbone.0.body.norm1.weight", "model.backbone.model.hidden_states_norms.stage2.weight")			)
      rename_keys.append(("backbone.0.body.norm1.bias", "model.backbone.model.hidden_states_norms.stage2.bias")			)
      rename_keys.append(("backbone.0.body.norm2.weight", "model.backbone.model.hidden_states_norms.stage3.weight")			)
      rename_keys.append(("backbone.0.body.norm2.bias", "model.backbone.model.hidden_states_norms.stage3.bias")			)
      rename_keys.append(("backbone.0.body.norm3.weight", "model.backbone.model.hidden_states_norms.stage4.weight")			)
      rename_keys.append(("backbone.0.body.norm3.bias", "model.backbone.model.hidden_states_norms.stage4.bias")			)

      # transformer encoder
      for i in range(config.encoder_layers			):
            rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', F'''model.encoder.layers.{i}.self_attn.attention_weights.weight''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', F'''model.encoder.layers.{i}.self_attn.attention_weights.bias''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', F'''model.encoder.layers.{i}.self_attn.value_proj.weight''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', F'''model.encoder.layers.{i}.self_attn.value_proj.bias''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', F'''model.encoder.layers.{i}.self_attn.output_proj.weight''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', F'''model.encoder.layers.{i}.self_attn.output_proj.bias''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.weight''', F'''model.encoder.layers.{i}.self_attn_layer_norm.weight''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''model.encoder.layers.{i}.self_attn_layer_norm.bias''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''model.encoder.layers.{i}.fc1.weight''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''model.encoder.layers.{i}.fc1.bias''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''model.encoder.layers.{i}.fc2.weight''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''model.encoder.layers.{i}.fc2.bias''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''model.encoder.layers.{i}.final_layer_norm.weight''')			)
            rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''model.encoder.layers.{i}.final_layer_norm.bias''')			)

      # transformer decoder
      for i in range(config.decoder_layers			):
            rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.weight''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''model.decoder.layers.{i}.self_attn.out_proj.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''model.decoder.layers.{i}.self_attn.out_proj.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.weight''', F'''model.decoder.layers.{i}.self_attn_layer_norm.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.bias''', F'''model.decoder.layers.{i}.self_attn_layer_norm.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''model.decoder.layers.{i}.fc1.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''model.decoder.layers.{i}.fc1.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''model.decoder.layers.{i}.fc2.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''model.decoder.layers.{i}.fc2.bias''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''model.decoder.layers.{i}.final_layer_norm.weight''')			)
            rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''model.decoder.layers.{i}.final_layer_norm.bias''')			)

      # fmt: on

      return rename_keys




def 					lowercase__    (					lowercase_		,lowercase_		,lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[Any]						=       dct.pop(lowercase_			)
      _UpperCamelCase      :	Optional[Any]						=       val




def 					lowercase__    (					lowercase_		,lowercase_			)					->		Tuple:




      """simple docstring"""

      _UpperCamelCase      :	Dict						=       [int(backbone_config.embed_dim * 2**i			) for i in range(len(backbone_config.depths			)			)]
      for i in range(len(backbone_config.depths			)			):
            _UpperCamelCase      :	List[str]						=       num_features[i]
            for j in range(backbone_config.depths[i]			):
                  # fmt: off
                  # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
                  _UpperCamelCase      :	Optional[Any]						=       state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight'''			)
                  _UpperCamelCase      :	Optional[int]						=       state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias'''			)
                  # next, add query, keys and values (in that order) to the state dict
                  _UpperCamelCase      :	int						=       in_proj_weight[:dim, :]
                  _UpperCamelCase      :	Any						=       in_proj_bias[: dim]
                  _UpperCamelCase      :	List[str]						=       in_proj_weight[
                      dim : dim * 2, :
                  ]
                  _UpperCamelCase      :	Union[str, Any]						=       in_proj_bias[
                      dim : dim * 2
                  ]
                  _UpperCamelCase      :	List[Any]						=       in_proj_weight[
                      -dim :, :
                  ]
                  _UpperCamelCase      :	Optional[int]						=       in_proj_bias[-dim :]
                  # fmt: on




def 					lowercase__    (					lowercase_		,lowercase_			)					->		int:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       config.d_model
      for i in range(config.decoder_layers			):
            # read in weights + bias of input projection layer of self-attention
            _UpperCamelCase      :	str						=       state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight'''			)
            _UpperCamelCase      :	Optional[int]						=       state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_bias'''			)
            # next, add query, keys and values (in that order) to the state dict
            _UpperCamelCase      :	List[str]						=       in_proj_weight[:hidden_size, :]
            _UpperCamelCase      :	Dict						=       in_proj_bias[:hidden_size]
            _UpperCamelCase      :	Dict						=       in_proj_weight[
                hidden_size : hidden_size * 2, :
            ]
            _UpperCamelCase      :	Any						=       in_proj_bias[hidden_size : hidden_size * 2]
            _UpperCamelCase      :	int						=       in_proj_weight[-hidden_size:, :]
            _UpperCamelCase      :	int						=       in_proj_bias[-hidden_size:]




def 					lowercase__    (					)					->		Optional[int]:




      """simple docstring"""

      _UpperCamelCase      :	List[str]						=       "http://images.cocodataset.org/val2017/000000039769.jpg"
      _UpperCamelCase      :	int						=       Image.open(requests.get(lowercase_		,stream=lowercase_			).raw			)

      return im




@torch.no_grad()
def 					lowercase__    (					lowercase_		,lowercase_		,lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[Any]						=       get_deta_config(lowercase_			)

      # load original state dict
      if model_name == "deta-swin-large":
            _UpperCamelCase      :	Optional[int]						=       hf_hub_download(repo_id="nielsr/deta-checkpoints"		,filename="adet_swin_ft.pth"			)
      elif model_name == "deta-swin-large-o365":
            _UpperCamelCase      :	Any						=       hf_hub_download(repo_id="jozhang97/deta-swin-l-o365"		,filename="deta_swin_pt_o365.pth"			)
      else:
            raise ValueError(F'''Model name {model_name} not supported'''			)

      _UpperCamelCase      :	Dict						=       torch.load(lowercase_		,map_location="cpu"			)["model"]

      # original state dict
      for name, param in state_dict.items():
            print(lowercase_		,param.shape			)

      # rename keys
      _UpperCamelCase      :	Dict						=       create_rename_keys(lowercase_			)
      for src, dest in rename_keys:
            rename_key(lowercase_		,lowercase_		,lowercase_			)
      read_in_swin_q_k_v(lowercase_		,config.backbone_config			)
      read_in_decoder_q_k_v(lowercase_		,lowercase_			)

      # fix some prefixes
      for key in state_dict.copy().keys():
            if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key:
                  _UpperCamelCase      :	Optional[int]						=       state_dict.pop(lowercase_			)
                  _UpperCamelCase      :	Tuple						=       val
            if "input_proj" in key:
                  _UpperCamelCase      :	Union[str, Any]						=       state_dict.pop(lowercase_			)
                  _UpperCamelCase      :	Union[str, Any]						=       val
            if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key:
                  _UpperCamelCase      :	List[Any]						=       state_dict.pop(lowercase_			)
                  _UpperCamelCase      :	Optional[Any]						=       val

    # finally, create HuggingFace model and load state dict
      _UpperCamelCase      :	Union[str, Any]						=       DetaForObjectDetection(lowercase_			)
      model.load_state_dict(lowercase_			)
      model.eval()

      _UpperCamelCase      :	List[str]						=       "cuda" if torch.cuda.is_available() else "cpu"
      model.to(lowercase_			)

      # load image processor
      _UpperCamelCase      :	int						=       DetaImageProcessor(format="coco_detection"			)

      # verify our conversion on image
      _UpperCamelCase      :	Optional[int]						=       prepare_img()
      _UpperCamelCase      :	Dict						=       processor(images=lowercase_		,return_tensors="pt"			)
      _UpperCamelCase      :	Optional[Any]						=       encoding["pixel_values"]
      _UpperCamelCase      :	Any						=       model(pixel_values.to(lowercase_			)			)

      # verify logits
      print("Logits:"		,outputs.logits[0, :3, :3]			)
      print("Boxes:"		,outputs.pred_boxes[0, :3, :3]			)
      if model_name == "deta-swin-large":
            _UpperCamelCase      :	Tuple						=       torch.tensor(
                [[-7.6308, -2.8485, -5.3737], [-7.2037, -4.5505, -4.8027], [-7.2943, -4.2611, -4.6617]]			)
            _UpperCamelCase      :	List[Any]						=       torch.tensor([[0.4987, 0.4969, 0.9999], [0.2549, 0.5498, 0.4805], [0.5498, 0.2757, 0.0569]]			)
      elif model_name == "deta-swin-large-o365":
            _UpperCamelCase      :	Dict						=       torch.tensor(
                [[-8.0122, -3.5720, -4.9717], [-8.1547, -3.6886, -4.6389], [-7.6610, -3.6194, -5.0134]]			)
            _UpperCamelCase      :	int						=       torch.tensor([[0.2523, 0.5549, 0.4881], [0.7715, 0.4149, 0.4601], [0.5503, 0.2753, 0.0575]]			)
      assert torch.allclose(outputs.logits[0, :3, :3]		,expected_logits.to(lowercase_			)		,atol=1e-4			)
      assert torch.allclose(outputs.pred_boxes[0, :3, :3]		,expected_boxes.to(lowercase_			)		,atol=1e-4			)
      print("Everything ok!"			)

      if pytorch_dump_folder_path:
            # Save model and processor
            logger.info(F'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...'''			)
            Path(lowercase_			).mkdir(exist_ok=lowercase_			)
            model.save_pretrained(lowercase_			)
            processor.save_pretrained(lowercase_			)

      # Push to hub
      if push_to_hub:
            print("Pushing model and processor to hub..."			)
            model.push_to_hub(F'''jozhang97/{model_name}'''			)
            processor.push_to_hub(F'''jozhang97/{model_name}'''			)


if __name__ == "__main__":
  lowerCamelCase__				  =   argparse.ArgumentParser()

  parser.add_argument(
      "--model_name",
      type=str,
      default="deta-swin-large",
      choices=["deta-swin-large", "deta-swin-large-o365"],
      help="Name of the model you'd like to convert.",
  )
  parser.add_argument(
      "--pytorch_dump_folder_path",
      default=None,
      type=str,
      help="Path to the folder to output PyTorch model.",
  )
  parser.add_argument(
      "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
  )
  lowerCamelCase__				  =   parser.parse_args()
  convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)







"""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
