


'''simple docstring'''



import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
		import torch

		__A				=True
except ImportError:
		__A				=False


try:
		from torch.hub import _get_torch_home

		__A				=_get_torch_home()
except ImportError:
		__A				=os.path.expanduser(
		    os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
		)

__A				=os.path.join(torch_cache_home, 'transformers')

__A				='https://cdn.huggingface.co'
__A				='https://s3.amazonaws.com/models.huggingface.co/bert'
__A				='/'.join(str(Path(__file__).resolve()).split('/')[:-1])
__A				=os.path.join(PATH, 'config.yaml')
__A				=os.path.join(PATH, 'attributes.txt')
__A				=os.path.join(PATH, 'objects.txt')
__A				=os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
__A				=os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
__A				=os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
__A				='pytorch_model.bin'
__A				='config.yaml'







def       _UpperCamelCase (						UpperCamelCase__=OBJECTS	, UpperCamelCase__=ATTRIBUTES   ):
			UpperCAmelCase__					:   Optional[int]       				=       []
			with open(snake_case_   ) as f:
						for object in f.readlines():
									vg_classes.append(object.split(""","""   )[0].lower().strip()   )

			UpperCAmelCase__					:   Tuple       				=       []
			with open(snake_case_   ) as f:
						for object in f.readlines():
									vg_attrs.append(object.split(""","""   )[0].lower().strip()   )
			return vg_classes, vg_attrs







def       _UpperCamelCase (						UpperCamelCase__   ):
			UpperCAmelCase__					:   Optional[int]       				=       OrderedDict()
			with open(snake_case_	, """rb"""   ) as f:
						UpperCAmelCase__					:   Union[str, Any]       				=       pkl.load(snake_case_   )["""model"""]
			for k in copy.deepcopy(list(ckp.keys()   )   ):
						UpperCAmelCase__					:   List[str]       				=       ckp.pop(snake_case_   )
						if isinstance(snake_case_	, np.ndarray   ):
									UpperCAmelCase__					:   Optional[Any]       				=       torch.tensor(snake_case_   )
						else:
									assert isinstance(snake_case_	, torch.tensor   ), type(snake_case_   )
						UpperCAmelCase__					:   Optional[int]       				=       v
			return r


