





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				(							a_     ):



						"""simple docstring"""

						_UpperCamelCase  :	torch.FloatTensor



class 			lowercase				(							nn.Module     ):



						"""simple docstring"""

						def __init__(    self			:		Optional[int] ,				lowerCamelCase_			:		Union[str, Any]=3 ,				lowerCamelCase_			:		Any=3 ,				lowerCamelCase_			:		Any=("DownEncoderBlock2D",) ,				lowerCamelCase_			:		Dict=(64,) ,				lowerCamelCase_			:		List[str]=2 ,				lowerCamelCase_			:		Optional[Any]=32 ,				lowerCamelCase_			:		Optional[int]="silu" ,				lowerCamelCase_			:		List[str]=True ,				):





										'''simple docstring'''







										super().__init__()
										_snake_case :			Optional[int]  						=   layers_per_block

										_snake_case :			str  						=   torch.nn.Convad(
										    lowerCamelCase_ ,				block_out_channels[0] ,				kernel_size=3 ,				stride=1 ,				padding=1 ,				)

										_snake_case :			Optional[int]  						=   None
										_snake_case :			Optional[int]  						=   nn.ModuleList([]					)

										# down
										_snake_case :			Any  						=   block_out_channels[0]
										for i, down_block_type in enumerate(lowerCamelCase_					):
														_snake_case :			List[Any]  						=   output_channel
														_snake_case :			Tuple  						=   block_out_channels[i]
														_snake_case :			List[str]  						=   i == len(lowerCamelCase_					) - 1

														_snake_case :			List[str]  						=   get_down_block(
														    lowerCamelCase_ ,				num_layers=self.layers_per_block ,				in_channels=lowerCamelCase_ ,				out_channels=lowerCamelCase_ ,				add_downsample=not is_final_block ,				resnet_eps=1e-6 ,				downsample_padding=0 ,				resnet_act_fn=lowerCamelCase_ ,				resnet_groups=lowerCamelCase_ ,				attention_head_dim=lowerCamelCase_ ,				temb_channels=lowerCamelCase_ ,				)
														self.down_blocks.append(lowerCamelCase_					)

										# mid
										_snake_case :			Optional[int]  						=   UNetMidBlockaD(
										    in_channels=block_out_channels[-1] ,				resnet_eps=1e-6 ,				resnet_act_fn=lowerCamelCase_ ,				output_scale_factor=1 ,				resnet_time_scale_shift='default' ,				attention_head_dim=block_out_channels[-1] ,				resnet_groups=lowerCamelCase_ ,				temb_channels=lowerCamelCase_ ,				)

										# out
										_snake_case :			int  						=   nn.GroupNorm(num_channels=block_out_channels[-1] ,				num_groups=lowerCamelCase_ ,				eps=1e-6					)
										_snake_case :			Optional[int]  						=   nn.SiLU()

										_snake_case :			List[Any]  						=   2 * out_channels if double_z else out_channels
										_snake_case :			int  						=   nn.Convad(block_out_channels[-1] ,				lowerCamelCase_ ,				3 ,				padding=1					)

										_snake_case :			str  						=   False







						def 		__UpperCAmelCase       (    self			:		Tuple ,				lowerCamelCase_			:		str					):





										'''simple docstring'''







										_snake_case :			str  						=   x
										_snake_case :			Tuple  						=   self.conv_in(lowerCamelCase_					)

										if self.training and self.gradient_checkpointing:

														def create_custom_forward(lowerCamelCase_			:		List[str]					):
																		def custom_forward(*lowerCamelCase_			:		List[Any]					):
																						return module(*lowerCamelCase_					)

																		return custom_forward

														# down
														if is_torch_version('>=' ,				'1.11.0'					):
																		for down_block in self.down_blocks:
																						_snake_case :			List[Any]  						=   torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(lowerCamelCase_					) ,				lowerCamelCase_ ,				use_reentrant=lowerCamelCase_					)
																		# middle
																		_snake_case :			Union[str, Any]  						=   torch.utils.checkpoint.checkpoint(
																		    create_custom_forward(self.mid_block					) ,				lowerCamelCase_ ,				use_reentrant=lowerCamelCase_					)
														else:
																		for down_block in self.down_blocks:
																						_snake_case :			List[str]  						=   torch.utils.checkpoint.checkpoint(create_custom_forward(lowerCamelCase_					) ,				lowerCamelCase_					)
																		# middle
																		_snake_case :			Dict  						=   torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block					) ,				lowerCamelCase_					)

										else:
														# down
														for down_block in self.down_blocks:
																		_snake_case :			Tuple  						=   down_block(lowerCamelCase_					)

														# middle
														_snake_case :			List[str]  						=   self.mid_block(lowerCamelCase_					)

										# post-process
										_snake_case :			Optional[Any]  						=   self.conv_norm_out(lowerCamelCase_					)
										_snake_case :			int  						=   self.conv_act(lowerCamelCase_					)
										_snake_case :			Optional[Any]  						=   self.conv_out(lowerCamelCase_					)

										return sample



