





"""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 						lowercase   (   _UpperCAmelCase   ):
      _SCREAMING_SNAKE_CASE							      = 42







class 						lowercase   (   _UpperCAmelCase	,    _UpperCAmelCase   ):





      @register_to_config
      def __init__(			self ,		lowercase = 32 ,		lowercase = 64 ,		lowercase = 20 ,		lowercase = 768 ,		lowercase=77 ,		lowercase=4 ,		lowercase = 0.0 ,		lowercase = "silu" ,		lowercase = None ,		lowercase = None ,		lowercase = "linear" ,		lowercase = "prd" ,		lowercase = None ,		lowercase = None ,		lowercase = None ,		)						->	Tuple:
            super().__init__()
            lowerCAmelCase    		=			num_attention_heads
            lowerCAmelCase    		=			attention_head_dim
            lowerCAmelCase    		=			num_attention_heads * attention_head_dim
            lowerCAmelCase    		=			additional_embeddings

            lowerCAmelCase    		=			time_embed_dim or inner_dim
            lowerCAmelCase    		=			embedding_proj_dim or embedding_dim
            lowerCAmelCase    		=			clip_embed_dim or embedding_dim

            lowerCAmelCase    		=			Timesteps(lowercase ,		lowercase ,		0					)
            lowerCAmelCase    		=			TimestepEmbedding(lowercase ,		lowercase ,		out_dim=lowercase ,		act_fn=lowercase					)

            lowerCAmelCase    		=			nn.Linear(lowercase ,		lowercase					)

            if embedding_proj_norm_type is None:
                  lowerCAmelCase    		=			None
            elif embedding_proj_norm_type == "layer":
                  lowerCAmelCase    		=			nn.LayerNorm(lowercase					)
            else:
                  raise ValueError(f'unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'					)

            lowerCAmelCase    		=			nn.Linear(lowercase ,		lowercase					)

            if encoder_hid_proj_type is None:
                  lowerCAmelCase    		=			None
            elif encoder_hid_proj_type == "linear":
                  lowerCAmelCase    		=			nn.Linear(lowercase ,		lowercase					)
            else:
                  raise ValueError(f'unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'					)

            lowerCAmelCase    		=			nn.Parameter(torch.zeros(1 ,		num_embeddings + additional_embeddings ,		lowercase					)					)

            if added_emb_type == "prd":
                  lowerCAmelCase    		=			nn.Parameter(torch.zeros(1 ,		1 ,		lowercase					)					)
            elif added_emb_type is None:
                  lowerCAmelCase    		=			None
            else:
                  raise ValueError(
                      f'`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.'					)

            lowerCAmelCase    		=			nn.ModuleList(
                [
                    BasicTransformerBlock(
                        lowercase ,		lowercase ,		lowercase ,		dropout=lowercase ,		activation_fn="""gelu""" ,		attention_bias=lowercase ,		)
                    for d in range(lowercase					)
                ]					)

            if norm_in_type == "layer":
                  lowerCAmelCase    		=			nn.LayerNorm(lowercase					)
            elif norm_in_type is None:
                  lowerCAmelCase    		=			None
            else:
                  raise ValueError(f'Unsupported norm_in_type: {norm_in_type}.'					)

            lowerCAmelCase    		=			nn.LayerNorm(lowercase					)

            lowerCAmelCase    		=			nn.Linear(lowercase ,		lowercase					)

            lowerCAmelCase    		=			torch.full(
                [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] ,		-10_000.0					)
            causal_attention_mask.triu_(1					)
            lowerCAmelCase    		=			causal_attention_mask[None, ...]
            self.register_buffer("""causal_attention_mask""" ,		lowercase ,		persistent=lowercase					)

            lowerCAmelCase    		=			nn.Parameter(torch.zeros(1 ,		lowercase					)					)
            lowerCAmelCase    		=			nn.Parameter(torch.zeros(1 ,		lowercase					)					)





      @property
      # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
      def        _snake_case     (			self					)						->	Dict[str, AttentionProcessor]:
            lowerCAmelCase    		=			{}

            def fn_recursive_add_processors(lowercase ,		lowercase ,		lowercase					):
                  if hasattr(lowercase ,		"""set_processor"""					):
                        lowerCAmelCase    		=			module.processor

                  for sub_name, child in module.named_children():
                        fn_recursive_add_processors(f'{name}.{sub_name}' ,		lowercase ,		lowercase					)

                  return processors

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

            return processors





      def        _snake_case     (			self ,		lowercase					)						->	Tuple:
            lowerCAmelCase    		=			len(self.attn_processors.keys()					)

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

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

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





      def        _snake_case     (			self					)						->	List[str]:
            self.set_attn_processor(AttnProcessor()					)





      def        _snake_case     (			self ,		lowercase ,		lowercase ,		lowercase ,		lowercase = None ,		lowercase = None ,		lowercase = True ,		)						->	Dict:
            lowerCAmelCase    		=			hidden_states.shape[0]

            lowerCAmelCase    		=			timestep
            if not torch.is_tensor(lowercase					):
                  lowerCAmelCase    		=			torch.tensor([timesteps] ,		dtype=torch.long ,		device=hidden_states.device					)
            elif torch.is_tensor(lowercase					) and len(timesteps.shape					) == 0:
                  lowerCAmelCase    		=			timesteps[None].to(hidden_states.device					)

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

            lowerCAmelCase    		=			self.time_proj(lowercase					)

            # timesteps does not contain any weights and will always return f32 tensors
            # but time_embedding might be fp16, so we need to cast here.
            lowerCAmelCase    		=			timesteps_projected.to(dtype=self.dtype					)
            lowerCAmelCase    		=			self.time_embedding(lowercase					)

            if self.embedding_proj_norm is not None:
                  lowerCAmelCase    		=			self.embedding_proj_norm(lowercase					)

            lowerCAmelCase    		=			self.embedding_proj(lowercase					)
            if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
                  lowerCAmelCase    		=			self.encoder_hidden_states_proj(lowercase					)
            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"""					)

            lowerCAmelCase    		=			self.proj_in(lowercase					)

            lowerCAmelCase    		=			self.positional_embedding.to(hidden_states.dtype					)

            lowerCAmelCase    		=			[]
            lowerCAmelCase    		=			0

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

            if len(proj_embeddings.shape					) == 2:
                  lowerCAmelCase    		=			proj_embeddings[:, None, :]

            if len(hidden_states.shape					) == 2:
                  lowerCAmelCase    		=			hidden_states[:, None, :]

            lowerCAmelCase    		=			additional_embeds + [
                proj_embeddings,
                time_embeddings[:, None, :],
                hidden_states,
            ]

            if self.prd_embedding is not None:
                  lowerCAmelCase    		=			self.prd_embedding.to(hidden_states.dtype					).expand(lowercase ,		-1 ,		-1					)
                  additional_embeds.append(lowercase					)

            lowerCAmelCase    		=			torch.cat(
                lowercase ,		dim=1 ,		)

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

            lowerCAmelCase    		=			hidden_states + positional_embeddings

            if attention_mask is not None:
                  lowerCAmelCase    		=			(1 - attention_mask.to(hidden_states.dtype					)) * -10_000.0
                  lowerCAmelCase    		=			F.pad(lowercase ,		(0, self.additional_embeddings) ,		value=0.0					)
                  lowerCAmelCase    		=			(attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype					)
                  lowerCAmelCase    		=			attention_mask.repeat_interleave(self.config.num_attention_heads ,		dim=0					)

            if self.norm_in is not None:
                  lowerCAmelCase    		=			self.norm_in(lowercase					)

            for block in self.transformer_blocks:
                  lowerCAmelCase    		=			block(lowercase ,		attention_mask=lowercase					)

            lowerCAmelCase    		=			self.norm_out(lowercase					)

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

            lowerCAmelCase    		=			self.proj_to_clip_embeddings(lowercase					)

            if not return_dict:
                  return (predicted_image_embedding,)

            return PriorTransformerOutput(predicted_image_embedding=lowercase					)





      def        _snake_case     (			self ,		lowercase					)						->	str:
            lowerCAmelCase    		=			(prior_latents * self.clip_std) + self.clip_mean
            return prior_latents