class 						_snake_case   :
					lowerCAmelCase :Optional[Any]						=   {}




					def __init__( self							,							_lowerCamelCase							,							_lowerCamelCase = "root"							,							_lowerCamelCase=0):
								UpperCAmelCase__					:   str       				=       name
								UpperCAmelCase__					:   Any       				=       level
								UpperCAmelCase__					:   Union[str, Any]       				=       {}
								for k, v in dictionary.items():
											if v is None:
														raise ValueError()
											UpperCAmelCase__					:   Dict       				=       copy.deepcopy(__a)
											UpperCAmelCase__					:   Optional[int]       				=       copy.deepcopy(__a)
											if isinstance(__a							,							__a):
														UpperCAmelCase__					:   str       				=       Config(__a							,							name=__a							,							level=level + 1)
											UpperCAmelCase__					:   Optional[Any]       				=       v
											setattr(self							,							__a							,							__a)

								UpperCAmelCase__					:   List[Any]       				=       d




					def __repr__( self):
								return str(list((self._pointer.keys())))




					def __setattr__( self							,							_lowerCamelCase							,							_lowerCamelCase):
								UpperCAmelCase__					:   List[str]       				=       val
								UpperCAmelCase__					:   Any       				=       val
								UpperCAmelCase__					:   str       				=       key.split(""".""")
								UpperCAmelCase__					:   Optional[int]       				=       len(__a) - 1
								UpperCAmelCase__					:   Optional[int]       				=       self._pointer
								if len(__a) > 1:
											for i, l in enumerate(__a):
														if hasattr(self							,							__a) and isinstance(getattr(self							,							__a)							,							__a):
																	setattr(getattr(self							,							__a)							,							""".""".join(levels[i:])							,							__a)
														if l == last_level:
																	UpperCAmelCase__					:   Any       				=       val
														else:
																	UpperCAmelCase__					:   Any       				=       pointer[l]




					def 			snake_case__  ( self):
								return self._pointer




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase):
								with open(f'''{file_name}'''							,							"""w""") as stream:
											dump(__a							,							__a)




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase):
								with open(f'''{file_name}'''							,							"""w""") as stream:
											json.dump(__a							,							__a)




					@staticmethod
					def 			snake_case__  ( _lowerCamelCase):
								with open(__a) as stream:
											UpperCAmelCase__					:   str       				=       load(__a							,							Loader=__a)
								return data




					def __str__( self):
								UpperCAmelCase__					:   str       				=       """    """
								if self._name != "root":
											UpperCAmelCase__					:   Optional[int]       				=       f'''{t * (self._level-1)}{self._name}:\n'''
								else:
											UpperCAmelCase__					:   Dict       				=       """"""
								UpperCAmelCase__					:   Optional[int]       				=       self._level
								for i, (k, v) in enumerate(self._pointer.items()):
											if isinstance(__a							,							__a):
														r += f'''{t * (self._level)}{v}\n'''
														self._level += 1
											else:
														r += f'''{t * (self._level)}{k}: {v} ({type(__a).__name__})\n'''
											UpperCAmelCase__					:   List[str]       				=       level
								return r[:-1]




					@classmethod
					def 			snake_case__  ( cls							,							_lowerCamelCase							,							**_lowerCamelCase):
								UpperCAmelCase__				,    UpperCAmelCase__					:   Any       				=       cls.get_config_dict(__a							,							**__a)
								return cls(__a)




					@classmethod
					def 			snake_case__  ( cls							,							_lowerCamelCase							,							**_lowerCamelCase):
								UpperCAmelCase__					:   List[str]       				=       kwargs.pop("""cache_dir"""							,							__a)
								UpperCAmelCase__					:   List[str]       				=       kwargs.pop("""force_download"""							,							__a)
								UpperCAmelCase__					:   Dict       				=       kwargs.pop("""resume_download"""							,							__a)
								UpperCAmelCase__					:   int       				=       kwargs.pop("""proxies"""							,							__a)
								UpperCAmelCase__					:   Union[str, Any]       				=       kwargs.pop("""local_files_only"""							,							__a)

								if os.path.isdir(__a):
											UpperCAmelCase__					:   int       				=       os.path.join(__a							,							__a)
								elif os.path.isfile(__a) or is_remote_url(__a):
											UpperCAmelCase__					:   str       				=       pretrained_model_name_or_path
								else:
											UpperCAmelCase__					:   Tuple       				=       hf_bucket_url(__a							,							filename=__a							,							use_cdn=__a)

								try:
											# Load from URL or cache if already cached
											UpperCAmelCase__					:   str       				=       cached_path(
											    __a							,							cache_dir=__a							,							force_download=__a							,							proxies=__a							,							resume_download=__a							,							local_files_only=__a							,							)
											# Load config dict
											if resolved_config_file is None:
														raise EnvironmentError

											UpperCAmelCase__					:   Union[str, Any]       				=       Config.load_yaml(__a)

								except EnvironmentError:
											UpperCAmelCase__					:   List[Any]       				=       """Can't load config for"""
											raise EnvironmentError(__a)

								if resolved_config_file == config_file:
											print("""loading configuration file from path""")
								else:
											print("""loading configuration file cache""")

								return Config.load_yaml(__a), kwargs







def       _UpperCamelCase (						UpperCamelCase__   ):
			UpperCAmelCase__					:   Dict       				=       torch.load("""dump.pt"""	, map_location=in_tensor.device   )
			UpperCAmelCase__					:   Union[str, Any]       				=       in_tensor.numpy()
			UpperCAmelCase__					:   Optional[Any]       				=       out_tensor.numpy()[0]
			print(na.shape	, na[0, 0, :5]   )
			print(na.shape	, na[0, 0, :5]   )
			assert np.allclose(snake_case_	, snake_case_	, rtol=0.01	, atol=0.1   ), (
			    f'''{sum([1 for x in np.isclose(snake_case_	, snake_case_	, rtol=0.01	, atol=0.1   ).flatten() if x is False]   )/len(na.flatten()   )*1_0_0:.4f} %'''
			    " element-wise mismatch"
			)
			raise Exception("""tensors are all good"""   )

			# Hugging face functions below







