




import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import numpy as np
import pandas as pd
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    BartForSequenceClassification,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    TapexTokenizer,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.17.0.dev0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")

__A        =    logging.getLogger(__name__)







@dataclass
class     __lowerCAmelCase :

			"""simple docstring"""







			snake_case_   		=       field(
			    default='''tab_fact'''			,				metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} )
			snake_case_   		=       field(
			    default='''tab_fact'''			,				metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}			,				)
			snake_case_   		=       field(
			    default=10_24			,				metadata={
			        '''help''': (
			            '''The maximum total input sequence length after tokenization. Sequences longer '''
			            '''than this will be truncated, sequences shorter will be padded.'''
			        )
			    }			,				)
			snake_case_   		=       field(
			    default=__a			,				metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} )
			snake_case_   		=       field(
			    default=__a			,				metadata={
			        '''help''': (
			            '''Whether to pad all samples to `max_seq_length`. '''
			            '''If False, will pad the samples dynamically when batching to the maximum length in the batch.'''
			        )
			    }			,				)
			snake_case_   		=       field(
			    default=__a			,				metadata={
			        '''help''': (
			            '''For debugging purposes or quicker training, truncate the number of training examples to this '''
			            '''value if set.'''
			        )
			    }			,				)
			snake_case_   		=       field(
			    default=__a			,				metadata={
			        '''help''': (
			            '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
			            '''value if set.'''
			        )
			    }			,				)
			snake_case_   		=       field(
			    default=__a			,				metadata={
			        '''help''': (
			            '''For debugging purposes or quicker training, truncate the number of prediction examples to this '''
			            '''value if set.'''
			        )
			    }			,				)
			snake_case_   		=       field(
			    default=__a			,				metadata={'''help''': '''A csv or a json file containing the training data.'''} )
			snake_case_   		=       field(
			    default=__a			,				metadata={'''help''': '''A csv or a json file containing the validation data.'''} )
			snake_case_   		=       field(default=__a			,				metadata={'''help''': '''A csv or a json file containing the test data.'''} )


			def       lowercase_    (      self							)    ->      Dict:



							'''simple docstring'''

							if self.dataset_name is not None:
											pass
							elif self.train_file is None or self.validation_file is None:
											raise ValueError('Need either a GLUE task, a training/validation file or a dataset name.'							)
							else:
											__lowerCamelCase		       =    self.train_file.split('.'							)[-1]
											assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file."
											__lowerCamelCase		       =    self.validation_file.split('.'							)[-1]
											assert (
											    validation_extension == train_extension
											), "`validation_file` should have the same extension (csv or json) as `train_file`."







@dataclass
class     __lowerCAmelCase :

			"""simple docstring"""







			snake_case_   		=       field(
			    default=__a			,				metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} )
			snake_case_   		=       field(
			    default=__a			,				metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} )
			snake_case_   		=       field(
			    default=__a			,				metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} )
			snake_case_   		=       field(
			    default=__a			,				metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}			,				)
			snake_case_   		=       field(
			    default=__a			,				metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''}			,				)
			snake_case_   		=       field(
			    default='''main'''			,				metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}			,				)
			snake_case_   		=       field(
			    default=__a			,				metadata={
			        '''help''': (
			            '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
			            '''with private models).'''
			        )
			    }			,				)







