





import argparse
import json
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging


logging.set_verbosity_info()
_SCREAMING_SNAKE_CASE							=						logging.get_logger(__name__)


def 							SCREAMING_SNAKE_CASE__  (			__a      ,       __a=False      ):
	snake_case_						:	List[str]      =		[]
	for i in range(config.num_hidden_layers      ):
		# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
		rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""")      )
		rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""")      )
		rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""")      )
		rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""")      )
		rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""")      )
		rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""")      )
		rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""")      )
		rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""")      )
		rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""")      )
		rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""")      )

	# projection layer + position embeddings
	rename_keys.extend(
	    [
	        ('cls_token', 'vit.embeddings.cls_token'),
	        ('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'),
	        ('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'),
	        ('pos_embed', 'vit.embeddings.position_embeddings'),
	    ]      )

	if base_model:
		# layernorm + pooler
		rename_keys.extend(
		    [
		        ('norm.weight', 'layernorm.weight'),
		        ('norm.bias', 'layernorm.bias'),
		    ]      )

		# if just the base model, we should remove "vit" from all keys that start with "vit"
		snake_case_						:	List[Any]      =		[(pair[0], pair[1][4:]) if pair[1].startswith('vit'      ) else pair for pair in rename_keys]
	else:
		# layernorm + classification head
		rename_keys.extend(
		    [
		        ('norm.weight', 'vit.layernorm.weight'),
		        ('norm.bias', 'vit.layernorm.bias'),
		        ('head.weight', 'classifier.weight'),
		        ('head.bias', 'classifier.bias'),
		    ]      )

	return rename_keys


def 							SCREAMING_SNAKE_CASE__  (			__a      ,       __a      ,       __a=False      ):
	for i in range(config.num_hidden_layers      ):
		if base_model:
			snake_case_						:	Optional[int]      =		''
		else:
			snake_case_						:	List[str]      =		'vit.'
		# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
		snake_case_						:	Any      =		state_dict.pop(f"""blocks.{i}.attn.qkv.weight"""      )
		snake_case_						:	Tuple      =		state_dict.pop(f"""blocks.{i}.attn.qkv.bias"""      )
		# next, add query, keys and values (in that order) to the state dict
		snake_case_						:	Tuple      =		in_proj_weight[
		    : config.hidden_size, :
		]
		snake_case_						:	Tuple      =		in_proj_bias[: config.hidden_size]
		snake_case_						:	List[Any]      =		in_proj_weight[
		    config.hidden_size : config.hidden_size * 2, :
		]
		snake_case_						:	Union[str, Any]      =		in_proj_bias[
		    config.hidden_size : config.hidden_size * 2
		]
		snake_case_						:	str      =		in_proj_weight[
		    -config.hidden_size :, :
		]
		snake_case_						:	Dict      =		in_proj_bias[-config.hidden_size :]


def 							SCREAMING_SNAKE_CASE__  (			__a      ):
	snake_case_						:	Optional[int]      =		['head.weight', 'head.bias']
	for k in ignore_keys:
		state_dict.pop(A__      ,       A__      )


def 							SCREAMING_SNAKE_CASE__  (			__a      ,       __a      ,       __a      ):
	snake_case_						:	int      =		dct.pop(A__      )
	snake_case_						:	Dict      =		val


def 							SCREAMING_SNAKE_CASE__  (			):
	snake_case_						:	str      =		'http://images.cocodataset.org/val2017/000000039769.jpg'
	snake_case_						:	Any      =		Image.open(requests.get(A__      ,       stream=A__      ).raw      )
	return im


