






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

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()




def      lowercase__      (     __snake_case    :							str     ,       __snake_case    :							str     ,       __snake_case    :							str     ,       __snake_case    :							PreTrainedTokenizer     ,       __snake_case    :							int     ,       __snake_case    :							Optional[int] = None     ,       ):


					'''simple docstring'''


					UpperCAmelCase_    :      Any            =						{}

					if train_file is not None:
										UpperCAmelCase_    :      Any            =						[train_file]
					if eval_file is not None:
										UpperCAmelCase_    :      int            =						[eval_file]
					if test_file is not None:
										UpperCAmelCase_    :      str            =						[test_file]

					UpperCAmelCase_    :      int            =						datasets.load_dataset('csv'     ,       data_files=__snake_case  )
					UpperCAmelCase_    :      List[Any]            =						list(ds[list(files.keys()  )[0]].features.keys()  )
					UpperCAmelCase_    :      List[str]            =						features_name.pop(__snake_case  )
					UpperCAmelCase_    :      Any            =						list(set(ds[list(files.keys()  )[0]][label_name]  )  )
					UpperCAmelCase_    :      List[str]            =						{label: i for i, label in enumerate(__snake_case  )}
					UpperCAmelCase_    :      Dict            =						tokenizer.model_input_names
					UpperCAmelCase_    :      Optional[int]            =						{}

					if len(__snake_case  ) == 1:
										for k in files.keys():
															UpperCAmelCase_    :      List[Any]            =						ds[k].map(
															    lambda __snake_case  : tokenizer.batch_encode_plus(
															        example[features_name[0]]     ,       truncation=__snake_case     ,       max_length=__snake_case     ,       padding='max_length'  )     ,       batched=__snake_case     ,       )
					elif len(__snake_case  ) == 2:
										for k in files.keys():
															UpperCAmelCase_    :      Union[str, Any]            =						ds[k].map(
															    lambda __snake_case  : tokenizer.batch_encode_plus(
															        (example[features_name[0]], example[features_name[1]])     ,       truncation=__snake_case     ,       max_length=__snake_case     ,       padding='max_length'     ,       )     ,       batched=__snake_case     ,       )

					def gen_train():
										for ex in transformed_ds[datasets.Split.TRAIN]:
															UpperCAmelCase_    :      Tuple            =						{k: v for k, v in ex.items() if k in input_names}
															UpperCAmelCase_    :      str            =						labelaid[ex[label_name]]
															yield (d, label)

					def gen_val():
										for ex in transformed_ds[datasets.Split.VALIDATION]:
															UpperCAmelCase_    :      Any            =						{k: v for k, v in ex.items() if k in input_names}
															UpperCAmelCase_    :      List[str]            =						labelaid[ex[label_name]]
															yield (d, label)

					def gen_test():
										for ex in transformed_ds[datasets.Split.TEST]:
															UpperCAmelCase_    :      Any            =						{k: v for k, v in ex.items() if k in input_names}
															UpperCAmelCase_    :      Dict            =						labelaid[ex[label_name]]
															yield (d, label)

					UpperCAmelCase_    :      str            =						(
					    tf.data.Dataset.from_generator(
					        __snake_case     ,       ({k: tf.intaa for k in input_names}, tf.intaa)     ,       ({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))     ,       )
					    if datasets.Split.TRAIN in transformed_ds
					    else None
					)

					if train_ds is not None:
										UpperCAmelCase_    :      Tuple            =						train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]  )  )  )

					UpperCAmelCase_    :      str            =						(
					    tf.data.Dataset.from_generator(
					        __snake_case     ,       ({k: tf.intaa for k in input_names}, tf.intaa)     ,       ({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))     ,       )
					    if datasets.Split.VALIDATION in transformed_ds
					    else None
					)

					if val_ds is not None:
										UpperCAmelCase_    :      int            =						val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]  )  )  )

					UpperCAmelCase_    :      List[str]            =						(
					    tf.data.Dataset.from_generator(
					        __snake_case     ,       ({k: tf.intaa for k in input_names}, tf.intaa)     ,       ({k: tf.TensorShape([None]  ) for k in input_names}, tf.TensorShape([]  ))     ,       )
					    if datasets.Split.TEST in transformed_ds
					    else None
					)

					if test_ds is not None:
										UpperCAmelCase_    :      List[Any]            =						test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]  )  )  )

					return train_ds, val_ds, test_ds, labelaid


__UpperCAmelCase								=						logging.getLogger(__name__)



