




"""simple docstring"""





from dataclasses import dataclass
from typing import Dict, Optional, Union

import torch
import torch.nn.functional as F
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .attention_processor import AttentionProcessor, AttnProcessor
from .embeddings import TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin



@dataclass
class   a__					(						__magic_name__ ):
			lowercase_		=						42






class   a__					(						__magic_name__				,     __magic_name__ ):


			@register_to_config
			def __init__(   self   :     Optional[int]   ,	UpperCamelCase_   :     int = 32   ,	UpperCamelCase_   :     int = 64   ,	UpperCamelCase_   :     int = 20   ,	UpperCamelCase_   :     int = 768   ,	UpperCamelCase_   :     List[Any]=77   ,	UpperCamelCase_   :     Dict=4   ,	UpperCamelCase_   :     float = 0.0   ,	UpperCamelCase_   :     str = "silu"   ,	UpperCamelCase_   :     Optional[str] = None   ,	UpperCamelCase_   :     Optional[str] = None   ,	UpperCamelCase_   :     Optional[str] = "linear"   ,	UpperCamelCase_   :     Optional[str] = "prd"   ,	UpperCamelCase_   :     Optional[int] = None   ,	UpperCamelCase_   :     Optional[int] = None   ,	UpperCamelCase_   :     Optional[int] = None   ,	):


						"""simple docstring"""




						super().__init__()
						__UpperCAmelCase						:			int												=       num_attention_heads
						__UpperCAmelCase						:			int												=       attention_head_dim
						__UpperCAmelCase						:			Tuple												=       num_attention_heads * attention_head_dim
						__UpperCAmelCase						:			List[str]												=       additional_embeddings

						__UpperCAmelCase						:			int												=       time_embed_dim or inner_dim
						__UpperCAmelCase						:			List[str]												=       embedding_proj_dim or embedding_dim
						__UpperCAmelCase						:			Optional[Any]												=       clip_embed_dim or embedding_dim

						__UpperCAmelCase						:			Tuple												=       Timesteps(UpperCamelCase_   ,	UpperCamelCase_   ,	0)
						__UpperCAmelCase						:			List[str]												=       TimestepEmbedding(UpperCamelCase_   ,	UpperCamelCase_   ,	out_dim=UpperCamelCase_   ,	act_fn=UpperCamelCase_)

						__UpperCAmelCase						:			int												=       nn.Linear(UpperCamelCase_   ,	UpperCamelCase_)

						if embedding_proj_norm_type is None:
									__UpperCAmelCase						:			Union[str, Any]												=       None
						elif embedding_proj_norm_type == "layer":
									__UpperCAmelCase						:			str												=       nn.LayerNorm(UpperCamelCase_)
						else:
									raise ValueError(F"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}")

						__UpperCAmelCase						:			List[str]												=       nn.Linear(UpperCamelCase_   ,	UpperCamelCase_)

						if encoder_hid_proj_type is None:
									__UpperCAmelCase						:			List[str]												=       None
						elif encoder_hid_proj_type == "linear":
									__UpperCAmelCase						:			List[str]												=       nn.Linear(UpperCamelCase_   ,	UpperCamelCase_)
						else:
									raise ValueError(F"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}")

						__UpperCAmelCase						:			List[Any]												=       nn.Parameter(torch.zeros(1   ,	num_embeddings + additional_embeddings   ,	UpperCamelCase_))

						if added_emb_type == "prd":
									__UpperCAmelCase						:			Union[str, Any]												=       nn.Parameter(torch.zeros(1   ,	1   ,	UpperCamelCase_))
						elif added_emb_type is None:
									__UpperCAmelCase						:			int												=       None
						else:
									raise ValueError(
									    F"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`.")

						__UpperCAmelCase						:			Union[str, Any]												=       nn.ModuleList(
						    [
						        BasicTransformerBlock(
						            UpperCamelCase_   ,	UpperCamelCase_   ,	UpperCamelCase_   ,	dropout=UpperCamelCase_   ,	activation_fn="gelu"   ,	attention_bias=UpperCamelCase_   ,	)
						        for d in range(UpperCamelCase_)
						    ])

						if norm_in_type == "layer":
									__UpperCAmelCase						:			List[Any]												=       nn.LayerNorm(UpperCamelCase_)
						elif norm_in_type is None:
									__UpperCAmelCase						:			Any												=       None
						else:
									raise ValueError(F"Unsupported norm_in_type: {norm_in_type}.")

						__UpperCAmelCase						:			List[str]												=       nn.LayerNorm(UpperCamelCase_)

						__UpperCAmelCase						:			Any												=       nn.Linear(UpperCamelCase_   ,	UpperCamelCase_)

						__UpperCAmelCase						:			Any												=       torch.full(
						    [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]   ,	-10000.0)
						causal_attention_mask.triu_(1)
						__UpperCAmelCase						:			str												=       causal_attention_mask[None, ...]
						self.register_buffer("causal_attention_mask"   ,	UpperCamelCase_   ,	persistent=UpperCamelCase_)

						__UpperCAmelCase						:			Tuple												=       nn.Parameter(torch.zeros(1   ,	UpperCamelCase_))
						__UpperCAmelCase						:			Any												=       nn.Parameter(torch.zeros(1   ,	UpperCamelCase_))


			@property
			# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
			def    a_  (   self   :     Optional[Any]):


						"""simple docstring"""




						__UpperCAmelCase						:			Dict												=       {}

						def fn_recursive_add_processors(UpperCamelCase_   :     str   ,	UpperCamelCase_   :     torch.nn.Module   ,	UpperCamelCase_   :     Dict[str, AttentionProcessor]):
									if hasattr(UpperCamelCase_   ,	"set_processor"):
												__UpperCAmelCase						:			int												=       module.processor

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

									return processors

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

						return processors


			def    a_  (   self   :     str   ,	UpperCamelCase_   :     Union[AttentionProcessor, Dict[str, AttentionProcessor]]):


						"""simple docstring"""




						__UpperCAmelCase						:			int												=       len(self.attn_processors.keys())

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

						def fn_recursive_attn_processor(UpperCamelCase_   :     str   ,	UpperCamelCase_   :     torch.nn.Module   ,	UpperCamelCase_   :     Any):
									if hasattr(UpperCamelCase_   ,	"set_processor"):
												if not isinstance(UpperCamelCase_   ,	UpperCamelCase_):
															module.set_processor(UpperCamelCase_)
												else:
															module.set_processor(processor.pop(F"{name}.processor"))

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

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


			def    a_  (   self   :     str):


						"""simple docstring"""




						self.set_attn_processor(AttnProcessor())


			def    a_  (   self   :     Dict   ,	UpperCamelCase_   :     List[Any]   ,	UpperCamelCase_   :     Union[torch.Tensor, float, int]   ,	UpperCamelCase_   :     torch.FloatTensor   ,	UpperCamelCase_   :     Optional[torch.FloatTensor] = None   ,	UpperCamelCase_   :     Optional[torch.BoolTensor] = None   ,	UpperCamelCase_   :     bool = True   ,	):


						"""simple docstring"""




						__UpperCAmelCase						:			int												=       hidden_states.shape[0]

						__UpperCAmelCase						:			Union[str, Any]												=       timestep
						if not torch.is_tensor(UpperCamelCase_):
									__UpperCAmelCase						:			Dict												=       torch.tensor([timesteps]   ,	dtype=torch.long   ,	device=hidden_states.device)
						elif torch.is_tensor(UpperCamelCase_) and len(timesteps.shape) == 0:
									__UpperCAmelCase						:			Union[str, Any]												=       timesteps[None].to(hidden_states.device)

						# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
						__UpperCAmelCase						:			str												=       timesteps * torch.ones(UpperCamelCase_   ,	dtype=timesteps.dtype   ,	device=timesteps.device)

						__UpperCAmelCase						:			Union[str, Any]												=       self.time_proj(UpperCamelCase_)

						# timesteps does not contain any weights and will always return f32 tensors
						# but time_embedding might be fp16, so we need to cast here.
						__UpperCAmelCase						:			Any												=       timesteps_projected.to(dtype=self.dtype)
						__UpperCAmelCase						:			Optional[int]												=       self.time_embedding(UpperCamelCase_)

						if self.embedding_proj_norm is not None:
									__UpperCAmelCase						:			List[str]												=       self.embedding_proj_norm(UpperCamelCase_)

						__UpperCAmelCase						:			Union[str, Any]												=       self.embedding_proj(UpperCamelCase_)
						if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
									__UpperCAmelCase						:			Union[str, Any]												=       self.encoder_hidden_states_proj(UpperCamelCase_)
						elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
									raise ValueError("`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set")

						__UpperCAmelCase						:			List[Any]												=       self.proj_in(UpperCamelCase_)

						__UpperCAmelCase						:			str												=       self.positional_embedding.to(hidden_states.dtype)

						__UpperCAmelCase						:			int												=       []
						__UpperCAmelCase						:			Union[str, Any]												=       0

						if encoder_hidden_states is not None:
									additional_embeds.append(UpperCamelCase_)
									additional_embeddings_len += encoder_hidden_states.shape[1]

						if len(proj_embeddings.shape) == 2:
									__UpperCAmelCase						:			Union[str, Any]												=       proj_embeddings[:, None, :]

						if len(hidden_states.shape) == 2:
									__UpperCAmelCase						:			List[str]												=       hidden_states[:, None, :]

						__UpperCAmelCase						:			List[str]												=       additional_embeds + [
						    proj_embeddings,
						    time_embeddings[:, None, :],
						    hidden_states,
						]

						if self.prd_embedding is not None:
									__UpperCAmelCase						:			Union[str, Any]												=       self.prd_embedding.to(hidden_states.dtype).expand(UpperCamelCase_   ,	-1   ,	-1)
									additional_embeds.append(UpperCamelCase_)

						__UpperCAmelCase						:			Optional[int]												=       torch.cat(
						    UpperCamelCase_   ,	dim=1   ,	)

						# Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
						__UpperCAmelCase						:			List[Any]												=       additional_embeddings_len + proj_embeddings.shape[1] + 1
						if positional_embeddings.shape[1] < hidden_states.shape[1]:
									__UpperCAmelCase						:			str												=       F.pad(
									    UpperCamelCase_   ,	(
									        0,
									        0,
									        additional_embeddings_len,
									        self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
									    )   ,	value=0.0   ,	)

						__UpperCAmelCase						:			Tuple												=       hidden_states + positional_embeddings

						if attention_mask is not None:
									__UpperCAmelCase						:			Dict												=       (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
									__UpperCAmelCase						:			str												=       F.pad(UpperCamelCase_   ,	(0, self.additional_embeddings)   ,	value=0.0)
									__UpperCAmelCase						:			List[str]												=       (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype)
									__UpperCAmelCase						:			List[Any]												=       attention_mask.repeat_interleave(self.config.num_attention_heads   ,	dim=0)

						if self.norm_in is not None:
									__UpperCAmelCase						:			int												=       self.norm_in(UpperCamelCase_)

						for block in self.transformer_blocks:
									__UpperCAmelCase						:			int												=       block(UpperCamelCase_   ,	attention_mask=UpperCamelCase_)

						__UpperCAmelCase						:			Any												=       self.norm_out(UpperCamelCase_)

						if self.prd_embedding is not None:
									__UpperCAmelCase						:			Dict												=       hidden_states[:, -1]
						else:
									__UpperCAmelCase						:			str												=       hidden_states[:, additional_embeddings_len:]

						__UpperCAmelCase						:			List[str]												=       self.proj_to_clip_embeddings(UpperCamelCase_)

						if not return_dict:
									return (predicted_image_embedding,)

						return PriorTransformerOutput(predicted_image_embedding=UpperCamelCase_)


			def    a_  (   self   :     str   ,	UpperCamelCase_   :     Dict):


						"""simple docstring"""




						__UpperCAmelCase						:			str												=       (prior_latents * self.clip_std) + self.clip_mean
						return prior_latents










def     a_   (__A				,       __A				,       __A				,       __A      )				->						int:



					"""simple docstring"""
					__a      ,			__a					:						Any      =					len(__A      ), len(grid[0]      )
					if (
					    min(__A				,       __A      ) < 0
					    or row == row_length
					    or col == col_length
					    or (row, col) in visit
					    or grid[row][col] == 1
					):
										return 0
					if row == row_length - 1 and col == col_length - 1:
										return 1

					visit.add((row, col)      )

					__a					:						Dict      =					0
					count += depth_first_search(__A				,       row + 1				,       __A				,       __A      )
					count += depth_first_search(__A				,       row - 1				,       __A				,       __A      )
					count += depth_first_search(__A				,       __A				,       col + 1				,       __A      )
					count += depth_first_search(__A				,       __A				,       col - 1				,       __A      )

					visit.remove((row, col)      )
					return count


if __name__ == "__main__":
			import doctest

			doctest.testmod()