class 			lowercase				(							nn.Module     ):



						"""simple docstring"""

						def __init__(    self			:		List[Any] ,				lowerCamelCase_			:		str=3 ,				lowerCamelCase_			:		List[str]=3 ,				lowerCamelCase_			:		Dict=("UpDecoderBlock2D",) ,				lowerCamelCase_			:		Optional[Any]=(64,) ,				lowerCamelCase_			:		Optional[Any]=2 ,				lowerCamelCase_			:		List[str]=32 ,				lowerCamelCase_			:		List[Any]="silu" ,				lowerCamelCase_			:		Optional[Any]="group" ,				):





										'''simple docstring'''







										super().__init__()
										_snake_case :			Dict  						=   layers_per_block

										_snake_case :			Tuple  						=   nn.Convad(
										    lowerCamelCase_ ,				block_out_channels[-1] ,				kernel_size=3 ,				stride=1 ,				padding=1 ,				)

										_snake_case :			str  						=   None
										_snake_case :			List[Any]  						=   nn.ModuleList([]					)

										_snake_case :			str  						=   in_channels if norm_type == 'spatial' else None

										# mid
										_snake_case :			str  						=   UNetMidBlockaD(
										    in_channels=block_out_channels[-1] ,				resnet_eps=1e-6 ,				resnet_act_fn=lowerCamelCase_ ,				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=lowerCamelCase_ ,				temb_channels=lowerCamelCase_ ,				)

										# up
										_snake_case :			Tuple  						=   list(reversed(lowerCamelCase_					)					)
										_snake_case :			Tuple  						=   reversed_block_out_channels[0]
										for i, up_block_type in enumerate(lowerCamelCase_					):
														_snake_case :			int  						=   output_channel
														_snake_case :			Any  						=   reversed_block_out_channels[i]

														_snake_case :			Any  						=   i == len(lowerCamelCase_					) - 1

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

										# out
										if norm_type == "spatial":
														_snake_case :			Dict  						=   SpatialNorm(block_out_channels[0] ,				lowerCamelCase_					)
										else:
														_snake_case :			int  						=   nn.GroupNorm(num_channels=block_out_channels[0] ,				num_groups=lowerCamelCase_ ,				eps=1e-6					)
										_snake_case :			Optional[Any]  						=   nn.SiLU()
										_snake_case :			Optional[int]  						=   nn.Convad(block_out_channels[0] ,				lowerCamelCase_ ,				3 ,				padding=1					)

										_snake_case :			List[Any]  						=   False







						def 		__UpperCAmelCase       (    self			:		List[str] ,				lowerCamelCase_			:		Union[str, Any] ,				lowerCamelCase_			:		List[Any]=None					):





										'''simple docstring'''







										_snake_case :			Tuple  						=   z
										_snake_case :			Any  						=   self.conv_in(lowerCamelCase_					)

										_snake_case :			List[str]  						=   next(iter(self.up_blocks.parameters()					)					).dtype
										if self.training and self.gradient_checkpointing:

														def create_custom_forward(lowerCamelCase_			:		int					):
																		def custom_forward(*lowerCamelCase_			:		Dict					):
																						return module(*lowerCamelCase_					)

																		return custom_forward

														if is_torch_version('>=' ,				'1.11.0'					):
																		# middle
																		_snake_case :			List[Any]  						=   torch.utils.checkpoint.checkpoint(
																		    create_custom_forward(self.mid_block					) ,				lowerCamelCase_ ,				lowerCamelCase_ ,				use_reentrant=lowerCamelCase_					)
																		_snake_case :			List[str]  						=   sample.to(lowerCamelCase_					)

																		# up
																		for up_block in self.up_blocks:
																						_snake_case :			List[str]  						=   torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(lowerCamelCase_					) ,				lowerCamelCase_ ,				lowerCamelCase_ ,				use_reentrant=lowerCamelCase_					)
														else:
																		# middle
																		_snake_case :			str  						=   torch.utils.checkpoint.checkpoint(
																		    create_custom_forward(self.mid_block					) ,				lowerCamelCase_ ,				lowerCamelCase_					)
																		_snake_case :			Optional[int]  						=   sample.to(lowerCamelCase_					)

																		# up
																		for up_block in self.up_blocks:
																						_snake_case :			Dict  						=   torch.utils.checkpoint.checkpoint(create_custom_forward(lowerCamelCase_					) ,				lowerCamelCase_ ,				lowerCamelCase_					)
										else:
														# middle
														_snake_case :			List[Any]  						=   self.mid_block(lowerCamelCase_ ,				lowerCamelCase_					)
														_snake_case :			Any  						=   sample.to(lowerCamelCase_					)

														# up
														for up_block in self.up_blocks:
																		_snake_case :			str  						=   up_block(lowerCamelCase_ ,				lowerCamelCase_					)

        # post-process
										if latent_embeds is None:
														_snake_case :			Tuple  						=   self.conv_norm_out(lowerCamelCase_					)
										else:
														_snake_case :			List[Any]  						=   self.conv_norm_out(lowerCamelCase_ ,				lowerCamelCase_					)
										_snake_case :			Optional[Any]  						=   self.conv_act(lowerCamelCase_					)
										_snake_case :			Union[str, Any]  						=   self.conv_out(lowerCamelCase_					)

										return sample



