




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 			_UpperCamelCase      (				lowerCAmelCase		):
      UpperCAmelCase_        =		42



class 			_UpperCamelCase      (				lowerCAmelCase	,       lowerCAmelCase		):
      @register_to_config
      def __init__(			self   :Optional[int] ,      lowerCamelCase   :int = 32 ,      lowerCamelCase   :int = 64 ,      lowerCamelCase   :int = 20 ,      lowerCamelCase   :int = 768 ,      lowerCamelCase   :Tuple=77 ,      lowerCamelCase   :Optional[Any]=4 ,      lowerCamelCase   :float = 0.0 ,      lowerCamelCase   :str = "silu" ,      lowerCamelCase   :Optional[str] = None ,      lowerCamelCase   :Optional[str] = None ,      lowerCamelCase   :Optional[str] = "linear" ,      lowerCamelCase   :Optional[str] = "prd" ,      lowerCamelCase   :Optional[int] = None ,      lowerCamelCase   :Optional[int] = None ,      lowerCamelCase   :Optional[int] = None ,      )     ->			List[str]:
       super().__init__()
       UpperCAmelCase__							 =						num_attention_heads
       UpperCAmelCase__							 =						attention_head_dim
       UpperCAmelCase__							 =						num_attention_heads * attention_head_dim
       UpperCAmelCase__							 =						additional_embeddings

       UpperCAmelCase__							 =						time_embed_dim or inner_dim
       UpperCAmelCase__							 =						embedding_proj_dim or embedding_dim
       UpperCAmelCase__							 =						clip_embed_dim or embedding_dim

       UpperCAmelCase__							 =						Timesteps(lowerCamelCase ,      lowerCamelCase ,      0      )
       UpperCAmelCase__							 =						TimestepEmbedding(lowerCamelCase ,      lowerCamelCase ,      out_dim=lowerCamelCase ,      act_fn=lowerCamelCase      )

       UpperCAmelCase__							 =						nn.Linear(lowerCamelCase ,      lowerCamelCase      )

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

       UpperCAmelCase__							 =						nn.Linear(lowerCamelCase ,      lowerCamelCase      )

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

       UpperCAmelCase__							 =						nn.Parameter(torch.zeros(1 ,      num_embeddings + additional_embeddings ,      lowerCamelCase      )      )

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

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

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

       UpperCAmelCase__							 =						nn.LayerNorm(lowerCamelCase      )

       UpperCAmelCase__							 =						nn.Linear(lowerCamelCase ,      lowerCamelCase      )

       UpperCAmelCase__							 =						torch.full(
           [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] ,      -1_0000.0      )
       causal_attention_mask.triu_(1      )
       UpperCAmelCase__							 =						causal_attention_mask[None, ...]
       self.register_buffer("causal_attention_mask" ,      lowerCamelCase ,      persistent=lowerCamelCase      )

       UpperCAmelCase__							 =						nn.Parameter(torch.zeros(1 ,      lowerCamelCase      )      )
       UpperCAmelCase__							 =						nn.Parameter(torch.zeros(1 ,      lowerCamelCase      )      )
      @property
      # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
      def 	UpperCAmelCase_						(			self   :Dict      )     ->			Dict[str, AttentionProcessor]:
       UpperCAmelCase__							 =						{}

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

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

        return processors

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

       return processors
      def 	UpperCAmelCase_						(			self   :Union[str, Any] ,      lowerCamelCase   :Union[AttentionProcessor, Dict[str, AttentionProcessor]]      )     ->			Union[str, Any]:
       UpperCAmelCase__							 =						len(self.attn_processors.keys()      )

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

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

       for name, module in self.named_children():
        fn_recursive_attn_processor(lowerCamelCase ,      lowerCamelCase ,      lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :Optional[Any]      )     ->			str:
       self.set_attn_processor(AttnProcessor()      )
      def 	UpperCAmelCase_						(			self   :Tuple ,      lowerCamelCase   :Optional[int] ,      lowerCamelCase   :Union[torch.Tensor, float, int] ,      lowerCamelCase   :torch.FloatTensor ,      lowerCamelCase   :Optional[torch.FloatTensor] = None ,      lowerCamelCase   :Optional[torch.BoolTensor] = None ,      lowerCamelCase   :bool = True ,      )     ->			List[Any]:
       UpperCAmelCase__							 =						hidden_states.shape[0]

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

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

       UpperCAmelCase__							 =						self.time_proj(lowerCamelCase      )

       # 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__							 =						timesteps_projected.to(dtype=self.dtype      )
       UpperCAmelCase__							 =						self.time_embedding(lowerCamelCase      )

       if self.embedding_proj_norm is not None:
        UpperCAmelCase__							 =						self.embedding_proj_norm(lowerCamelCase      )

       UpperCAmelCase__							 =						self.embedding_proj(lowerCamelCase      )
       if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
        UpperCAmelCase__							 =						self.encoder_hidden_states_proj(lowerCamelCase      )
       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__							 =						self.proj_in(lowerCamelCase      )

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

       UpperCAmelCase__							 =						[]
       UpperCAmelCase__							 =						0

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

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

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

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

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

       UpperCAmelCase__							 =						torch.cat(
           lowerCamelCase ,      dim=1 ,      )

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

       UpperCAmelCase__							 =						hidden_states + positional_embeddings

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

       if self.norm_in is not None:
        UpperCAmelCase__							 =						self.norm_in(lowerCamelCase      )

       for block in self.transformer_blocks:
        UpperCAmelCase__							 =						block(lowerCamelCase ,      attention_mask=lowerCamelCase      )

       UpperCAmelCase__							 =						self.norm_out(lowerCamelCase      )

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

       UpperCAmelCase__							 =						self.proj_to_clip_embeddings(lowerCamelCase      )

       if not return_dict:
        return (predicted_image_embedding,)

       return PriorTransformerOutput(predicted_image_embedding=lowerCamelCase      )







      def 	UpperCAmelCase_						(			self   :List[str] ,      lowerCamelCase   :Dict      )     ->			str:
       UpperCAmelCase__							 =						(prior_latents * self.clip_std) + self.clip_mean
       return prior_latents











