



'''simple docstring'''
import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


_UpperCamelCase							 =	get_logger(__name__)



class _A     :





		def __init__(   self       ,				__UpperCAmelCase = None )				->   int:

					'''simple docstring'''
					__UpperCAmelCase      :					Any   =   (
					    os.path.join(__UpperCAmelCase       ,				config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH
					)
					__UpperCAmelCase      :					Optional[int]   =   Extractor





		def 							__A				(   self       ,				__UpperCAmelCase )				->   str:

					'''simple docstring'''
					from .file_utils import hash_url_to_filename

					# Path where we extract compressed archives
					# We extract in the cache dir, and get the extracted path name by hashing the original path"
					__UpperCAmelCase      :					Dict   =   os.path.abspath(__UpperCAmelCase )
					return os.path.join(self.extract_dir       ,				hash_url_to_filename(__UpperCAmelCase ) )





		def 							__A				(   self       ,				__UpperCAmelCase       ,				__UpperCAmelCase )				->   bool:

					'''simple docstring'''
					return force_extract or (
					    not os.path.isfile(__UpperCAmelCase ) and not (os.path.isdir(__UpperCAmelCase ) and os.listdir(__UpperCAmelCase ))
					)





		def 							__A				(   self       ,				__UpperCAmelCase       ,				__UpperCAmelCase = False )				->   str:

					'''simple docstring'''
					__UpperCAmelCase      :					str   =   self.extractor.infer_extractor_format(__UpperCAmelCase )
					if not extractor_format:
								return input_path
					__UpperCAmelCase      :					Dict   =   self._get_output_path(__UpperCAmelCase )
					if self._do_extract(__UpperCAmelCase       ,				__UpperCAmelCase ):
								self.extractor.extract(__UpperCAmelCase       ,				__UpperCAmelCase       ,				__UpperCAmelCase )
					return output_path



class _A     (			__A			):





		@classmethod
		@abstractmethod
		def 							__A				(   cls       ,				__UpperCAmelCase       ,				**__UpperCAmelCase )				->   bool:

					'''simple docstring'''
					...





		@staticmethod
		@abstractmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					...



class _A     (			__A		, __A			):
		_SCREAMING_SNAKE_CASE    :			List[bytes]  					=	[]





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   Optional[int]:

					'''simple docstring'''
					with open(__UpperCAmelCase       ,				"""rb""" ) as f:
								return f.read(__UpperCAmelCase )





		@classmethod
		def 							__A				(   cls       ,				__UpperCAmelCase       ,				__UpperCAmelCase = b"" )				->   bool:

					'''simple docstring'''
					if not magic_number:
								__UpperCAmelCase      :					str   =   max(len(__UpperCAmelCase ) for cls_magic_number in cls.magic_numbers )
								try:
											__UpperCAmelCase      :					int   =   cls.read_magic_number(__UpperCAmelCase       ,				__UpperCAmelCase )
								except OSError:
											return False
					return any(magic_number.startswith(__UpperCAmelCase ) for cls_magic_number in cls.magic_numbers )



class _A     (			__A			):





		@classmethod
		def 							__A				(   cls       ,				__UpperCAmelCase       ,				**__UpperCAmelCase )				->   bool:

					'''simple docstring'''
					return tarfile.is_tarfile(__UpperCAmelCase )





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   List[Any]:

					'''simple docstring'''

					def resolved(__UpperCAmelCase ) -> str:
								return os.path.realpath(os.path.abspath(__UpperCAmelCase ) )

					def badpath(__UpperCAmelCase       ,				__UpperCAmelCase ) -> bool:
								# joinpath will ignore base if path is absolute
								return not resolved(os.path.join(__UpperCAmelCase       ,				__UpperCAmelCase ) ).startswith(__UpperCAmelCase )

					def badlink(__UpperCAmelCase       ,				__UpperCAmelCase ) -> bool:
								# Links are interpreted relative to the directory containing the link
								__UpperCAmelCase      :					str   =   resolved(os.path.join(__UpperCAmelCase       ,				os.path.dirname(info.name ) ) )
								return badpath(info.linkname       ,				base=__UpperCAmelCase )

					__UpperCAmelCase      :					str   =   resolved(__UpperCAmelCase )

					for finfo in members:
								if badpath(finfo.name       ,				__UpperCAmelCase ):
											logger.error(f'Extraction of {finfo.name} is blocked (illegal path)' )
								elif finfo.issym() and badlink(__UpperCAmelCase       ,				__UpperCAmelCase ):
											logger.error(f'Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}' )
								elif finfo.islnk() and badlink(__UpperCAmelCase       ,				__UpperCAmelCase ):
											logger.error(f'Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}' )
								else:
											yield finfo





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					os.makedirs(__UpperCAmelCase       ,				exist_ok=__UpperCAmelCase )
					__UpperCAmelCase      :					int   =   tarfile.open(__UpperCAmelCase )
					tar_file.extractall(__UpperCAmelCase       ,				members=TarExtractor.safemembers(__UpperCAmelCase       ,				__UpperCAmelCase ) )
					tar_file.close()



class _A     (			__A			):
		_SCREAMING_SNAKE_CASE    :			List[str]  					=	[B'\x1F\x8B']





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					with gzip.open(__UpperCAmelCase       ,				"""rb""" ) as gzip_file:
								with open(__UpperCAmelCase       ,				"""wb""" ) as extracted_file:
											shutil.copyfileobj(__UpperCAmelCase       ,				__UpperCAmelCase )



class _A     (			__A			):
		_SCREAMING_SNAKE_CASE    :			Union[str, Any]  					=	[
		    B'PK\x03\x04',
		    B'PK\x05\x06',  # empty archive
		    B'PK\x07\x08',  # spanned archive
		]





		@classmethod
		def 							__A				(   cls       ,				__UpperCAmelCase       ,				__UpperCAmelCase = b"" )				->   bool:

					'''simple docstring'''
					if super().is_extractable(__UpperCAmelCase       ,				magic_number=__UpperCAmelCase ):
								return True
					try:
								# Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
								# From: https://github.com/python/cpython/pull/5053
								from zipfile import (
								    _CD_SIGNATURE,
								    _ECD_DISK_NUMBER,
								    _ECD_DISK_START,
								    _ECD_ENTRIES_TOTAL,
								    _ECD_OFFSET,
								    _ECD_SIZE,
								    _EndRecData,
								    sizeCentralDir,
								    stringCentralDir,
								    structCentralDir,
								)

								with open(__UpperCAmelCase       ,				"""rb""" ) as fp:
											__UpperCAmelCase      :					Union[str, Any]   =   _EndRecData(__UpperCAmelCase )
											if endrec:
														if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
																	return True  # Empty zipfiles are still zipfiles
														elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
																	fp.seek(endrec[_ECD_OFFSET] )  # Central directory is on the same disk
																	if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
																				__UpperCAmelCase      :					Optional[Any]   =   fp.read(__UpperCAmelCase )  # CD is where we expect it to be
																				if len(__UpperCAmelCase ) == sizeCentralDir:
																							__UpperCAmelCase      :					str   =   struct.unpack(__UpperCAmelCase       ,				__UpperCAmelCase )  # CD is the right size
																							if centdir[_CD_SIGNATURE] == stringCentralDir:
																										return True  # First central directory entry  has correct magic number
								return False
					except Exception:  # catch all errors in case future python versions change the zipfile internals
								return False





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					os.makedirs(__UpperCAmelCase       ,				exist_ok=__UpperCAmelCase )
					with zipfile.ZipFile(__UpperCAmelCase       ,				"""r""" ) as zip_file:
								zip_file.extractall(__UpperCAmelCase )
								zip_file.close()



class _A     (			__A			):
		_SCREAMING_SNAKE_CASE    :			Any  					=	[B'\xFD\x37\x7A\x58\x5A\x00']





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					with lzma.open(__UpperCAmelCase ) as compressed_file:
								with open(__UpperCAmelCase       ,				"""wb""" ) as extracted_file:
											shutil.copyfileobj(__UpperCAmelCase       ,				__UpperCAmelCase )



class _A     (			__A			):
		_SCREAMING_SNAKE_CASE    :			Optional[int]  					=	[B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					if not config.RARFILE_AVAILABLE:
								raise ImportError("""Please pip install rarfile""" )
					import rarfile

					os.makedirs(__UpperCAmelCase       ,				exist_ok=__UpperCAmelCase )
					__UpperCAmelCase      :					List[Any]   =   rarfile.RarFile(__UpperCAmelCase )
					rf.extractall(__UpperCAmelCase )
					rf.close()



class _A     (			__A			):
		_SCREAMING_SNAKE_CASE    :			Dict  					=	[B'\x28\xb5\x2F\xFD']





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					if not config.ZSTANDARD_AVAILABLE:
								raise ImportError("""Please pip install zstandard""" )
					import zstandard as zstd

					__UpperCAmelCase      :					List[Any]   =   zstd.ZstdDecompressor()
					with open(__UpperCAmelCase       ,				"""rb""" ) as ifh, open(__UpperCAmelCase       ,				"""wb""" ) as ofh:
								dctx.copy_stream(__UpperCAmelCase       ,				__UpperCAmelCase )



class _A     (			__A			):
		_SCREAMING_SNAKE_CASE    :			Optional[Any]  					=	[B'\x42\x5A\x68']





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					with bza.open(__UpperCAmelCase       ,				"""rb""" ) as compressed_file:
								with open(__UpperCAmelCase       ,				"""wb""" ) as extracted_file:
											shutil.copyfileobj(__UpperCAmelCase       ,				__UpperCAmelCase )



class _A     (			__A			):
		_SCREAMING_SNAKE_CASE    :			str  					=	[B'\x37\x7A\xBC\xAF\x27\x1C']





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					if not config.PY7ZR_AVAILABLE:
								raise ImportError("""Please pip install py7zr""" )
					import pyazr

					os.makedirs(__UpperCAmelCase       ,				exist_ok=__UpperCAmelCase )
					with pyazr.SevenZipFile(__UpperCAmelCase       ,				"""r""" ) as archive:
								archive.extractall(__UpperCAmelCase )



class _A     (			__A			):
		_SCREAMING_SNAKE_CASE    :			int  					=	[B'\x04\x22\x4D\x18']





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   None:

					'''simple docstring'''
					if not config.LZ4_AVAILABLE:
								raise ImportError("""Please pip install lz4""" )
					import lza.frame

					with lza.frame.open(__UpperCAmelCase       ,				"""rb""" ) as compressed_file:
								with open(__UpperCAmelCase       ,				"""wb""" ) as extracted_file:
											shutil.copyfileobj(__UpperCAmelCase       ,				__UpperCAmelCase )



class _A     :
		#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
		_SCREAMING_SNAKE_CASE    :			Dict[str, Type[BaseExtractor]]  					=	{
		    "tar": TarExtractor,
		    "gzip": GzipExtractor,
		    "zip": ZipExtractor,
		    "xz": XzExtractor,
		    "rar": RarExtractor,
		    "zstd": ZstdExtractor,
		    "bz2": BzipaExtractor,
		    "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
		    "lz4": LzaExtractor,  # <Added version="2.4.0"/>
		}





		@classmethod
		def 							__A				(   cls )				->   List[str]:

					'''simple docstring'''
					return max(
					    len(__UpperCAmelCase )
					    for extractor in cls.extractors.values()
					    if issubclass(__UpperCAmelCase       ,				__UpperCAmelCase )
					    for extractor_magic_number in extractor.magic_numbers )





		@staticmethod
		def 							__A				(   __UpperCAmelCase       ,				__UpperCAmelCase )				->   List[str]:

					'''simple docstring'''
					try:
								return MagicNumberBaseExtractor.read_magic_number(__UpperCAmelCase       ,				magic_number_length=__UpperCAmelCase )
					except OSError:
								return b""





		@classmethod
		def 							__A				(   cls       ,				__UpperCAmelCase       ,				__UpperCAmelCase = False )				->   bool:

					'''simple docstring'''
					warnings.warn(
					    """Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
					    """Use \'infer_extractor_format\' instead."""       ,				category=__UpperCAmelCase       ,				)
					__UpperCAmelCase      :					Tuple   =   cls.infer_extractor_format(__UpperCAmelCase )
					if extractor_format:
								return True if not return_extractor else (True, cls.extractors[extractor_format])
					return False if not return_extractor else (False, None)





		@classmethod
		def 							__A				(   cls       ,				__UpperCAmelCase )				->   str:  # <Added version="2.4.0"/>

					'''simple docstring'''
					__UpperCAmelCase      :					Union[str, Any]   =   cls._get_magic_number_max_length()
					__UpperCAmelCase      :					Dict   =   cls._read_magic_number(__UpperCAmelCase       ,				__UpperCAmelCase )
					for extractor_format, extractor in cls.extractors.items():
								if extractor.is_extractable(__UpperCAmelCase       ,				magic_number=__UpperCAmelCase ):
											return extractor_format





		@classmethod
		def 							__A				(   cls       ,				__UpperCAmelCase       ,				__UpperCAmelCase       ,				__UpperCAmelCase = None       ,				__UpperCAmelCase = "deprecated"       ,				)				->   None:

					'''simple docstring'''
					os.makedirs(os.path.dirname(__UpperCAmelCase )       ,				exist_ok=__UpperCAmelCase )
					# Prevent parallel extractions
					__UpperCAmelCase      :					Dict   =   str(Path(__UpperCAmelCase ).with_suffix(""".lock""" ) )
					with FileLock(__UpperCAmelCase ):
								shutil.rmtree(__UpperCAmelCase       ,				ignore_errors=__UpperCAmelCase )
								if extractor_format or extractor != "deprecated":
											if extractor != "deprecated" or not isinstance(__UpperCAmelCase       ,				__UpperCAmelCase ):  # passed as positional arg
														warnings.warn(
														    """Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
														    """Use \'extractor_format\' instead."""       ,				category=__UpperCAmelCase       ,				)
														__UpperCAmelCase      :					Any   =   extractor if extractor != """deprecated""" else extractor_format
											else:
														__UpperCAmelCase      :					Tuple   =   cls.extractors[extractor_format]
											return extractor.extract(__UpperCAmelCase       ,				__UpperCAmelCase )
								else:
											warnings.warn(
											    """Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an """
											    """exception in 3.0.0."""       ,				category=__UpperCAmelCase       ,				)
											for extractor in cls.extractors.values():
														if extractor.is_extractable(__UpperCAmelCase ):
																	return extractor.extract(__UpperCAmelCase       ,				__UpperCAmelCase )





"""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 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  torch.FloatTensor






class 			UpperCamelCase__(	nn.Module       ):





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

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

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

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

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

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

													A__		   =							False





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Optional[int]:
													A__		   =							x
													A__		   =							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:
																																		A__		   =							torch.utils.checkpoint.checkpoint(
																																		    create_custom_forward(__UpperCAmelCase   )						,__UpperCAmelCase						,use_reentrant=__UpperCAmelCase   )
																											# middle
																											A__		   =							torch.utils.checkpoint.checkpoint(
																											    create_custom_forward(self.mid_block   )						,__UpperCAmelCase						,use_reentrant=__UpperCAmelCase   )
																				else:
																											for down_block in self.down_blocks:
																																		A__		   =							torch.utils.checkpoint.checkpoint(create_custom_forward(__UpperCAmelCase   )						,__UpperCAmelCase   )
																											# middle
																											A__		   =							torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block   )						,__UpperCAmelCase   )

													else:
																				# down
																				for down_block in self.down_blocks:
																											A__		   =							down_block(__UpperCAmelCase   )

																				# middle
																				A__		   =							self.mid_block(__UpperCAmelCase   )

													# post-process
													A__		   =							self.conv_norm_out(__UpperCAmelCase   )
													A__		   =							self.conv_act(__UpperCAmelCase   )
													A__		   =							self.conv_out(__UpperCAmelCase   )

													return sample






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase=3						,__UpperCAmelCase=3						,__UpperCAmelCase=("UpDecoderBlock2D",)						,__UpperCAmelCase=(64,)						,__UpperCAmelCase=2						,__UpperCAmelCase=32						,__UpperCAmelCase="silu"						,__UpperCAmelCase="group"						,)    -> Any:
													super().__init__()
													A__		   =							layers_per_block

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

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

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

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

																				A__		   =							i == len(__UpperCAmelCase   ) - 1

																				A__		   =							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   )
																				A__		   =							output_channel

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

													A__		   =							False





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=None   )    -> Dict:
													A__		   =							z
													A__		   =							self.conv_in(__UpperCAmelCase   )

													A__		   =							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
																											A__		   =							torch.utils.checkpoint.checkpoint(
																											    create_custom_forward(self.mid_block   )						,__UpperCAmelCase						,__UpperCAmelCase						,use_reentrant=__UpperCAmelCase   )
																											A__		   =							sample.to(__UpperCAmelCase   )

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

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

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

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

													return sample






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase=None						,__UpperCAmelCase="random"						,__UpperCAmelCase=False						,__UpperCAmelCase=True   )    -> Tuple:
													super().__init__()
													A__		   =							n_e
													A__		   =							vq_embed_dim
													A__		   =							beta
													A__		   =							legacy

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

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

													A__		   =							sane_index_shape





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





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





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Dict:
													# reshape z -> (batch, height, width, channel) and flatten
													A__		   =							z.permute(0						,2						,3						,1   ).contiguous()
													A__		   =							z.view(-1						,self.vq_embed_dim   )

													# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
													A__		   =							torch.argmin(torch.cdist(__UpperCAmelCase						,self.embedding.weight   )						,dim=1   )

													A__		   =							self.embedding(__UpperCAmelCase   ).view(z.shape   )
													A__		   =							None
													A__		   =							None

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

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

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

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

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

													# get quantized latent vectors
													A__		   =							self.embedding(__UpperCAmelCase   )

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

													return z_q






class 			UpperCamelCase__(	__A       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase=False   )    -> Any:
													A__		   =							parameters
													A__   ,     A__		   =							torch.chunk(__UpperCAmelCase						,2						,dim=1   )
													A__		   =							torch.clamp(self.logvar						,-3_0.0						,2_0.0   )
													A__		   =							deterministic
													A__		   =							torch.exp(0.5 * self.logvar   )
													A__		   =							torch.exp(self.logvar   )
													if self.deterministic:
																				A__		   =							A__		   =							torch.zeros_like(
																				    self.mean						,device=self.parameters.device						,dtype=self.parameters.dtype   )





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





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





