


from typing import Optional, Tuple

import jax
import jax.numpy as jnp
from flax import linen as nn
from flax.core.frozen_dict import FrozenDict
from transformers import CLIPConfig, FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule



def        UpperCamelCase_(   lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_=1e-12				)					->		Optional[Any]:
    _lowercase :							str   	=	jnp.divide(emb_a.T							,				jnp.clip(jnp.linalg.norm(lowerCamelCase_							,				axis=1				)							,				a_min=lowerCamelCase_				)				).T
    _lowercase :							List[Any]   	=	jnp.divide(emb_a.T							,				jnp.clip(jnp.linalg.norm(lowerCamelCase_							,				axis=1				)							,				a_min=lowerCamelCase_				)				).T
    return jnp.matmul(lowerCamelCase_							,				norm_emb_a.T				)






class _lowerCamelCase(		nn.Module     ):
       lowercase_				:			CLIPConfig
       lowercase_				:			jnp.dtype									=    jnp.floataa
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           _lowercase :							List[Any]   	=	FlaxCLIPVisionModule(self.config.vision_config)
           _lowercase :							List[str]   	=	nn.Dense(self.config.projection_dim,   use_bias=lowerCamelCase,   dtype=self.dtype)

           _lowercase :							Dict   	=	self.param('concept_embeds',   jax.nn.initializers.ones,   (17, self.config.projection_dim))
           _lowercase :							Optional[int]   	=	self.param(
               'special_care_embeds',   jax.nn.initializers.ones,   (3, self.config.projection_dim))

           _lowercase :							Union[str, Any]   	=	self.param('concept_embeds_weights',   jax.nn.initializers.ones,   (17,))
           _lowercase :							Any   	=	self.param('special_care_embeds_weights',   jax.nn.initializers.ones,   (3,))




       def __call__(      self,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							List[Any]   	=	self.vision_model(lowerCamelCase)[1]
           _lowercase :							Dict   	=	self.visual_projection(lowerCamelCase)

           _lowercase :							Optional[int]   	=	jax_cosine_distance(lowerCamelCase,   self.special_care_embeds)
           _lowercase :							str   	=	jax_cosine_distance(lowerCamelCase,   self.concept_embeds)

           # increase this value to create a stronger `nfsw` filter
           # at the cost of increasing the possibility of filtering benign image inputs
           _lowercase :							str   	=	0.0

           _lowercase :							Union[str, Any]   	=	special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
           _lowercase :							int   	=	jnp.round(lowerCamelCase,   3)
           _lowercase :							Optional[Any]   	=	jnp.any(special_scores > 0,   axis=1,   keepdims=lowerCamelCase)
           # Use a lower threshold if an image has any special care concept
           _lowercase :							Optional[Any]   	=	is_special_care * 0.0_1

           _lowercase :							Optional[Any]   	=	cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
           _lowercase :							List[str]   	=	jnp.round(lowerCamelCase,   3)
           _lowercase :							Optional[int]   	=	jnp.any(concept_scores > 0,   axis=1)

           return has_nsfw_concepts






class _lowerCamelCase(		_a     ):
       lowercase_				:			str									=    CLIPConfig
       lowercase_				:			int									=    """clip_input"""
       lowercase_				:			List[str]									=    FlaxStableDiffusionSafetyCheckerModule
       def __init__(      self,   lowerCamelCase,   lowerCamelCase = None,   lowerCamelCase = 0,   lowerCamelCase = jnp.floataa,   lowerCamelCase = True,   **lowerCamelCase,   ) ->     Dict:




           """simple docstring"""

           if input_shape is None:
               _lowercase :							Dict   	=	(1, 2_24, 2_24, 3)
           _lowercase :							Tuple   	=	self.module_class(config=lowerCamelCase,   dtype=lowerCamelCase,   **lowerCamelCase)
           super().__init__(lowerCamelCase,   lowerCamelCase,   input_shape=lowerCamelCase,   seed=lowerCamelCase,   dtype=lowerCamelCase,   _do_init=_do_init)
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase = None) ->     FrozenDict:




           """simple docstring"""

           _lowercase :							str   	=	jax.random.normal(lowerCamelCase,   lowerCamelCase)

           _lowercase	,       _lowercase :							Dict   	=	jax.random.split(lowerCamelCase)
           _lowercase :							Dict   	=	{'params': params_rng, 'dropout': dropout_rng}

           _lowercase :							Optional[int]   	=	self.module.init(lowerCamelCase,   lowerCamelCase)['params']

           return random_params




       def __call__(      self,   lowerCamelCase,   lowerCamelCase = None,   ) ->     int:




           """simple docstring"""

           _lowercase :							Dict   	=	jnp.transpose(lowerCamelCase,   (0, 2, 3, 1))

           return self.module.apply(
               {'params': params or self.params},   jnp.array(lowerCamelCase,   dtype=jnp.floataa),   rngs={},   )