class 			lowercase				(							nn.Module     ):



						"""simple docstring"""

						def __init__(    self			:		Optional[Any] ,				lowerCamelCase_			:		Optional[Any] ,				lowerCamelCase_			:		List[Any] ,				lowerCamelCase_			:		Dict ,				lowerCamelCase_			:		Union[str, Any]=None ,				lowerCamelCase_			:		List[Any]="random" ,				lowerCamelCase_			:		Union[str, Any]=False ,				lowerCamelCase_			:		str=True					):





										'''simple docstring'''







										super().__init__()
										_snake_case :			Optional[int]  						=   n_e
										_snake_case :			Dict  						=   vq_embed_dim
										_snake_case :			int  						=   beta
										_snake_case :			List[Any]  						=   legacy

										_snake_case :			Optional[int]  						=   nn.Embedding(self.n_e ,				self.vq_embed_dim					)
										self.embedding.weight.data.uniform_(-1.0 / self.n_e ,				1.0 / self.n_e					)

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

										_snake_case :			List[str]  						=   sane_index_shape







						def 		__UpperCAmelCase       (    self			:		List[Any] ,				lowerCamelCase_			:		str					):





										'''simple docstring'''







										_snake_case :			List[str]  						=   inds.shape
										assert len(lowerCamelCase_					) > 1
										_snake_case :			Union[str, Any]  						=   inds.reshape(ishape[0] ,				-1					)
										_snake_case :			List[str]  						=   self.used.to(lowerCamelCase_					)
										_snake_case :			List[Any]  						=   (inds[:, :, None] == used[None, None, ...]).long()
										_snake_case :			Union[str, Any]  						=   match.argmax(-1					)
										_snake_case :			Optional[int]  						=   match.sum(2					) < 1
										if self.unknown_index == "random":
														_snake_case :			str  						=   torch.randint(0 ,				self.re_embed ,				size=new[unknown].shape					).to(device=new.device					)
										else:
														_snake_case :			Tuple  						=   self.unknown_index
										return new.reshape(lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		Dict ,				lowerCamelCase_			:		Any					):





										'''simple docstring'''







										_snake_case :			Dict  						=   inds.shape
										assert len(lowerCamelCase_					) > 1
										_snake_case :			str  						=   inds.reshape(ishape[0] ,				-1					)
										_snake_case :			Dict  						=   self.used.to(lowerCamelCase_					)
										if self.re_embed > self.used.shape[0]:  # extra token
														_snake_case :			Tuple  						=   0  # simply set to zero
										_snake_case :			Union[str, Any]  						=   torch.gather(used[None, :][inds.shape[0] * [0], :] ,				1 ,				lowerCamelCase_					)
										return back.reshape(lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		Optional[Any] ,				lowerCamelCase_			:		Optional[Any]					):





										'''simple docstring'''







										_snake_case :			Tuple  						=   z.permute(0 ,				2 ,				3 ,				1					).contiguous()
										_snake_case :			Tuple  						=   z.view(-1 ,				self.vq_embed_dim					)

										# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
										_snake_case :			Optional[Any]  						=   torch.argmin(torch.cdist(lowerCamelCase_ ,				self.embedding.weight					) ,				dim=1					)

										_snake_case :			Any  						=   self.embedding(lowerCamelCase_					).view(z.shape					)
										_snake_case :			Union[str, Any]  						=   None
										_snake_case :			Dict  						=   None

										# compute loss for embedding
										if not self.legacy:
														_snake_case :			List[Any]  						=   self.beta * torch.mean((z_q.detach() - z) ** 2					) + torch.mean((z_q - z.detach()) ** 2					)
										else:
														_snake_case :			Optional[int]  						=   torch.mean((z_q.detach() - z) ** 2					) + self.beta * torch.mean((z_q - z.detach()) ** 2					)

										# preserve gradients
										_snake_case :			Tuple  						=   z + (z_q - z).detach()

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

										if self.remap is not None:
														_snake_case :			Tuple  						=   min_encoding_indices.reshape(z.shape[0] ,				-1					)  # add batch axis
														_snake_case :			Union[str, Any]  						=   self.remap_to_used(lowerCamelCase_					)
														_snake_case :			Union[str, Any]  						=   min_encoding_indices.reshape(-1 ,				1					)  # flatten

										if self.sane_index_shape:
														_snake_case :			int  						=   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			:		Optional[int] ,				lowerCamelCase_			:		Optional[Any] ,				lowerCamelCase_			:		List[str]					):





										'''simple docstring'''







										if self.remap is not None:
														_snake_case :			Union[str, Any]  						=   indices.reshape(shape[0] ,				-1					)  # add batch axis
														_snake_case :			Tuple  						=   self.unmap_to_all(lowerCamelCase_					)
														_snake_case :			Optional[Any]  						=   indices.reshape(-1					)  # flatten again

										# get quantized latent vectors
										_snake_case :			Any  						=   self.embedding(lowerCamelCase_					)

										if shape is not None:
														_snake_case :			Tuple  						=   z_q.view(lowerCamelCase_					)
														# reshape back to match original input shape
														_snake_case :			List[str]  						=   z_q.permute(0 ,				3 ,				1 ,				2					).contiguous()

										return z_q



