


import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()



def        UpperCamelCase_(   lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_							,				lowerCamelCase_ = None							,				)					->		Any:
    _lowercase :							List[Any]   	=	{}

    if train_file is not None:
        _lowercase :							str   	=	[train_file]
    if eval_file is not None:
        _lowercase :							List[Any]   	=	[eval_file]
    if test_file is not None:
        _lowercase :							Union[str, Any]   	=	[test_file]

    _lowercase :							str   	=	datasets.load_dataset('csv'							,				data_files=lowerCamelCase_				)
    _lowercase :							str   	=	list(ds[list(files.keys()				)[0]].features.keys()				)
    _lowercase :							str   	=	features_name.pop(lowerCamelCase_				)
    _lowercase :							Optional[int]   	=	list(set(ds[list(files.keys()				)[0]][label_name]				)				)
    _lowercase :							int   	=	{label: i for i, label in enumerate(lowerCamelCase_				)}
    _lowercase :							Union[str, Any]   	=	tokenizer.model_input_names
    _lowercase :							Dict   	=	{}

    if len(lowerCamelCase_				) == 1:
        for k in files.keys():
            _lowercase :							Tuple   	=	ds[k].map(
                lambda lowerCamelCase_				: tokenizer.batch_encode_plus(
                    example[features_name[0]]							,				truncation=lowerCamelCase_							,				max_length=lowerCamelCase_							,				padding='max_length'				)							,				batched=lowerCamelCase_							,				)
    elif len(lowerCamelCase_				) == 2:
        for k in files.keys():
            _lowercase :							str   	=	ds[k].map(
                lambda lowerCamelCase_				: tokenizer.batch_encode_plus(
                    (example[features_name[0]], example[features_name[1]])							,				truncation=lowerCamelCase_							,				max_length=lowerCamelCase_							,				padding='max_length'							,				)							,				batched=lowerCamelCase_							,				)

    def gen_train():
        for ex in transformed_ds[datasets.Split.TRAIN]:
            _lowercase :							Tuple   	=	{k: v for k, v in ex.items() if k in input_names}
            _lowercase :							str   	=	labelaid[ex[label_name]]
            yield (d, label)

    def gen_val():
        for ex in transformed_ds[datasets.Split.VALIDATION]:
            _lowercase :							List[str]   	=	{k: v for k, v in ex.items() if k in input_names}
            _lowercase :							str   	=	labelaid[ex[label_name]]
            yield (d, label)

    def gen_test():
        for ex in transformed_ds[datasets.Split.TEST]:
            _lowercase :							Dict   	=	{k: v for k, v in ex.items() if k in input_names}
            _lowercase :							int   	=	labelaid[ex[label_name]]
            yield (d, label)

    _lowercase :							int   	=	(
        tf.data.Dataset.from_generator(
            lowerCamelCase_							,				({k: tf.intaa for k in input_names}, tf.intaa)							,				({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				))							,				)
        if datasets.Split.TRAIN in transformed_ds
        else None
    )

    if train_ds is not None:
        _lowercase :							Union[str, Any]   	=	train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]				)				)				)

    _lowercase :							Any   	=	(
        tf.data.Dataset.from_generator(
            lowerCamelCase_							,				({k: tf.intaa for k in input_names}, tf.intaa)							,				({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				))							,				)
        if datasets.Split.VALIDATION in transformed_ds
        else None
    )

    if val_ds is not None:
        _lowercase :							Union[str, Any]   	=	val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]				)				)				)

    _lowercase :							List[str]   	=	(
        tf.data.Dataset.from_generator(
            lowerCamelCase_							,				({k: tf.intaa for k in input_names}, tf.intaa)							,				({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				))							,				)
        if datasets.Split.TEST in transformed_ds
        else None
    )

    if test_ds is not None:
        _lowercase :							Optional[int]   	=	test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]				)				)				)

    return train_ds, val_ds, test_ds, labelaid


SCREAMING_SNAKE_CASE :   List[str]							      =				logging.getLogger(__name__)