"""simple docstring"""





from ...configuration_utils import PretrainedConfig
from ...utils import logging


SCREAMING_SNAKE_CASE__   =  logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__   =  {
    "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json",
    "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json"
    # See all FNet models at https://huggingface.co/models?filter=fnet
}

class 						lowercase   (   _UpperCAmelCase   ):
      _SCREAMING_SNAKE_CASE							      = 'fnet'





      def __init__(			self ,		lowercase=32_000 ,		lowercase=768 ,		lowercase=12 ,		lowercase=3_072 ,		lowercase="gelu_new" ,		lowercase=0.1 ,		lowercase=512 ,		lowercase=4 ,		lowercase=0.02 ,		lowercase=1e-12 ,		lowercase=False ,		lowercase=512 ,		lowercase=3 ,		lowercase=1 ,		lowercase=2 ,		**lowercase ,		)						->	int:
            super().__init__(pad_token_id=lowercase ,		bos_token_id=lowercase ,		eos_token_id=lowercase ,		**lowercase					)

            lowerCAmelCase    		=			vocab_size
            lowerCAmelCase    		=			max_position_embeddings
            lowerCAmelCase    		=			hidden_size
            lowerCAmelCase    		=			num_hidden_layers
            lowerCAmelCase    		=			intermediate_size
            lowerCAmelCase    		=			hidden_act
            lowerCAmelCase    		=			hidden_dropout_prob
            lowerCAmelCase    		=			initializer_range
            lowerCAmelCase    		=			type_vocab_size
            lowerCAmelCase    		=			layer_norm_eps
            lowerCAmelCase    		=			use_tpu_fourier_optimizations
            lowerCAmelCase    		=			tpu_short_seq_length






