

'''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_						(		a			):

  '''simple docstring'''





  __lowerCAmelCase       :			torch.FloatTensor




class 							lowercase_						(		a			,							a			):

  '''simple docstring'''





  @register_to_config
  def __init__(  self ,			a_ = 3_2 ,			a_ = 6_4 ,			a_ = 2_0 ,			a_ = 7_6_8 ,			a_=7_7 ,			a_=4 ,			a_ = 0.0 ,			a_ = "silu" ,			a_ = None ,			a_ = None ,			a_ = "linear" ,			a_ = "prd" ,			a_ = None ,			a_ = None ,			a_ = None ,			)				->					Optional[int]:


    """simple docstring"""
    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(a_ ,			a_ ,			0  )
    UpperCAmelCase    				=						TimestepEmbedding(a_ ,			a_ ,			out_dim=a_ ,			act_fn=a_  )

    UpperCAmelCase    				=						nn.Linear(a_ ,			a_  )

    if embedding_proj_norm_type is None:
      UpperCAmelCase    				=						None
    elif embedding_proj_norm_type == "layer":
      UpperCAmelCase    				=						nn.LayerNorm(a_  )
    else:
      raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''  )

    UpperCAmelCase    				=						nn.Linear(a_ ,			a_  )

    if encoder_hid_proj_type is None:
      UpperCAmelCase    				=						None
    elif encoder_hid_proj_type == "linear":
      UpperCAmelCase    				=						nn.Linear(a_ ,			a_  )
    else:
      raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''  )

    UpperCAmelCase    				=						nn.Parameter(torch.zeros(1 ,			num_embeddings + additional_embeddings ,			a_  )  )

    if added_emb_type == "prd":
      UpperCAmelCase    				=						nn.Parameter(torch.zeros(1 ,			1 ,			a_  )  )
    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(
                a_ ,			a_ ,			a_ ,			dropout=a_ ,			activation_fn='gelu' ,			attention_bias=a_ ,			)
            for d in range(a_  )
        ]  )

    if norm_in_type == "layer":
      UpperCAmelCase    				=						nn.LayerNorm(a_  )
    elif norm_in_type is None:
      UpperCAmelCase    				=						None
    else:
      raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.'''  )

    UpperCAmelCase    				=						nn.LayerNorm(a_  )

    UpperCAmelCase    				=						nn.Linear(a_ ,			a_  )

    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' ,			a_ ,			persistent=a_  )

    UpperCAmelCase    				=						nn.Parameter(torch.zeros(1 ,			a_  )  )
    UpperCAmelCase    				=						nn.Parameter(torch.zeros(1 ,			a_  )  )
  @property
  # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
  def     snake_case_      (  self  )				->					Dict[str, AttentionProcessor]:


    """simple docstring"""
    UpperCAmelCase    				=						{}

    def fn_recursive_add_processors(a_ ,			a_ ,			a_  ):
      if hasattr(a_ ,			'set_processor'  ):
        UpperCAmelCase    				=						module.processor

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

      return processors

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

    return processors
  def     snake_case_      (  self ,			a_  )				->					Optional[Any]:


    """simple docstring"""
    UpperCAmelCase    				=						len(self.attn_processors.keys()  )

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

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

    for name, module in self.named_children():
      fn_recursive_attn_processor(a_ ,			a_ ,			a_  )
  def     snake_case_      (  self  )				->					Optional[Any]:


    """simple docstring"""
    self.set_attn_processor(AttnProcessor()  )
  def     snake_case_      (  self ,			a_ ,			a_ ,			a_ ,			a_ = None ,			a_ = None ,			a_ = True ,			)				->					Dict:


    """simple docstring"""
    UpperCAmelCase    				=						hidden_states.shape[0]

    UpperCAmelCase    				=						timestep
    if not torch.is_tensor(a_  ):
      UpperCAmelCase    				=						torch.tensor([timesteps] ,			dtype=torch.long ,			device=hidden_states.device  )
    elif torch.is_tensor(a_  ) 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(a_ ,			dtype=timesteps.dtype ,			device=timesteps.device  )

    UpperCAmelCase    				=						self.time_proj(a_  )

    # 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(a_  )

    if self.embedding_proj_norm is not None:
      UpperCAmelCase    				=						self.embedding_proj_norm(a_  )

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

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

    UpperCAmelCase    				=						[]
    UpperCAmelCase    				=						0

    if encoder_hidden_states is not None:
      additional_embeds.append(a_  )
      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(a_ ,			-1 ,			-1  )
      additional_embeds.append(a_  )

    UpperCAmelCase    				=						torch.cat(
        a_ ,			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(
          a_ ,			(
              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(a_ ,			(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(a_  )

    for block in self.transformer_blocks:
      UpperCAmelCase    				=						block(a_ ,			attention_mask=a_  )

    UpperCAmelCase    				=						self.norm_out(a_  )

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

    UpperCAmelCase    				=						self.proj_to_clip_embeddings(a_  )

    if not return_dict:
      return (predicted_image_embedding,)

    return PriorTransformerOutput(predicted_image_embedding=a_  )





  def     snake_case_      (  self ,			a_  )				->					Optional[Any]:


    """simple docstring"""
    UpperCAmelCase    				=						(prior_latents * self.clip_std) + self.clip_mean
    return prior_latents





'''simple docstring'''




import hashlib
import unittest
from typing import Dict

import numpy as np

from transformers import (
    MODEL_FOR_MASK_GENERATION_MAPPING,
    TF_MODEL_FOR_MASK_GENERATION_MAPPING,
    is_vision_available,
    pipeline,
)
from transformers.pipelines import MaskGenerationPipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)


if is_vision_available():
  from PIL import Image
else:



  class 							lowercase_						:

    '''simple docstring'''





    @staticmethod
    def     snake_case_      (  *a_ ,			**a_  )				->					Tuple:


      """simple docstring"""
      pass


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Image    ):
  UpperCAmelCase    				=						hashlib.mda(image.tobytes()    )
  return m.hexdigest()[:10]


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Image    ):
  UpperCAmelCase    				=						np.array(SCREAMING_SNAKE_CASE    )
  UpperCAmelCase    				=						npimg.shape
  return {"hash": hashimage(SCREAMING_SNAKE_CASE    ), "shape": shape}



@is_pipeline_test
@require_vision
@require_torch
class 							lowercase_						(		unittest.TestCase			):

  '''simple docstring'''





  __lowerCAmelCase       :			Tuple     	= dict(
      (list(MODEL_FOR_MASK_GENERATION_MAPPING.items()			) if MODEL_FOR_MASK_GENERATION_MAPPING else [])			)
  __lowerCAmelCase       :			Tuple     	= dict(
      (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items()			) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else [])			)
  def     snake_case_      (  self ,			a_ ,			a_ ,			a_  )				->					Dict:


    """simple docstring"""
    UpperCAmelCase    				=						MaskGenerationPipeline(model=a_ ,			image_processor=a_  )
    return image_segmenter, [
        "./tests/fixtures/tests_samples/COCO/000000039769.png",
        "./tests/fixtures/tests_samples/COCO/000000039769.png",
    ]
  def     snake_case_      (  self ,			a_ ,			a_  )				->					Optional[Any]:


    """simple docstring"""
    pass
  @require_tf
  @unittest.skip('Image segmentation not implemented in TF'  )
  def     snake_case_      (  self  )				->					Union[str, Any]:


    """simple docstring"""
    pass
  @slow
  @require_torch
  def     snake_case_      (  self  )				->					Optional[int]:


    """simple docstring"""
    UpperCAmelCase    				=						pipeline('mask-generation' ,			model='facebook/sam-vit-huge'  )

    UpperCAmelCase    				=						image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' ,			points_per_batch=2_5_6  )

    # Shortening by hashing
    UpperCAmelCase    				=						[]
    for i, o in enumerate(outputs['masks']  ):
      new_outupt += [{"mask": mask_to_test_readable(a_  ), "scores": outputs["scores"][i]}]

    # fmt: off
    self.assertEqual(
        nested_simplify(a_ ,			decimals=4  ) ,			[
            {'mask': {'hash': '115ad19f5f', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0444},
            {'mask': {'hash': '6affa964c6', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.021},
            {'mask': {'hash': 'dfe28a0388', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0167},
            {'mask': {'hash': 'c0a5f4a318', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0132},
            {'mask': {'hash': 'fe8065c197', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0053},
            {'mask': {'hash': 'e2d0b7a0b7', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9967},
            {'mask': {'hash': '453c7844bd', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.993},
            {'mask': {'hash': '3d44f2926d', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9909},
            {'mask': {'hash': '64033ddc3f', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9879},
            {'mask': {'hash': '801064ff79', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9834},
            {'mask': {'hash': '6172f276ef', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9716},
            {'mask': {'hash': 'b49e60e084', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9612},
            {'mask': {'hash': 'a811e775fd', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9599},
            {'mask': {'hash': 'a6a8ebcf4b', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9552},
            {'mask': {'hash': '9d8257e080', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9532},
            {'mask': {'hash': '32de6454a8', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9516},
            {'mask': {'hash': 'af3d4af2c8', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9499},
            {'mask': {'hash': '3c6db475fb', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9483},
            {'mask': {'hash': 'c290813fb9', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9464},
            {'mask': {'hash': 'b6f0b8f606', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.943},
            {'mask': {'hash': '92ce16bfdf', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.943},
            {'mask': {'hash': 'c749b25868', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9408},
            {'mask': {'hash': 'efb6cab859', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9335},
            {'mask': {'hash': '1ff2eafb30', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9326},
            {'mask': {'hash': '788b798e24', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.9262},
            {'mask': {'hash': 'abea804f0e', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.8999},
            {'mask': {'hash': '7b9e8ddb73', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.8986},
            {'mask': {'hash': 'cd24047c8a', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.8984},
            {'mask': {'hash': '6943e6bcbd', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.8873},
            {'mask': {'hash': 'b5f47c9191', 'shape': (4_8_0, 6_4_0)}, 'scores': 0.8871}
        ] ,			)
    # fmt: on





  @require_torch
  @slow
  def     snake_case_      (  self  )				->					Dict:


    """simple docstring"""
    UpperCAmelCase    				=						'facebook/sam-vit-huge'
    UpperCAmelCase    				=						pipeline('mask-generation' ,			model=a_  )

    UpperCAmelCase    				=						image_segmenter(
        'http://images.cocodataset.org/val2017/000000039769.jpg' ,			pred_iou_thresh=1 ,			points_per_batch=2_5_6  )

    # Shortening by hashing
    UpperCAmelCase    				=						[]
    for i, o in enumerate(outputs['masks']  ):
      new_outupt += [{"mask": mask_to_test_readable(a_  ), "scores": outputs["scores"][i]}]

    self.assertEqual(
        nested_simplify(a_ ,			decimals=4  ) ,			[
            {'mask': {'hash': '115ad19f5f', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0444},
            {'mask': {'hash': '6affa964c6', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0210},
            {'mask': {'hash': 'dfe28a0388', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0167},
            {'mask': {'hash': 'c0a5f4a318', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0132},
            {'mask': {'hash': 'fe8065c197', 'shape': (4_8_0, 6_4_0)}, 'scores': 1.0053},
        ] ,			)