def 			lowerCamelCase_		(       )     ->       Dict:





				"""simple docstring"""


				__lowerCamelCase		       =    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )
				if len(sys.argv      ) == 2 and sys.argv[1].endswith('.json'      ):
								# If we pass only one argument to the script and it's the path to a json file,
								# let's parse it to get our arguments.
								__lowerCamelCase		       =    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]      )      )
				else:
								__lowerCamelCase		       =    parser.parse_args_into_dataclasses()

				# Setup logging
				logging.basicConfig(
				    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' ,     datefmt='%m/%d/%Y %H:%M:%S' ,     handlers=[logging.StreamHandler(sys.stdout      )] ,     )

				__lowerCamelCase		       =    training_args.get_process_log_level()
				logger.setLevel(lowerCAmelCase_      )
				datasets.utils.logging.set_verbosity(lowerCAmelCase_      )
				transformers.utils.logging.set_verbosity(lowerCAmelCase_      )
				transformers.utils.logging.enable_default_handler()
				transformers.utils.logging.enable_explicit_format()

				# Log on each process the small summary:
				logger.warning(
				    F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
				    + F"""distributed training: {bool(training_args.local_rank != -1      )}, 16-bits training: {training_args.fpaa}"""      )
				logger.info(F"""Training/evaluation parameters {training_args}"""      )

				# Detecting last checkpoint.
				__lowerCamelCase		       =    None
				if os.path.isdir(training_args.output_dir      ) and training_args.do_train and not training_args.overwrite_output_dir:
								__lowerCamelCase		       =    get_last_checkpoint(training_args.output_dir      )
								if last_checkpoint is None and len(os.listdir(training_args.output_dir      )      ) > 0:
												raise ValueError(
												    F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
												    'Use --overwrite_output_dir to overcome.'      )
								elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
												logger.info(
												    F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
												    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'      )

    # Set seed before initializing model.
				set_seed(training_args.seed      )

				# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
				# or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
				#
				# For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table.
				#
				# If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
				# single column. You can easily tweak this behavior (see below)
				#
				# In distributed training, the load_dataset function guarantee that only one local process can concurrently
				# download the dataset.
				if data_args.dataset_name is not None:
								# Downloading and loading a dataset from the hub.
								__lowerCamelCase		       =    load_dataset(
								    data_args.dataset_name ,     data_args.dataset_config_name ,     cache_dir=model_args.cache_dir      )
				else:
								# Loading a dataset from your local files.
								# CSV/JSON training and evaluation files are needed.
								__lowerCamelCase		       =    {"""train""": data_args.train_file, """validation""": data_args.validation_file}

								# Get the test dataset: you can provide your own CSV/JSON test file (see below)
								# when you use `do_predict` without specifying a GLUE benchmark task.
								if training_args.do_predict:
												if data_args.test_file is not None:
																__lowerCamelCase		       =    data_args.train_file.split('.'      )[-1]
																__lowerCamelCase		       =    data_args.test_file.split('.'      )[-1]
																assert (
																    test_extension == train_extension
																), "`test_file` should have the same extension (csv or json) as `train_file`."
																__lowerCamelCase		       =    data_args.test_file
												else:
																raise ValueError('Need either a GLUE task or a test file for `do_predict`.'      )

								for key in data_files.keys():
												logger.info(F"""load a local file for {key}: {data_files[key]}"""      )

								if data_args.train_file.endswith('.csv'      ):
												# Loading a dataset from local csv files
												__lowerCamelCase		       =    load_dataset('csv' ,     data_files=lowerCAmelCase_ ,     cache_dir=model_args.cache_dir      )
								else:
												# Loading a dataset from local json files
												__lowerCamelCase		       =    load_dataset('json' ,     data_files=lowerCAmelCase_ ,     cache_dir=model_args.cache_dir      )
    # See more about loading any type of standard or custom dataset at
    # https://huggingface.co/docs/datasets/loading_datasets.html.

    # Labels
				__lowerCamelCase		       =    raw_datasets["""train"""].features["""label"""].names
				__lowerCamelCase		       =    len(lowerCAmelCase_      )

				# Load pretrained model and tokenizer
				#
				# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.
				__lowerCamelCase		       =    AutoConfig.from_pretrained(
				    model_args.config_name if model_args.config_name else model_args.model_name_or_path ,     num_labels=lowerCAmelCase_ ,     cache_dir=model_args.cache_dir ,     revision=model_args.model_revision ,     use_auth_token=True if model_args.use_auth_token else None ,     )
				# load tapex tokenizer
				__lowerCamelCase		       =    TapexTokenizer.from_pretrained(
				    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,     cache_dir=model_args.cache_dir ,     use_fast=model_args.use_fast_tokenizer ,     revision=model_args.model_revision ,     use_auth_token=True if model_args.use_auth_token else None ,     add_prefix_space=lowerCAmelCase_ ,     )
				__lowerCamelCase		       =    BartForSequenceClassification.from_pretrained(
				    model_args.model_name_or_path ,     from_tf=bool('.ckpt' in model_args.model_name_or_path      ) ,     config=lowerCAmelCase_ ,     cache_dir=model_args.cache_dir ,     revision=model_args.model_revision ,     use_auth_token=True if model_args.use_auth_token else None ,     )

				# Padding strategy
				if data_args.pad_to_max_length:
								__lowerCamelCase		       =    """max_length"""
				else:
								# We will pad later, dynamically at batch creation, to the max sequence length in each batch
								__lowerCamelCase		       =    False

				# Some models have set the order of the labels to use, so let's make sure we do use it.
				__lowerCamelCase		       =    {"""Refused""": 0, """Entailed""": 1}
				__lowerCamelCase		       =    {0: """Refused""", 1: """Entailed"""}

				if data_args.max_seq_length > tokenizer.model_max_length:
								logger.warning(
								    F"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"""
								    F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."""      )
				__lowerCamelCase		       =    min(data_args.max_seq_length ,     tokenizer.model_max_length      )

				def preprocess_tabfact_function(UpperCamelCase__				:      int      ):
								# Tokenize the texts
								def _convert_table_text_to_pandas(UpperCamelCase__				:      List[Any]      ):
												__lowerCamelCase		       =    [_table_row.split('#'      ) for _table_row in _table_text.strip('\n'      ).split('\n'      )]
												__lowerCamelCase		       =    pd.DataFrame.from_records(_table_content[1:] ,     columns=_table_content[0]      )
												return _table_pd

								__lowerCamelCase		       =    examples["""statement"""]
								__lowerCamelCase		       =    list(map(_convert_table_text_to_pandas ,     examples['table_text']      )      )
								__lowerCamelCase		       =    tokenizer(lowerCAmelCase_ ,     lowerCAmelCase_ ,     padding=lowerCAmelCase_ ,     max_length=lowerCAmelCase_ ,     truncation=lowerCAmelCase_      )

								__lowerCamelCase		       =    examples["""label"""]
								return result

				with training_args.main_process_first(desc='dataset map pre-processing'      ):
								__lowerCamelCase		       =    raw_datasets.map(
								    lowerCAmelCase_ ,     batched=lowerCAmelCase_ ,     load_from_cache_file=not data_args.overwrite_cache ,     desc='Running tokenizer on dataset' ,     )
				if training_args.do_train:
								if "train" not in raw_datasets:
												raise ValueError('--do_train requires a train dataset'      )
								__lowerCamelCase		       =    raw_datasets["""train"""]
								if data_args.max_train_samples is not None:
												__lowerCamelCase		       =    train_dataset.select(range(data_args.max_train_samples      )      )

				if training_args.do_eval:
								if "validation" not in raw_datasets and "validation_matched" not in raw_datasets:
												raise ValueError('--do_eval requires a validation dataset'      )
								__lowerCamelCase		       =    raw_datasets["""validation"""]
								if data_args.max_eval_samples is not None:
												__lowerCamelCase		       =    eval_dataset.select(range(data_args.max_eval_samples      )      )

				if training_args.do_predict or data_args.test_file is not None:
								if "test" not in raw_datasets and "test_matched" not in raw_datasets:
												raise ValueError('--do_predict requires a test dataset'      )
								__lowerCamelCase		       =    raw_datasets["""test"""]
								if data_args.max_predict_samples is not None:
												__lowerCamelCase		       =    predict_dataset.select(range(data_args.max_predict_samples      )      )

    # Log a few random samples from the training set:
				if training_args.do_train:
								for index in random.sample(range(len(lowerCAmelCase_      )      ) ,     3      ):
												logger.info(F"""Sample {index} of the training set: {train_dataset[index]}."""      )

    # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
    # predictions and label_ids field) and has to return a dictionary string to float.
				def compute_metrics(UpperCamelCase__				:      EvalPrediction      ):
								__lowerCamelCase		       =    p.predictions[0] if isinstance(p.predictions ,     lowerCAmelCase_      ) else p.predictions
								__lowerCamelCase		       =    np.argmax(lowerCAmelCase_ ,     axis=1      )
								return {"accuracy": (preds == p.label_ids).astype(np.floataa      ).mean().item()}

				# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
				if data_args.pad_to_max_length:
								__lowerCamelCase		       =    default_data_collator
				elif training_args.fpaa:
								__lowerCamelCase		       =    DataCollatorWithPadding(lowerCAmelCase_ ,     pad_to_multiple_of=8      )
				else:
								__lowerCamelCase		       =    None

				# Initialize our Trainer
				__lowerCamelCase		       =    Trainer(
				    model=lowerCAmelCase_ ,     args=lowerCAmelCase_ ,     train_dataset=train_dataset if training_args.do_train else None ,     eval_dataset=eval_dataset if training_args.do_eval else None ,     compute_metrics=lowerCAmelCase_ ,     tokenizer=lowerCAmelCase_ ,     data_collator=lowerCAmelCase_ ,     )

				# Training
				if training_args.do_train:
								__lowerCamelCase		       =    None
								if training_args.resume_from_checkpoint is not None:
												__lowerCamelCase		       =    training_args.resume_from_checkpoint
								elif last_checkpoint is not None:
												__lowerCamelCase		       =    last_checkpoint
								__lowerCamelCase		       =    trainer.train(resume_from_checkpoint=lowerCAmelCase_      )
								__lowerCamelCase		       =    train_result.metrics
								__lowerCamelCase		       =    (
								    data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_      )
								)
								__lowerCamelCase		       =    min(lowerCAmelCase_ ,     len(lowerCAmelCase_      )      )

								trainer.save_model()  # Saves the tokenizer too for easy upload

								trainer.log_metrics('train' ,     lowerCAmelCase_      )
								trainer.save_metrics('train' ,     lowerCAmelCase_      )
								trainer.save_state()

				# Evaluation
				if training_args.do_eval:
								logger.info('*** Evaluate ***'      )

								__lowerCamelCase		       =    trainer.evaluate(eval_dataset=lowerCAmelCase_      )
								__lowerCamelCase		       =    data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCAmelCase_      )
								__lowerCamelCase		       =    min(lowerCAmelCase_ ,     len(lowerCAmelCase_      )      )

								trainer.log_metrics('eval' ,     lowerCAmelCase_      )
								trainer.save_metrics('eval' ,     lowerCAmelCase_      )

				if training_args.do_predict:
								logger.info('*** Predict ***'      )

								# Removing the `label` columns because it contains -1 and Trainer won't like that.
								__lowerCamelCase		       =    predict_dataset.remove_columns('label'      )
								__lowerCamelCase		       =    trainer.predict(lowerCAmelCase_ ,     metric_key_prefix='predict'      ).predictions
								__lowerCamelCase		       =    np.argmax(lowerCAmelCase_ ,     axis=1      )

								__lowerCamelCase		       =    os.path.join(training_args.output_dir ,     'predict_results_tabfact.txt'      )
								if trainer.is_world_process_zero():
												with open(lowerCAmelCase_ ,     'w'      ) as writer:
																logger.info('***** Predict Results *****'      )
																writer.write('index\tprediction\n'      )
																for index, item in enumerate(lowerCAmelCase_      ):
																				__lowerCamelCase		       =    label_list[item]
																				writer.write(F"""{index}\t{item}\n"""      )

				__lowerCamelCase		       =    {"""finetuned_from""": model_args.model_name_or_path, """tasks""": """text-classification"""}

				if training_args.push_to_hub:
								trainer.push_to_hub(**lowerCAmelCase_      )
				else:
								trainer.create_model_card(**lowerCAmelCase_      )







def 			lowerCamelCase_		(       UpperCamelCase__				:      Any      )     ->       Any:





				"""simple docstring"""


				main()


if __name__ == "__main__":
					main()










import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
	from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder
def 					snake_case_						(   lowerCAmelCase_				:  Dict				,				lowerCAmelCase_				:  Dict				,				lowerCAmelCase_				:  str				,				lowerCAmelCase_				:  List[Any]=None				,				lowerCAmelCase_				:  Any=None				,				lowerCAmelCase_				:  List[Any]=None				,				lowerCAmelCase_				:  Optional[Any]=None				,				lowerCAmelCase_				:  Tuple=None				,				):
							if attention_mask is None:
														__lowercase					:							Tuple			=   input_ids.ne(config.pad_token_id					)
							if decoder_attention_mask is None:
														__lowercase					:							Any			=   decoder_input_ids.ne(config.pad_token_id					)
							if head_mask is None:
														__lowercase					:							Any			=   torch.ones(config.encoder_layers				,				config.encoder_attention_heads				,				device=lowerCAmelCase_					)
							if decoder_head_mask is None:
														__lowercase					:							List[Any]			=   torch.ones(config.decoder_layers				,				config.decoder_attention_heads				,				device=lowerCAmelCase_					)
							if cross_attn_head_mask is None:
														__lowercase					:							List[Any]			=   torch.ones(config.decoder_layers				,				config.decoder_attention_heads				,				device=lowerCAmelCase_					)
							return {
							    "input_ids": input_ids,
							    "decoder_input_ids": decoder_input_ids,
							    "attention_mask": attention_mask,
							    "decoder_attention_mask": attention_mask,
							    "head_mask": head_mask,
							    "decoder_head_mask": decoder_head_mask,
							    "cross_attn_head_mask": cross_attn_head_mask,
							}

class 						lowerCAmelCase   :

					'''simple docstring'''

					def __init__(     self :		Union[str, Any]						,   __a :		str						,   __a :		Tuple=13						,   __a :		List[Any]=7						,   __a :		Any=True						,   __a :		List[str]=False						,   __a :		Optional[Any]=99						,   __a :		Tuple=16						,   __a :		int=2						,   __a :		Optional[Any]=4						,   __a :		int=4						,   __a :		Any="relu"						,   __a :		Optional[int]=0.1						,   __a :		List[str]=0.1						,   __a :		Dict=0.0						,   __a :		List[str]=0.0						,   __a :		Union[str, Any]=20						,   __a :		str=2						,   __a :		str=1						,   __a :		Optional[int]=0						,   )	->     Optional[int]:


												"""simple docstring"""

												__lowercase					:							Any			=   parent
												__lowercase					:							Tuple			=   batch_size
												__lowercase					:							Any			=   seq_length
												__lowercase					:							Tuple			=   is_training
												__lowercase					:							Optional[Any]			=   use_labels
												__lowercase					:							Dict			=   vocab_size
												__lowercase					:							Optional[Any]			=   hidden_size
												__lowercase					:							Dict			=   num_hidden_layers
												__lowercase					:							Dict			=   num_attention_heads
												__lowercase					:							Dict			=   intermediate_size
												__lowercase					:							Union[str, Any]			=   hidden_act
												__lowercase					:							Union[str, Any]			=   hidden_dropout_prob
												__lowercase					:							Tuple			=   attention_probs_dropout_prob
												__lowercase					:							Tuple			=   encoder_layerdrop
												__lowercase					:							List[str]			=   decoder_layerdrop
												__lowercase					:							Any			=   max_position_embeddings
												__lowercase					:							Any			=   eos_token_id
												__lowercase					:							Dict			=   pad_token_id
												__lowercase					:							List[str]			=   bos_token_id



					def 					lowerCAmelCase (     self :		Union[str, Any]							)	->     Optional[int]:


												"""simple docstring"""

												__lowercase					:							Tuple			=   ids_tensor([self.batch_size, self.seq_length]						,   self.vocab_size							)
												__lowercase					:							str			=   self.eos_token_id  # Eos Token
												__lowercase					:							str			=   ids_tensor([self.batch_size, self.seq_length]						,   self.vocab_size							)

												# we need to clamp the input ids here to avoid having pad token in between
												# this is because for M2M100 the position_ids are prepared such that
												# all pad tokens have pos id = 2 and rest are between 2..seq_length
												# and the seq_length here is seq_length - num_pad_tokens
												# but when using past, there is no way of knowing if the past input ids had
												# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
												# position_ids being off by num_pad_tokens in past input
												__lowercase					:							Tuple			=   input_ids.clamp(self.pad_token_id + 1							)
												__lowercase					:							Optional[int]			=   decoder_input_ids.clamp(self.pad_token_id + 1							)

												__lowercase					:							List[str]			=   self.get_config()
												__lowercase					:							str			=   prepare_mam_aaa_inputs_dict(__a						,   __a						,   __a							)
												return config, inputs_dict



					def 					lowerCAmelCase (     self :		str							)	->     Dict:


												"""simple docstring"""

												return MaMaaaConfig(
												    vocab_size=self.vocab_size						,   d_model=self.hidden_size						,   encoder_layers=self.num_hidden_layers						,   decoder_layers=self.num_hidden_layers						,   encoder_attention_heads=self.num_attention_heads						,   decoder_attention_heads=self.num_attention_heads						,   encoder_ffn_dim=self.intermediate_size						,   decoder_ffn_dim=self.intermediate_size						,   dropout=self.hidden_dropout_prob						,   attention_dropout=self.attention_probs_dropout_prob						,   encoder_layerdrop=self.encoder_layerdrop						,   decoder_layerdrop=self.decoder_layerdrop						,   max_position_embeddings=self.max_position_embeddings						,   eos_token_id=self.eos_token_id						,   bos_token_id=self.bos_token_id						,   pad_token_id=self.pad_token_id						,   )



					def 					lowerCAmelCase (     self :		Dict							)	->     str:


												"""simple docstring"""

												__lowercase	,	__lowercase					:							int			=   self.prepare_config_and_inputs()
												return config, inputs_dict



					def 					lowerCAmelCase (     self :		int						,   __a :		str						,   __a :		str							)	->     int:


												"""simple docstring"""

												__lowercase					:							Optional[Any]			=   MaMaaaModel(config=__a							).get_decoder().to(__a							).eval()
												__lowercase					:							List[str]			=   inputs_dict["""input_ids"""]
												__lowercase					:							Dict			=   inputs_dict["""attention_mask"""]
												__lowercase					:							List[Any]			=   inputs_dict["""head_mask"""]

												# first forward pass
												__lowercase					:							List[str]			=   model(__a						,   attention_mask=__a						,   head_mask=__a						,   use_cache=__a							)

												__lowercase	,	__lowercase					:							str			=   outputs.to_tuple()

												# create hypothetical multiple next token and extent to next_input_ids
												__lowercase					:							Union[str, Any]			=   ids_tensor((self.batch_size, 3)						,   config.vocab_size							)
												__lowercase					:							str			=   ids_tensor((self.batch_size, 3)						,   2							)

												# append to next input_ids and
												__lowercase					:							List[Any]			=   torch.cat([input_ids, next_tokens]						,   dim=-1							)
												__lowercase					:							Optional[Any]			=   torch.cat([attention_mask, next_attn_mask]						,   dim=-1							)

												__lowercase					:							Optional[int]			=   model(__a						,   attention_mask=__a							)["""last_hidden_state"""]
												__lowercase					:							Union[str, Any]			=   model(__a						,   attention_mask=__a						,   past_key_values=__a							)[
												    """last_hidden_state"""
												]

												# select random slice
												__lowercase					:							Optional[int]			=   ids_tensor((1,)						,   output_from_past.shape[-1]							).item()
												__lowercase					:							int			=   output_from_no_past[:, -3:, random_slice_idx].detach()
												__lowercase					:							Optional[Any]			=   output_from_past[:, :, random_slice_idx].detach()

												self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]							)

												# test that outputs are equal for slice
												self.parent.assertTrue(torch.allclose(__a						,   __a						,   atol=1E-2							)							)



					def 					lowerCAmelCase (     self :		List[str]						,   __a :		Tuple						,   __a :		List[str]							)	->     str:


												"""simple docstring"""

												__lowercase					:							Dict			=   MaMaaaModel(config=__a							).to(__a							).eval()
												__lowercase					:							Any			=   model(**__a							)

												__lowercase					:							str			=   outputs.encoder_last_hidden_state
												__lowercase					:							Optional[Any]			=   outputs.last_hidden_state

												with tempfile.TemporaryDirectory() as tmpdirname:
																			__lowercase					:							str			=   model.get_encoder()
																			encoder.save_pretrained(__a							)
																			__lowercase					:							List[Any]			=   MaMaaaEncoder.from_pretrained(__a							).to(__a							)

												__lowercase					:							Tuple			=   encoder(inputs_dict["""input_ids"""]						,   attention_mask=inputs_dict["""attention_mask"""]							)[
												    0
												]

												self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3							)

												with tempfile.TemporaryDirectory() as tmpdirname:
																			__lowercase					:							Tuple			=   model.get_decoder()
																			decoder.save_pretrained(__a							)
																			__lowercase					:							Tuple			=   MaMaaaDecoder.from_pretrained(__a							).to(__a							)

												__lowercase					:							Tuple			=   decoder(
												    input_ids=inputs_dict["""decoder_input_ids"""]						,   attention_mask=inputs_dict["""decoder_attention_mask"""]						,   encoder_hidden_states=__a						,   encoder_attention_mask=inputs_dict["""attention_mask"""]						,   )[0]

												self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3							)







@require_torch
class 						lowerCAmelCase   (       __a					,				__a					,				__a					,				unittest.TestCase	):

					'''simple docstring'''

					_A  :	int     =					(
					    (
					        MaMaaaModel,
					        MaMaaaForConditionalGeneration,
					    )
					    if is_torch_available()
					    else ()
					)
					_A  :	int     =					(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
					_A  :	Union[str, Any]     =					(
					    {
					        '''conversational''': MaMaaaForConditionalGeneration,
					        '''feature-extraction''': MaMaaaModel,
					        '''summarization''': MaMaaaForConditionalGeneration,
					        '''text2text-generation''': MaMaaaForConditionalGeneration,
					        '''translation''': MaMaaaForConditionalGeneration,
					    }
					    if is_torch_available()
					    else {}
					)
					_A  :	Optional[int]     =					True
					_A  :	Union[str, Any]     =					True
					_A  :	Any     =					False
					_A  :	int     =					False



					def 					lowerCAmelCase (     self :		str						,   __a :		Union[str, Any]						,   __a :		Optional[int]						,   __a :		List[Any]						,   __a :		Tuple						,   __a :		Optional[int]							)	->     Any:


												"""simple docstring"""

												if pipeline_test_casse_name == "TranslationPipelineTests":
																			# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
																			# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
																			return True

												return False



					def 					lowerCAmelCase (     self :		Union[str, Any]							)	->     List[Any]:


												"""simple docstring"""

												__lowercase					:							int			=   MaMaaaModelTester(self							)
												__lowercase					:							Union[str, Any]			=   ConfigTester(self						,   config_class=__a							)



					def 					lowerCAmelCase (     self :		Any							)	->     str:


												"""simple docstring"""

												self.config_tester.run_common_tests()



					def 					lowerCAmelCase (     self :		List[Any]							)	->     Any:


												"""simple docstring"""

												__lowercase	,	__lowercase					:							Any			=   self.model_tester.prepare_config_and_inputs()
												for model_class in self.all_model_classes:
																			__lowercase					:							List[str]			=   model_class(__a							)

																			with tempfile.TemporaryDirectory() as tmpdirname:
																										model.save_pretrained(__a							)
																										__lowercase	,	__lowercase					:							str			=   model_class.from_pretrained(__a						,   output_loading_info=__a							)
																			self.assertEqual(info["""missing_keys"""]						,   []							)



					def 					lowerCAmelCase (     self :		int							)	->     List[Any]:


												"""simple docstring"""

												__lowercase					:							List[Any]			=   self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_decoder_model_past_large_inputs(*__a							)



					def 					lowerCAmelCase (     self :		Union[str, Any]							)	->     Optional[Any]:


												"""simple docstring"""

												__lowercase					:							Optional[int]			=   self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.check_encoder_decoder_model_standalone(*__a							)



					def 					lowerCAmelCase (     self :		int							)	->     Any:


												"""simple docstring"""

												__lowercase	,	__lowercase					:							Optional[Any]			=   self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
																			__lowercase					:							Union[str, Any]			=   model_class(__a							)
																			model.to(__a							)
																			model.eval()

																			__lowercase					:							Any			=   copy.deepcopy(self._prepare_for_class(__a						,   __a							)							)

																			if not self.is_encoder_decoder:
																										__lowercase					:							int			=   inputs["""input_ids"""]
																										del inputs["input_ids"]
																			else:
																										__lowercase					:							Optional[int]			=   inputs["""input_ids"""]
																										__lowercase					:							Optional[Any]			=   inputs.get("""decoder_input_ids"""						,   __a							)
																										del inputs["input_ids"]
																										inputs.pop("""decoder_input_ids"""						,   __a							)

																			__lowercase					:							Union[str, Any]			=   model.get_input_embeddings()
																			if not self.is_encoder_decoder:
																										__lowercase					:							Dict			=   wte(__a							)
																			else:
																										__lowercase					:							str			=   wte(__a							)
																										__lowercase					:							Union[str, Any]			=   wte(__a							)

																			with torch.no_grad():
																										model(**__a							)[0]



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     Optional[int]:


												"""simple docstring"""

												__lowercase	,	__lowercase					:							str			=   self.model_tester.prepare_config_and_inputs()
												__lowercase					:							List[str]			=   input_dict["""input_ids"""]
												__lowercase					:							Optional[int]			=   input_ids.ne(1							).to(__a							)
												__lowercase					:							List[Any]			=   MaMaaaForConditionalGeneration(__a							).eval().to(__a							)
												if torch_device == "cuda":
																			model.half()
												model.generate(__a						,   attention_mask=__a							)
												model.generate(num_beams=4						,   do_sample=__a						,   early_stopping=__a						,   num_return_sequences=3							)







def 					snake_case_						(   lowerCAmelCase_				:  Optional[Any]					):
							return torch.tensor(lowerCAmelCase_				,				dtype=torch.long				,				device=lowerCAmelCase_					)


lowerCamelCase       :       Dict        =				1E-4



@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 						lowerCAmelCase   (       unittest.TestCase	):

					'''simple docstring'''

					@cached_property
					def 					lowerCAmelCase (     self :		List[str]							)	->     Tuple:


												"""simple docstring"""

												return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""							)



					def 					lowerCAmelCase (     self :		Any							)	->     Tuple:


												"""simple docstring"""

												__lowercase					:							List[str]			=   MaMaaaModel.from_pretrained("""facebook/m2m100_418M"""							).to(__a							)
												__lowercase					:							Union[str, Any]			=   _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]							)
												__lowercase					:							int			=   _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]							)
												__lowercase					:							int			=   prepare_mam_aaa_inputs_dict(model.config						,   __a						,   __a							)
												with torch.no_grad():
																			__lowercase					:							int			=   model(**__a							)[0]
												__lowercase					:							int			=   torch.Size((1, 11, 1024)							)
												self.assertEqual(output.shape						,   __a							)
												# change to expected output here
												__lowercase					:							Dict			=   torch.tensor(
												    [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]						,   device=__a							)
												self.assertTrue(torch.allclose(output[:, :3, :3]						,   __a						,   atol=__a							)							)



					def 					lowerCAmelCase (     self :		Union[str, Any]							)	->     Optional[Any]:


												"""simple docstring"""

												__lowercase					:							Tuple			=   MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""							).to(__a							)

												# change to intended input
												__lowercase					:							Any			=   _long_tensor([[128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38, 2]]							)
												__lowercase					:							Union[str, Any]			=   _long_tensor([[2, 128028, 98, 12, 30527, 2732, 159, 7755, 61904, 39144, 38]]							)
												__lowercase					:							Tuple			=   prepare_mam_aaa_inputs_dict(model.config						,   __a						,   __a							)
												with torch.no_grad():
																			__lowercase					:							Optional[Any]			=   model(**__a							)[0]
												__lowercase					:							Tuple			=   torch.Size((1, 11, model.config.vocab_size)							)
												self.assertEqual(output.shape						,   __a							)
												# change to expected output here
												__lowercase					:							Union[str, Any]			=   torch.tensor(
												    [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]						,   device=__a							)
												self.assertTrue(torch.allclose(output[:, :3, :3]						,   __a						,   atol=__a							)							)



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     int:


												"""simple docstring"""

												__lowercase					:							List[str]			=   MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""							).to(__a							)
												__lowercase					:							Tuple			=   MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""						,   src_lang="""fr"""						,   tgt_lang="""en"""							)

												__lowercase					:							Dict			=   [
												    """L'affaire NSA souligne l'absence totale de débat sur le renseignement""",
												    """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""",
												    """Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent"""
												    """ Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de"""
												    """ l'ampleur de la surveillance américaine sur l'ensemble des communications en France.""",
												]

												# The below article tests that we don't add any hypotheses outside of the top n_beams
												__lowercase					:							Union[str, Any]			=   tokenizer(__a						,   padding=__a						,   return_tensors="""pt"""							)

												__lowercase					:							Dict			=   model.generate(
												    input_ids=dct["""input_ids"""].to(__a							)						,   attention_mask=dct["""attention_mask"""].to(__a							)						,   num_beams=5						,   forced_bos_token_id=tokenizer.get_lang_id("""en"""							)						,   )

												__lowercase					:							Any			=   [
												    """The NSA case highlights the total absence of intelligence debate""",
												    """I think there are two levels of response from the French government.""",
												    """When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S."""
												    """ Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all"""
												    """ communications in France.""",
												]

												__lowercase					:							Dict			=   tokenizer.batch_decode(
												    hypotheses_batch.tolist()						,   clean_up_tokenization_spaces=__a						,   skip_special_tokens=__a							)
												assert generated == expected_en