import unittest

from transformers import MraConfig, 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, floats_tensor, ids_tensor, random_attention_mask


if is_torch_available():
 import torch

 from transformers import (
     MraForMaskedLM,
     MraForMultipleChoice,
     MraForQuestionAnswering,
     MraForSequenceClassification,
     MraForTokenClassification,
     MraModel,
 )
 from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST






class _lowerCamelCase:
       def __init__(      self,   lowerCamelCase,   lowerCamelCase=2,   lowerCamelCase=8,   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=True,   lowerCamelCase=99,   lowerCamelCase=16,   lowerCamelCase=5,   lowerCamelCase=2,   lowerCamelCase=36,   lowerCamelCase="gelu",   lowerCamelCase=0.0,   lowerCamelCase=0.0,   lowerCamelCase=5_12,   lowerCamelCase=16,   lowerCamelCase=2,   lowerCamelCase=0.0_2,   lowerCamelCase=3,   lowerCamelCase=4,   lowerCamelCase=None,   ) ->     Dict:




           """simple docstring"""

           _lowercase :							Union[str, Any]   	=	parent
           _lowercase :							List[str]   	=	batch_size
           _lowercase :							Dict   	=	seq_length
           _lowercase :							List[str]   	=	is_training
           _lowercase :							Any   	=	use_input_mask
           _lowercase :							Any   	=	use_token_type_ids
           _lowercase :							Optional[int]   	=	use_labels
           _lowercase :							str   	=	vocab_size
           _lowercase :							str   	=	hidden_size
           _lowercase :							str   	=	num_hidden_layers
           _lowercase :							List[Any]   	=	num_attention_heads
           _lowercase :							Union[str, Any]   	=	intermediate_size
           _lowercase :							Tuple   	=	hidden_act
           _lowercase :							Optional[int]   	=	hidden_dropout_prob
           _lowercase :							Optional[Any]   	=	attention_probs_dropout_prob
           _lowercase :							int   	=	max_position_embeddings
           _lowercase :							str   	=	type_vocab_size
           _lowercase :							Tuple   	=	type_sequence_label_size
           _lowercase :							Optional[Any]   	=	initializer_range
           _lowercase :							Dict   	=	num_labels
           _lowercase :							Dict   	=	num_choices
           _lowercase :							int   	=	scope
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							str   	=	ids_tensor([self.batch_size, self.seq_length],   self.vocab_size)

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

           _lowercase :							List[Any]   	=	None
           if self.use_token_type_ids:
               _lowercase :							Dict   	=	ids_tensor([self.batch_size, self.seq_length],   self.type_vocab_size)

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

           _lowercase :							Optional[int]   	=	self.get_config()

           return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           return MraConfig(
               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     UpperCamelCase  (      self) ->     Union[str, Any]:




           """simple docstring"""

           _lowercase :							Any   	=	self.get_config()
           _lowercase :							List[str]   	=	3_00
           return config
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           (
               (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       
           ) :							List[str]   	=	self.prepare_config_and_inputs()

           _lowercase :							Tuple   	=	True
           _lowercase :							Any   	=	floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
           _lowercase :							Union[str, Any]   	=	ids_tensor([self.batch_size, self.seq_length],   vocab_size=2)

           return (
               config,
               input_ids,
               token_type_ids,
               input_mask,
               sequence_labels,
               token_labels,
               choice_labels,
               encoder_hidden_states,
               encoder_attention_mask,
           )
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     Optional[int]:




           """simple docstring"""

           _lowercase :							Dict   	=	MraModel(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Dict   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase)
           _lowercase :							Optional[Any]   	=	model(lowerCamelCase,   token_type_ids=lowerCamelCase)
           _lowercase :							Tuple   	=	model(lowerCamelCase)
           self.parent.assertEqual(result.last_hidden_state.shape,   (self.batch_size, self.seq_length, self.hidden_size))
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   ) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							int   	=	True
           _lowercase :							List[Any]   	=	MraModel(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Tuple   	=	model(
               lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase,   encoder_hidden_states=lowerCamelCase,   encoder_attention_mask=lowerCamelCase,   )
           _lowercase :							Union[str, Any]   	=	model(
               lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase,   encoder_hidden_states=lowerCamelCase,   )
           _lowercase :							Any   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase)
           self.parent.assertEqual(result.last_hidden_state.shape,   (self.batch_size, self.seq_length, self.hidden_size))
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	MraForMaskedLM(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							int   	=	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     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     Any:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	MraForQuestionAnswering(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Union[str, 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     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							str   	=	self.num_labels
           _lowercase :							List[Any]   	=	MraForSequenceClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Optional[int]   	=	model(lowerCamelCase,   attention_mask=lowerCamelCase,   token_type_ids=lowerCamelCase,   labels=lowerCamelCase)
           self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels))
       def     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     str:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.num_labels
           _lowercase :							str   	=	MraForTokenClassification(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							Optional[int]   	=	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     UpperCamelCase  (      self,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase,   lowerCamelCase) ->     int:




           """simple docstring"""

           _lowercase :							Any   	=	self.num_choices
           _lowercase :							Optional[Any]   	=	MraForMultipleChoice(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase :							List[Any]   	=	input_ids.unsqueeze(1).expand(-1,   self.num_choices,   -1).contiguous()
           _lowercase :							str   	=	token_type_ids.unsqueeze(1).expand(-1,   self.num_choices,   -1).contiguous()
           _lowercase :							Dict   	=	input_mask.unsqueeze(1).expand(-1,   self.num_choices,   -1).contiguous()
           _lowercase :							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     UpperCamelCase  (      self) ->     Dict:




           """simple docstring"""

           _lowercase :							List[Any]   	=	self.prepare_config_and_inputs()
           (
               (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       (
               _lowercase
           )	,       
           ) :							Tuple   	=	config_and_inputs
           _lowercase :							Optional[Any]   	=	{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
           return config, inputs_dict






@require_torch
class _lowerCamelCase(		_a,				unittest.TestCase     ):
       lowercase_				:			Optional[int]									=    (
           (
               MraModel,
               MraForMaskedLM,
               MraForMultipleChoice,
               MraForQuestionAnswering,
               MraForSequenceClassification,
               MraForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       lowercase_				:			Optional[int]									=    False
       lowercase_				:			Optional[int]									=    False
       lowercase_				:			int									=    False
       lowercase_				:			Optional[Any]									=    False

       lowercase_				:			Any									=    ()
       def     UpperCamelCase  (      self) ->     Optional[Any]:




           """simple docstring"""

           _lowercase :							List[str]   	=	MraModelTester(self)
           _lowercase :							Any   	=	ConfigTester(self,   config_class=lowerCamelCase,   hidden_size=37)
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           self.config_tester.run_common_tests()
       def     UpperCamelCase  (      self) ->     int:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           _lowercase :							Tuple   	=	self.model_tester.prepare_config_and_inputs()
           for type in ["absolute", "relative_key", "relative_key_query"]:
               _lowercase :							Optional[int]   	=	type
               self.model_tester.create_and_check_model(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           _lowercase :							Optional[Any]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							int   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Any:




           """simple docstring"""

           _lowercase :							Tuple   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_question_answering(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							List[str]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase)
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_token_classification(*lowerCamelCase)
       @slow
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase :							List[str]   	=	MraModel.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)




       @unittest.skip(reason='MRA does not output attentions')
       def     UpperCamelCase  (      self) ->     Tuple:




           """simple docstring"""

           return






@require_torch
class _lowerCamelCase(		unittest.TestCase     ):
       @slow
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							Dict   	=	MraModel.from_pretrained('uw-madison/mra-base-512-4')
           _lowercase :							Any   	=	torch.arange(2_56).unsqueeze(0)

           with torch.no_grad():
               _lowercase :							str   	=	model(lowerCamelCase)[0]

           _lowercase :							Union[str, Any]   	=	torch.Size((1, 2_56, 7_68))
           self.assertEqual(output.shape,   lowerCamelCase)

           _lowercase :							Dict   	=	torch.tensor(
               [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]])

           self.assertTrue(torch.allclose(output[:, :3, :3],   lowerCamelCase,   atol=1E-4))
       @slow
       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							List[str]   	=	MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4')
           _lowercase :							Optional[int]   	=	torch.arange(2_56).unsqueeze(0)

           with torch.no_grad():
               _lowercase :							str   	=	model(lowerCamelCase)[0]

           _lowercase :							Union[str, Any]   	=	5_02_65

           _lowercase :							int   	=	torch.Size((1, 2_56, vocab_size))
           self.assertEqual(output.shape,   lowerCamelCase)

           _lowercase :							Optional[Any]   	=	torch.tensor(
               [[[9.2_5_9_5, -3.6_0_3_8, 1_1.8_8_1_9], [9.3_8_6_9, -3.2_6_9_3, 1_1.0_9_5_6], [1_1.8_5_2_4, -3.4_9_3_8, 1_3.1_2_1_0]]])

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




       @slow
       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           _lowercase :							Any   	=	MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3')
           _lowercase :							Optional[int]   	=	torch.arange(40_96).unsqueeze(0)

           with torch.no_grad():
               _lowercase :							str   	=	model(lowerCamelCase)[0]

           _lowercase :							Optional[Any]   	=	5_02_65

           _lowercase :							Union[str, Any]   	=	torch.Size((1, 40_96, vocab_size))
           self.assertEqual(output.shape,   lowerCamelCase)

           _lowercase :							Any   	=	torch.tensor(
               [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]])

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


