
'''simple docstring'''
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  __A				:
 def __init__(   self			:    Any				,   lowerCamelCase			:    Union[str, Any]				,   lowerCamelCase			:    Optional[int]=2				,   lowerCamelCase			:    Tuple=8				,   lowerCamelCase			:    Any=True				,   lowerCamelCase			:    Optional[Any]=True				,   lowerCamelCase			:    Union[str, Any]=True				,   lowerCamelCase			:    List[str]=True				,   lowerCamelCase			:    str=99				,   lowerCamelCase			:    Tuple=16				,   lowerCamelCase			:    Tuple=5				,   lowerCamelCase			:    Any=2				,   lowerCamelCase			:    List[Any]=36				,   lowerCamelCase			:    Union[str, Any]="gelu"				,   lowerCamelCase			:    Optional[Any]=0.0				,   lowerCamelCase			:    Union[str, Any]=0.0				,   lowerCamelCase			:    Optional[int]=5_12				,   lowerCamelCase			:    Dict=16				,   lowerCamelCase			:    List[str]=2				,   lowerCamelCase			:    Any=0.02				,   lowerCamelCase			:    Tuple=3				,   lowerCamelCase			:    Optional[Any]=4				,   lowerCamelCase			:    Any=None				,   ):



   """simple docstring"""





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



   """simple docstring"""





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

   __A		:     Tuple												=		None
   if self.use_input_mask:
     __A		:     Optional[int]												=		random_attention_mask([self.batch_size, self.seq_length]       )

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

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

   __A		:     List[Any]												=		self.get_config()

   return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
 def 		lowercase_(   self			:    Union[str, Any]       ):



   """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 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





   __A		:     Tuple												=		self.get_config()
   __A		:     Any												=		3_00
   return config
 def 		lowercase_(   self			:    Optional[int]       ):



   """simple docstring"""





   (
       __A					
   )		:     Union[str, Any]												=		self.prepare_config_and_inputs()

   __A		:     List[Any]												=		True
   __A		:     List[str]												=		floats_tensor([self.batch_size, self.seq_length, self.hidden_size]       )
   __A		:     Tuple												=		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 		lowercase_(   self			:    List[str]				,   lowerCamelCase			:    str				,   lowerCamelCase			:    List[str]				,   lowerCamelCase			:    Dict				,   lowerCamelCase			:    List[str]				,   lowerCamelCase			:    int				,   lowerCamelCase			:    int				,   lowerCamelCase			:    Optional[int]       ):



   """simple docstring"""





   __A		:     Optional[Any]												=		MraModel(config=lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()
   __A		:     str												=		model(lowerCamelCase				,   attention_mask=lowerCamelCase				,   token_type_ids=lowerCamelCase       )
   __A		:     Optional[int]												=		model(lowerCamelCase				,   token_type_ids=lowerCamelCase       )
   __A		:     Union[str, Any]												=		model(lowerCamelCase       )
   self.parent.assertEqual(result.last_hidden_state.shape				,   (self.batch_size, self.seq_length, self.hidden_size)       )
 def 		lowercase_(   self			:    Optional[int]				,   lowerCamelCase			:    Optional[int]				,   lowerCamelCase			:    Union[str, Any]				,   lowerCamelCase			:    str				,   lowerCamelCase			:    Optional[Any]				,   lowerCamelCase			:    Dict				,   lowerCamelCase			:    Dict				,   lowerCamelCase			:    str				,   lowerCamelCase			:    Dict				,   lowerCamelCase			:    List[Any]				,   ):



   """simple docstring"""





   __A		:     List[Any]												=		True
   __A		:     Union[str, Any]												=		MraModel(lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()
   __A		:     Any												=		model(
       lowerCamelCase				,   attention_mask=lowerCamelCase				,   token_type_ids=lowerCamelCase				,   encoder_hidden_states=lowerCamelCase				,   encoder_attention_mask=lowerCamelCase				,   )
   __A		:     str												=		model(
       lowerCamelCase				,   attention_mask=lowerCamelCase				,   token_type_ids=lowerCamelCase				,   encoder_hidden_states=lowerCamelCase				,   )
   __A		:     Optional[int]												=		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 		lowercase_(   self			:    Optional[Any]				,   lowerCamelCase			:    int				,   lowerCamelCase			:    Tuple				,   lowerCamelCase			:    int				,   lowerCamelCase			:    Optional[Any]				,   lowerCamelCase			:    List[Any]				,   lowerCamelCase			:    Union[str, Any]				,   lowerCamelCase			:    Any       ):



   """simple docstring"""





   __A		:     Dict												=		MraForMaskedLM(config=lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()
   __A		:     Tuple												=		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 		lowercase_(   self			:    str				,   lowerCamelCase			:    Optional[int]				,   lowerCamelCase			:    Union[str, Any]				,   lowerCamelCase			:    Tuple				,   lowerCamelCase			:    Optional[int]				,   lowerCamelCase			:    Any				,   lowerCamelCase			:    List[Any]				,   lowerCamelCase			:    Optional[int]       ):



   """simple docstring"""





   __A		:     Dict												=		MraForQuestionAnswering(config=lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()
   __A		:     Dict												=		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 		lowercase_(   self			:    Tuple				,   lowerCamelCase			:    str				,   lowerCamelCase			:    Tuple				,   lowerCamelCase			:    Optional[int]				,   lowerCamelCase			:    int				,   lowerCamelCase			:    List[Any]				,   lowerCamelCase			:    Tuple				,   lowerCamelCase			:    Dict       ):



   """simple docstring"""





   __A		:     List[Any]												=		self.num_labels
   __A		:     str												=		MraForSequenceClassification(lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()
   __A		:     Dict												=		model(lowerCamelCase				,   attention_mask=lowerCamelCase				,   token_type_ids=lowerCamelCase				,   labels=lowerCamelCase       )
   self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.num_labels)       )
 def 		lowercase_(   self			:    str				,   lowerCamelCase			:    Any				,   lowerCamelCase			:    Tuple				,   lowerCamelCase			:    List[str]				,   lowerCamelCase			:    Optional[int]				,   lowerCamelCase			:    Optional[Any]				,   lowerCamelCase			:    str				,   lowerCamelCase			:    int       ):



   """simple docstring"""





   __A		:     List[str]												=		self.num_labels
   __A		:     Any												=		MraForTokenClassification(config=lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()
   __A		:     str												=		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 		lowercase_(   self			:    Tuple				,   lowerCamelCase			:    Dict				,   lowerCamelCase			:    Optional[Any]				,   lowerCamelCase			:    List[Any]				,   lowerCamelCase			:    Tuple				,   lowerCamelCase			:    Union[str, Any]				,   lowerCamelCase			:    Optional[Any]				,   lowerCamelCase			:    Union[str, Any]       ):



   """simple docstring"""





   __A		:     Any												=		self.num_choices
   __A		:     Optional[int]												=		MraForMultipleChoice(config=lowerCamelCase       )
   model.to(lowerCamelCase       )
   model.eval()
   __A		:     Optional[Any]												=		input_ids.unsqueeze(1       ).expand(-1				,   self.num_choices				,   -1       ).contiguous()
   __A		:     Optional[Any]												=		token_type_ids.unsqueeze(1       ).expand(-1				,   self.num_choices				,   -1       ).contiguous()
   __A		:     int												=		input_mask.unsqueeze(1       ).expand(-1				,   self.num_choices				,   -1       ).contiguous()
   __A		:     int												=		model(
       lowerCamelCase				,   attention_mask=lowerCamelCase				,   token_type_ids=lowerCamelCase				,   labels=lowerCamelCase				,   )
   self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.num_choices)       )






 def 		lowercase_(   self			:    List[Any]       ):



   """simple docstring"""





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







@require_torch
class  __A				( _SCREAMING_SNAKE_CASE    ,						unittest.TestCase			):
 lowerCamelCase				       =(
     (
         MraModel,
         MraForMaskedLM,
         MraForMultipleChoice,
         MraForQuestionAnswering,
         MraForSequenceClassification,
         MraForTokenClassification,
     )
     if is_torch_available()
     else ()
 )
 lowerCamelCase				       =False
 lowerCamelCase				       =False
 lowerCamelCase				       =False
 lowerCamelCase				       =False

 lowerCamelCase				       =()
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   __A		:     Optional[int]												=		MraModelTester(self       )
   __A		:     List[Any]												=		ConfigTester(self				,   config_class=lowerCamelCase				,   hidden_size=37       )
 def 		lowercase_(   self			:    str       ):



   """simple docstring"""





   self.config_tester.run_common_tests()
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   __A		:     List[str]												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCamelCase       )
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   __A		:     List[Any]												=		self.model_tester.prepare_config_and_inputs()
   for type in ["absolute", "relative_key", "relative_key_query"]:
     __A		:     Optional[Any]												=		type
     self.model_tester.create_and_check_model(*lowerCamelCase       )
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   __A		:     List[str]												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase       )
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   __A		:     Tuple												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase       )
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   __A		:     Dict												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_question_answering(*lowerCamelCase       )
 def 		lowercase_(   self			:    List[Any]       ):



   """simple docstring"""





   __A		:     int												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase       )
 def 		lowercase_(   self			:    Union[str, Any]       ):



   """simple docstring"""





   __A		:     Optional[int]												=		self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_token_classification(*lowerCamelCase       )
 @slow
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __A		:     int												=		MraModel.from_pretrained(lowerCamelCase       )
     self.assertIsNotNone(lowerCamelCase       )






 @unittest.skip(reason="""MRA does not output attentions"""       )
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   return







@require_torch
class  __A				( unittest.TestCase			):
 @slow
 def 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





   __A		:     Tuple												=		MraModel.from_pretrained("""uw-madison/mra-base-512-4"""       )
   __A		:     str												=		torch.arange(2_56       ).unsqueeze(0       )

   with torch.no_grad():
     __A		:     int												=		model(lowerCamelCase       )[0]

   __A		:     Dict												=		torch.Size((1, 2_56, 7_68)       )
   self.assertEqual(output.shape				,   lowerCamelCase       )

   __A		:     Tuple												=		torch.tensor(
       [[[-0.0_140, 0.0_830, -0.0_381], [0.1_546, 0.1_402, 0.0_220], [0.1_162, 0.0_851, 0.0_165]]]       )

   self.assertTrue(torch.allclose(output[:, :3, :3]				,   lowerCamelCase				,   atol=1e-4       )       )
 @slow
 def 		lowercase_(   self			:    Dict       ):



   """simple docstring"""





   __A		:     int												=		MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4"""       )
   __A		:     Union[str, Any]												=		torch.arange(2_56       ).unsqueeze(0       )

   with torch.no_grad():
     __A		:     int												=		model(lowerCamelCase       )[0]

   __A		:     Optional[Any]												=		5_02_65

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

   __A		:     Tuple												=		torch.tensor(
       [[[9.2_595, -3.6_038, 11.8_819], [9.3_869, -3.2_693, 11.0_956], [11.8_524, -3.4_938, 13.1_210]]]       )

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






 @slow
 def 		lowercase_(   self			:    str       ):



   """simple docstring"""





   __A		:     Tuple												=		MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3"""       )
   __A		:     int												=		torch.arange(40_96       ).unsqueeze(0       )

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

   __A		:     Dict												=		5_02_65

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

   __A		:     Optional[Any]												=		torch.tensor(
       [[[5.4_789, -2.3_564, 7.5_064], [7.9_067, -1.3_369, 9.9_668], [9.0_712, -1.8_106, 7.0_380]]]       )

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





'''simple docstring'''
from typing import Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
     from PIL import Image

     from ..image_utils import load_image

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING

A__   :		Any 		=logging.get_logger(__name__)







@add_end_docstrings(_SCREAMING_SNAKE_CASE			)
class  __A				( _SCREAMING_SNAKE_CASE			):
 def __init__(   self			:    Union[str, Any]				,   *lowerCamelCase			:    int				,   **lowerCamelCase			:    Optional[int]       ):



   """simple docstring"""





   super().__init__(*lowerCamelCase				,   **lowerCamelCase       )
   self.check_model_type(lowerCamelCase       )
 def 		lowercase_(   self			:    Any				,   lowerCamelCase			:    Dict=None				,   lowerCamelCase			:    Union[str, Any]=None				,   lowerCamelCase			:    int=None				,   **lowerCamelCase			:    int       ):



   """simple docstring"""





   __A							,					__A		:     Tuple												=		{}, {}
   if padding is not None:
     __A		:     Any												=		padding
   if truncation is not None:
     __A		:     Optional[Any]												=		truncation
   if top_k is not None:
     __A		:     List[str]												=		top_k
   return preprocess_params, {}, postprocess_params
 def __call__(   self			:    Any				,   lowerCamelCase			:    Union["Image.Image", str]				,   lowerCamelCase			:    str = None				,   **lowerCamelCase			:    Tuple       ):



   """simple docstring"""





   if isinstance(lowerCamelCase				,   (Image.Image, str)       ) and isinstance(lowerCamelCase				,   lowerCamelCase       ):
     __A		:     Tuple												=		{"""image""": image, """question""": question}
   else:
     __A		:     List[Any]												=		image
   __A		:     Any												=		super().__call__(lowerCamelCase				,   **lowerCamelCase       )
   return results
 def 		lowercase_(   self			:    int				,   lowerCamelCase			:    Optional[int]				,   lowerCamelCase			:    Dict=False				,   lowerCamelCase			:    str=False       ):



   """simple docstring"""





   __A		:     List[str]												=		load_image(inputs["""image"""]       )
   __A		:     Optional[Any]												=		self.tokenizer(
       inputs["""question"""]				,   return_tensors=self.framework				,   padding=lowerCamelCase				,   truncation=lowerCamelCase       )
   __A		:     Union[str, Any]												=		self.image_processor(images=lowerCamelCase				,   return_tensors=self.framework       )
   model_inputs.update(lowerCamelCase       )
   return model_inputs
 def 		lowercase_(   self			:    List[str]				,   lowerCamelCase			:    Tuple       ):



   """simple docstring"""





   __A		:     List[str]												=		self.model(**lowerCamelCase       )
   return model_outputs






 def 		lowercase_(   self			:    str				,   lowerCamelCase			:    Optional[Any]				,   lowerCamelCase			:    List[Any]=5       ):



   """simple docstring"""





   if top_k > self.model.config.num_labels:
     __A		:     str												=		self.model.config.num_labels

   if self.framework == "pt":
     __A		:     Optional[Any]												=		model_outputs.logits.sigmoid()[0]
     __A							,					__A		:     int												=		probs.topk(lowerCamelCase       )
   else:
     raise ValueError(f"Unsupported framework: {self.framework}"       )

   __A		:     Optional[Any]												=		scores.tolist()
   __A		:     Dict												=		ids.tolist()
   return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowerCamelCase				,   lowerCamelCase       )]



