




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_00_00.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_00_00.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











import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation


_lowerCAmelCase						:   str		=   logging.get_logger(__name__)

_lowerCAmelCase						:   List[Any]		=   {"tokenizer_file": "tokenizer.json"}

_lowerCAmelCase						:   Tuple		=   {
    "tokenizer_file": {
        "bigscience/tokenizer": "https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json",
        "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json",
        "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json",
        "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json",
        "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json",
        "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json",
        "bigscience/bloom": "https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json",
    },
}
class 			_UpperCamelCase      (				lowerCAmelCase		):
      UpperCAmelCase_        =		VOCAB_FILES_NAMES
      UpperCAmelCase_        =		PRETRAINED_VOCAB_FILES_MAP
      UpperCAmelCase_        =		["""input_ids""", """attention_mask"""]
      UpperCAmelCase_        =		None
      def __init__(			self   :List[Any] ,      lowerCamelCase   :Union[str, Any]=None ,      lowerCamelCase   :Optional[Any]=None ,      lowerCamelCase   :List[Any]=None ,      lowerCamelCase   :Union[str, Any]="<unk>" ,      lowerCamelCase   :Union[str, Any]="<s>" ,      lowerCamelCase   :Union[str, Any]="</s>" ,      lowerCamelCase   :str="<pad>" ,      lowerCamelCase   :Any=False ,      lowerCamelCase   :Optional[Any]=False ,      **lowerCamelCase   :Optional[Any] ,      )     ->			Any:
       super().__init__(
           lowerCamelCase ,      lowerCamelCase ,      tokenizer_file=lowerCamelCase ,      unk_token=lowerCamelCase ,      bos_token=lowerCamelCase ,      eos_token=lowerCamelCase ,      pad_token=lowerCamelCase ,      add_prefix_space=lowerCamelCase ,      clean_up_tokenization_spaces=lowerCamelCase ,      **lowerCamelCase ,      )
       UpperCAmelCase__							 =						json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()      )
       if pre_tok_state.get("add_prefix_space" ,      lowerCamelCase      ) != add_prefix_space:
        UpperCAmelCase__							 =						getattr(lowerCamelCase ,      pre_tok_state.pop("type"      )      )
        UpperCAmelCase__							 =						add_prefix_space
        UpperCAmelCase__							 =						pre_tok_class(**lowerCamelCase      )

       UpperCAmelCase__							 =						add_prefix_space
      def 	UpperCAmelCase_						(			self   :int ,      *lowerCamelCase   :Any ,      **lowerCamelCase   :int      )     ->			BatchEncoding:
       UpperCAmelCase__							 =						kwargs.get("is_split_into_words" ,      lowerCamelCase      )
       if not (self.add_prefix_space or not is_split_into_words):
        raise Exception(
            f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with'''
            " pretokenized inputs."      )

       return super()._batch_encode_plus(*lowerCamelCase ,      **lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :Any ,      *lowerCamelCase   :List[Any] ,      **lowerCamelCase   :Union[str, Any]      )     ->			BatchEncoding:
       UpperCAmelCase__							 =						kwargs.get("is_split_into_words" ,      lowerCamelCase      )

       if not (self.add_prefix_space or not is_split_into_words):
        raise Exception(
            f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with'''
            " pretokenized inputs."      )

       return super()._encode_plus(*lowerCamelCase ,      **lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :Tuple ,      lowerCamelCase   :str ,      lowerCamelCase   :Optional[str] = None      )     ->			Tuple[str]:
       UpperCAmelCase__							 =						self._tokenizer.model.save(lowerCamelCase ,      name=lowerCamelCase      )
       return tuple(lowerCamelCase      )







      def 	UpperCAmelCase_						(			self   :List[str] ,      lowerCamelCase   :"Conversation"      )     ->			List[int]:
       UpperCAmelCase__							 =						[]
       for is_user, text in conversation.iter_texts():
        input_ids.extend(self.encode(lowerCamelCase ,      add_special_tokens=lowerCamelCase      ) + [self.eos_token_id]      )

       if len(lowerCamelCase      ) > self.model_max_length:
        UpperCAmelCase__							 =						input_ids[-self.model_max_length :]
       return input_ids