from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


_lowerCAmelCase						:   Any		=   logging.get_logger(__name__)
class 			_UpperCamelCase      (				lowerCAmelCase		):
      UpperCAmelCase_        =		["""input_values""", """padding_mask"""]
      def __init__(			self   :Dict ,      lowerCamelCase   :int = 1 ,      lowerCamelCase   :int = 2_4000 ,      lowerCamelCase   :float = 0.0 ,      lowerCamelCase   :float = None ,      lowerCamelCase   :float = None ,      **lowerCamelCase   :Optional[Any] ,      )     ->			str:
       super().__init__(feature_size=lowerCamelCase ,      sampling_rate=lowerCamelCase ,      padding_value=lowerCamelCase ,      **lowerCamelCase      )
       UpperCAmelCase__							 =						chunk_length_s
       UpperCAmelCase__							 =						overlap
      @property
      def 	UpperCAmelCase_						(			self   :Optional[Any]      )     ->			Optional[int]:
       if self.chunk_length_s is None:
        return None
       else:
        return int(self.chunk_length_s * self.sampling_rate      )
      @property
      def 	UpperCAmelCase_						(			self   :str      )     ->			Optional[int]:
       if self.chunk_length_s is None or self.overlap is None:
        return None
       else:
        return max(1 ,      int((1.0 - self.overlap) * self.chunk_length      )      )







      def __call__(			self   :List[Any] ,      lowerCamelCase   :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] ,      lowerCamelCase   :Optional[Union[bool, str, PaddingStrategy]] = None ,      lowerCamelCase   :Optional[bool] = False ,      lowerCamelCase   :Optional[int] = None ,      lowerCamelCase   :Optional[Union[str, TensorType]] = None ,      lowerCamelCase   :Optional[int] = None ,      )     ->			BatchFeature:
       if sampling_rate is not None:
        if sampling_rate != self.sampling_rate:
         raise ValueError(
             f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
             f''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with'''
             f''' {self.sampling_rate} and not {sampling_rate}.'''      )
       else:
        logger.warning(
            "It is strongly recommended to pass the `sampling_rate` argument to this function. "
            "Failing to do so can result in silent errors that might be hard to debug."      )

       if padding and truncation:
        raise ValueError("Both padding and truncation were set. Make sure you only set one."      )
       elif padding is None:
        # by default let's pad the inputs
        UpperCAmelCase__							 =						True

       UpperCAmelCase__							 =						bool(
           isinstance(lowerCamelCase ,      (list, tuple)      ) and (isinstance(raw_audio[0] ,      (np.ndarray, tuple, list)      ))      )

       if is_batched:
        UpperCAmelCase__							 =						[np.asarray(lowerCamelCase ,      dtype=np.floataa      ).T for audio in raw_audio]
       elif not is_batched and not isinstance(lowerCamelCase ,      np.ndarray      ):
        UpperCAmelCase__							 =						np.asarray(lowerCamelCase ,      dtype=np.floataa      )
       elif isinstance(lowerCamelCase ,      np.ndarray      ) and raw_audio.dtype is np.dtype(np.floataa      ):
        UpperCAmelCase__							 =						raw_audio.astype(np.floataa      )

       # always return batch
       if not is_batched:
        UpperCAmelCase__							 =						[np.asarray(lowerCamelCase      ).T]

       # verify inputs are valid
       for idx, example in enumerate(lowerCamelCase      ):
        if example.ndim > 2:
         raise ValueError(f'''Expected input shape (channels, length) but got shape {example.shape}'''      )
        if self.feature_size == 1 and example.ndim != 1:
         raise ValueError(f'''Expected mono audio but example has {example.shape[-1]} channels'''      )
        if self.feature_size == 2 and example.shape[-1] != 2:
         raise ValueError(f'''Expected stereo audio but example has {example.shape[-1]} channels'''      )

       UpperCAmelCase__							 =						None
       UpperCAmelCase__							 =						BatchFeature({"input_values": raw_audio}      )
       if self.chunk_stride is not None and self.chunk_length is not None and max_length is None:
        if truncation:
         UpperCAmelCase__							 =						min(array.shape[0] for array in raw_audio      )
         UpperCAmelCase__							 =						int(np.floor(max_length / self.chunk_stride      )      )
         UpperCAmelCase__							 =						(nb_step - 1) * self.chunk_stride + self.chunk_length
        elif padding:
         UpperCAmelCase__							 =						max(array.shape[0] for array in raw_audio      )
         UpperCAmelCase__							 =						int(np.ceil(max_length / self.chunk_stride      )      )
         UpperCAmelCase__							 =						(nb_step - 1) * self.chunk_stride + self.chunk_length
         UpperCAmelCase__							 =						"max_length"
        else:
         UpperCAmelCase__							 =						input_values

        # normal padding on batch
       if padded_inputs is None:
        UpperCAmelCase__							 =						self.pad(
            lowerCamelCase ,      max_length=lowerCamelCase ,      truncation=lowerCamelCase ,      padding=lowerCamelCase ,      return_attention_mask=lowerCamelCase ,      )
        if padding:
         UpperCAmelCase__							 =						padded_inputs.pop("attention_mask"      )

       UpperCAmelCase__							 =						[]
       for example in padded_inputs.pop("input_values"      ):
        if self.feature_size == 1:
         UpperCAmelCase__							 =						example[..., None]
        input_values.append(example.T      )

       UpperCAmelCase__							 =						input_values
       if return_tensors is not None:
        UpperCAmelCase__							 =						padded_inputs.convert_to_tensors(lowerCamelCase      )

       return padded_inputs





