'''simple docstring'''





import colorsys

from PIL import Image  # type: ignore
def 						__A							(     UpperCAmelCase     ,UpperCAmelCase     ,UpperCAmelCase					)     ->			float:




						'''simple docstring'''
						_UpperCamelCase			:			str   			=						x
						_UpperCamelCase			:			Any   			=						y
						for step in range(UpperCAmelCase					):  # noqa: B007
												_UpperCamelCase			:			Any   			=						a * a - b * b + x
												_UpperCamelCase			:			Any   			=						2 * a * b + y
												_UpperCamelCase			:			Optional[int]   			=						a_new

												# divergence happens for all complex number with an absolute value
												# greater than 4
												if a * a + b * b > 4:
																		break
						return step / (max_step - 1)
def 						__A							(     UpperCAmelCase					)     ->			tuple:




						'''simple docstring'''
						if distance == 1:
												return (0, 0, 0)
						else:
												return (2_5_5, 2_5_5, 2_5_5)
def 						__A							(     UpperCAmelCase					)     ->			tuple:




						'''simple docstring'''
						if distance == 1:
												return (0, 0, 0)
						else:
												return tuple(round(i * 2_5_5					) for i in colorsys.hsv_to_rgb(UpperCAmelCase     ,1     ,1					)					)
def 						__A							(     UpperCAmelCase = 8_0_0     ,UpperCAmelCase = 6_0_0     ,UpperCAmelCase = -0.6     ,UpperCAmelCase = 0     ,UpperCAmelCase = 3.2     ,UpperCAmelCase = 5_0     ,UpperCAmelCase = True     ,)     ->			Image.Image:




						'''simple docstring'''
						_UpperCamelCase			:			Optional[Any]   			=						Image.new("RGB"     ,(image_width, image_height)					)
						_UpperCamelCase			:			str   			=						img.load()

						# loop through the image-coordinates
						for image_x in range(UpperCAmelCase					):
												for image_y in range(UpperCAmelCase					):
																		# determine the figure-coordinates based on the image-coordinates
																		_UpperCamelCase			:			Dict   			=						figure_width / image_width * image_height
																		_UpperCamelCase			:			str   			=						figure_center_x + (image_x / image_width - 0.5) * figure_width
																		_UpperCamelCase			:			Any   			=						figure_center_y + (image_y / image_height - 0.5) * figure_height

																		_UpperCamelCase			:			Any   			=						get_distance(UpperCAmelCase     ,UpperCAmelCase     ,UpperCAmelCase					)

																		# color the corresponding pixel based on the selected coloring-function
																		if use_distance_color_coding:
																								_UpperCamelCase			:			str   			=						get_color_coded_rgb(UpperCAmelCase					)
																		else:
																								_UpperCamelCase			:			Optional[Any]   			=						get_black_and_white_rgb(UpperCAmelCase					)

						return img


if __name__ == "__main__":
			import doctest

			doctest.testmod()

			# colored version, full figure
			lowerCAmelCase_	:		str			=     get_image()

			# uncomment for colored version, different section, zoomed in
			# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
			# figure_width = 0.8)

			# uncomment for black and white version, full figure
			# img = get_image(use_distance_color_coding = False)

			# uncomment to save the image
			# img.save("mandelbrot.png")

			img.show()



