
import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import numpy as np
import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForMaskedImageModeling,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
_UpperCAmelCase :			Union[str, Any]              =	logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt")

_UpperCAmelCase :			Dict              =	list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys())
_UpperCAmelCase :			List[Any]              =	tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)


@dataclass
class     lowercase :
		__lowercase	:	Optional[str]     					=    field(
		    default="cifar10"  ,       metadata={"help": "Name of a dataset from the datasets package"}       )
		__lowercase	:	Optional[str]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}       )
		__lowercase	:	Optional[str]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "The column name of the images in the files. If not set, will try to use 'image' or 'img'."}  ,       )
		__lowercase	:	Optional[str]     					=    field(default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "A folder containing the training data."}       )
		__lowercase	:	Optional[str]     					=    field(default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "A folder containing the validation data."}       )
		__lowercase	:	Optional[float]     					=    field(
		    default=0.1_5  ,       metadata={"help": "Percent to split off of train for validation."}       )
		__lowercase	:	int     					=    field(default=32  ,       metadata={"help": "The size of the square patches to use for masking."}       )
		__lowercase	:	float     					=    field(
		    default=0.6  ,       metadata={"help": "Percentage of patches to mask."}  ,       )
		__lowercase	:	Optional[int]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={
		        "help": (
		            "For debugging purposes or quicker training, truncate the number of training examples to this "
		            "value if set."
		        )
		    }  ,       )
		__lowercase	:	Optional[int]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={
		        "help": (
		            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
		            "value if set."
		        )
		    }  ,       )



		def __UpperCamelCase			(			self	)  -> Tuple:
				"""simple docstring"""
				UpperCamelCase          =					{}
				if self.train_dir is not None:
						UpperCamelCase          =					self.train_dir
				if self.validation_dir is not None:
						UpperCamelCase          =					self.validation_dir
				UpperCamelCase          =					data_files if data_files else None






@dataclass
class     lowercase :
		__lowercase	:	str     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={
		        "help": (
		            "The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a "
		            "checkpoint identifier on the hub. "
		            "Don't set if you want to train a model from scratch."
		        )
		    }  ,       )
		__lowercase	:	Optional[str]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(_SCREAMING_SNAKE_CASE       )}  ,       )
		__lowercase	:	Optional[str]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "Pretrained config name or path if not the same as model_name"}       )
		__lowercase	:	Optional[str]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={
		        "help": (
		            "Override some existing default config settings when a model is trained from scratch. Example: "
		            "n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"
		        )
		    }  ,       )
		__lowercase	:	Optional[str]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"}  ,       )
		__lowercase	:	str     					=    field(
		    default="main"  ,       metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}  ,       )
		__lowercase	:	str     					=    field(default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "Name or path of preprocessor config."}       )
		__lowercase	:	bool     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={
		        "help": (
		            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
		            "with private models)."
		        )
		    }  ,       )
		__lowercase	:	Optional[int]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={
		        "help": (
		            "The size (resolution) of each image. If not specified, will use `image_size` of the configuration."
		        )
		    }  ,       )
		__lowercase	:	Optional[int]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={
		        "help": (
		            "The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration."
		        )
		    }  ,       )
		__lowercase	:	Optional[int]     					=    field(
		    default=_SCREAMING_SNAKE_CASE  ,       metadata={"help": "Stride to use for the encoder."}  ,       )






class     lowercase :



		def __init__(			self    ,				A_=192    ,				A_=32    ,				A_=4    ,				A_=0.6	)  -> Optional[Any]:
				"""simple docstring"""
				UpperCamelCase          =					input_size
				UpperCamelCase          =					mask_patch_size
				UpperCamelCase          =					model_patch_size
				UpperCamelCase          =					mask_ratio

				if self.input_size % self.mask_patch_size != 0:
						raise ValueError('Input size must be divisible by mask patch size'	)
				if self.mask_patch_size % self.model_patch_size != 0:
						raise ValueError('Mask patch size must be divisible by model patch size'	)

				UpperCamelCase          =					self.input_size // self.mask_patch_size
				UpperCamelCase          =					self.mask_patch_size // self.model_patch_size

				UpperCamelCase          =					self.rand_size**2
				UpperCamelCase          =					int(np.ceil(self.token_count * self.mask_ratio	)	)



		def __call__(			self	)  -> str:
				"""simple docstring"""
				UpperCamelCase          =					np.random.permutation(self.token_count	)[: self.mask_count]
				UpperCamelCase          =					np.zeros(self.token_count    ,				dtype=A_	)
				UpperCamelCase          =					1

				UpperCamelCase          =					mask.reshape((self.rand_size, self.rand_size)	)
				UpperCamelCase          =					mask.repeat(self.scale    ,				axis=0	).repeat(self.scale    ,				axis=1	)

				return torch.tensor(mask.flatten()	)






