




import unittest

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

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
 import jax

 from transformers.models.big_bird.modeling_flax_big_bird import (
     FlaxBigBirdForCausalLM,
     FlaxBigBirdForMaskedLM,
     FlaxBigBirdForMultipleChoice,
     FlaxBigBirdForPreTraining,
     FlaxBigBirdForQuestionAnswering,
     FlaxBigBirdForSequenceClassification,
     FlaxBigBirdForTokenClassification,
     FlaxBigBirdModel,
 )







class   A(						unittest.TestCase       ):



 '''simple docstring'''


 def __init__(    self :  Optional[Any]						,							A_ :  Tuple						,							A_ :  Optional[int]=2						,							A_ :  Union[str, Any]=56						,							A_ :  Tuple=True						,							A_ :  int=True						,							A_ :  Any=True						,							A_ :  Tuple=True						,							A_ :  List[str]=99						,							A_ :  List[str]=32						,							A_ :  Dict=2						,							A_ :  Dict=2						,							A_ :  Optional[int]=7						,							A_ :  List[Any]="gelu_new"						,							A_ :  Union[str, Any]=0.1						,							A_ :  Optional[Any]=0.1						,							A_ :  int=512						,							A_ :  Optional[Any]=16						,							A_ :  Dict=2						,							A_ :  Optional[Any]=0.02						,							A_ :  Tuple=4						,							A_ :  Optional[Any]="block_sparse"						,							A_ :  Optional[int]=True						,							A_ :  Union[str, Any]=False						,							A_ :  str=2						,							A_ :  Optional[Any]=3						,							)       ->     List[Any]:

       """simple docstring"""






       lowerCamelCase_							=   parent
       lowerCamelCase_							=   batch_size
       lowerCamelCase_							=   seq_length
       lowerCamelCase_							=   is_training
       lowerCamelCase_							=   use_attention_mask
       lowerCamelCase_							=   use_token_type_ids
       lowerCamelCase_							=   use_labels
       lowerCamelCase_							=   vocab_size
       lowerCamelCase_							=   hidden_size
       lowerCamelCase_							=   num_hidden_layers
       lowerCamelCase_							=   num_attention_heads
       lowerCamelCase_							=   intermediate_size
       lowerCamelCase_							=   hidden_act
       lowerCamelCase_							=   hidden_dropout_prob
       lowerCamelCase_							=   attention_probs_dropout_prob
       lowerCamelCase_							=   max_position_embeddings
       lowerCamelCase_							=   type_vocab_size
       lowerCamelCase_							=   type_sequence_label_size
       lowerCamelCase_							=   initializer_range
       lowerCamelCase_							=   num_choices

       lowerCamelCase_							=   rescale_embeddings
       lowerCamelCase_							=   attention_type
       lowerCamelCase_							=   use_bias
       lowerCamelCase_							=   block_size
       lowerCamelCase_							=   num_random_blocks

 def     a__			(    self :  str  )       ->     str:

       """simple docstring"""






       lowerCamelCase_							=   ids_tensor([self.batch_size, self.seq_length]						,							self.vocab_size  )

       lowerCamelCase_							=   None
       if self.use_attention_mask:
             lowerCamelCase_							=   random_attention_mask([self.batch_size, self.seq_length]  )

       lowerCamelCase_							=   None
       if self.use_token_type_ids:
             lowerCamelCase_							=   ids_tensor([self.batch_size, self.seq_length]						,							self.type_vocab_size  )

       lowerCamelCase_							=   BigBirdConfig(
           vocab_size=self.vocab_size						,							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						,							max_position_embeddings=self.max_position_embeddings						,							type_vocab_size=self.type_vocab_size						,							is_decoder=A_						,							initializer_range=self.initializer_range						,							attention_type=self.attention_type						,							block_size=self.block_size						,							num_random_blocks=self.num_random_blocks						,							use_bias=self.use_bias						,							rescale_embeddings=self.rescale_embeddings						,							)

       return config, input_ids, token_type_ids, attention_mask





 def     a__			(    self :  Any  )       ->     Dict:

       """simple docstring"""






       lowerCamelCase_							=   self.prepare_config_and_inputs()
       lowerCamelCase_					,    lowerCamelCase_					,    lowerCamelCase_					,    lowerCamelCase_							=   config_and_inputs
       lowerCamelCase_							=   {
           'input_ids': input_ids,
           'token_type_ids': token_type_ids,
           'attention_mask': attention_mask,
       }
       return config, inputs_dict