def       _UpperCamelCase (						UpperCamelCase__   ):
			UpperCAmelCase__					:   str       				=       urlparse(snake_case_   )
			return parsed.scheme in ("http", "https")







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__	, UpperCamelCase__=True   ):
			UpperCAmelCase__					:   Any       				=       CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
			UpperCAmelCase__					:   Dict       				=       """/""" not in model_id
			if legacy_format:
						return f'''{endpoint}/{model_id}-{filename}'''
			else:
						return f'''{endpoint}/{model_id}/{filename}'''







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__	, UpperCamelCase__=None	, UpperCamelCase__=0	, UpperCamelCase__=None	, ):
			UpperCAmelCase__					:   str       				=       """python/{}""".format(sys.version.split()[0]   )
			if _torch_available:
						ua += "; torch/{}".format(torch.__version__   )
			if isinstance(snake_case_	, snake_case_   ):
						ua += "; " + "; ".join("""{}/{}""".format(snake_case_	, snake_case_   ) for k, v in user_agent.items()   )
			elif isinstance(snake_case_	, snake_case_   ):
						ua += "; " + user_agent
			UpperCAmelCase__					:   Optional[Any]       				=       {"""user-agent""": ua}
			if resume_size > 0:
						UpperCAmelCase__					:   str       				=       """bytes=%d-""" % (resume_size,)
			UpperCAmelCase__					:   int       				=       requests.get(snake_case_	, stream=snake_case_	, proxies=snake_case_	, headers=snake_case_   )
			if response.status_code == 4_1_6:  # Range not satisfiable
						return
			UpperCAmelCase__					:   Dict       				=       response.headers.get("""Content-Length"""   )
			UpperCAmelCase__					:   Any       				=       resume_size + int(snake_case_   ) if content_length is not None else None
			UpperCAmelCase__					:   int       				=       tqdm(
			    unit="""B"""	, unit_scale=snake_case_	, total=snake_case_	, initial=snake_case_	, desc="""Downloading"""	, )
			for chunk in response.iter_content(chunk_size=1_0_2_4   ):
						if chunk:  # filter out keep-alive new chunks
									progress.update(len(snake_case_   )   )
									temp_file.write(snake_case_   )
			progress.close()







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__=None	, UpperCamelCase__=False	, UpperCamelCase__=None	, UpperCamelCase__=1_0	, UpperCamelCase__=False	, UpperCamelCase__=None	, UpperCamelCase__=False	, ):




			if cache_dir is None:
						UpperCAmelCase__					:   Any       				=       TRANSFORMERS_CACHE
			if isinstance(snake_case_	, snake_case_   ):
						UpperCAmelCase__					:   Any       				=       str(snake_case_   )

			os.makedirs(snake_case_	, exist_ok=snake_case_   )

			UpperCAmelCase__					:   Dict       				=       None
			if not local_files_only:
						try:
									UpperCAmelCase__					:   Dict       				=       requests.head(snake_case_	, allow_redirects=snake_case_	, proxies=snake_case_	, timeout=snake_case_   )
									if response.status_code == 2_0_0:
												UpperCAmelCase__					:   List[Any]       				=       response.headers.get("""ETag"""   )
						except (EnvironmentError, requests.exceptions.Timeout):
									# etag is already None
									pass

			UpperCAmelCase__					:   str       				=       url_to_filename(snake_case_	, snake_case_   )

			# get cache path to put the file
			UpperCAmelCase__					:   Optional[int]       				=       os.path.join(snake_case_	, snake_case_   )

			# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
			# try to get the last downloaded one
			if etag is None:
						if os.path.exists(snake_case_   ):
									return cache_path
						else:
									UpperCAmelCase__					:   List[str]       				=       [
									    file
									    for file in fnmatch.filter(os.listdir(snake_case_   )	, filename + """.*"""   )
									    if not file.endswith(""".json"""   ) and not file.endswith(""".lock"""   )
									]
									if len(snake_case_   ) > 0:
												return os.path.join(snake_case_	, matching_files[-1]   )
									else:
												# If files cannot be found and local_files_only=True,
												# the models might've been found if local_files_only=False
												# Notify the user about that
												if local_files_only:
															raise ValueError(
															    """Cannot find the requested files in the cached path and outgoing traffic has been"""
															    """ disabled. To enable model look-ups and downloads online, set 'local_files_only'"""
															    """ to False."""   )
												return None

    # From now on, etag is not None.
			if os.path.exists(snake_case_   ) and not force_download:
						return cache_path

			# Prevent parallel downloads of the same file with a lock.
			UpperCAmelCase__					:   Tuple       				=       cache_path + """.lock"""
			with FileLock(snake_case_   ):
						# If the download just completed while the lock was activated.
						if os.path.exists(snake_case_   ) and not force_download:
									# Even if returning early like here, the lock will be released.
									return cache_path

						if resume_download:
									UpperCAmelCase__					:   Union[str, Any]       				=       cache_path + """.incomplete"""

									@contextmanager
									def _resumable_file_manager():
												with open(snake_case_	, """a+b"""   ) as f:
															yield f

									UpperCAmelCase__					:   Union[str, Any]       				=       _resumable_file_manager
									if os.path.exists(snake_case_   ):
												UpperCAmelCase__					:   List[str]       				=       os.stat(snake_case_   ).st_size
									else:
												UpperCAmelCase__					:   int       				=       0
						else:
									UpperCAmelCase__					:   List[str]       				=       partial(tempfile.NamedTemporaryFile	, dir=snake_case_	, delete=snake_case_   )
									UpperCAmelCase__					:   Tuple       				=       0

						# Download to temporary file, then copy to cache dir once finished.
						# Otherwise you get corrupt cache entries if the download gets interrupted.
						with temp_file_manager() as temp_file:
									print(
									    """%s not found in cache or force_download set to True, downloading to %s"""	, snake_case_	, temp_file.name	, )

									http_get(
									    snake_case_	, snake_case_	, proxies=snake_case_	, resume_size=snake_case_	, user_agent=snake_case_	, )

						os.replace(temp_file.name	, snake_case_   )

						UpperCAmelCase__					:   Dict       				=       {"""url""": url, """etag""": etag}
						UpperCAmelCase__					:   Optional[Any]       				=       cache_path + """.json"""
						with open(snake_case_	, """w"""   ) as meta_file:
									json.dump(snake_case_	, snake_case_   )

			return cache_path







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__=None   ):
			UpperCAmelCase__					:   int       				=       url.encode("""utf-8"""   )
			UpperCAmelCase__					:   str       				=       shaaaa(snake_case_   )
			UpperCAmelCase__					:   Tuple       				=       url_hash.hexdigest()

			if etag:
						UpperCAmelCase__					:   List[str]       				=       etag.encode("""utf-8"""   )
						UpperCAmelCase__					:   int       				=       shaaaa(snake_case_   )
						filename += "." + etag_hash.hexdigest()

			if url.endswith(""".h5"""   ):
						filename += ".h5"

			return filename







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__=None	, UpperCamelCase__=False	, UpperCamelCase__=None	, UpperCamelCase__=False	, UpperCamelCase__=None	, UpperCamelCase__=False	, UpperCamelCase__=False	, UpperCamelCase__=False	, ):




			if cache_dir is None:
						UpperCAmelCase__					:   List[Any]       				=       TRANSFORMERS_CACHE
			if isinstance(snake_case_	, snake_case_   ):
						UpperCAmelCase__					:   List[Any]       				=       str(snake_case_   )
			if isinstance(snake_case_	, snake_case_   ):
						UpperCAmelCase__					:   str       				=       str(snake_case_   )

			if is_remote_url(snake_case_   ):
						# URL, so get it from the cache (downloading if necessary)
						UpperCAmelCase__					:   Union[str, Any]       				=       get_from_cache(
						    snake_case_	, cache_dir=snake_case_	, force_download=snake_case_	, proxies=snake_case_	, resume_download=snake_case_	, user_agent=snake_case_	, local_files_only=snake_case_	, )
			elif os.path.exists(snake_case_   ):
						# File, and it exists.
						UpperCAmelCase__					:   Tuple       				=       url_or_filename
			elif urlparse(snake_case_   ).scheme == "":
						# File, but it doesn't exist.
						raise EnvironmentError("""file {} not found""".format(snake_case_   )   )
			else:
						# Something unknown
						raise ValueError("""unable to parse {} as a URL or as a local path""".format(snake_case_   )   )

			if extract_compressed_file:
						if not is_zipfile(snake_case_   ) and not tarfile.is_tarfile(snake_case_   ):
									return output_path

						# Path where we extract compressed archives
						# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
						UpperCAmelCase__				,    UpperCAmelCase__					:   Any       				=       os.path.split(snake_case_   )
						UpperCAmelCase__					:   Any       				=       output_file.replace("""."""	, """-"""   ) + """-extracted"""
						UpperCAmelCase__					:   List[Any]       				=       os.path.join(snake_case_	, snake_case_   )

						if os.path.isdir(snake_case_   ) and os.listdir(snake_case_   ) and not force_extract:
									return output_path_extracted

						# Prevent parallel extractions
						UpperCAmelCase__					:   Union[str, Any]       				=       output_path + """.lock"""
						with FileLock(snake_case_   ):
									shutil.rmtree(snake_case_	, ignore_errors=snake_case_   )
									os.makedirs(snake_case_   )
									if is_zipfile(snake_case_   ):
												with ZipFile(snake_case_	, """r"""   ) as zip_file:
															zip_file.extractall(snake_case_   )
															zip_file.close()
									elif tarfile.is_tarfile(snake_case_   ):
												UpperCAmelCase__					:   Union[str, Any]       				=       tarfile.open(snake_case_   )
												tar_file.extractall(snake_case_   )
												tar_file.close()
									else:
												raise EnvironmentError("""Archive format of {} could not be identified""".format(snake_case_   )   )

						return output_path_extracted

			return output_path







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__=","   ):
			assert isinstance(snake_case_	, snake_case_   )
			if os.path.isfile(snake_case_   ):
						with open(snake_case_   ) as f:
									UpperCAmelCase__					:   str       				=       eval(f.read()   )
			else:
						UpperCAmelCase__					:   Any       				=       requests.get(snake_case_   )
						try:
									UpperCAmelCase__					:   List[str]       				=       requests.json()
						except Exception:
									UpperCAmelCase__					:   List[Any]       				=       req.content.decode()
									assert data is not None, "could not connect"
									try:
												UpperCAmelCase__					:   Optional[Any]       				=       eval(snake_case_   )
									except Exception:
												UpperCAmelCase__					:   Union[str, Any]       				=       data.split("""\n"""   )
						req.close()
			return data