@torch.no_grad()
def 							SCREAMING_SNAKE_CASE__  (			__a      ,       __a      ,       __a=True      ):
	snake_case_						:	List[str]      =		ViTConfig()
	# patch_size
	if model_name[-1] == "8":
		snake_case_						:	Optional[Any]      =		8
	# set labels if required
	if not base_model:
		snake_case_						:	Any      =		10_00
		snake_case_						:	Optional[int]      =		'huggingface/label-files'
		snake_case_						:	List[Any]      =		'imagenet-1k-id2label.json'
		snake_case_						:	List[Any]      =		json.load(open(hf_hub_download(A__      ,       A__      ,       repo_type='dataset'      )      ,       'r'      )      )
		snake_case_						:	int      =		{int(A__      ): v for k, v in idalabel.items()}
		snake_case_						:	str      =		idalabel
		snake_case_						:	List[Any]      =		{v: k for k, v in idalabel.items()}
	# size of the architecture
	if model_name in ["dino_vits8", "dino_vits16"]:
		snake_case_						:	Union[str, Any]      =		3_84
		snake_case_						:	Optional[Any]      =		15_36
		snake_case_						:	str      =		12
		snake_case_						:	Optional[int]      =		6

	# load original model from torch hub
	snake_case_						:	Any      =		torch.hub.load('facebookresearch/dino:main'      ,       A__      )
	original_model.eval()

	# load state_dict of original model, remove and rename some keys
	snake_case_						:	List[str]      =		original_model.state_dict()
	if base_model:
		remove_classification_head_(A__      )
	snake_case_						:	Optional[int]      =		create_rename_keys(A__      ,       base_model=A__      )
	for src, dest in rename_keys:
		rename_key(A__      ,       A__      ,       A__      )
	read_in_q_k_v(A__      ,       A__      ,       A__      )

	# load HuggingFace model
	if base_model:
		snake_case_						:	str      =		ViTModel(A__      ,       add_pooling_layer=A__      ).eval()
	else:
		snake_case_						:	Any      =		ViTForImageClassification(A__      ).eval()
	model.load_state_dict(A__      )

	# Check outputs on an image, prepared by ViTImageProcessor
	snake_case_						:	str      =		ViTImageProcessor()
	snake_case_						:	List[Any]      =		image_processor(images=prepare_img()      ,       return_tensors='pt'      )
	snake_case_						:	Any      =		encoding['pixel_values']
	snake_case_						:	Union[str, Any]      =		model(A__      )

	if base_model:
		snake_case_						:	Optional[Any]      =		original_model(A__      )
		assert torch.allclose(A__      ,       outputs.last_hidden_state[:, 0, :]      ,       atol=1E-1      )
	else:
		snake_case_						:	Any      =		original_model(A__      )
		assert logits.shape == outputs.logits.shape
		assert torch.allclose(A__      ,       outputs.logits      ,       atol=1E-3      )

	Path(A__      ).mkdir(exist_ok=A__      )
	print(f"""Saving model {model_name} to {pytorch_dump_folder_path}"""      )
	model.save_pretrained(A__      )
	print(f"""Saving image processor to {pytorch_dump_folder_path}"""      )
	image_processor.save_pretrained(A__      )