'''simple docstring'''





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







				'''simple docstring'''
				UpperCAmelCase__							=							42





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Optional[Any]       ,		lowercase__					:						List[str]=3       ,		lowercase__					:						Tuple=3       ,		lowercase__					:						List[str]=("DownEncoderBlock2D",)       ,		lowercase__					:						Optional[int]=(64,)       ,		lowercase__					:						List[Any]=2       ,		lowercase__					:						int=32       ,		lowercase__					:						Optional[int]="silu"       ,		lowercase__					:						List[Any]=True       ,		)							->Optional[Any]:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			Union[str, Any]   			=						layers_per_block

										_UpperCamelCase			:			Union[str, Any]   			=						torch.nn.Convad(
										    lowercase__       ,		block_out_channels[0]       ,		kernel_size=3       ,		stride=1       ,		padding=1       ,		)

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

										# down
										_UpperCamelCase			:			Optional[int]   			=						block_out_channels[0]
										for i, down_block_type in enumerate(lowercase__					):
																_UpperCamelCase			:			int   			=						output_channel
																_UpperCamelCase			:			int   			=						block_out_channels[i]
																_UpperCamelCase			:			Tuple   			=						i == len(lowercase__					) - 1

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

										# mid
										_UpperCamelCase			:			Dict   			=						UNetMidBlockaD(
										    in_channels=block_out_channels[-1]       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		output_scale_factor=1       ,		resnet_time_scale_shift="default"       ,		attention_head_dim=block_out_channels[-1]       ,		resnet_groups=lowercase__       ,		temb_channels=lowercase__       ,		)

										# out
										_UpperCamelCase			:			List[str]   			=						nn.GroupNorm(num_channels=block_out_channels[-1]       ,		num_groups=lowercase__       ,		eps=1e-6					)
										_UpperCamelCase			:			Union[str, Any]   			=						nn.SiLU()

										_UpperCamelCase			:			Tuple   			=						2 * out_channels if double_z else out_channels
										_UpperCamelCase			:			List[Any]   			=						nn.Convad(block_out_channels[-1]       ,		lowercase__       ,		3       ,		padding=1					)

										_UpperCamelCase			:			Tuple   			=						False







				def  snake_case__				(						self					:						str       ,		lowercase__					:						Any					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						x
										_UpperCamelCase			:			str   			=						self.conv_in(lowercase__					)

										if self.training and self.gradient_checkpointing:

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

																						return custom_forward

																# down
																if is_torch_version(">="       ,		"1.11.0"					):
																						for down_block in self.down_blocks:
																												_UpperCamelCase			:			Optional[Any]   			=						torch.utils.checkpoint.checkpoint(
																												    create_custom_forward(lowercase__					)       ,		lowercase__       ,		use_reentrant=lowercase__					)
																						# middle
																						_UpperCamelCase			:			List[Any]   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		use_reentrant=lowercase__					)
																else:
																						for down_block in self.down_blocks:
																												_UpperCamelCase			:			List[str]   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__					)       ,		lowercase__					)
																						# middle
																						_UpperCamelCase			:			Union[str, Any]   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block					)       ,		lowercase__					)

										else:
																# down
																for down_block in self.down_blocks:
																						_UpperCamelCase			:			Tuple   			=						down_block(lowercase__					)

																# middle
																_UpperCamelCase			:			Optional[int]   			=						self.mid_block(lowercase__					)

										# post-process
										_UpperCamelCase			:			List[Any]   			=						self.conv_norm_out(lowercase__					)
										_UpperCamelCase			:			Tuple   			=						self.conv_act(lowercase__					)
										_UpperCamelCase			:			int   			=						self.conv_out(lowercase__					)

										return sample





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





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


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			List[Any]   			=						layers_per_block

										_UpperCamelCase			:			Any   			=						nn.Convad(
										    lowercase__       ,		block_out_channels[-1]       ,		kernel_size=3       ,		stride=1       ,		padding=1       ,		)

										_UpperCamelCase			:			List[str]   			=						None
										_UpperCamelCase			:			Dict   			=						nn.ModuleList([]					)

										_UpperCamelCase			:			Optional[int]   			=						in_channels if norm_type == "spatial" else None

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

										# up
										_UpperCamelCase			:			Dict   			=						list(reversed(lowercase__					)					)
										_UpperCamelCase			:			Tuple   			=						reversed_block_out_channels[0]
										for i, up_block_type in enumerate(lowercase__					):
																_UpperCamelCase			:			Union[str, Any]   			=						output_channel
																_UpperCamelCase			:			Dict   			=						reversed_block_out_channels[i]

																_UpperCamelCase			:			List[str]   			=						i == len(lowercase__					) - 1

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

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

										_UpperCamelCase			:			Optional[Any]   			=						False







				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						Union[str, Any]       ,		lowercase__					:						Optional[Any]=None					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						z
										_UpperCamelCase			:			str   			=						self.conv_in(lowercase__					)

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

																def create_custom_forward(lowercase__					:						Optional[int]					):
																						def custom_forward(*lowercase__					:						List[str]					):
																												return module(*lowercase__					)

																						return custom_forward

																if is_torch_version(">="       ,		"1.11.0"					):
																						# middle
																						_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		lowercase__       ,		use_reentrant=lowercase__					)
																						_UpperCamelCase			:			Union[str, Any]   			=						sample.to(lowercase__					)

																						# up
																						for up_block in self.up_blocks:
																												_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(
																												    create_custom_forward(lowercase__					)       ,		lowercase__       ,		lowercase__       ,		use_reentrant=lowercase__					)
																else:
																						# middle
																						_UpperCamelCase			:			Any   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		lowercase__					)
																						_UpperCamelCase			:			int   			=						sample.to(lowercase__					)

																						# up
																						for up_block in self.up_blocks:
																												_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__					)       ,		lowercase__       ,		lowercase__					)
										else:
																# middle
																_UpperCamelCase			:			str   			=						self.mid_block(lowercase__       ,		lowercase__					)
																_UpperCamelCase			:			int   			=						sample.to(lowercase__					)

																# up
																for up_block in self.up_blocks:
																						_UpperCamelCase			:			str   			=						up_block(lowercase__       ,		lowercase__					)

        # post-process
										if latent_embeds is None:
																_UpperCamelCase			:			Union[str, Any]   			=						self.conv_norm_out(lowercase__					)
										else:
																_UpperCamelCase			:			Any   			=						self.conv_norm_out(lowercase__       ,		lowercase__					)
										_UpperCamelCase			:			List[str]   			=						self.conv_act(lowercase__					)
										_UpperCamelCase			:			Dict   			=						self.conv_out(lowercase__					)

										return sample





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Optional[int]       ,		lowercase__					:						str       ,		lowercase__					:						Tuple       ,		lowercase__					:						Optional[Any]       ,		lowercase__					:						Tuple=None       ,		lowercase__					:						Dict="random"       ,		lowercase__					:						List[Any]=False       ,		lowercase__					:						List[Any]=True					)							->Optional[int]:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			List[Any]   			=						n_e
										_UpperCamelCase			:			List[str]   			=						vq_embed_dim
										_UpperCamelCase			:			List[str]   			=						beta
										_UpperCamelCase			:			Any   			=						legacy

										_UpperCamelCase			:			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					)

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

										_UpperCamelCase			:			Optional[Any]   			=						sane_index_shape





				def  snake_case__				(						self					:						str       ,		lowercase__					:						Dict					)							->Optional[int]:


										'''simple docstring'''




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





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Optional[Any]					)							->int:


										'''simple docstring'''




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





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						Union[str, Any]					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Any   			=						z.permute(0       ,		2       ,		3       ,		1					).contiguous()
										_UpperCamelCase			:			Optional[Any]   			=						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			:			Optional[Any]   			=						torch.argmin(torch.cdist(lowercase__       ,		self.embedding.weight					)       ,		dim=1					)

										_UpperCamelCase			:			List[str]   			=						self.embedding(lowercase__					).view(z.shape					)
										_UpperCamelCase			:			Optional[int]   			=						None
										_UpperCamelCase			:			Tuple   			=						None

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

										# preserve gradients
										_UpperCamelCase			:			List[Any]   			=						z + (z_q - z).detach()

										# reshape back to match original input shape
										_UpperCamelCase			:			List[Any]   			=						z_q.permute(0       ,		3       ,		1       ,		2					).contiguous()

										if self.remap is not None:
																_UpperCamelCase			:			str   			=						min_encoding_indices.reshape(z.shape[0]       ,		-1					)  # add batch axis
																_UpperCamelCase			:			int   			=						self.remap_to_used(lowercase__					)
																_UpperCamelCase			:			List[str]   			=						min_encoding_indices.reshape(-1       ,		1					)  # flatten

										if self.sane_index_shape:
																_UpperCamelCase			:			Tuple   			=						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  snake_case__				(						self					:						Optional[Any]       ,		lowercase__					:						List[str]       ,		lowercase__					:						List[str]					)							->Dict:


										'''simple docstring'''




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

										# get quantized latent vectors
										_UpperCamelCase			:			Dict   			=						self.embedding(lowercase__					)

										if shape is not None:
																_UpperCamelCase			:			List[Any]   			=						z_q.view(lowercase__					)
																# reshape back to match original input shape
																_UpperCamelCase			:			Optional[int]   			=						z_q.permute(0       ,		3       ,		1       ,		2					).contiguous()

										return z_q





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]=False					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						parameters
										_UpperCamelCase			,       _UpperCamelCase			:			Tuple   			=						torch.chunk(lowercase__       ,		2       ,		dim=1					)
										_UpperCamelCase			:			str   			=						torch.clamp(self.logvar       ,		-3_0.0       ,		2_0.0					)
										_UpperCamelCase			:			str   			=						deterministic
										_UpperCamelCase			:			Optional[Any]   			=						torch.exp(0.5 * self.logvar					)
										_UpperCamelCase			:			Optional[Any]   			=						torch.exp(self.logvar					)
										if self.deterministic:
																_UpperCamelCase			:			Optional[Any]   			=						torch.zeros_like(
																    self.mean       ,		device=self.parameters.device       ,		dtype=self.parameters.dtype					)





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Optional[torch.Generator] = None					)							->torch.FloatTensor:


										'''simple docstring'''




										_UpperCamelCase			:			Union[str, Any]   			=						randn_tensor(
										    self.mean.shape       ,		generator=lowercase__       ,		device=self.parameters.device       ,		dtype=self.parameters.dtype					)
										_UpperCamelCase			:			Optional[int]   			=						self.mean + self.std * sample
										return x





				def  snake_case__				(						self					:						str       ,		lowercase__					:						Optional[int]=None					)							->List[str]:


										'''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  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]=[1, 2, 3]					)							->Dict:


										'''simple docstring'''




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







				def  snake_case__				(						self					:						List[Any]					)							->str:


										'''simple docstring'''




										return self.mean