@dataclass
class   lowerCamelCase      :







		'''simple docstring'''



		_snake_case    :    int       						=  field(metadata={'''help''': '''Which column contains the label'''}			)
		_snake_case    :    str       						=  field(default=_snake_case ,  metadata={'''help''': '''The path of the training file'''}			)
		_snake_case    :    Optional[str]       						=  field(default=_snake_case ,  metadata={'''help''': '''The path of the development file'''}			)
		_snake_case    :    Optional[str]       						=  field(default=_snake_case ,  metadata={'''help''': '''The path of the test file'''}			)
		_snake_case    :    int       						=  field(
		    default=1_2_8 ,  metadata={
		        '''help''': (
		            '''The maximum total input sequence length after tokenization. Sequences longer '''
		            '''than this will be truncated, sequences shorter will be padded.'''
		        )
		    } ,  )
		_snake_case    :    bool       						=  field(
		    default=_snake_case ,  metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}			)





@dataclass
class   lowerCamelCase      :







		'''simple docstring'''



		_snake_case    :    str       						=  field(
		    metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}			)
		_snake_case    :    Optional[str]       						=  field(
		    default=_snake_case ,  metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}			)
		_snake_case    :    Optional[str]       						=  field(
		    default=_snake_case ,  metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}			)
		_snake_case    :    bool       						=  field(default=_snake_case ,  metadata={'''help''': '''Set this flag to use fast tokenization.'''}			)
		# If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
		# or just modify its tokenizer_config.json.
		_snake_case    :    Optional[str]       						=  field(
		    default=_snake_case ,  metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} ,  )