@dataclass
class _lowerCamelCase:
       lowercase_				:			int									=    field(metadata={"""help""": """Which column contains the label"""}     )
       lowercase_				:			str									=    field(default=_a,				metadata={"""help""": """The path of the training file"""}     )
       lowercase_				:			Optional[str]									=    field(default=_a,				metadata={"""help""": """The path of the development file"""}     )
       lowercase_				:			Optional[str]									=    field(default=_a,				metadata={"""help""": """The path of the test file"""}     )
       lowercase_				:			int									=    field(
           default=1_28,				metadata={
               """help""": (
                   """The maximum total input sequence length after tokenization. Sequences longer """
                   """than this will be truncated, sequences shorter will be padded."""
               )
           },				)
       lowercase_				:			bool									=    field(
           default=_a,				metadata={"""help""": """Overwrite the cached training and evaluation sets"""}     )






@dataclass
class _lowerCamelCase:
       lowercase_				:			str									=    field(
           metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}     )
       lowercase_				:			Optional[str]									=    field(
           default=_a,				metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}     )
       lowercase_				:			Optional[str]									=    field(
           default=_a,				metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}     )
       lowercase_				:			bool									=    field(default=_a,				metadata={"""help""": """Set this flag to use fast tokenization."""}     )
       # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
       # or just modify its tokenizer_config.json.
       lowercase_				:			Optional[str]									=    field(
           default=_a,				metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""},				)



def        UpperCamelCase_(   )					->		Dict:
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.
    _lowercase :							List[Any]   	=	HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)				)
    _lowercase	,       _lowercase	,       _lowercase :							List[Any]   	=	parser.parse_args_into_dataclasses()

    if (
        os.path.exists(training_args.output_dir				)
        and os.listdir(training_args.output_dir				)
        and training_args.do_train
        and not training_args.overwrite_output_dir
    ):
        raise ValueError(
            F'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
            ' --overwrite_output_dir to overcome.'				)

    # Setup logging
    logging.basicConfig(
        format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'							,				datefmt='%m/%d/%Y %H:%M:%S'							,				level=logging.INFO							,				)
    logger.info(
        F'''n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1				)}, '''
        F'''16-bits training: {training_args.fpaa}'''				)
    logger.info(F'''Training/evaluation parameters {training_args}'''				)

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    _lowercase :							Dict   	=	AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path							,				cache_dir=model_args.cache_dir							,				)

    _lowercase	,       _lowercase	,       _lowercase	,       _lowercase :							Dict   	=	get_tfds(
        train_file=data_args.train_file							,				eval_file=data_args.dev_file							,				test_file=data_args.test_file							,				tokenizer=lowerCamelCase_							,				label_column_id=data_args.label_column_id							,				max_seq_length=data_args.max_seq_length							,				)

    _lowercase :							Optional[Any]   	=	AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path							,				num_labels=len(lowerCamelCase_				)							,				labelaid=lowerCamelCase_							,				idalabel={id: label for label, id in labelaid.items()}							,				finetuning_task='text-classification'							,				cache_dir=model_args.cache_dir							,				)

    with training_args.strategy.scope():
        _lowercase :							Union[str, Any]   	=	TFAutoModelForSequenceClassification.from_pretrained(
            model_args.model_name_or_path							,				from_pt=bool('.bin' in model_args.model_name_or_path				)							,				config=lowerCamelCase_							,				cache_dir=model_args.cache_dir							,				)

    def compute_metrics(lowerCamelCase_				) -> Dict:
        _lowercase :							Dict   	=	np.argmax(p.predictions							,				axis=1				)

        return {"acc": (preds == p.label_ids).mean()}

    # Initialize our Trainer
    _lowercase :							int   	=	TFTrainer(
        model=lowerCamelCase_							,				args=lowerCamelCase_							,				train_dataset=lowerCamelCase_							,				eval_dataset=lowerCamelCase_							,				compute_metrics=lowerCamelCase_							,				)

    # Training
    if training_args.do_train:
        trainer.train()
        trainer.save_model()
        tokenizer.save_pretrained(training_args.output_dir				)

    # Evaluation
    _lowercase :							Optional[int]   	=	{}
    if training_args.do_eval:
        logger.info('*** Evaluate ***'				)
        _lowercase :							Union[str, Any]   	=	trainer.evaluate()
        _lowercase :							Union[str, Any]   	=	os.path.join(training_args.output_dir							,				'eval_results.txt'				)

        with open(lowerCamelCase_							,				'w'				) as writer:
            logger.info('***** Eval results *****'				)

            for key, value in result.items():
                logger.info(F'''  {key} = {value}'''				)
                writer.write(F'''{key} = {value}\n'''				)

            results.update(lowerCamelCase_				)

    return results


if __name__ == "__main__":
 main()






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))