@require_flax
class   A(						UpperCamelCase							,				unittest.TestCase       ):



 '''simple docstring'''


 UpperCamelCase						       =						(
     (
         FlaxBigBirdForCausalLM,
         FlaxBigBirdModel,
         FlaxBigBirdForPreTraining,
         FlaxBigBirdForMaskedLM,
         FlaxBigBirdForMultipleChoice,
         FlaxBigBirdForQuestionAnswering,
         FlaxBigBirdForSequenceClassification,
         FlaxBigBirdForTokenClassification,
     )
     if is_flax_available()
     else ()
 )

 UpperCamelCase						       =						False
 UpperCamelCase						       =						False

 def     a__			(    self :  Union[str, Any]  )       ->     Any:

       """simple docstring"""






       lowerCamelCase_							=   FlaxBigBirdModelTester(self  )

 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def     a__			(    self :  Optional[int]  )       ->     str:

       """simple docstring"""






       super().test_from_pretrained_save_pretrained()

 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def     a__			(    self :  Tuple  )       ->     Tuple:

       """simple docstring"""






       super().test_from_pretrained_with_no_automatic_init()

 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def     a__			(    self :  Dict  )       ->     Union[str, Any]:

       """simple docstring"""






       super().test_no_automatic_init()

 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def     a__			(    self :  int  )       ->     List[Any]:

       """simple docstring"""






       super().test_hidden_states_output()

 @slow
 def     a__			(    self :  Dict  )       ->     Any:

       """simple docstring"""






       for model_class_name in self.all_model_classes:
             lowerCamelCase_							=   model_class_name.from_pretrained('google/bigbird-roberta-base'  )
             self.assertIsNotNone(A_  )

 def     a__			(    self :  str  )       ->     Dict:

       """simple docstring"""






       if self.test_attn_probs:
             super().test_attention_outputs()

 @slow
 # copied from `test_modeling_flax_common` because it takes much longer than other models
 def     a__			(    self :  Any  )       ->     Optional[int]:

       """simple docstring"""






       lowerCamelCase_					,    lowerCamelCase_							=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__  ):
                   lowerCamelCase_							=   self._prepare_for_class(A_						,							A_  )
                   lowerCamelCase_							=   model_class(A_  )

                   @jax.jit
                   def model_jitted(A_ :  List[str]						,							A_ :  Union[str, Any]=None						,							**A_ :  int  ):
                         return model(input_ids=A_						,							attention_mask=A_						,							**A_  )

                   with self.subTest('JIT Enabled'  ):
                         lowerCamelCase_							=   model_jitted(**A_  ).to_tuple()

                   with self.subTest('JIT Disabled'  ):
                         with jax.disable_jit():
                               lowerCamelCase_							=   model_jitted(**A_  ).to_tuple()

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





 def     a__			(    self :  List[str]						,							A_ :  List[Any]						,							A_ :  Dict						,							A_ :  Union[str, Any]						,							A_ :  Optional[Any]=1E-5						,							A_ :  str="outputs"						,							A_ :  Tuple=None  )       ->     List[Any]:

       """simple docstring"""






       if name.startswith('outputs.attentions'  ):
             return
       else:
             super().check_pt_flax_outputs(A_						,							A_						,							A_						,							A_						,							A_						,							A_  )









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   A(						UpperCamelCase       ):



 '''simple docstring'''


 UpperCamelCase						       =						42







