
import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
					    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
					    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
					    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
					    LayoutLMvaConfig,
					    LayoutLMvaForQuestionAnswering,
					    LayoutLMvaForSequenceClassification,
					    LayoutLMvaForTokenClassification,
					    LayoutLMvaModel,
					)
					from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
					from PIL import Image

					from transformers import LayoutLMvaImageProcessor


class     lowercase :



		def __init__(			self    ,				A_    ,				A_=2    ,				A_=3    ,				A_=4    ,				A_=2    ,				A_=7    ,				A_=True    ,				A_=True    ,				A_=True    ,				A_=True    ,				A_=99    ,				A_=36    ,				A_=3    ,				A_=4    ,				A_=37    ,				A_="gelu"    ,				A_=0.1    ,				A_=0.1    ,				A_=512    ,				A_=16    ,				A_=2    ,				A_=0.02    ,				A_=6    ,				A_=6    ,				A_=3    ,				A_=4    ,				A_=None    ,				A_=1_000    ,				)  -> str:
				"""simple docstring"""
				UpperCamelCase          =					parent
				UpperCamelCase          =					batch_size
				UpperCamelCase          =					num_channels
				UpperCamelCase          =					image_size
				UpperCamelCase          =					patch_size
				UpperCamelCase          =					text_seq_length
				UpperCamelCase          =					is_training
				UpperCamelCase          =					use_input_mask
				UpperCamelCase          =					use_token_type_ids
				UpperCamelCase          =					use_labels
				UpperCamelCase          =					vocab_size
				UpperCamelCase          =					hidden_size
				UpperCamelCase          =					num_hidden_layers
				UpperCamelCase          =					num_attention_heads
				UpperCamelCase          =					intermediate_size
				UpperCamelCase          =					hidden_act
				UpperCamelCase          =					hidden_dropout_prob
				UpperCamelCase          =					attention_probs_dropout_prob
				UpperCamelCase          =					max_position_embeddings
				UpperCamelCase          =					type_vocab_size
				UpperCamelCase          =					type_sequence_label_size
				UpperCamelCase          =					initializer_range
				UpperCamelCase          =					coordinate_size
				UpperCamelCase          =					shape_size
				UpperCamelCase          =					num_labels
				UpperCamelCase          =					num_choices
				UpperCamelCase          =					scope
				UpperCamelCase          =					range_bbox

				# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
				UpperCamelCase          =					text_seq_length
				UpperCamelCase          =					(image_size // patch_size) ** 2 + 1
				UpperCamelCase          =					self.text_seq_length + self.image_seq_length



		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				UpperCamelCase          =					ids_tensor([self.batch_size, self.text_seq_length]    ,				self.vocab_size	)

				UpperCamelCase          =					ids_tensor([self.batch_size, self.text_seq_length, 4]    ,				self.range_bbox	)
				# Ensure that bbox is legal
				for i in range(bbox.shape[0]	):
						for j in range(bbox.shape[1]	):
								if bbox[i, j, 3] < bbox[i, j, 1]:
										UpperCamelCase          =					bbox[i, j, 3]
										UpperCamelCase          =					bbox[i, j, 1]
										UpperCamelCase          =					t
								if bbox[i, j, 2] < bbox[i, j, 0]:
										UpperCamelCase          =					bbox[i, j, 2]
										UpperCamelCase          =					bbox[i, j, 0]
										UpperCamelCase          =					t

				UpperCamelCase          =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

				UpperCamelCase          =					None
				if self.use_input_mask:
						UpperCamelCase          =					random_attention_mask([self.batch_size, self.text_seq_length]	)

				UpperCamelCase          =					None
				if self.use_token_type_ids:
						UpperCamelCase          =					ids_tensor([self.batch_size, self.text_seq_length]    ,				self.type_vocab_size	)

				UpperCamelCase          =					None
				UpperCamelCase          =					None
				if self.use_labels:
						UpperCamelCase          =					ids_tensor([self.batch_size]    ,				self.type_sequence_label_size	)
						UpperCamelCase          =					ids_tensor([self.batch_size, self.text_seq_length]    ,				self.num_labels	)

				UpperCamelCase          =					LayoutLMvaConfig(
				    vocab_size=self.vocab_size    ,				hidden_size=self.hidden_size    ,				num_hidden_layers=self.num_hidden_layers    ,				num_attention_heads=self.num_attention_heads    ,				intermediate_size=self.intermediate_size    ,				hidden_act=self.hidden_act    ,				hidden_dropout_prob=self.hidden_dropout_prob    ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,				max_position_embeddings=self.max_position_embeddings    ,				type_vocab_size=self.type_vocab_size    ,				initializer_range=self.initializer_range    ,				coordinate_size=self.coordinate_size    ,				shape_size=self.shape_size    ,				input_size=self.image_size    ,				patch_size=self.patch_size    ,				)

				return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> int:
				"""simple docstring"""
				UpperCamelCase          =					LayoutLMvaModel(config=A_	)
				model.to(A_	)
				model.eval()

				# text + image
				UpperCamelCase          =					model(A_    ,				pixel_values=A_	)
				UpperCamelCase          =					model(
				    A_    ,				bbox=A_    ,				pixel_values=A_    ,				attention_mask=A_    ,				token_type_ids=A_	)
				UpperCamelCase          =					model(A_    ,				bbox=A_    ,				pixel_values=A_    ,				token_type_ids=A_	)
				UpperCamelCase          =					model(A_    ,				bbox=A_    ,				pixel_values=A_	)

				self.parent.assertEqual(result.last_hidden_state.shape    ,				(self.batch_size, self.seq_length, self.hidden_size)	)

				# text only
				UpperCamelCase          =					model(A_	)
				self.parent.assertEqual(
				    result.last_hidden_state.shape    ,				(self.batch_size, self.text_seq_length, self.hidden_size)	)

				# image only
				UpperCamelCase          =					model(pixel_values=A_	)
				self.parent.assertEqual(
				    result.last_hidden_state.shape    ,				(self.batch_size, self.image_seq_length, self.hidden_size)	)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> Optional[Any]:
				"""simple docstring"""
				UpperCamelCase          =					self.num_labels
				UpperCamelCase          =					LayoutLMvaForSequenceClassification(A_	)
				model.to(A_	)
				model.eval()
				UpperCamelCase          =					model(
				    A_    ,				bbox=A_    ,				pixel_values=A_    ,				attention_mask=A_    ,				token_type_ids=A_    ,				labels=A_    ,				)
				self.parent.assertEqual(result.logits.shape    ,				(self.batch_size, self.num_labels)	)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> Dict:
				"""simple docstring"""
				UpperCamelCase          =					self.num_labels
				UpperCamelCase          =					LayoutLMvaForTokenClassification(config=A_	)
				model.to(A_	)
				model.eval()
				UpperCamelCase          =					model(
				    A_    ,				bbox=A_    ,				pixel_values=A_    ,				attention_mask=A_    ,				token_type_ids=A_    ,				labels=A_    ,				)
				self.parent.assertEqual(result.logits.shape    ,				(self.batch_size, self.text_seq_length, self.num_labels)	)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> List[str]:
				"""simple docstring"""
				UpperCamelCase          =					LayoutLMvaForQuestionAnswering(config=A_	)
				model.to(A_	)
				model.eval()
				UpperCamelCase          =					model(
				    A_    ,				bbox=A_    ,				pixel_values=A_    ,				attention_mask=A_    ,				token_type_ids=A_    ,				start_positions=A_    ,				end_positions=A_    ,				)
				self.parent.assertEqual(result.start_logits.shape    ,				(self.batch_size, self.seq_length)	)
				self.parent.assertEqual(result.end_logits.shape    ,				(self.batch_size, self.seq_length)	)



		def __UpperCamelCase			(			self	)  -> int:
				"""simple docstring"""
				UpperCamelCase          =					self.prepare_config_and_inputs()
				(
				    (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  (
				    UpperCamelCase
				)     ,  
				)          =					config_and_inputs
				UpperCamelCase          =					{
				    'input_ids': input_ids,
				    'bbox': bbox,
				    'pixel_values': pixel_values,
				    'token_type_ids': token_type_ids,
				    'attention_mask': input_mask,
				}
				return config, inputs_dict






@require_torch
class     lowercase (		_SCREAMING_SNAKE_CASE  ,       _SCREAMING_SNAKE_CASE  ,       unittest.TestCase       ):
		__lowercase	:	Tuple     					=    False
		__lowercase	:	List[Any]     					=    False
		__lowercase	:	str     					=    False

		__lowercase	:	Tuple     					=    (
		    (
		        LayoutLMvaModel,
		        LayoutLMvaForSequenceClassification,
		        LayoutLMvaForTokenClassification,
		        LayoutLMvaForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		__lowercase	:	List[str]     					=    (
		    {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel}
		    if is_torch_available()
		    else {}
		)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_    ,				A_    ,				A_	)  -> int:
				"""simple docstring"""
				# `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
				# embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
				# the sequence dimension of the text embedding only.
				# (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
				return True



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				UpperCamelCase          =					LayoutLMvaModelTester(self	)
				UpperCamelCase          =					ConfigTester(self    ,				config_class=A_    ,				hidden_size=37	)



		def __UpperCamelCase			(			self    ,				A_    ,				A_    ,				A_=False	)  -> int:
				"""simple docstring"""
				UpperCamelCase          =					copy.deepcopy(A_	)
				if model_class in get_values(A_	):
						UpperCamelCase          =					{
						    k: v.unsqueeze(1	).expand(-1    ,				self.model_tester.num_choices    ,				-1	).contiguous()
						    if isinstance(A_    ,				torch.Tensor	) and v.ndim > 1
						    else v
						    for k, v in inputs_dict.items()
						}
				if return_labels:
						if model_class in get_values(A_	):
								UpperCamelCase          =					torch.ones(self.model_tester.batch_size    ,				dtype=torch.long    ,				device=A_	)
						elif model_class in get_values(A_	):
								UpperCamelCase          =					torch.zeros(
								    self.model_tester.batch_size    ,				dtype=torch.long    ,				device=A_	)
								UpperCamelCase          =					torch.zeros(
								    self.model_tester.batch_size    ,				dtype=torch.long    ,				device=A_	)
						elif model_class in [
						    *get_values(A_	),
						]:
								UpperCamelCase          =					torch.zeros(
								    self.model_tester.batch_size    ,				dtype=torch.long    ,				device=A_	)
						elif model_class in [
						    *get_values(A_	),
						]:
								UpperCamelCase          =					torch.zeros(
								    (self.model_tester.batch_size, self.model_tester.text_seq_length)    ,				dtype=torch.long    ,				device=A_    ,				)

				return inputs_dict



		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				self.config_tester.run_common_tests()



		def __UpperCamelCase			(			self	)  -> str:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*A_	)



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				for type in ["absolute", "relative_key", "relative_key_query"]:
						UpperCamelCase          =					type
						self.model_tester.create_and_check_model(*A_	)



		def __UpperCamelCase			(			self	)  -> List[Any]:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_sequence_classification(*A_	)



		def __UpperCamelCase			(			self	)  -> Optional[Any]:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_token_classification(*A_	)



		def __UpperCamelCase			(			self	)  -> Union[str, Any]:
				"""simple docstring"""
				UpperCamelCase          =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_question_answering(*A_	)



		@slow
		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						UpperCamelCase          =					LayoutLMvaModel.from_pretrained(A_	)
						self.assertIsNotNone(A_	)






def 				A	( )       ->  int:
		'''simple docstring'''

		UpperCamelCase          =					Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
		return image


@require_torch
class     lowercase (		unittest.TestCase       ):



		@cached_property
		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				return LayoutLMvaImageProcessor(apply_ocr=A_	) if is_vision_available() else None



		@slow
		def __UpperCamelCase			(			self	)  -> Optional[int]:
				"""simple docstring"""
				UpperCamelCase          =					LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'	).to(A_	)

				UpperCamelCase          =					self.default_image_processor
				UpperCamelCase          =					prepare_img()
				UpperCamelCase          =					image_processor(images=A_    ,				return_tensors='pt'	).pixel_values.to(A_	)

				UpperCamelCase          =					torch.tensor([[1, 2]]	)
				UpperCamelCase          =					torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]	).unsqueeze(0	)

				# forward pass
				UpperCamelCase          =					model(
				    input_ids=input_ids.to(A_	)    ,				bbox=bbox.to(A_	)    ,				pixel_values=pixel_values.to(A_	)    ,				)

				# verify the logits
				UpperCamelCase          =					torch.Size((1, 199, 768)	)
				self.assertEqual(outputs.last_hidden_state.shape    ,				A_	)

				UpperCamelCase          =					torch.tensor(
				    [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]	).to(A_	)

				self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]    ,				A_    ,				atol=1e-4	)	)