def 				A	( lowercase			)       ->  Tuple:
		'''simple docstring'''

		UpperCamelCase          =					torch.stack([example['pixel_values'] for example in examples]			)
		UpperCamelCase          =					torch.stack([example['mask'] for example in examples]			)
		return {"pixel_values": pixel_values, "bool_masked_pos": mask}


def 				A	( )       ->  List[Any]:
		'''simple docstring'''

		UpperCamelCase          =					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)
		if len(sys.argv			) == 2 and sys.argv[1].endswith('.json'			):
				# If we pass only one argument to the script and it's the path to a json file,
				# let's parse it to get our arguments.
				UpperCamelCase     ,  UpperCamelCase     ,  UpperCamelCase          =					parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
		else:
				UpperCamelCase     ,  UpperCamelCase     ,  UpperCamelCase          =					parser.parse_args_into_dataclasses()

		# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
		# information sent is the one passed as arguments along with your Python/PyTorch versions.
		send_example_telemetry('run_mim'   ,	lowercase   ,	lowercase			)

		# Setup logging
		logging.basicConfig(
		    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'   ,	datefmt='%m/%d/%Y %H:%M:%S'   ,	handlers=[logging.StreamHandler(sys.stdout			)]   ,	)

		if training_args.should_log:
				# The default of training_args.log_level is passive, so we set log level at info here to have that default.
				transformers.utils.logging.set_verbosity_info()

		UpperCamelCase          =					training_args.get_process_log_level()
		logger.setLevel(lowercase			)
		transformers.utils.logging.set_verbosity(lowercase			)
		transformers.utils.logging.enable_default_handler()
		transformers.utils.logging.enable_explicit_format()

		# Log on each process the small summary:
		logger.warning(
		    f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
		    + f'''distributed training: {bool(training_args.local_rank != -1			)}, 16-bits training: {training_args.fpaa}'''			)
		logger.info(f'''Training/evaluation parameters {training_args}'''			)

		# Detecting last checkpoint.
		UpperCamelCase          =					None
		if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
				UpperCamelCase          =					get_last_checkpoint(training_args.output_dir			)
				if last_checkpoint is None and len(os.listdir(training_args.output_dir			)			) > 0:
						raise ValueError(
						    f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
						    'Use --overwrite_output_dir to overcome.'			)
				elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
						logger.info(
						    f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
						    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'			)

    # Initialize our dataset.
		UpperCamelCase          =					load_dataset(
		    data_args.dataset_name   ,	data_args.dataset_config_name   ,	data_files=data_args.data_files   ,	cache_dir=model_args.cache_dir   ,	use_auth_token=True if model_args.use_auth_token else None   ,	)

		# If we don't have a validation split, split off a percentage of train as validation.
		UpperCamelCase          =					None if 'validation' in ds.keys() else data_args.train_val_split
		if isinstance(data_args.train_val_split   ,	lowercase			) and data_args.train_val_split > 0.0:
				UpperCamelCase          =					ds['train'].train_test_split(data_args.train_val_split			)
				UpperCamelCase          =					split['train']
				UpperCamelCase          =					split['test']

		# Create config
		# Distributed training:
		# The .from_pretrained methods guarantee that only one local process can concurrently
		# download model & vocab.
		UpperCamelCase          =					{
		    'cache_dir': model_args.cache_dir,
		    'revision': model_args.model_revision,
		    'use_auth_token': True if model_args.use_auth_token else None,
		}
		if model_args.config_name_or_path:
				UpperCamelCase          =					AutoConfig.from_pretrained(model_args.config_name_or_path   ,	**lowercase			)
		elif model_args.model_name_or_path:
				UpperCamelCase          =					AutoConfig.from_pretrained(model_args.model_name_or_path   ,	**lowercase			)
		else:
				UpperCamelCase          =					CONFIG_MAPPING[model_args.model_type]()
				logger.warning('You are instantiating a new config instance from scratch.'			)
				if model_args.config_overrides is not None:
						logger.info(f'''Overriding config: {model_args.config_overrides}'''			)
						config.update_from_string(model_args.config_overrides			)
						logger.info(f'''New config: {config}'''			)

    # make sure the decoder_type is "simmim" (only relevant for BEiT)
		if hasattr(lowercase   ,	'decoder_type'			):
				UpperCamelCase          =					'simmim'

		# adapt config
		UpperCamelCase          =					model_args.image_size if model_args.image_size is not None else config.image_size
		UpperCamelCase          =					model_args.patch_size if model_args.patch_size is not None else config.patch_size
		UpperCamelCase          =					(
		    model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride
		)

		config.update(
		    {
		        'image_size': model_args.image_size,
		        'patch_size': model_args.patch_size,
		        'encoder_stride': model_args.encoder_stride,
		    }			)

		# create image processor
		if model_args.image_processor_name:
				UpperCamelCase          =					AutoImageProcessor.from_pretrained(model_args.image_processor_name   ,	**lowercase			)
		elif model_args.model_name_or_path:
				UpperCamelCase          =					AutoImageProcessor.from_pretrained(model_args.model_name_or_path   ,	**lowercase			)
		else:
				UpperCamelCase          =					{
				    conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items()
				}
				UpperCamelCase          =					IMAGE_PROCESSOR_TYPES[model_args.model_type]()

		# create model
		if model_args.model_name_or_path:
				UpperCamelCase          =					AutoModelForMaskedImageModeling.from_pretrained(
				    model_args.model_name_or_path   ,	from_tf=bool('.ckpt' in model_args.model_name_or_path			)   ,	config=lowercase   ,	cache_dir=model_args.cache_dir   ,	revision=model_args.model_revision   ,	use_auth_token=True if model_args.use_auth_token else None   ,	)
		else:
				logger.info('Training new model from scratch'			)
				UpperCamelCase          =					AutoModelForMaskedImageModeling.from_config(lowercase			)

		if training_args.do_train:
				UpperCamelCase          =					ds['train'].column_names
		else:
				UpperCamelCase          =					ds['validation'].column_names

		if data_args.image_column_name is not None:
				UpperCamelCase          =					data_args.image_column_name
		elif "image" in column_names:
				UpperCamelCase          =					'image'
		elif "img" in column_names:
				UpperCamelCase          =					'img'
		else:
				UpperCamelCase          =					column_names[0]

		# transformations as done in original SimMIM paper
		# source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py
		UpperCamelCase          =					Compose(
		    [
		        Lambda(lambda lowercase			: img.convert('RGB'			) if img.mode != "RGB" else img			),
		        RandomResizedCrop(model_args.image_size   ,	scale=(0.6_7, 1.0)   ,	ratio=(3.0 / 4.0, 4.0 / 3.0)			),
		        RandomHorizontalFlip(),
		        ToTensor(),
		        Normalize(mean=image_processor.image_mean   ,	std=image_processor.image_std			),
		    ]			)

		# create mask generator
		UpperCamelCase          =					MaskGenerator(
		    input_size=model_args.image_size   ,	mask_patch_size=data_args.mask_patch_size   ,	model_patch_size=model_args.patch_size   ,	mask_ratio=data_args.mask_ratio   ,	)

		def preprocess_images(lowercase			):
				UpperCamelCase          =					[transforms(lowercase			) for image in examples[image_column_name]]
				UpperCamelCase          =					[mask_generator() for i in range(len(examples[image_column_name]			)			)]

				return examples

		if training_args.do_train:
				if "train" not in ds:
						raise ValueError('--do_train requires a train dataset'			)
				if data_args.max_train_samples is not None:
						UpperCamelCase          =					ds['train'].shuffle(seed=training_args.seed			).select(range(data_args.max_train_samples			)			)
				# Set the training transforms
				ds["train"].set_transform(lowercase			)

		if training_args.do_eval:
				if "validation" not in ds:
						raise ValueError('--do_eval requires a validation dataset'			)
				if data_args.max_eval_samples is not None:
						UpperCamelCase          =					(
						    ds['validation'].shuffle(seed=training_args.seed			).select(range(data_args.max_eval_samples			)			)
						)
				# Set the validation transforms
				ds["validation"].set_transform(lowercase			)

		# Initialize our trainer
		UpperCamelCase          =					Trainer(
		    model=lowercase   ,	args=lowercase   ,	train_dataset=ds['train'] if training_args.do_train else None   ,	eval_dataset=ds['validation'] if training_args.do_eval else None   ,	tokenizer=lowercase   ,	data_collator=lowercase   ,	)

		# Training
		if training_args.do_train:
				UpperCamelCase          =					None
				if training_args.resume_from_checkpoint is not None:
						UpperCamelCase          =					training_args.resume_from_checkpoint
				elif last_checkpoint is not None:
						UpperCamelCase          =					last_checkpoint
				UpperCamelCase          =					trainer.train(resume_from_checkpoint=lowercase			)
				trainer.save_model()
				trainer.log_metrics('train'   ,	train_result.metrics			)
				trainer.save_metrics('train'   ,	train_result.metrics			)
				trainer.save_state()

		# Evaluation
		if training_args.do_eval:
				UpperCamelCase          =					trainer.evaluate()
				trainer.log_metrics('eval'   ,	lowercase			)
				trainer.save_metrics('eval'   ,	lowercase			)

		# Write model card and (optionally) push to hub
		UpperCamelCase          =					{
		    'finetuned_from': model_args.model_name_or_path,
		    'tasks': 'masked-image-modeling',
		    'dataset': data_args.dataset_name,
		    'tags': ['masked-image-modeling'],
		}
		if training_args.push_to_hub:
				trainer.push_to_hub(**lowercase			)
		else:
				trainer.create_model_card(**lowercase			)


if __name__ == "__main__":
					main()


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     lowercase (		_SCREAMING_SNAKE_CASE       ):
		__lowercase	:	torch.FloatTensor






class     lowercase (		nn.Module       ):



		def __init__(			self    ,				A_=3    ,				A_=3    ,				A_=("DownEncoderBlock2D",)    ,				A_=(64,)    ,				A_=2    ,				A_=32    ,				A_="silu"    ,				A_=True    ,				)  -> List[Any]:
				"""simple docstring"""
				super().__init__()
				UpperCamelCase          =					layers_per_block

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

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

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

						UpperCamelCase          =					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          =					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          =					nn.GroupNorm(num_channels=block_out_channels[-1]    ,				num_groups=A_    ,				eps=1e-6	)
				UpperCamelCase          =					nn.SiLU()

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

				UpperCamelCase          =					False



		def __UpperCamelCase			(			self    ,				A_	)  -> Optional[Any]:
				"""simple docstring"""
				UpperCamelCase          =					x
				UpperCamelCase          =					self.conv_in(A_	)

				if self.training and self.gradient_checkpointing:

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

								return custom_forward

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

				else:
						# down
						for down_block in self.down_blocks:
								UpperCamelCase          =					down_block(A_	)

						# middle
						UpperCamelCase          =					self.mid_block(A_	)

				# post-process
				UpperCamelCase          =					self.conv_norm_out(A_	)
				UpperCamelCase          =					self.conv_act(A_	)
				UpperCamelCase          =					self.conv_out(A_	)

				return sample






class     lowercase (		nn.Module       ):



		def __init__(			self    ,				A_=3    ,				A_=3    ,				A_=("UpDecoderBlock2D",)    ,				A_=(64,)    ,				A_=2    ,				A_=32    ,				A_="silu"    ,				A_="group"    ,				)  -> Tuple:
				"""simple docstring"""
				super().__init__()
				UpperCamelCase          =					layers_per_block

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

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

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

				# mid
				UpperCamelCase          =					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(reversed(A_	)	)
				UpperCamelCase          =					reversed_block_out_channels[0]
				for i, up_block_type in enumerate(A_	):
						UpperCamelCase          =					output_channel
						UpperCamelCase          =					reversed_block_out_channels[i]

						UpperCamelCase          =					i == len(A_	) - 1

						UpperCamelCase          =					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          =					output_channel

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

				UpperCamelCase          =					False



		def __UpperCamelCase			(			self    ,				A_    ,				A_=None	)  -> Dict:
				"""simple docstring"""
				UpperCamelCase          =					z
				UpperCamelCase          =					self.conv_in(A_	)

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

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

								return custom_forward

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

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

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

						# up
						for up_block in self.up_blocks:
								UpperCamelCase          =					up_block(A_    ,				A_	)

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

				return sample






class     lowercase (		nn.Module       ):



		def __init__(			self    ,				A_    ,				A_    ,				A_    ,				A_=None    ,				A_="random"    ,				A_=False    ,				A_=True	)  -> Tuple:
				"""simple docstring"""
				super().__init__()
				UpperCamelCase          =					n_e
				UpperCamelCase          =					vq_embed_dim
				UpperCamelCase          =					beta
				UpperCamelCase          =					legacy

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

				UpperCamelCase          =					sane_index_shape



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



		def __UpperCamelCase			(			self    ,				A_	)  -> List[str]:
				"""simple docstring"""
				UpperCamelCase          =					inds.shape
				assert len(A_	) > 1
				UpperCamelCase          =					inds.reshape(ishape[0]    ,				-1	)
				UpperCamelCase          =					self.used.to(A_	)
				if self.re_embed > self.used.shape[0]:  # extra token
						UpperCamelCase          =					0  # simply set to zero
				UpperCamelCase          =					torch.gather(used[None, :][inds.shape[0] * [0], :]    ,				1    ,				A_	)
				return back.reshape(A_	)



		def __UpperCamelCase			(			self    ,				A_	)  -> List[str]:
				"""simple docstring"""
				# reshape z -> (batch, height, width, channel) and flatten
				UpperCamelCase          =					z.permute(0    ,				2    ,				3    ,				1	).contiguous()
				UpperCamelCase          =					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          =					torch.argmin(torch.cdist(A_    ,				self.embedding.weight	)    ,				dim=1	)

				UpperCamelCase          =					self.embedding(A_	).view(z.shape	)
				UpperCamelCase          =					None
				UpperCamelCase          =					None

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

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

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

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

				if self.sane_index_shape:
						UpperCamelCase          =					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    ,				A_    ,				A_	)  -> Optional[int]:
				"""simple docstring"""
				# shape specifying (batch, height, width, channel)
				if self.remap is not None:
						UpperCamelCase          =					indices.reshape(shape[0]    ,				-1	)  # add batch axis
						UpperCamelCase          =					self.unmap_to_all(A_	)
						UpperCamelCase          =					indices.reshape(-1	)  # flatten again

				# get quantized latent vectors
				UpperCamelCase          =					self.embedding(A_	)

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

				return z_q






class     lowercase (		_SCREAMING_SNAKE_CASE       ):



		def __init__(			self    ,				A_    ,				A_=False	)  -> Any:
				"""simple docstring"""
				UpperCamelCase          =					parameters
				UpperCamelCase     ,  UpperCamelCase          =					torch.chunk(A_    ,				2    ,				dim=1	)
				UpperCamelCase          =					torch.clamp(self.logvar    ,				-30.0    ,				20.0	)
				UpperCamelCase          =					deterministic
				UpperCamelCase          =					torch.exp(0.5 * self.logvar	)
				UpperCamelCase          =					torch.exp(self.logvar	)
				if self.deterministic:
						UpperCamelCase          =					UpperCamelCase          =					torch.zeros_like(
						    self.mean    ,				device=self.parameters.device    ,				dtype=self.parameters.dtype	)



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



		def __UpperCamelCase			(			self    ,				A_=None	)  -> Tuple:
				"""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    ,				A_    ,				A_=[1, 2, 3]	)  -> Optional[Any]:
				"""simple docstring"""
				if self.deterministic:
						return torch.Tensor([0.0]	)
				UpperCamelCase          =					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 __UpperCamelCase			(			self	)  -> Union[str, Any]:
				"""simple docstring"""
				return self.mean