class 			lowercase				(							a_     ):



						"""simple docstring"""

						def __init__(    self			:		List[str] ,				lowerCamelCase_			:		Tuple ,				lowerCamelCase_			:		List[str]=False					):





										'''simple docstring'''







										_snake_case :			List[str]  						=   parameters
										_snake_case						,			_snake_case :			Tuple  						=   torch.chunk(lowerCamelCase_ ,				2 ,				dim=1					)
										_snake_case :			Dict  						=   torch.clamp(self.logvar ,				-30.0 ,				20.0					)
										_snake_case :			Optional[Any]  						=   deterministic
										_snake_case :			str  						=   torch.exp(0.5 * self.logvar					)
										_snake_case :			Optional[Any]  						=   torch.exp(self.logvar					)
										if self.deterministic:
														_snake_case :			Any  						=   torch.zeros_like(
														    self.mean ,				device=self.parameters.device ,				dtype=self.parameters.dtype					)







						def 		__UpperCAmelCase       (    self			:		Optional[Any] ,				lowerCamelCase_			:		Optional[torch.Generator] = None					):





										'''simple docstring'''







										_snake_case :			Tuple  						=   randn_tensor(
										    self.mean.shape ,				generator=lowerCamelCase_ ,				device=self.parameters.device ,				dtype=self.parameters.dtype					)
										_snake_case :			Union[str, Any]  						=   self.mean + self.std * sample
										return x







						def 		__UpperCAmelCase       (    self			:		Optional[Any] ,				lowerCamelCase_			:		Optional[Any]=None					):





										'''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			:		str ,				lowerCamelCase_			:		Tuple ,				lowerCamelCase_			:		Optional[int]=[1, 2, 3]					):





										'''simple docstring'''







										if self.deterministic:
														return torch.Tensor([0.0]					)
										_snake_case :			Optional[int]  						=   np.log(2.0 * np.pi					)
										return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean ,				2					) / self.var ,				dim=lowerCamelCase_					)







						def 		__UpperCAmelCase       (    self			:		str					):





										'''simple docstring'''







										return self.mean













from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


lowercase_		:				Any				=						{
    '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''],
    '''tokenization_canine''': ['''CanineTokenizer'''],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase_		:				Optional[Any]				=						[
		    '''CANINE_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''CanineForMultipleChoice''',
		    '''CanineForQuestionAnswering''',
		    '''CanineForSequenceClassification''',
		    '''CanineForTokenClassification''',
		    '''CanineLayer''',
		    '''CanineModel''',
		    '''CaninePreTrainedModel''',
		    '''load_tf_weights_in_canine''',
		]


if TYPE_CHECKING:
		from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
		from .tokenization_canine import CanineTokenizer

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_canine import (
				    CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
				    CanineForMultipleChoice,
				    CanineForQuestionAnswering,
				    CanineForSequenceClassification,
				    CanineForTokenClassification,
				    CanineLayer,
				    CanineModel,
				    CaninePreTrainedModel,
				    load_tf_weights_in_canine,
				)


else:
		import sys

		lowercase_		:				str				=						_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)