from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block


@dataclass
class     lowercase (		_SCREAMING_SNAKE_CASE       ):
		__lowercase	:	torch.FloatTensor






class     lowercase (		nn.Module       ):



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

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

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

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

						UpperCamelCase          =					get_down_block(
						    A_    ,				num_layers=self.layers_per_block    ,				in_channels=A_    ,				out_channels=A_    ,				add_downsample=not is_final_block    ,				resnet_eps=1e-6    ,				downsample_padding=0    ,				resnet_act_fn=A_    ,				resnet_groups=A_    ,				attention_head_dim=A_    ,				temb_channels=A_    ,				)
						self.down_blocks.append(A_	)

				# mid
				UpperCamelCase          =					UNetMidBlockaD(
				    in_channels=block_out_channels[-1]    ,				resnet_eps=1e-6    ,				resnet_act_fn=A_    ,				output_scale_factor=1    ,				resnet_time_scale_shift='default'    ,				attention_head_dim=block_out_channels[-1]    ,				resnet_groups=A_    ,				temb_channels=A_    ,				)

				# out
				UpperCamelCase          =					nn.GroupNorm(num_channels=block_out_channels[-1]    ,				num_groups=A_    ,				eps=1e-6	)
				UpperCamelCase          =					nn.SiLU()

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

				UpperCamelCase          =					False



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

				if self.training and self.gradient_checkpointing:

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

								return custom_forward

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

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

						# middle
						UpperCamelCase          =					self.mid_block(A_	)

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

				return sample