class   A(						UpperCamelCase							,				UpperCamelCase       ):



 '''simple docstring'''


 @register_to_config
 def __init__(    self :  Tuple						,							A_ :  int = 32						,							A_ :  int = 64						,							A_ :  int = 20						,							A_ :  int = 768						,							A_ :  Optional[Any]=77						,							A_ :  Optional[int]=4						,							A_ :  float = 0.0						,							A_ :  str = "silu"						,							A_ :  Optional[str] = None						,							A_ :  Optional[str] = None						,							A_ :  Optional[str] = "linear"						,							A_ :  Optional[str] = "prd"						,							A_ :  Optional[int] = None						,							A_ :  Optional[int] = None						,							A_ :  Optional[int] = None						,							)       ->     List[Any]:

       """simple docstring"""






       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(A_						,							A_						,							0  )
       lowerCamelCase_							=   TimestepEmbedding(A_						,							A_						,							out_dim=A_						,							act_fn=A_  )

       lowerCamelCase_							=   nn.Linear(A_						,							A_  )

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

       lowerCamelCase_							=   nn.Linear(A_						,							A_  )

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

       lowerCamelCase_							=   nn.Parameter(torch.zeros(1						,							num_embeddings + additional_embeddings						,							A_  )  )

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

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

       lowerCamelCase_							=   nn.LayerNorm(A_  )

       lowerCamelCase_							=   nn.Linear(A_						,							A_  )

       lowerCamelCase_							=   torch.full(
           [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]						,							-10000.0  )
       causal_attention_mask.triu_(1  )
       lowerCamelCase_							=   causal_attention_mask[None, ...]
       self.register_buffer('causal_attention_mask'						,							A_						,							persistent=A_  )

       lowerCamelCase_							=   nn.Parameter(torch.zeros(1						,							A_  )  )
       lowerCamelCase_							=   nn.Parameter(torch.zeros(1						,							A_  )  )

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

       """simple docstring"""






       lowerCamelCase_							=   {}

       def fn_recursive_add_processors(A_ :  str						,							A_ :  torch.nn.Module						,							A_ :  Dict[str, AttentionProcessor]  ):
             if hasattr(A_						,							'set_processor'  ):
                   lowerCamelCase_							=   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     a__			(    self :  List[Any]						,							A_ :  Union[AttentionProcessor, Dict[str, AttentionProcessor]]  )       ->     Dict:

       """simple docstring"""






       lowerCamelCase_							=   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_ :  str						,							A_ :  torch.nn.Module						,							A_ :  Union[str, Any]  ):
             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     a__			(    self :  List[Any]  )       ->     List[Any]:

       """simple docstring"""






       self.set_attn_processor(AttnProcessor()  )

 def     a__			(    self :  Dict						,							A_ :  List[Any]						,							A_ :  Union[torch.Tensor, float, int]						,							A_ :  torch.FloatTensor						,							A_ :  Optional[torch.FloatTensor] = None						,							A_ :  Optional[torch.BoolTensor] = None						,							A_ :  bool = True						,							)       ->     str:

       """simple docstring"""






       lowerCamelCase_							=   hidden_states.shape[0]

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

       lowerCamelCase_							=   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.
       lowerCamelCase_							=   timesteps_projected.to(dtype=self.dtype  )
       lowerCamelCase_							=   self.time_embedding(A_  )

       if self.embedding_proj_norm is not None:
             lowerCamelCase_							=   self.embedding_proj_norm(A_  )

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

       lowerCamelCase_							=   self.proj_in(A_  )

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

       lowerCamelCase_							=   []
       lowerCamelCase_							=   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:
             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(A_						,							-1						,							-1  )
             additional_embeds.append(A_  )

       lowerCamelCase_							=   torch.cat(
           A_						,							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(
                 A_						,							(
                     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  )) * -10000.0
             lowerCamelCase_							=   F.pad(A_						,							(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(A_  )

       for block in self.transformer_blocks:
             lowerCamelCase_							=   block(A_						,							attention_mask=A_  )

       lowerCamelCase_							=   self.norm_out(A_  )

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

       lowerCamelCase_							=   self.proj_to_clip_embeddings(A_  )

       if not return_dict:
             return (predicted_image_embedding,)

       return PriorTransformerOutput(predicted_image_embedding=A_  )





 def     a__			(    self :  Tuple						,							A_ :  List[Any]  )       ->     Any:

       """simple docstring"""






       lowerCamelCase_							=   (prior_latents * self.clip_std) + self.clip_mean
       return prior_latents