if __name__ == "__main__":
						_SCREAMING_SNAKE_CASE							=						argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    """--model_name""",
						    default="""dino_vitb16""",
						    type=str,
						    help="""Name of the model trained with DINO you'd like to convert.""",
						)
						parser.add_argument(
						    """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
						)
						parser.add_argument(
						    """--base_model""",
						    action="""store_true""",
						    help="""Whether to only convert the base model (no projection head weights).""",
						)

						parser.set_defaults(base_model=True)
						_SCREAMING_SNAKE_CASE							=						parser.parse_args()
						convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)






'''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  SCREAMING_SNAKE_CASE :






    """simple docstring"""





    def __init__(  self      :					Any  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					Any=2  ,						UpperCamelCase__      :					Union[str, Any]=8  ,						UpperCamelCase__      :					List[Any]=True  ,						UpperCamelCase__      :					Any=True  ,						UpperCamelCase__      :					str=True  ,						UpperCamelCase__      :					Dict=True  ,						UpperCamelCase__      :					List[Any]=9_9  ,						UpperCamelCase__      :					List[Any]=1_6  ,						UpperCamelCase__      :					List[str]=5  ,						UpperCamelCase__      :					Dict=2  ,						UpperCamelCase__      :					Optional[int]=3_6  ,						UpperCamelCase__      :					str="gelu"  ,						UpperCamelCase__      :					Dict=0.0  ,						UpperCamelCase__      :					Dict=0.0  ,						UpperCamelCase__      :					Optional[int]=5_1_2  ,						UpperCamelCase__      :					Dict=1_6  ,						UpperCamelCase__      :					List[str]=2  ,						UpperCamelCase__      :					Any=0.0_2  ,						UpperCamelCase__      :					str=3  ,						UpperCamelCase__      :					Tuple=4  ,						UpperCamelCase__      :					Union[str, Any]=None  ,						):


       """simple docstring"""







       UpperCamelCase					=  parent
       UpperCamelCase					=  batch_size
       UpperCamelCase					=  seq_length
       UpperCamelCase					=  is_training
       UpperCamelCase					=  use_input_mask
       UpperCamelCase					=  use_token_type_ids
       UpperCamelCase					=  use_labels
       UpperCamelCase					=  vocab_size
       UpperCamelCase					=  hidden_size
       UpperCamelCase					=  num_hidden_layers
       UpperCamelCase					=  num_attention_heads
       UpperCamelCase					=  intermediate_size
       UpperCamelCase					=  hidden_act
       UpperCamelCase					=  hidden_dropout_prob
       UpperCamelCase					=  attention_probs_dropout_prob
       UpperCamelCase					=  max_position_embeddings
       UpperCamelCase					=  type_vocab_size
       UpperCamelCase					=  type_sequence_label_size
       UpperCamelCase					=  initializer_range
       UpperCamelCase					=  num_labels
       UpperCamelCase					=  num_choices
       UpperCamelCase					=  scope






    def  A       (  self      :					int ):


       """simple docstring"""







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

       UpperCamelCase					=  None
       if self.use_input_mask:
          UpperCamelCase					=  random_attention_mask([self.batch_size, self.seq_length] )

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

       UpperCamelCase					=  None
       UpperCamelCase					=  None
       UpperCamelCase					=  None
       if self.use_labels:
          UpperCamelCase					=  ids_tensor([self.batch_size]  ,						self.type_sequence_label_size )
          UpperCamelCase					=  ids_tensor([self.batch_size, self.seq_length]  ,						self.num_labels )
          UpperCamelCase					=  ids_tensor([self.batch_size]  ,						self.num_choices )

       UpperCamelCase					=  self.get_config()

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






    def  A       (  self      :					Optional[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=UpperCamelCase__  ,						initializer_range=self.initializer_range  ,						)






    def  A       (  self      :					Any ):


       """simple docstring"""







       UpperCamelCase					=  self.get_config()
       UpperCamelCase					=  3_0_0
       return config






    def  A       (  self      :					Tuple ):


       """simple docstring"""







       (
           (
           UpperCamelCase
       )				,      (
           UpperCamelCase
       )				,      (
           UpperCamelCase
       )				,      (
           UpperCamelCase
       )				,      (
           UpperCamelCase
       )				,      (
           UpperCamelCase
       )				,      (
           UpperCamelCase
       )				,      
       )					=  self.prepare_config_and_inputs()

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


       """simple docstring"""







       UpperCamelCase					=  MraModel(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__ )
       UpperCamelCase					=  model(UpperCamelCase__  ,						token_type_ids=UpperCamelCase__ )
       UpperCamelCase					=  model(UpperCamelCase__ )
       self.parent.assertEqual(result.last_hidden_state.shape  ,						(self.batch_size, self.seq_length, self.hidden_size) )






    def  A       (  self      :					List[str]  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					Optional[Any]  ,						):


       """simple docstring"""







       UpperCamelCase					=  True
       UpperCamelCase					=  MraModel(UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(
           UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__  ,						encoder_hidden_states=UpperCamelCase__  ,						encoder_attention_mask=UpperCamelCase__  ,						)
       UpperCamelCase					=  model(
           UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__  ,						encoder_hidden_states=UpperCamelCase__  ,						)
       UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__ )
       self.parent.assertEqual(result.last_hidden_state.shape  ,						(self.batch_size, self.seq_length, self.hidden_size) )






    def  A       (  self      :					int  ,						UpperCamelCase__      :					Optional[int]  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					List[str]  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  MraForMaskedLM(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__  ,						labels=UpperCamelCase__ )
       self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.seq_length, self.vocab_size) )






    def  A       (  self      :					Any  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					List[str]  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					Optional[Any] ):


       """simple docstring"""







       UpperCamelCase					=  MraForQuestionAnswering(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(
           UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__  ,						start_positions=UpperCamelCase__  ,						end_positions=UpperCamelCase__  ,						)
       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  A       (  self      :					Optional[int]  ,						UpperCamelCase__      :					Union[str, Any]  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					Optional[int]  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					int  ,						UpperCamelCase__      :					Optional[Any]  ,						UpperCamelCase__      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  self.num_labels
       UpperCamelCase					=  MraForSequenceClassification(UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__  ,						labels=UpperCamelCase__ )
       self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.num_labels) )






    def  A       (  self      :					Any  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					Optional[int]  ,						UpperCamelCase__      :					int  ,						UpperCamelCase__      :					int  ,						UpperCamelCase__      :					Optional[Any] ):


       """simple docstring"""







       UpperCamelCase					=  self.num_labels
       UpperCamelCase					=  MraForTokenClassification(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  model(UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__  ,						labels=UpperCamelCase__ )
       self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.seq_length, self.num_labels) )






    def  A       (  self      :					int  ,						UpperCamelCase__      :					Optional[Any]  ,						UpperCamelCase__      :					Any  ,						UpperCamelCase__      :					Optional[int]  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					Dict ):


       """simple docstring"""







       UpperCamelCase					=  self.num_choices
       UpperCamelCase					=  MraForMultipleChoice(config=UpperCamelCase__ )
       model.to(UpperCamelCase__ )
       model.eval()
       UpperCamelCase					=  input_ids.unsqueeze(1 ).expand(-1  ,						self.num_choices  ,						-1 ).contiguous()
       UpperCamelCase					=  token_type_ids.unsqueeze(1 ).expand(-1  ,						self.num_choices  ,						-1 ).contiguous()
       UpperCamelCase					=  input_mask.unsqueeze(1 ).expand(-1  ,						self.num_choices  ,						-1 ).contiguous()
       UpperCamelCase					=  model(
           UpperCamelCase__  ,						attention_mask=UpperCamelCase__  ,						token_type_ids=UpperCamelCase__  ,						labels=UpperCamelCase__  ,						)
       self.parent.assertEqual(result.logits.shape  ,						(self.batch_size, self.num_choices) )






    def  A       (  self      :					int ):


       """simple docstring"""







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

@require_torch
class  SCREAMING_SNAKE_CASE (  _a   ,						unittest.TestCase		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  (
        (
            MraModel,
            MraForMaskedLM,
            MraForMultipleChoice,
            MraForQuestionAnswering,
            MraForSequenceClassification,
            MraForTokenClassification,
        )
        if is_torch_available()
        else ()
    )
    _SCREAMING_SNAKE_CASE	  =  False
    _SCREAMING_SNAKE_CASE	  =  False
    _SCREAMING_SNAKE_CASE	  =  False
    _SCREAMING_SNAKE_CASE	  =  False

    _SCREAMING_SNAKE_CASE	  =  ()






    def  A       (  self      :					str ):


       """simple docstring"""







       UpperCamelCase					=  MraModelTester(self )
       UpperCamelCase					=  ConfigTester(self  ,						config_class=UpperCamelCase__  ,						hidden_size=3_7 )






    def  A       (  self      :					str ):


       """simple docstring"""







       self.config_tester.run_common_tests()






    def  A       (  self      :					Optional[Any] ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__ )






    def  A       (  self      :					str ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
          UpperCamelCase					=  type
          self.model_tester.create_and_check_model(*UpperCamelCase__ )






    def  A       (  self      :					Optional[int] ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ )






    def  A       (  self      :					List[Any] ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ )






    def  A       (  self      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ )






    def  A       (  self      :					Any ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ )






    def  A       (  self      :					Any ):


       """simple docstring"""







       UpperCamelCase					=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ )






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


       """simple docstring"""







       for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          UpperCamelCase					=  MraModel.from_pretrained(UpperCamelCase__ )
          self.assertIsNotNone(UpperCamelCase__ )






    @unittest.skip(reason='MRA does not output attentions' )
    def  A       (  self      :					List[str] ):


       """simple docstring"""







       return

@require_torch
class  SCREAMING_SNAKE_CASE (  unittest.TestCase		):






    """simple docstring"""





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


       """simple docstring"""







       UpperCamelCase					=  MraModel.from_pretrained('uw-madison/mra-base-512-4' )
       UpperCamelCase					=  torch.arange(2_5_6 ).unsqueeze(0 )

       with torch.no_grad():
          UpperCamelCase					=  model(UpperCamelCase__ )[0]

       UpperCamelCase					=  torch.Size((1, 2_5_6, 7_6_8) )
       self.assertEqual(output.shape  ,						UpperCamelCase__ )

       UpperCamelCase					=  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]  ,						UpperCamelCase__  ,						atol=1E-4 ) )






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


       """simple docstring"""







       UpperCamelCase					=  MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4' )
       UpperCamelCase					=  torch.arange(2_5_6 ).unsqueeze(0 )

       with torch.no_grad():
          UpperCamelCase					=  model(UpperCamelCase__ )[0]

       UpperCamelCase					=  5_0_2_6_5

       UpperCamelCase					=  torch.Size((1, 2_5_6, vocab_size) )
       self.assertEqual(output.shape  ,						UpperCamelCase__ )

       UpperCamelCase					=  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]  ,						UpperCamelCase__  ,						atol=1E-4 ) )






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


       """simple docstring"""







       UpperCamelCase					=  MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3' )
       UpperCamelCase					=  torch.arange(4_0_9_6 ).unsqueeze(0 )

       with torch.no_grad():
          UpperCamelCase					=  model(UpperCamelCase__ )[0]

       UpperCamelCase					=  5_0_2_6_5

       UpperCamelCase					=  torch.Size((1, 4_0_9_6, vocab_size) )
       self.assertEqual(output.shape  ,						UpperCamelCase__ )

       UpperCamelCase					=  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]  ,						UpperCamelCase__  ,						atol=1E-4 ) )