class     lowercase (		nn.Module       ):



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

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

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

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

				# mid
				UpperCamelCase          =					UNetMidBlockaD(
				    in_channels=block_out_channels[-1]    ,				resnet_eps=1e-6    ,				resnet_act_fn=A_    ,				output_scale_factor=1    ,				resnet_time_scale_shift='default' if norm_type == 'group' else norm_type    ,				attention_head_dim=block_out_channels[-1]    ,				resnet_groups=A_    ,				temb_channels=A_    ,				)

				# up
				UpperCamelCase          =					list(reversed(A_	)	)
				UpperCamelCase          =					reversed_block_out_channels[0]
				for i, up_block_type in enumerate(A_	):
						UpperCamelCase          =					output_channel
						UpperCamelCase          =					reversed_block_out_channels[i]

						UpperCamelCase          =					i == len(A_	) - 1

						UpperCamelCase          =					get_up_block(
						    A_    ,				num_layers=self.layers_per_block + 1    ,				in_channels=A_    ,				out_channels=A_    ,				prev_output_channel=A_    ,				add_upsample=not is_final_block    ,				resnet_eps=1e-6    ,				resnet_act_fn=A_    ,				resnet_groups=A_    ,				attention_head_dim=A_    ,				temb_channels=A_    ,				resnet_time_scale_shift=A_    ,				)
						self.up_blocks.append(A_	)
						UpperCamelCase          =					output_channel

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

				UpperCamelCase          =					False



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

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

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

								return custom_forward

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

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

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

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

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

				return sample