def       _UpperCamelCase (						UpperCamelCase__   ):
			UpperCAmelCase__					:   Optional[int]       				=       requests.get(snake_case_   )
			UpperCAmelCase__					:   List[str]       				=       np.array(Image.open(BytesIO(response.content   )   )   )
			return img







def       _UpperCamelCase (						UpperCamelCase__   ):
			UpperCAmelCase__					:   Optional[Any]       				=       url.split("""/"""   )[-1]
			if fn not in os.listdir(os.getcwd()   ):
						wget.download(snake_case_   )
			with open(snake_case_	, """rb"""   ) as stream:
						UpperCAmelCase__					:   Optional[int]       				=       pkl.load(snake_case_   )
			UpperCAmelCase__					:   Tuple       				=       weights.pop("""model"""   )
			UpperCAmelCase__					:   List[str]       				=       {}
			for k, v in model.items():
						UpperCAmelCase__					:   Dict       				=       torch.from_numpy(snake_case_   )
						if "running_var" in k:
									UpperCAmelCase__					:   Dict       				=       torch.tensor([0]   )
									UpperCAmelCase__					:   List[str]       				=       k.replace("""running_var"""	, """num_batches_tracked"""   )
									UpperCAmelCase__					:   Union[str, Any]       				=       zero
			return new







