
"""simple docstring"""






import unittest

from transformers import AutoTokenizer, NystromformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     NystromformerForMaskedLM,
     NystromformerForMultipleChoice,
     NystromformerForQuestionAnswering,
     NystromformerForSequenceClassification,
     NystromformerForTokenClassification,
     NystromformerModel,
 )
 from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST





class 				a__					:



     def __init__(							self :Any      ,  _lowerCamelCase :str      ,  _lowerCamelCase :Dict=13      ,  _lowerCamelCase :str=7      ,  _lowerCamelCase :Union[str, Any]=True      ,  _lowerCamelCase :str=True      ,  _lowerCamelCase :Optional[Any]=True      ,  _lowerCamelCase :List[Any]=True      ,  _lowerCamelCase :Union[str, Any]=99      ,  _lowerCamelCase :Dict=32      ,  _lowerCamelCase :Any=5      ,  _lowerCamelCase :Optional[Any]=4      ,  _lowerCamelCase :Optional[int]=37      ,  _lowerCamelCase :List[Any]="gelu"      ,  _lowerCamelCase :Any=0.1      ,  _lowerCamelCase :List[str]=0.1      ,  _lowerCamelCase :Any=512      ,  _lowerCamelCase :List[Any]=16      ,  _lowerCamelCase :List[Any]=2      ,  _lowerCamelCase :Optional[Any]=0.02      ,  _lowerCamelCase :Tuple=3      ,  _lowerCamelCase :List[str]=4      ,  _lowerCamelCase :List[Any]=None      ,  ):







      '''simple docstring'''



      UpperCamelCase_     :					Any   	=parent
      UpperCamelCase_     :					Any   	=batch_size
      UpperCamelCase_     :					Any   	=seq_length
      UpperCamelCase_     :					Tuple   	=is_training
      UpperCamelCase_     :					int   	=use_input_mask
      UpperCamelCase_     :					List[Any]   	=use_token_type_ids
      UpperCamelCase_     :					Dict   	=use_labels
      UpperCamelCase_     :					Union[str, Any]   	=vocab_size
      UpperCamelCase_     :					Optional[int]   	=hidden_size
      UpperCamelCase_     :					Union[str, Any]   	=num_hidden_layers
      UpperCamelCase_     :					int   	=num_attention_heads
      UpperCamelCase_     :					Optional[Any]   	=intermediate_size
      UpperCamelCase_     :					int   	=hidden_act
      UpperCamelCase_     :					int   	=hidden_dropout_prob
      UpperCamelCase_     :					int   	=attention_probs_dropout_prob
      UpperCamelCase_     :					Optional[int]   	=max_position_embeddings
      UpperCamelCase_     :					Union[str, Any]   	=type_vocab_size
      UpperCamelCase_     :					Dict   	=type_sequence_label_size
      UpperCamelCase_     :					int   	=initializer_range
      UpperCamelCase_     :					Tuple   	=num_labels
      UpperCamelCase_     :					str   	=num_choices
      UpperCamelCase_     :					List[str]   	=scope



     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					int   	=ids_tensor([self.batch_size, self.seq_length]      ,  self.vocab_size   )

      UpperCamelCase_     :					List[Any]   	=None
      if self.use_input_mask:
       UpperCamelCase_     :					List[Any]   	=random_attention_mask([self.batch_size, self.seq_length]   )

      UpperCamelCase_     :					str   	=None
      if self.use_token_type_ids:
       UpperCamelCase_     :					Optional[Any]   	=ids_tensor([self.batch_size, self.seq_length]      ,  self.type_vocab_size   )

      UpperCamelCase_     :					Tuple   	=None
      UpperCamelCase_     :					Tuple   	=None
      UpperCamelCase_     :					Dict   	=None
      if self.use_labels:
       UpperCamelCase_     :					int   	=ids_tensor([self.batch_size]      ,  self.type_sequence_label_size   )
       UpperCamelCase_     :					List[Any]   	=ids_tensor([self.batch_size, self.seq_length]      ,  self.num_labels   )
       UpperCamelCase_     :					Optional[Any]   	=ids_tensor([self.batch_size]      ,  self.num_choices   )

      UpperCamelCase_     :					str   	=self.get_config()

      return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      return NystromformerConfig(
          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=_lowerCamelCase      ,  initializer_range=self.initializer_range      ,  )



     def  lowerCamelCase_						(							self :Optional[Any]      ,  _lowerCamelCase :List[Any]      ,  _lowerCamelCase :Optional[Any]      ,  _lowerCamelCase :Dict      ,  _lowerCamelCase :Union[str, Any]      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :Dict      ,  _lowerCamelCase :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=NystromformerModel(config=_lowerCamelCase   )
      model.to(_lowerCamelCase   )
      model.eval()
      UpperCamelCase_     :					Optional[int]   	=model(_lowerCamelCase      ,  attention_mask=_lowerCamelCase      ,  token_type_ids=_lowerCamelCase   )
      UpperCamelCase_     :					Optional[int]   	=model(_lowerCamelCase      ,  token_type_ids=_lowerCamelCase   )
      UpperCamelCase_     :					Optional[Any]   	=model(_lowerCamelCase   )
      self.parent.assertEqual(result.last_hidden_state.shape      ,  (self.batch_size, self.seq_length, self.hidden_size)   )



     def  lowerCamelCase_						(							self :Union[str, Any]      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :Any      ,  _lowerCamelCase :Optional[int]      ,  _lowerCamelCase :int      ,  _lowerCamelCase :int      ,  _lowerCamelCase :List[Any]      ,  _lowerCamelCase :Dict   ):







      '''simple docstring'''



      UpperCamelCase_     :					Tuple   	=NystromformerForMaskedLM(config=_lowerCamelCase   )
      model.to(_lowerCamelCase   )
      model.eval()
      UpperCamelCase_     :					List[Any]   	=model(_lowerCamelCase      ,  attention_mask=_lowerCamelCase      ,  token_type_ids=_lowerCamelCase      ,  labels=_lowerCamelCase   )
      self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.seq_length, self.vocab_size)   )



     def  lowerCamelCase_						(							self :Any      ,  _lowerCamelCase :List[Any]      ,  _lowerCamelCase :Dict      ,  _lowerCamelCase :Union[str, Any]      ,  _lowerCamelCase :Union[str, Any]      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :Optional[Any]      ,  _lowerCamelCase :Dict   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=NystromformerForQuestionAnswering(config=_lowerCamelCase   )
      model.to(_lowerCamelCase   )
      model.eval()
      UpperCamelCase_     :					Any   	=model(
          _lowerCamelCase      ,  attention_mask=_lowerCamelCase      ,  token_type_ids=_lowerCamelCase      ,  start_positions=_lowerCamelCase      ,  end_positions=_lowerCamelCase      ,  )
      self.parent.assertEqual(result.start_logits.shape      ,  (self.batch_size, self.seq_length)   )
      self.parent.assertEqual(result.end_logits.shape      ,  (self.batch_size, self.seq_length)   )



     def  lowerCamelCase_						(							self :List[str]      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :int      ,  _lowerCamelCase :Optional[int]      ,  _lowerCamelCase :List[str]      ,  _lowerCamelCase :Optional[int]      ,  _lowerCamelCase :Any      ,  _lowerCamelCase :int   ):







      '''simple docstring'''



      UpperCamelCase_     :					Any   	=self.num_labels
      UpperCamelCase_     :					Union[str, Any]   	=NystromformerForSequenceClassification(_lowerCamelCase   )
      model.to(_lowerCamelCase   )
      model.eval()
      UpperCamelCase_     :					Union[str, Any]   	=model(_lowerCamelCase      ,  attention_mask=_lowerCamelCase      ,  token_type_ids=_lowerCamelCase      ,  labels=_lowerCamelCase   )
      self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.num_labels)   )



     def  lowerCamelCase_						(							self :Optional[int]      ,  _lowerCamelCase :Dict      ,  _lowerCamelCase :str      ,  _lowerCamelCase :Dict      ,  _lowerCamelCase :int      ,  _lowerCamelCase :Optional[int]      ,  _lowerCamelCase :Optional[Any]      ,  _lowerCamelCase :Optional[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=self.num_labels
      UpperCamelCase_     :					Any   	=NystromformerForTokenClassification(config=_lowerCamelCase   )
      model.to(_lowerCamelCase   )
      model.eval()
      UpperCamelCase_     :					Dict   	=model(_lowerCamelCase      ,  attention_mask=_lowerCamelCase      ,  token_type_ids=_lowerCamelCase      ,  labels=_lowerCamelCase   )
      self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.seq_length, self.num_labels)   )



     def  lowerCamelCase_						(							self :str      ,  _lowerCamelCase :Dict      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :Any      ,  _lowerCamelCase :List[Any]      ,  _lowerCamelCase :int      ,  _lowerCamelCase :List[str]   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=self.num_choices
      UpperCamelCase_     :					Dict   	=NystromformerForMultipleChoice(config=_lowerCamelCase   )
      model.to(_lowerCamelCase   )
      model.eval()
      UpperCamelCase_     :					Tuple   	=input_ids.unsqueeze(1   ).expand(-1      ,  self.num_choices      ,  -1   ).contiguous()
      UpperCamelCase_     :					Dict   	=token_type_ids.unsqueeze(1   ).expand(-1      ,  self.num_choices      ,  -1   ).contiguous()
      UpperCamelCase_     :					int   	=input_mask.unsqueeze(1   ).expand(-1      ,  self.num_choices      ,  -1   ).contiguous()
      UpperCamelCase_     :					Dict   	=model(
          _lowerCamelCase      ,  attention_mask=_lowerCamelCase      ,  token_type_ids=_lowerCamelCase      ,  labels=_lowerCamelCase      ,  )
      self.parent.assertEqual(result.logits.shape      ,  (self.batch_size, self.num_choices)   )




     def  lowerCamelCase_						(							self :int   ):







      '''simple docstring'''



      UpperCamelCase_     :					Union[str, Any]   	=self.prepare_config_and_inputs()
      (
          (
          UpperCamelCase_
      )	,     (
          UpperCamelCase_
      )	,     (
          UpperCamelCase_
      )	,     (
          UpperCamelCase_
      )	,     (
          UpperCamelCase_
      )	,     (
          UpperCamelCase_
      )	,     (
          UpperCamelCase_
      )	,     
      )     :					str   	=config_and_inputs
      UpperCamelCase_     :					List[Any]   	={'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
      return config, inputs_dict





@require_torch
class 				a__					(						A__   ,							A__   ,							unittest.TestCase       ):
     UpperCAmelCase__         =      (
         (
             NystromformerModel,
             NystromformerForMaskedLM,
             NystromformerForMultipleChoice,
             NystromformerForQuestionAnswering,
             NystromformerForSequenceClassification,
             NystromformerForTokenClassification,
         )
         if is_torch_available()
         else ()
     )
     UpperCAmelCase__         =      (
         {
             '''feature-extraction''': NystromformerModel,
             '''fill-mask''': NystromformerForMaskedLM,
             '''question-answering''': NystromformerForQuestionAnswering,
             '''text-classification''': NystromformerForSequenceClassification,
             '''token-classification''': NystromformerForTokenClassification,
             '''zero-shot''': NystromformerForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     UpperCAmelCase__         =      False
     UpperCAmelCase__         =      False



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=NystromformerModelTester(self   )
      UpperCamelCase_     :					str   	=ConfigTester(self      ,  config_class=_lowerCamelCase      ,  hidden_size=37   )



     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''simple docstring'''



      self.config_tester.run_common_tests()



     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
       UpperCamelCase_     :					List[Any]   	=type
       self.model_tester.create_and_check_model(*_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Tuple   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Tuple   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_multiple_choice(*_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Any   ):







      '''simple docstring'''



      UpperCamelCase_     :					int   	=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase   )



     def  lowerCamelCase_						(							self :List[str]   ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase   )



     def  lowerCamelCase_						(							self :Dict   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase   )




     @slow
     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''simple docstring'''



      for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCamelCase_     :					Optional[int]   	=NystromformerModel.from_pretrained(_lowerCamelCase   )
       self.assertIsNotNone(_lowerCamelCase   )





@require_torch
class 				a__					(						unittest.TestCase       ):



     @slow
     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	=NystromformerModel.from_pretrained('uw-madison/nystromformer-512'   )
      UpperCamelCase_     :					Optional[Any]   	=torch.tensor([[0, 1, 2, 3, 4, 5]]   )

      with torch.no_grad():
       UpperCamelCase_     :					Optional[int]   	=model(_lowerCamelCase   )[0]

      UpperCamelCase_     :					Optional[Any]   	=torch.Size((1, 6, 768)   )
      self.assertEqual(output.shape      ,  _lowerCamelCase   )

      UpperCamelCase_     :					Optional[int]   	=torch.tensor(
          [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]]   )

      self.assertTrue(torch.allclose(output[:, :3, :3]      ,  _lowerCamelCase      ,  atol=1E-4   )   )




     @slow
     def  lowerCamelCase_						(							self :List[str]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Optional[Any]   	='the [MASK] of Belgium is Brussels'

      UpperCamelCase_     :					Optional[int]   	=AutoTokenizer.from_pretrained('uw-madison/nystromformer-512'   )
      UpperCamelCase_     :					Optional[int]   	=NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512'   )

      UpperCamelCase_     :					str   	=tokenizer(_lowerCamelCase      ,  return_tensors='pt'   )

      with torch.no_grad():
       UpperCamelCase_     :					Optional[Any]   	=model(encoding.input_ids   ).logits

      UpperCamelCase_     :					Tuple   	=token_logits[:, 2, :].argmax(-1   )[0]

      self.assertEqual(tokenizer.decode(_lowerCamelCase   )      ,  'capital'   )


"""simple docstring"""






import math

import flax.linen as nn
import jax.numpy as jnp




def       A_  (				__lowercase						,	__lowercase						,	__lowercase = 1						,	__lowercase = 1						,	__lowercase = 1.0e4						,	__lowercase = False						,	__lowercase = 1.0						,	):
 assert timesteps.ndim == 1, "Timesteps should be a 1d-array"
 assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even'''
 UpperCamelCase_     :					Optional[int]   	=float(embedding_dim // 2	)
 UpperCamelCase_     :					Optional[Any]   	=math.log(max_timescale / min_timescale	) / (num_timescales - freq_shift)
 UpperCamelCase_     :					List[Any]   	=min_timescale * jnp.exp(jnp.arange(__lowercase						,	dtype=jnp.floataa	) * -log_timescale_increment	)
 UpperCamelCase_     :					int   	=jnp.expand_dims(__lowercase						,	1	) * jnp.expand_dims(__lowercase						,	0	)

 # scale embeddings
 UpperCamelCase_     :					List[str]   	=scale * emb

 if flip_sin_to_cos:
  UpperCamelCase_     :					Tuple   	=jnp.concatenate([jnp.cos(__lowercase	), jnp.sin(__lowercase	)]						,	axis=1	)
 else:
  UpperCamelCase_     :					Tuple   	=jnp.concatenate([jnp.sin(__lowercase	), jnp.cos(__lowercase	)]						,	axis=1	)
 UpperCamelCase_     :					List[Any]   	=jnp.reshape(__lowercase						,	[jnp.shape(__lowercase	)[0], embedding_dim]	)
 return signal





class 				a__					(						nn.Module       ):
     UpperCAmelCase__         =      32
     UpperCAmelCase__         =      jnp.floataa



     @nn.compact
     def __call__(							self :Optional[Any]      ,  _lowerCamelCase :List[str]   ):







      '''simple docstring'''



      UpperCamelCase_     :					Dict   	=nn.Dense(self.time_embed_dim      ,  dtype=self.dtype      ,  name='linear_1'   )(_lowerCamelCase   )
      UpperCamelCase_     :					Any   	=nn.silu(_lowerCamelCase   )
      UpperCamelCase_     :					Tuple   	=nn.Dense(self.time_embed_dim      ,  dtype=self.dtype      ,  name='linear_2'   )(_lowerCamelCase   )
      return temb





class 				a__					(						nn.Module       ):
     UpperCAmelCase__         =      32
     UpperCAmelCase__         =      False
     UpperCAmelCase__         =      1



     @nn.compact
     def __call__(							self :Union[str, Any]      ,  _lowerCamelCase :Dict   ):







      '''simple docstring'''



      return get_sinusoidal_embeddings(
          _lowerCamelCase      ,  embedding_dim=self.dim      ,  flip_sin_to_cos=self.flip_sin_to_cos      ,  freq_shift=self.freq_shift   )