class     lowercase (		nn.Module       ):



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

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

				UpperCamelCase          =					remap
				if self.remap is not None:
						self.register_buffer('used'    ,				torch.tensor(np.load(self.remap	)	)	)
						UpperCamelCase          =					self.used.shape[0]
						UpperCamelCase          =					unknown_index  # "random" or "extra" or integer
						if self.unknown_index == "extra":
								UpperCamelCase          =					self.re_embed
								UpperCamelCase          =					self.re_embed + 1
						print(
						    F'''Remapping {self.n_e} indices to {self.re_embed} indices. '''
						    F'''Using {self.unknown_index} for unknown indices.'''	)
				else:
						UpperCamelCase          =					n_e

				UpperCamelCase          =					sane_index_shape



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



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



		def __UpperCamelCase			(			self    ,				A_	)  -> List[str]:
				"""simple docstring"""
				# reshape z -> (batch, height, width, channel) and flatten
				UpperCamelCase          =					z.permute(0    ,				2    ,				3    ,				1	).contiguous()
				UpperCamelCase          =					z.view(-1    ,				self.vq_embed_dim	)

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

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

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

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

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

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

				if self.sane_index_shape:
						UpperCamelCase          =					min_encoding_indices.reshape(z_q.shape[0]    ,				z_q.shape[2]    ,				z_q.shape[3]	)

				return z_q, loss, (perplexity, min_encodings, min_encoding_indices)



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

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

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

				return z_q






class     lowercase (		_SCREAMING_SNAKE_CASE       ):



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



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



		def __UpperCamelCase			(			self    ,				A_=None	)  -> Tuple:
				"""simple docstring"""
				if self.deterministic:
						return torch.Tensor([0.0]	)
				else:
						if other is None:
								return 0.5 * torch.sum(torch.pow(self.mean    ,				2	) + self.var - 1.0 - self.logvar    ,				dim=[1, 2, 3]	)
						else:
								return 0.5 * torch.sum(
								    torch.pow(self.mean - other.mean    ,				2	) / other.var
								    + self.var / other.var
								    - 1.0
								    - self.logvar
								    + other.logvar    ,				dim=[1, 2, 3]    ,				)



		def __UpperCamelCase			(			self    ,				A_    ,				A_=[1, 2, 3]	)  -> Optional[Any]:
				"""simple docstring"""
				if self.deterministic:
						return torch.Tensor([0.0]	)
				UpperCamelCase          =					np.log(2.0 * np.pi	)
				return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean    ,				2	) / self.var    ,				dim=A_	)



		def __UpperCamelCase			(			self	)  -> Union[str, Any]:
				"""simple docstring"""
				return self.mean
