"""simple docstring"""







import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
       import jax

       from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel







class        UpperCamelCase		(			unittest.TestCase  ):
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase=13     ,__UpperCamelCase=30     ,__UpperCamelCase=2     ,__UpperCamelCase=3     ,__UpperCamelCase=True     ,__UpperCamelCase=True     ,__UpperCamelCase=32     ,__UpperCamelCase=5     ,__UpperCamelCase=4     ,__UpperCamelCase=37     ,__UpperCamelCase="gelu"     ,__UpperCamelCase=0.1     ,__UpperCamelCase=0.1     ,__UpperCamelCase=10     ,__UpperCamelCase=0.02     ,)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Tuple													=	parent
        lowercase_	:				Union[str, Any]													=	batch_size
        lowercase_	:				int													=	image_size
        lowercase_	:				Tuple													=	patch_size
        lowercase_	:				Optional[int]													=	num_channels
        lowercase_	:				Union[str, Any]													=	is_training
        lowercase_	:				Dict													=	use_labels
        lowercase_	:				Optional[int]													=	hidden_size
        lowercase_	:				List[str]													=	num_hidden_layers
        lowercase_	:				Optional[Any]													=	num_attention_heads
        lowercase_	:				Optional[int]													=	intermediate_size
        lowercase_	:				Tuple													=	hidden_act
        lowercase_	:				int													=	hidden_dropout_prob
        lowercase_	:				str													=	attention_probs_dropout_prob
        lowercase_	:				str													=	type_sequence_label_size
        lowercase_	:				Optional[int]													=	initializer_range

        # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        lowercase_	:				str													=	(image_size // patch_size) ** 2
        lowercase_	:				Optional[int]													=	num_patches + 1
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Tuple													=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

        lowercase_	:				List[Any]													=	ViTConfig(
            image_size=self.image_size     ,patch_size=self.patch_size     ,num_channels=self.num_channels     ,hidden_size=self.hidden_size     ,num_hidden_layers=self.num_hidden_layers     ,num_attention_heads=self.num_attention_heads     ,intermediate_size=self.intermediate_size     ,hidden_act=self.hidden_act     ,hidden_dropout_prob=self.hidden_dropout_prob     ,attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,is_decoder=__UpperCamelCase     ,initializer_range=self.initializer_range     ,)

        return config, pixel_values
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	FlaxViTModel(config=__UpperCamelCase			)
        lowercase_	:				Dict													=	model(__UpperCamelCase			)
        # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
        lowercase_	:				Union[str, Any]													=	(self.image_size, self.image_size)
        lowercase_	:				List[Any]													=	(self.patch_size, self.patch_size)
        lowercase_	:				List[str]													=	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
        self.parent.assertEqual(result.last_hidden_state.shape     ,(self.batch_size, num_patches + 1, self.hidden_size)			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Union[str, Any]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	self.type_sequence_label_size
        lowercase_	:				str													=	FlaxViTForImageClassification(config=__UpperCamelCase			)
        lowercase_	:				Optional[Any]													=	model(__UpperCamelCase			)
        self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.type_sequence_label_size)			)

        # test greyscale images
        lowercase_	:				Union[str, Any]													=	1
        lowercase_	:				Optional[int]													=	FlaxViTForImageClassification(__UpperCamelCase			)

        lowercase_	:				List[Any]													=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
        lowercase_	:				str													=	model(__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	self.prepare_config_and_inputs()
        (
            (
            lowercase_
        )							,  (
            lowercase_
        )							,  
        )	:				List[Any]													=	config_and_inputs
        lowercase_	:				Tuple													=	{'pixel_values': pixel_values}
        return config, inputs_dict







@require_flax
class        UpperCamelCase		(			lowercase_						,      unittest.TestCase  ):
   lowercase							=  (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()
   def 			_UpperCAmelCase   (			self			)	->      None:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	FlaxViTModelTester(self			)
        lowercase_	:				Union[str, Any]													=	ConfigTester(self     ,config_class=__UpperCamelCase     ,has_text_modality=__UpperCamelCase     ,hidden_size=37			)
   def 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        self.config_tester.run_common_tests()
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Any													=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             lowercase_	:				Optional[Any]													=	model_class(__UpperCamelCase			)
             lowercase_	:				Tuple													=	inspect.signature(model.__call__			)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             lowercase_	:				Union[str, Any]													=	[*signature.parameters.keys()]

             lowercase_	:				str													=	['pixel_values']
             self.assertListEqual(arg_names[:1]     ,__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				str													=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__			):
                  lowercase_	:				Optional[Any]													=	self._prepare_for_class(__UpperCamelCase     ,__UpperCamelCase			)
                  lowercase_	:				Dict													=	model_class(__UpperCamelCase			)

                  @jax.jit
                  def model_jitted(__UpperCamelCase     ,**__UpperCamelCase			):
                       return model(pixel_values=__UpperCamelCase     ,**__UpperCamelCase			)

                  with self.subTest('JIT Enabled'			):
                       lowercase_	:				Optional[int]													=	model_jitted(**__UpperCamelCase			).to_tuple()

                  with self.subTest('JIT Disabled'			):
                       with jax.disable_jit():
                            lowercase_	:				List[str]													=	model_jitted(**__UpperCamelCase			).to_tuple()

                  self.assertEqual(len(__UpperCamelCase			)     ,len(__UpperCamelCase			)			)
                  for jitted_output, output in zip(__UpperCamelCase     ,__UpperCamelCase			):
                       self.assertEqual(jitted_output.shape     ,output.shape			)







   @slow
   def 			_UpperCAmelCase   (			self			)	->      Optional[int]:


        '''simple docstring'''


        for model_class_name in self.all_model_classes:
             lowercase_	:				Optional[int]													=	model_class_name.from_pretrained('google/vit-base-patch16-224'			)
             lowercase_	:				int													=	model(np.ones((1, 3, 224, 224)			)			)
             self.assertIsNotNone(__UpperCamelCase			)


"""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        UpperCamelCase		(			lowercase_  ):
   lowercase							=  42







class        UpperCamelCase		(			lowercase_						,      lowercase_  ):
   @register_to_config
   def __init__(			self     ,__UpperCamelCase = 32     ,__UpperCamelCase = 64     ,__UpperCamelCase = 20     ,__UpperCamelCase = 768     ,__UpperCamelCase=77     ,__UpperCamelCase=4     ,__UpperCamelCase = 0.0     ,__UpperCamelCase = "silu"     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = "linear"     ,__UpperCamelCase = "prd"     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,)	->      List[str]:


        '''simple docstring'''


        super().__init__()
        lowercase_	:				Dict													=	num_attention_heads
        lowercase_	:				Dict													=	attention_head_dim
        lowercase_	:				Any													=	num_attention_heads * attention_head_dim
        lowercase_	:				Optional[Any]													=	additional_embeddings

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

        lowercase_	:				Union[str, Any]													=	Timesteps(__UpperCamelCase     ,__UpperCamelCase     ,0			)
        lowercase_	:				Tuple													=	TimestepEmbedding(__UpperCamelCase     ,__UpperCamelCase     ,out_dim=__UpperCamelCase     ,act_fn=__UpperCamelCase			)

        lowercase_	:				Optional[Any]													=	nn.Linear(__UpperCamelCase     ,__UpperCamelCase			)

        if embedding_proj_norm_type is None:
             lowercase_	:				Dict													=	None
        elif embedding_proj_norm_type == "layer":
             lowercase_	:				str													=	nn.LayerNorm(__UpperCamelCase			)
        else:
             raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''			)

        lowercase_	:				Tuple													=	nn.Linear(__UpperCamelCase     ,__UpperCamelCase			)

        if encoder_hid_proj_type is None:
             lowercase_	:				str													=	None
        elif encoder_hid_proj_type == "linear":
             lowercase_	:				Optional[int]													=	nn.Linear(__UpperCamelCase     ,__UpperCamelCase			)
        else:
             raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''			)

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

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

        lowercase_	:				Dict													=	nn.ModuleList(
            [
                BasicTransformerBlock(
                    __UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,dropout=__UpperCamelCase     ,activation_fn='gelu'     ,attention_bias=__UpperCamelCase     ,)
                for d in range(__UpperCamelCase			)
            ]			)

        if norm_in_type == "layer":
             lowercase_	:				Optional[int]													=	nn.LayerNorm(__UpperCamelCase			)
        elif norm_in_type is None:
             lowercase_	:				Dict													=	None
        else:
             raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.'''			)

        lowercase_	:				List[Any]													=	nn.LayerNorm(__UpperCamelCase			)

        lowercase_	:				Optional[int]													=	nn.Linear(__UpperCamelCase     ,__UpperCamelCase			)

        lowercase_	:				Dict													=	torch.full(
            [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]     ,-1_0000.0			)
        causal_attention_mask.triu_(1			)
        lowercase_	:				int													=	causal_attention_mask[None, ...]
        self.register_buffer('causal_attention_mask'     ,__UpperCamelCase     ,persistent=__UpperCamelCase			)

        lowercase_	:				List[Any]													=	nn.Parameter(torch.zeros(1     ,__UpperCamelCase			)			)
        lowercase_	:				Optional[int]													=	nn.Parameter(torch.zeros(1     ,__UpperCamelCase			)			)
   @property
   # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
   def 			_UpperCAmelCase   (			self			)	->      Dict[str, AttentionProcessor]:


        '''simple docstring'''


        lowercase_	:				Tuple													=	{}

        def fn_recursive_add_processors(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			):
             if hasattr(__UpperCamelCase     ,'set_processor'			):
                  lowercase_	:				List[str]													=	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 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				Dict													=	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     ,__UpperCamelCase     ,__UpperCamelCase			):
             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 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        self.set_attn_processor(AttnProcessor()			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = True     ,)	->      Any:


        '''simple docstring'''


        lowercase_	:				Any													=	hidden_states.shape[0]

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

        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
        lowercase_	:				Optional[int]													=	timesteps * torch.ones(__UpperCamelCase     ,dtype=timesteps.dtype     ,device=timesteps.device			)

        lowercase_	:				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.
        lowercase_	:				List[Any]													=	timesteps_projected.to(dtype=self.dtype			)
        lowercase_	:				Any													=	self.time_embedding(__UpperCamelCase			)

        if self.embedding_proj_norm is not None:
             lowercase_	:				List[str]													=	self.embedding_proj_norm(__UpperCamelCase			)

        lowercase_	:				Any													=	self.embedding_proj(__UpperCamelCase			)
        if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
             lowercase_	:				Optional[int]													=	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'			)

        lowercase_	:				List[Any]													=	self.proj_in(__UpperCamelCase			)

        lowercase_	:				List[str]													=	self.positional_embedding.to(hidden_states.dtype			)

        lowercase_	:				Dict													=	[]
        lowercase_	:				Tuple													=	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:
             lowercase_	:				List[Any]													=	proj_embeddings[:, None, :]

        if len(hidden_states.shape			) == 2:
             lowercase_	:				List[Any]													=	hidden_states[:, None, :]

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

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

        lowercase_	:				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
        lowercase_	:				Optional[Any]													=	additional_embeddings_len + proj_embeddings.shape[1] + 1
        if positional_embeddings.shape[1] < hidden_states.shape[1]:
             lowercase_	:				Any													=	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     ,)

        lowercase_	:				Dict													=	hidden_states + positional_embeddings

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

        if self.norm_in is not None:
             lowercase_	:				Optional[Any]													=	self.norm_in(__UpperCamelCase			)

        for block in self.transformer_blocks:
             lowercase_	:				int													=	block(__UpperCamelCase     ,attention_mask=__UpperCamelCase			)

        lowercase_	:				str													=	self.norm_out(__UpperCamelCase			)

        if self.prd_embedding is not None:
             lowercase_	:				Tuple													=	hidden_states[:, -1]
        else:
             lowercase_	:				List[Any]													=	hidden_states[:, additional_embeddings_len:]

        lowercase_	:				str													=	self.proj_to_clip_embeddings(__UpperCamelCase			)

        if not return_dict:
             return (predicted_image_embedding,)

        return PriorTransformerOutput(predicted_image_embedding=__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      int:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	(prior_latents * self.clip_std) + self.clip_mean
        return prior_latents