def      lowercase__      (     ):


					'''simple docstring'''


					UpperCAmelCase_    :      Dict            =						HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)  )
					UpperCAmelCase_       ,  UpperCAmelCase_       ,  UpperCAmelCase_    :      List[str]            =						parser.parse_args_into_dataclasses()

					if (
					    os.path.exists(training_args.output_dir  )
					    and os.listdir(training_args.output_dir  )
					    and training_args.do_train
					    and not training_args.overwrite_output_dir
					):
										raise ValueError(
										    F"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
										    ' --overwrite_output_dir to overcome.'  )

					# Setup logging
					logging.basicConfig(
					    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'     ,       datefmt='%m/%d/%Y %H:%M:%S'     ,       level=logging.INFO     ,       )
					logger.info(
					    F"n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1  )}, "
					    F"16-bits training: {training_args.fpaa}"  )
					logger.info(F"Training/evaluation parameters {training_args}"  )

					# Load pretrained model and tokenizer
					#
					# Distributed training:
					# The .from_pretrained methods guarantee that only one local process can concurrently
					# download model & vocab.

					UpperCAmelCase_    :      List[str]            =						AutoTokenizer.from_pretrained(
					    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path     ,       cache_dir=model_args.cache_dir     ,       )

					UpperCAmelCase_       ,  UpperCAmelCase_       ,  UpperCAmelCase_       ,  UpperCAmelCase_    :      Dict            =						get_tfds(
					    train_file=data_args.train_file     ,       eval_file=data_args.dev_file     ,       test_file=data_args.test_file     ,       tokenizer=__snake_case     ,       label_column_id=data_args.label_column_id     ,       max_seq_length=data_args.max_seq_length     ,       )

					UpperCAmelCase_    :      Any            =						AutoConfig.from_pretrained(
					    model_args.config_name if model_args.config_name else model_args.model_name_or_path     ,       num_labels=len(__snake_case  )     ,       labelaid=__snake_case     ,       idalabel={id: label for label, id in labelaid.items()}     ,       finetuning_task='text-classification'     ,       cache_dir=model_args.cache_dir     ,       )

					with training_args.strategy.scope():
										UpperCAmelCase_    :      Dict            =						TFAutoModelForSequenceClassification.from_pretrained(
										    model_args.model_name_or_path     ,       from_pt=bool('.bin' in model_args.model_name_or_path  )     ,       config=__snake_case     ,       cache_dir=model_args.cache_dir     ,       )

					def compute_metrics(__snake_case    :							EvalPrediction  ) -> Dict:
										UpperCAmelCase_    :      Tuple            =						np.argmax(p.predictions     ,       axis=1  )

										return {"acc": (preds == p.label_ids).mean()}

					# Initialize our Trainer
					UpperCAmelCase_    :      List[str]            =						TFTrainer(
					    model=__snake_case     ,       args=__snake_case     ,       train_dataset=__snake_case     ,       eval_dataset=__snake_case     ,       compute_metrics=__snake_case     ,       )

					# Training
					if training_args.do_train:
										trainer.train()
										trainer.save_model()
										tokenizer.save_pretrained(training_args.output_dir  )

					# Evaluation
					UpperCAmelCase_    :      List[Any]            =						{}
					if training_args.do_eval:
										logger.info('*** Evaluate ***'  )
										UpperCAmelCase_    :      Dict            =						trainer.evaluate()
										UpperCAmelCase_    :      Dict            =						os.path.join(training_args.output_dir     ,       'eval_results.txt'  )

										with open(__snake_case     ,       'w'  ) as writer:
															logger.info('***** Eval results *****'  )

															for key, value in result.items():
																				logger.info(F"  {key} = {value}"  )
																				writer.write(F"{key} = {value}\n"  )

															results.update(__snake_case  )

					return results


if __name__ == "__main__":
		main()














from dataclasses import dataclass
from typing import Dict, 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 .attention_processor import AttentionProcessor, AttnProcessor
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder



@dataclass
class   lowerCamelCase      (_snake_case			):







		'''simple docstring'''



		_snake_case    :    "DiagonalGaussianDistribution"





class   lowerCamelCase      (_snake_case ,  _snake_case			):







		'''simple docstring'''



		_snake_case    :    Optional[int]       						=  True



		@register_to_config
		def __init__(							self				,		_UpperCamelCase = 3				,		_UpperCamelCase = 3				,		_UpperCamelCase = ("DownEncoderBlock2D",)				,		_UpperCamelCase = ("UpDecoderBlock2D",)				,		_UpperCamelCase = (6_4,)				,		_UpperCamelCase = 1				,		_UpperCamelCase = "silu"				,		_UpperCamelCase = 4				,		_UpperCamelCase = 3_2				,		_UpperCamelCase = 3_2				,		_UpperCamelCase = 0.1_82_15				,		)	->							List[Any]:
							super().__init__()

							# pass init params to Encoder
							UpperCAmelCase_    :      List[str]            =						Encoder(
							    in_channels=_UpperCamelCase				,		out_channels=_UpperCamelCase				,		down_block_types=_UpperCamelCase				,		block_out_channels=_UpperCamelCase				,		layers_per_block=_UpperCamelCase				,		act_fn=_UpperCamelCase				,		norm_num_groups=_UpperCamelCase				,		double_z=_UpperCamelCase				,		)

							# pass init params to Decoder
							UpperCAmelCase_    :      Dict            =						Decoder(
							    in_channels=_UpperCamelCase				,		out_channels=_UpperCamelCase				,		up_block_types=_UpperCamelCase				,		block_out_channels=_UpperCamelCase				,		layers_per_block=_UpperCamelCase				,		norm_num_groups=_UpperCamelCase				,		act_fn=_UpperCamelCase				,		)

							UpperCAmelCase_    :      Any            =						nn.Convad(2 * latent_channels				,		2 * latent_channels				,		1   )
							UpperCAmelCase_    :      List[Any]            =						nn.Convad(_UpperCamelCase				,		_UpperCamelCase				,		1   )

							UpperCAmelCase_    :      Any            =						False
							UpperCAmelCase_    :      int            =						False

							# only relevant if vae tiling is enabled
							UpperCAmelCase_    :      Optional[int]            =						self.config.sample_size
							UpperCAmelCase_    :      int            =						(
							    self.config.sample_size[0]
							    if isinstance(self.config.sample_size				,		(list, tuple)   )
							    else self.config.sample_size
							)
							UpperCAmelCase_    :      Union[str, Any]            =						int(sample_size / (2 ** (len(self.config.block_out_channels   ) - 1))   )
							UpperCAmelCase_    :      Optional[Any]            =						0.25



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase=False   )	->							List[str]:
							if isinstance(_UpperCamelCase				,		(Encoder, Decoder)   ):
												UpperCAmelCase_    :      Union[str, Any]            =						value



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase = True   )	->							int:
							UpperCAmelCase_    :      Tuple            =						use_tiling



		def 					__UpperCAmelCase			(							self   )	->							Dict:
							self.enable_tiling(_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							UpperCAmelCase_    :      str            =						True



		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							UpperCAmelCase_    :      Optional[int]            =						False



		@property
		# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
		def 					__UpperCAmelCase			(							self   )	->							Dict[str, AttentionProcessor]:
							UpperCAmelCase_    :      Optional[int]            =						{}

							def fn_recursive_add_processors(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   ):
												if hasattr(_UpperCamelCase				,		'set_processor'   ):
																	UpperCAmelCase_    :      Optional[int]            =						module.processor

												for sub_name, child in module.named_children():
																	fn_recursive_add_processors(f"{name}.{sub_name}"				,		_UpperCamelCase				,		_UpperCamelCase   )

												return processors

							for name, module in self.named_children():
												fn_recursive_add_processors(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )

							return processors



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase   )	->							List[Any]:
							UpperCAmelCase_    :      Union[str, Any]            =						len(self.attn_processors.keys()   )

							if isinstance(_UpperCamelCase				,		_UpperCamelCase   ) and len(_UpperCamelCase   ) != count:
												raise ValueError(
												    f"A dict of processors was passed, but the number of processors {len(_UpperCamelCase   )} does not match the"
												    f" number of attention layers: {count}. Please make sure to pass {count} processor classes."   )

							def fn_recursive_attn_processor(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   ):
												if hasattr(_UpperCamelCase				,		'set_processor'   ):
																	if not isinstance(_UpperCamelCase				,		_UpperCamelCase   ):
																						module.set_processor(_UpperCamelCase   )
																	else:
																						module.set_processor(processor.pop(f"{name}.processor"   )   )

												for sub_name, child in module.named_children():
																	fn_recursive_attn_processor(f"{name}.{sub_name}"				,		_UpperCamelCase				,		_UpperCamelCase   )

							for name, module in self.named_children():
												fn_recursive_attn_processor(_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self   )	->							Union[str, Any]:
							self.set_attn_processor(AttnProcessor()   )



		@apply_forward_hook
		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase = True   )	->							AutoencoderKLOutput:
							if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
												return self.tiled_encode(_UpperCamelCase				,		return_dict=_UpperCamelCase   )

							if self.use_slicing and x.shape[0] > 1:
												UpperCAmelCase_    :      Union[str, Any]            =						[self.encoder(_UpperCamelCase   ) for x_slice in x.split(1   )]
												UpperCAmelCase_    :      Tuple            =						torch.cat(_UpperCamelCase   )
							else:
												UpperCAmelCase_    :      List[Any]            =						self.encoder(_UpperCamelCase   )

							UpperCAmelCase_    :      Optional[Any]            =						self.quant_conv(_UpperCamelCase   )
							UpperCAmelCase_    :      Tuple            =						DiagonalGaussianDistribution(_UpperCamelCase   )

							if not return_dict:
												return (posterior,)

							return AutoencoderKLOutput(latent_dist=_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase = True   )	->							Union[DecoderOutput, torch.FloatTensor]:
							if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
												return self.tiled_decode(_UpperCamelCase				,		return_dict=_UpperCamelCase   )

							UpperCAmelCase_    :      str            =						self.post_quant_conv(_UpperCamelCase   )
							UpperCAmelCase_    :      List[str]            =						self.decoder(_UpperCamelCase   )

							if not return_dict:
												return (dec,)

							return DecoderOutput(sample=_UpperCamelCase   )



		@apply_forward_hook
		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase = True   )	->							Union[DecoderOutput, torch.FloatTensor]:
							if self.use_slicing and z.shape[0] > 1:
												UpperCAmelCase_    :      List[str]            =						[self._decode(_UpperCamelCase   ).sample for z_slice in z.split(1   )]
												UpperCAmelCase_    :      Dict            =						torch.cat(_UpperCamelCase   )
							else:
												UpperCAmelCase_    :      Any            =						self._decode(_UpperCamelCase   ).sample

							if not return_dict:
												return (decoded,)

							return DecoderOutput(sample=_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )	->							Any:
							UpperCAmelCase_    :      Tuple            =						min(a.shape[2]				,		b.shape[2]				,		_UpperCamelCase   )
							for y in range(_UpperCamelCase   ):
												UpperCAmelCase_    :      str            =						a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
							return b



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase				,		_UpperCamelCase   )	->							Dict:
							UpperCAmelCase_    :      Tuple            =						min(a.shape[3]				,		b.shape[3]				,		_UpperCamelCase   )
							for x in range(_UpperCamelCase   ):
												UpperCAmelCase_    :      int            =						a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
							return b



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase = True   )	->							AutoencoderKLOutput:
							UpperCAmelCase_    :      Any            =						int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)   )
							UpperCAmelCase_    :      Tuple            =						int(self.tile_latent_min_size * self.tile_overlap_factor   )
							UpperCAmelCase_    :      Optional[int]            =						self.tile_latent_min_size - blend_extent

							# Split the image into 512x512 tiles and encode them separately.
							UpperCAmelCase_    :      List[str]            =						[]
							for i in range(0				,		x.shape[2]				,		_UpperCamelCase   ):
												UpperCAmelCase_    :      Any            =						[]
												for j in range(0				,		x.shape[3]				,		_UpperCamelCase   ):
																	UpperCAmelCase_    :      Any            =						x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
																	UpperCAmelCase_    :      Dict            =						self.encoder(_UpperCamelCase   )
																	UpperCAmelCase_    :      List[str]            =						self.quant_conv(_UpperCamelCase   )
																	row.append(_UpperCamelCase   )
												rows.append(_UpperCamelCase   )
							UpperCAmelCase_    :      str            =						[]
							for i, row in enumerate(_UpperCamelCase   ):
												UpperCAmelCase_    :      List[Any]            =						[]
												for j, tile in enumerate(_UpperCamelCase   ):
																	# blend the above tile and the left tile
																	# to the current tile and add the current tile to the result row
																	if i > 0:
																						UpperCAmelCase_    :      Dict            =						self.blend_v(rows[i - 1][j]				,		_UpperCamelCase				,		_UpperCamelCase   )
																	if j > 0:
																						UpperCAmelCase_    :      List[str]            =						self.blend_h(row[j - 1]				,		_UpperCamelCase				,		_UpperCamelCase   )
																	result_row.append(tile[:, :, :row_limit, :row_limit]   )
												result_rows.append(torch.cat(_UpperCamelCase				,		dim=3   )   )

							UpperCAmelCase_    :      Union[str, Any]            =						torch.cat(_UpperCamelCase				,		dim=2   )
							UpperCAmelCase_    :      List[Any]            =						DiagonalGaussianDistribution(_UpperCamelCase   )

							if not return_dict:
												return (posterior,)

							return AutoencoderKLOutput(latent_dist=_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase = True   )	->							Union[DecoderOutput, torch.FloatTensor]:
							UpperCAmelCase_    :      str            =						int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)   )
							UpperCAmelCase_    :      Dict            =						int(self.tile_sample_min_size * self.tile_overlap_factor   )
							UpperCAmelCase_    :      Dict            =						self.tile_sample_min_size - blend_extent

							# Split z into overlapping 64x64 tiles and decode them separately.
							# The tiles have an overlap to avoid seams between tiles.
							UpperCAmelCase_    :      Union[str, Any]            =						[]
							for i in range(0				,		z.shape[2]				,		_UpperCamelCase   ):
												UpperCAmelCase_    :      List[str]            =						[]
												for j in range(0				,		z.shape[3]				,		_UpperCamelCase   ):
																	UpperCAmelCase_    :      List[str]            =						z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
																	UpperCAmelCase_    :      Optional[Any]            =						self.post_quant_conv(_UpperCamelCase   )
																	UpperCAmelCase_    :      Tuple            =						self.decoder(_UpperCamelCase   )
																	row.append(_UpperCamelCase   )
												rows.append(_UpperCamelCase   )
							UpperCAmelCase_    :      Optional[Any]            =						[]
							for i, row in enumerate(_UpperCamelCase   ):
												UpperCAmelCase_    :      List[Any]            =						[]
												for j, tile in enumerate(_UpperCamelCase   ):
																	# blend the above tile and the left tile
																	# to the current tile and add the current tile to the result row
																	if i > 0:
																						UpperCAmelCase_    :      Union[str, Any]            =						self.blend_v(rows[i - 1][j]				,		_UpperCamelCase				,		_UpperCamelCase   )
																	if j > 0:
																						UpperCAmelCase_    :      Optional[Any]            =						self.blend_h(row[j - 1]				,		_UpperCamelCase				,		_UpperCamelCase   )
																	result_row.append(tile[:, :, :row_limit, :row_limit]   )
												result_rows.append(torch.cat(_UpperCamelCase				,		dim=3   )   )

							UpperCAmelCase_    :      Dict            =						torch.cat(_UpperCamelCase				,		dim=2   )
							if not return_dict:
												return (dec,)

							return DecoderOutput(sample=_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase = False				,		_UpperCamelCase = True				,		_UpperCamelCase = None				,		)	->							Union[DecoderOutput, torch.FloatTensor]:
							UpperCAmelCase_    :      Optional[Any]            =						sample
							UpperCAmelCase_    :      Union[str, Any]            =						self.encode(_UpperCamelCase   ).latent_dist
							if sample_posterior:
												UpperCAmelCase_    :      str            =						posterior.sample(generator=_UpperCamelCase   )
							else:
												UpperCAmelCase_    :      int            =						posterior.mode()
							UpperCAmelCase_    :      Dict            =						self.decode(_UpperCamelCase   ).sample

							if not return_dict:
												return (dec,)

							return DecoderOutput(sample=_UpperCamelCase   )