def       _UpperCamelCase (						):
			print(f'''{os.path.abspath(os.path.join(snake_case_	, os.pardir   )   )}/demo.ipynb'''   )







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__="RGB"   ):
			assert isinstance(snake_case_	, snake_case_   )
			if os.path.isfile(snake_case_   ):
						UpperCAmelCase__					:   Tuple       				=       cva.imread(snake_case_   )
			else:
						UpperCAmelCase__					:   Optional[Any]       				=       get_image_from_url(snake_case_   )
						assert img is not None, f'''could not connect to: {im}'''
			UpperCAmelCase__					:   str       				=       cva.cvtColor(snake_case_	, cva.COLOR_BGR2RGB   )
			if input_format == "RGB":
						UpperCAmelCase__					:   Tuple       				=       img[:, :, ::-1]
			return img







def       _UpperCamelCase (						UpperCamelCase__	, UpperCamelCase__=1   ):
			return (images[i : i + batch] for i in range(0	, len(snake_case_   )	, snake_case_   ))



'''simple docstring'''



from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer


@dataclass
class 						_snake_case   (       a__		):
					lowerCAmelCase :torch.FloatTensor


class 						_snake_case   (       a__    ,				a__		):




					@register_to_config
					def __init__( self							,							_lowerCamelCase = 3							,							_lowerCamelCase = 3							,							_lowerCamelCase = ("DownEncoderBlock2D",)							,							_lowerCamelCase = ("UpDecoderBlock2D",)							,							_lowerCamelCase = (64,)							,							_lowerCamelCase = 1							,							_lowerCamelCase = "silu"							,							_lowerCamelCase = 3							,							_lowerCamelCase = 32							,							_lowerCamelCase = 256							,							_lowerCamelCase = 32							,							_lowerCamelCase = None							,							_lowerCamelCase = 0.18215							,							_lowerCamelCase = "group"							,							):
								super().__init__()

								# pass init params to Encoder
								UpperCAmelCase__					:   str       				=       Encoder(
								    in_channels=_lowerCamelCase							,							out_channels=_lowerCamelCase							,							down_block_types=_lowerCamelCase							,							block_out_channels=_lowerCamelCase							,							layers_per_block=_lowerCamelCase							,							act_fn=_lowerCamelCase							,							norm_num_groups=_lowerCamelCase							,							double_z=_lowerCamelCase							,							)

								UpperCAmelCase__					:   Optional[Any]       				=       vq_embed_dim if vq_embed_dim is not None else latent_channels

								UpperCAmelCase__					:   Any       				=       nn.Convad(_lowerCamelCase							,							_lowerCamelCase							,							1)
								UpperCAmelCase__					:   Optional[int]       				=       VectorQuantizer(_lowerCamelCase							,							_lowerCamelCase							,							beta=0.25							,							remap=_lowerCamelCase							,							sane_index_shape=_lowerCamelCase)
								UpperCAmelCase__					:   Optional[int]       				=       nn.Convad(_lowerCamelCase							,							_lowerCamelCase							,							1)

								# pass init params to Decoder
								UpperCAmelCase__					:   str       				=       Decoder(
								    in_channels=_lowerCamelCase							,							out_channels=_lowerCamelCase							,							up_block_types=_lowerCamelCase							,							block_out_channels=_lowerCamelCase							,							layers_per_block=_lowerCamelCase							,							act_fn=_lowerCamelCase							,							norm_num_groups=_lowerCamelCase							,							norm_type=_lowerCamelCase							,							)




					@apply_forward_hook
					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = True):
								UpperCAmelCase__					:   Union[str, Any]       				=       self.encoder(_lowerCamelCase)
								UpperCAmelCase__					:   str       				=       self.quant_conv(_lowerCamelCase)

								if not return_dict:
											return (h,)

								return VQEncoderOutput(latents=_lowerCamelCase)




					@apply_forward_hook
					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = False							,							_lowerCamelCase = True):
								# also go through quantization layer
								if not force_not_quantize:
											UpperCAmelCase__				,    UpperCAmelCase__				,    UpperCAmelCase__					:   Optional[Any]       				=       self.quantize(_lowerCamelCase)
								else:
											UpperCAmelCase__					:   Union[str, Any]       				=       h
								UpperCAmelCase__					:   Any       				=       self.post_quant_conv(_lowerCamelCase)
								UpperCAmelCase__					:   Any       				=       self.decoder(_lowerCamelCase							,							quant if self.config.norm_type == """spatial""" else None)

								if not return_dict:
											return (dec,)

								return DecoderOutput(sample=_lowerCamelCase)




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = True):
								UpperCAmelCase__					:   Dict       				=       sample
								UpperCAmelCase__					:   Dict       				=       self.encode(_lowerCamelCase).latents
								UpperCAmelCase__					:   List[str]       				=       self.decode(_lowerCamelCase).sample

								if not return_dict:
											return (dec,)

								return DecoderOutput(sample=_lowerCamelCase)