

import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
lowerCamelCase      				=     logging.getLogger(__name__)


def        __lowercase    (  UpperCAmelCase__		,					UpperCAmelCase__      ):

					"""simple docstring"""






					__lowerCAmelCase					=							np.argmax(UpperCAmelCase__		,					axis=1      )
					return np.sum(outputs == labels      )


def        __lowercase    (  UpperCAmelCase__      ):

					"""simple docstring"""






					with open(UpperCAmelCase__		,					encoding='utf_8'      ) as f:
										__lowerCAmelCase					=							csv.reader(UpperCAmelCase__      )
										__lowerCAmelCase					=							[]
										next(UpperCAmelCase__      )  # skip the first line
										for line in tqdm(UpperCAmelCase__      ):
															output.append((' '.join(line[1:5]      ), line[5], line[6], int(line[-1]      ) - 1)      )
					return output


def        __lowercase    (  UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__      ):

					"""simple docstring"""






					__lowerCAmelCase					=							[]
					for dataset in encoded_datasets:
										__lowerCAmelCase					=							len(UpperCAmelCase__      )
										__lowerCAmelCase					=							np.zeros((n_batch, 2, input_len)		,					dtype=np.intaa      )
										__lowerCAmelCase					=							np.zeros((n_batch, 2)		,					dtype=np.intaa      )
										__lowerCAmelCase					=							np.full((n_batch, 2, input_len)		,					fill_value=-100		,					dtype=np.intaa      )
										__lowerCAmelCase					=							np.zeros((n_batch,)		,					dtype=np.intaa      )
										for (
										    i,
										    (story, conta, conta, mc_label),
										) in enumerate(UpperCAmelCase__      ):
															__lowerCAmelCase					=							[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
															__lowerCAmelCase					=							[start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
															__lowerCAmelCase					=							with_conta
															__lowerCAmelCase					=							with_conta
															__lowerCAmelCase					=							len(UpperCAmelCase__      ) - 1
															__lowerCAmelCase					=							len(UpperCAmelCase__      ) - 1
															__lowerCAmelCase					=							with_conta
															__lowerCAmelCase					=							with_conta
															__lowerCAmelCase					=							mc_label
										__lowerCAmelCase					=							(input_ids, mc_token_ids, lm_labels, mc_labels)
										tensor_datasets.append(tuple(torch.tensor(UpperCAmelCase__      ) for t in all_inputs      )      )
					return tensor_datasets


def        __lowercase    (  ):

					"""simple docstring"""






					__lowerCAmelCase					=							argparse.ArgumentParser()
					parser.add_argument('--model_name'		,					type=UpperCAmelCase__		,					default='openai-gpt'		,					help='pretrained model name'      )
					parser.add_argument('--do_train'		,					action='store_true'		,					help='Whether to run training.'      )
					parser.add_argument('--do_eval'		,					action='store_true'		,					help='Whether to run eval on the dev set.'      )
					parser.add_argument(
					    '--output_dir'		,					default=UpperCAmelCase__		,					type=UpperCAmelCase__		,					required=UpperCAmelCase__		,					help='The output directory where the model predictions and checkpoints will be written.'		,					)
					parser.add_argument('--train_dataset'		,					type=UpperCAmelCase__		,					default=''      )
					parser.add_argument('--eval_dataset'		,					type=UpperCAmelCase__		,					default=''      )
					parser.add_argument('--seed'		,					type=UpperCAmelCase__		,					default=42      )
					parser.add_argument('--num_train_epochs'		,					type=UpperCAmelCase__		,					default=3      )
					parser.add_argument('--train_batch_size'		,					type=UpperCAmelCase__		,					default=8      )
					parser.add_argument('--eval_batch_size'		,					type=UpperCAmelCase__		,					default=16      )
					parser.add_argument('--adam_epsilon'		,					default=1E-8		,					type=UpperCAmelCase__		,					help='Epsilon for Adam optimizer.'      )
					parser.add_argument('--max_grad_norm'		,					type=UpperCAmelCase__		,					default=1      )
					parser.add_argument(
					    '--max_steps'		,					default=-1		,					type=UpperCAmelCase__		,					help=(
					        'If > 0: set total number of training                         steps to perform. Override num_train_epochs.'
					    )		,					)
					parser.add_argument(
					    '--gradient_accumulation_steps'		,					type=UpperCAmelCase__		,					default=1		,					help='Number of updates steps to accumulate before                        performing a backward/update pass.'		,					)
					parser.add_argument('--learning_rate'		,					type=UpperCAmelCase__		,					default=6.25E-5      )
					parser.add_argument('--warmup_steps'		,					default=0		,					type=UpperCAmelCase__		,					help='Linear warmup over warmup_steps.'      )
					parser.add_argument('--lr_schedule'		,					type=UpperCAmelCase__		,					default='warmup_linear'      )
					parser.add_argument('--weight_decay'		,					type=UpperCAmelCase__		,					default=0.01      )
					parser.add_argument('--lm_coef'		,					type=UpperCAmelCase__		,					default=0.9      )
					parser.add_argument('--n_valid'		,					type=UpperCAmelCase__		,					default=374      )

					parser.add_argument('--server_ip'		,					type=UpperCAmelCase__		,					default=''		,					help='Can be used for distant debugging.'      )
					parser.add_argument('--server_port'		,					type=UpperCAmelCase__		,					default=''		,					help='Can be used for distant debugging.'      )
					__lowerCAmelCase					=							parser.parse_args()
					print(UpperCAmelCase__      )

					if args.server_ip and args.server_port:
										# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
										import ptvsd

										print('Waiting for debugger attach'      )
										ptvsd.enable_attach(address=(args.server_ip, args.server_port)		,					redirect_output=UpperCAmelCase__      )
										ptvsd.wait_for_attach()

					random.seed(args.seed      )
					np.random.seed(args.seed      )
					torch.manual_seed(args.seed      )
					torch.cuda.manual_seed_all(args.seed      )

					__lowerCAmelCase					=							torch.device('cuda' if torch.cuda.is_available() else 'cpu'      )
					__lowerCAmelCase					=							torch.cuda.device_count()
					logger.info('device: {}, n_gpu {}'.format(UpperCAmelCase__		,					UpperCAmelCase__      )      )

					if not args.do_train and not args.do_eval:
										raise ValueError('At least one of `do_train` or `do_eval` must be True.'      )

					if not os.path.exists(args.output_dir      ):
										os.makedirs(args.output_dir      )

					# Load tokenizer and model
					# This loading functions also add new tokens and embeddings called `special tokens`
					# These new embeddings will be fine-tuned on the RocStories dataset
					__lowerCAmelCase					=							['_start_', '_delimiter_', '_classify_']
					__lowerCAmelCase					=							OpenAIGPTTokenizer.from_pretrained(args.model_name      )
					tokenizer.add_tokens(UpperCAmelCase__      )
					__lowerCAmelCase					=							tokenizer.convert_tokens_to_ids(UpperCAmelCase__      )
					__lowerCAmelCase					=							OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name      )
					model.resize_token_embeddings(len(UpperCAmelCase__      )      )
					model.to(UpperCAmelCase__      )

					# Load and encode the datasets
					def tokenize_and_encode(UpperCAmelCase__      ):
										if isinstance(UpperCAmelCase__		,					UpperCAmelCase__      ):
															return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(UpperCAmelCase__      )      )
										elif isinstance(UpperCAmelCase__		,					UpperCAmelCase__      ):
															return obj
										return [tokenize_and_encode(UpperCAmelCase__      ) for o in obj]

					logger.info('Encoding dataset...'      )
					__lowerCAmelCase					=							load_rocstories_dataset(args.train_dataset      )
					__lowerCAmelCase					=							load_rocstories_dataset(args.eval_dataset      )
					__lowerCAmelCase					=							(train_dataset, eval_dataset)
					__lowerCAmelCase					=							tokenize_and_encode(UpperCAmelCase__      )

					# Compute the max input length for the Transformer
					__lowerCAmelCase					=							model.config.n_positions // 2 - 2
					__lowerCAmelCase					=							max(
					    len(story[:max_length]      ) + max(len(conta[:max_length]      )		,					len(conta[:max_length]      )      ) + 3
					    for dataset in encoded_datasets
					    for story, conta, conta, _ in dataset      )
					__lowerCAmelCase					=							min(UpperCAmelCase__		,					model.config.n_positions      )  # Max size of input for the pre-trained model

					# Prepare inputs tensors and dataloaders
					__lowerCAmelCase					=							pre_process_datasets(UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__		,					*UpperCAmelCase__      )
					__lowerCAmelCase,	__lowerCAmelCase					=							tensor_datasets[0], tensor_datasets[1]

					__lowerCAmelCase					=							TensorDataset(*UpperCAmelCase__      )
					__lowerCAmelCase					=							RandomSampler(UpperCAmelCase__      )
					__lowerCAmelCase					=							DataLoader(UpperCAmelCase__		,					sampler=UpperCAmelCase__		,					batch_size=args.train_batch_size      )

					__lowerCAmelCase					=							TensorDataset(*UpperCAmelCase__      )
					__lowerCAmelCase					=							SequentialSampler(UpperCAmelCase__      )
					__lowerCAmelCase					=							DataLoader(UpperCAmelCase__		,					sampler=UpperCAmelCase__		,					batch_size=args.eval_batch_size      )

					# Prepare optimizer
					if args.do_train:
										if args.max_steps > 0:
															__lowerCAmelCase					=							args.max_steps
															__lowerCAmelCase					=							args.max_steps // (len(UpperCAmelCase__      ) // args.gradient_accumulation_steps) + 1
										else:
															__lowerCAmelCase					=							len(UpperCAmelCase__      ) // args.gradient_accumulation_steps * args.num_train_epochs

										__lowerCAmelCase					=							list(model.named_parameters()      )
										__lowerCAmelCase					=							['bias', 'LayerNorm.bias', 'LayerNorm.weight']
										__lowerCAmelCase					=							[
										    {
										        'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay      )],
										        'weight_decay': args.weight_decay,
										    },
										    {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay      )], 'weight_decay': 0.0},
										]
										__lowerCAmelCase					=							AdamW(UpperCAmelCase__		,					lr=args.learning_rate		,					eps=args.adam_epsilon      )
										__lowerCAmelCase					=							get_linear_schedule_with_warmup(
										    UpperCAmelCase__		,					num_warmup_steps=args.warmup_steps		,					num_training_steps=UpperCAmelCase__      )

					if args.do_train:
										__lowerCAmelCase,	__lowerCAmelCase,	__lowerCAmelCase					=							0, 0, None
										model.train()
										for _ in trange(int(args.num_train_epochs      )		,					desc='Epoch'      ):
															__lowerCAmelCase					=							0
															__lowerCAmelCase					=							0
															__lowerCAmelCase					=							tqdm(UpperCAmelCase__		,					desc='Training'      )
															for step, batch in enumerate(UpperCAmelCase__      ):
																				__lowerCAmelCase					=							tuple(t.to(UpperCAmelCase__      ) for t in batch      )
																				__lowerCAmelCase,	__lowerCAmelCase,	__lowerCAmelCase,	__lowerCAmelCase					=							batch
																				__lowerCAmelCase					=							model(UpperCAmelCase__		,					mc_token_ids=UpperCAmelCase__		,					lm_labels=UpperCAmelCase__		,					mc_labels=UpperCAmelCase__      )
																				__lowerCAmelCase					=							args.lm_coef * losses[0] + losses[1]
																				loss.backward()
																				optimizer.step()
																				scheduler.step()
																				optimizer.zero_grad()
																				tr_loss += loss.item()
																				__lowerCAmelCase					=							(
																				    loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
																				)
																				nb_tr_steps += 1
																				__lowerCAmelCase					=							'Training loss: {:.2e} lr: {:.2e}'.format(UpperCAmelCase__		,					scheduler.get_lr()[0]      )

    # Save a trained model
					if args.do_train:
										# Save a trained model, configuration and tokenizer
										__lowerCAmelCase					=							model.module if hasattr(UpperCAmelCase__		,					'module'      ) else model  # Only save the model itself

										# If we save using the predefined names, we can load using `from_pretrained`
										__lowerCAmelCase					=							os.path.join(args.output_dir		,					UpperCAmelCase__      )
										__lowerCAmelCase					=							os.path.join(args.output_dir		,					UpperCAmelCase__      )

										torch.save(model_to_save.state_dict()		,					UpperCAmelCase__      )
										model_to_save.config.to_json_file(UpperCAmelCase__      )
										tokenizer.save_vocabulary(args.output_dir      )

										# Load a trained model and vocabulary that you have fine-tuned
										__lowerCAmelCase					=							OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir      )
										__lowerCAmelCase					=							OpenAIGPTTokenizer.from_pretrained(args.output_dir      )
										model.to(UpperCAmelCase__      )

					if args.do_eval:
										model.eval()
										__lowerCAmelCase,	__lowerCAmelCase					=							0, 0
										__lowerCAmelCase,	__lowerCAmelCase					=							0, 0
										for batch in tqdm(UpperCAmelCase__		,					desc='Evaluating'      ):
															__lowerCAmelCase					=							tuple(t.to(UpperCAmelCase__      ) for t in batch      )
															__lowerCAmelCase,	__lowerCAmelCase,	__lowerCAmelCase,	__lowerCAmelCase					=							batch
															with torch.no_grad():
																				__lowerCAmelCase,	__lowerCAmelCase,	__lowerCAmelCase,	__lowerCAmelCase					=							model(
																				    UpperCAmelCase__		,					mc_token_ids=UpperCAmelCase__		,					lm_labels=UpperCAmelCase__		,					mc_labels=UpperCAmelCase__      )

															__lowerCAmelCase					=							mc_logits.detach().cpu().numpy()
															__lowerCAmelCase					=							mc_labels.to('cpu'      ).numpy()
															__lowerCAmelCase					=							accuracy(UpperCAmelCase__		,					UpperCAmelCase__      )

															eval_loss += mc_loss.mean().item()
															eval_accuracy += tmp_eval_accuracy

															nb_eval_examples += input_ids.size(0      )
															nb_eval_steps += 1

										__lowerCAmelCase					=							eval_loss / nb_eval_steps
										__lowerCAmelCase					=							eval_accuracy / nb_eval_examples
										__lowerCAmelCase					=							tr_loss / nb_tr_steps if args.do_train else None
										__lowerCAmelCase					=							{'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

										__lowerCAmelCase					=							os.path.join(args.output_dir		,					'eval_results.txt'      )
										with open(UpperCAmelCase__		,					'w'      ) as writer:
															logger.info('***** Eval results *****'      )
															for key in sorted(result.keys()      ):
																				logger.info('  %s = %s'		,					UpperCAmelCase__		,					str(result[key]      )      )
																				writer.write('%s = %s\n' % (key, str(result[key]      ))      )


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     snake_case_			(				_a							):


							"""simple docstring"""





							__UpperCAmelCase       =42





class     snake_case_			(				_a			, _a							):


							"""simple docstring"""





							__UpperCAmelCase       =True




							@register_to_config
							def __init__( self					,						_A = 3					,						_A = 3					,						_A = ("DownEncoderBlock2D",)					,						_A = ("UpDecoderBlock2D",)					,						_A = (6_4,)					,						_A = 1					,						_A = "silu"					,						_A = 4					,						_A = 3_2					,						_A = 3_2					,						_A = 0.1_8215					,						):
												super().__init__()

												# pass init params to Encoder
												__lowerCAmelCase					=							Encoder(
												    in_channels=_A					,						out_channels=_A					,						down_block_types=_A					,						block_out_channels=_A					,						layers_per_block=_A					,						act_fn=_A					,						norm_num_groups=_A					,						double_z=_A					,						)

												# pass init params to Decoder
												__lowerCAmelCase					=							Decoder(
												    in_channels=_A					,						out_channels=_A					,						up_block_types=_A					,						block_out_channels=_A					,						layers_per_block=_A					,						norm_num_groups=_A					,						act_fn=_A					,						)

												__lowerCAmelCase					=							nn.Convad(2 * latent_channels					,						2 * latent_channels					,						1							)
												__lowerCAmelCase					=							nn.Convad(_A					,						_A					,						1							)

												__lowerCAmelCase					=							False
												__lowerCAmelCase					=							False

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




							def        A__  ( self					,						_A					,						_A=False							):
												if isinstance(_A					,						(Encoder, Decoder)							):
																	__lowerCAmelCase					=							value




							def        A__  ( self					,						_A = True							):
												__lowerCAmelCase					=							use_tiling




							def        A__  ( self							):
												self.enable_tiling(_A							)




							def        A__  ( self							):
												__lowerCAmelCase					=							True




							def        A__  ( self							):
												__lowerCAmelCase					=							False




							@property
							# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
							def        A__  ( self							):
												__lowerCAmelCase					=							{}

												def fn_recursive_add_processors(_A					,						_A					,						_A							):
																	if hasattr(_A					,						'set_processor'							):
																						__lowerCAmelCase					=							module.processor

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

																	return processors

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

												return processors




							def        A__  ( self					,						_A							):
												__lowerCAmelCase					=							len(self.attn_processors.keys()							)

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

												def fn_recursive_attn_processor(_A					,						_A					,						_A							):
																	if hasattr(_A					,						'set_processor'							):
																						if not isinstance(_A					,						_A							):
																											module.set_processor(_A							)
																						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}"""					,						_A					,						_A							)

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




							def        A__  ( self							):
												self.set_attn_processor(AttnProcessor()							)




							@apply_forward_hook
							def        A__  ( self					,						_A					,						_A = True							):
												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(_A					,						return_dict=_A							)

												if self.use_slicing and x.shape[0] > 1:
																	__lowerCAmelCase					=							[self.encoder(_A							) for x_slice in x.split(1							)]
																	__lowerCAmelCase					=							torch.cat(_A							)
												else:
																	__lowerCAmelCase					=							self.encoder(_A							)

												__lowerCAmelCase					=							self.quant_conv(_A							)
												__lowerCAmelCase					=							DiagonalGaussianDistribution(_A							)

												if not return_dict:
																	return (posterior,)

												return AutoencoderKLOutput(latent_dist=_A							)




							def        A__  ( self					,						_A					,						_A = True							):
												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(_A					,						return_dict=_A							)

												__lowerCAmelCase					=							self.post_quant_conv(_A							)
												__lowerCAmelCase					=							self.decoder(_A							)

												if not return_dict:
																	return (dec,)

												return DecoderOutput(sample=_A							)




							@apply_forward_hook
							def        A__  ( self					,						_A					,						_A = True							):
												if self.use_slicing and z.shape[0] > 1:
																	__lowerCAmelCase					=							[self._decode(_A							).sample for z_slice in z.split(1							)]
																	__lowerCAmelCase					=							torch.cat(_A							)
												else:
																	__lowerCAmelCase					=							self._decode(_A							).sample

												if not return_dict:
																	return (decoded,)

												return DecoderOutput(sample=_A							)




							def        A__  ( self					,						_A					,						_A					,						_A							):
												__lowerCAmelCase					=							min(a.shape[2]					,						b.shape[2]					,						_A							)
												for y in range(_A							):
																	__lowerCAmelCase					=							a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
												return b




							def        A__  ( self					,						_A					,						_A					,						_A							):
												__lowerCAmelCase					=							min(a.shape[3]					,						b.shape[3]					,						_A							)
												for x in range(_A							):
																	__lowerCAmelCase					=							a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
												return b




							def        A__  ( self					,						_A					,						_A = True							):
												__lowerCAmelCase					=							int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)							)
												__lowerCAmelCase					=							int(self.tile_latent_min_size * self.tile_overlap_factor							)
												__lowerCAmelCase					=							self.tile_latent_min_size - blend_extent

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

												__lowerCAmelCase					=							torch.cat(_A					,						dim=2							)
												__lowerCAmelCase					=							DiagonalGaussianDistribution(_A							)

												if not return_dict:
																	return (posterior,)

												return AutoencoderKLOutput(latent_dist=_A							)




							def        A__  ( self					,						_A					,						_A = True							):
												__lowerCAmelCase					=							int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)							)
												__lowerCAmelCase					=							int(self.tile_sample_min_size * self.tile_overlap_factor							)
												__lowerCAmelCase					=							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.
												__lowerCAmelCase					=							[]
												for i in range(0					,						z.shape[2]					,						_A							):
																	__lowerCAmelCase					=							[]
																	for j in range(0					,						z.shape[3]					,						_A							):
																						__lowerCAmelCase					=							z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
																						__lowerCAmelCase					=							self.post_quant_conv(_A							)
																						__lowerCAmelCase					=							self.decoder(_A							)
																						row.append(_A							)
																	rows.append(_A							)
												__lowerCAmelCase					=							[]
												for i, row in enumerate(_A							):
																	__lowerCAmelCase					=							[]
																	for j, tile in enumerate(_A							):
																						# blend the above tile and the left tile
																						# to the current tile and add the current tile to the result row
																						if i > 0:
																											__lowerCAmelCase					=							self.blend_v(rows[i - 1][j]					,						_A					,						_A							)
																						if j > 0:
																											__lowerCAmelCase					=							self.blend_h(row[j - 1]					,						_A					,						_A							)
																						result_row.append(tile[:, :, :row_limit, :row_limit]							)
																	result_rows.append(torch.cat(_A					,						dim=3							)							)

												__lowerCAmelCase					=							torch.cat(_A					,						dim=2							)
												if not return_dict:
																	return (dec,)

												return DecoderOutput(sample=_A							)




							def        A__  ( self					,						_A					,						_A = False					,						_A = True					,						_A = None					,						):
												__lowerCAmelCase					=							sample
												__lowerCAmelCase					=							self.encode(_A							).latent_dist
												if sample_posterior:
																	__lowerCAmelCase					=							posterior.sample(generator=_A							)
												else:
																	__lowerCAmelCase					=							posterior.mode()
												__lowerCAmelCase					=							self.decode(_A							).sample

												if not return_dict:
																	return (dec,)

												return DecoderOutput(sample=_A							)






