

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

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


A__						=							logging.getLogger(__name__)

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

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




def 					_lowercase     (				a_				:					np.ndarray					,a_				:					float					,a_				:					int = 1_6_0_0_0				)				->	Union[str, Any]:




					'''simple docstring'''







					__magic_name__							=    int(round(sample_rate * max_length				)				)
					if len(a_				) <= sample_length:
										return wav
					__magic_name__							=    randint(0					,len(a_				) - sample_length - 1				)
					return wav[random_offset : random_offset + sample_length]

@dataclass
class 				__UpperCamelCase				:
	_lowercase  :   Optional[str]       				=  field(default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "Name of a dataset from the datasets package"}			)
	_lowercase  :   Optional[str]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}			)
	_lowercase  :   Optional[str]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "A file containing the training audio paths and labels."}			)
	_lowercase  :   Optional[str]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "A file containing the validation audio paths and labels."}			)
	_lowercase  :   str       				=  field(
	    default="train"  ,						metadata={
	        "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
	    }  ,						)
	_lowercase  :   str       				=  field(
	    default="validation"  ,						metadata={
	        "help": (
	            "The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
	        )
	    }  ,						)
	_lowercase  :   str       				=  field(
	    default="audio"  ,						metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"}  ,						)
	_lowercase  :   str       				=  field(
	    default="label"  ,						metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"}			)
	_lowercase  :   Optional[int]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of training examples to this "
	            "value if set."
	        )
	    }  ,						)
	_lowercase  :   Optional[int]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
	            "value if set."
	        )
	    }  ,						)
	_lowercase  :   float       				=  field(
	    default=2_0  ,						metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."}  ,						)




@dataclass
class 				__UpperCamelCase				:
	_lowercase  :   str       				=  field(
	    default="facebook/wav2vec2-base"  ,						metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}  ,						)
	_lowercase  :   Optional[str]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "Pretrained config name or path if not the same as model_name"}			)
	_lowercase  :   Optional[str]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"}			)
	_lowercase  :   str       				=  field(
	    default="main"  ,						metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}  ,						)
	_lowercase  :   Optional[str]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "Name or path of preprocessor config."}			)
	_lowercase  :   bool       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "Whether to freeze the feature encoder layers of the model."}			)
	_lowercase  :   bool       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "Whether to generate an attention mask in the feature extractor."}			)
	_lowercase  :   bool       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={
	        "help": (
	            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
	            "with private models)."
	        )
	    }  ,						)
	_lowercase  :   Optional[bool]       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "Whether to freeze the feature extractor layers of the model."}			)
	_lowercase  :   bool       				=  field(
	    default=SCREAMING_SNAKE_CASE  ,						metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}  ,						)







	def 	_SCREAMING_SNAKE_CASE							(   self: str      ):

						'''simple docstring'''





						if not self.freeze_feature_extractor and self.freeze_feature_encoder:
											warnings.warn(
											    'The argument `--freeze_feature_extractor` is deprecated and '
											    'will be removed in a future version. Use `--freeze_feature_encoder`'
											    'instead. Setting `freeze_feature_encoder==True`.'  , __UpperCamelCase  , )
						if self.freeze_feature_extractor and not self.freeze_feature_encoder:
											raise ValueError(
											    'The argument `--freeze_feature_extractor` is deprecated and '
											    'should not be used in combination with `--freeze_feature_encoder`.'
											    'Only make use of `--freeze_feature_encoder`.'      )




def 					_lowercase     (				)				->	Dict:




					'''simple docstring'''







					__magic_name__							=    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.
										__magic_name__,	__magic_name__,	__magic_name__							=    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
					else:
										__magic_name__,	__magic_name__,	__magic_name__							=    parser.parse_args_into_dataclasses()

					# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
					# information sent is the one passed as arguments along with your Python/PyTorch versions.
					send_example_telemetry('run_audio_classification'					,a_					,a_				)

					# 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				)]					,)

					if training_args.should_log:
										# The default of training_args.log_level is passive, so we set log level at info here to have that default.
										transformers.utils.logging.set_verbosity_info()

					__magic_name__							=    training_args.get_process_log_level()
					logger.setLevel(a_				)
					transformers.utils.logging.set_verbosity(a_				)
					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}'				)

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

					# Detecting last checkpoint.
					__magic_name__							=    None
					if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
										__magic_name__							=    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 train from scratch.'				)
										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.'				)

    # Initialize our dataset and prepare it for the audio classification task.
					__magic_name__							=    DatasetDict()
					__magic_name__							=    load_dataset(
					    data_args.dataset_name					,data_args.dataset_config_name					,split=data_args.train_split_name					,use_auth_token=True if model_args.use_auth_token else None					,)
					__magic_name__							=    load_dataset(
					    data_args.dataset_name					,data_args.dataset_config_name					,split=data_args.eval_split_name					,use_auth_token=True if model_args.use_auth_token else None					,)

					if data_args.audio_column_name not in raw_datasets["train"].column_names:
										raise ValueError(
										    F'--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. '
										    'Make sure to set `--audio_column_name` to the correct audio column - one of '
										    F'{", ".join(raw_datasets["train"].column_names				)}.'				)

					if data_args.label_column_name not in raw_datasets["train"].column_names:
										raise ValueError(
										    F'--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. '
										    'Make sure to set `--label_column_name` to the correct text column - one of '
										    F'{", ".join(raw_datasets["train"].column_names				)}.'				)

					# Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
					# transformer outputs in the classifier, but it doesn't always lead to better accuracy
					__magic_name__							=    AutoFeatureExtractor.from_pretrained(
					    model_args.feature_extractor_name or model_args.model_name_or_path					,return_attention_mask=model_args.attention_mask					,cache_dir=model_args.cache_dir					,revision=model_args.model_revision					,use_auth_token=True if model_args.use_auth_token else None					,)

					# `datasets` takes care of automatically loading and resampling the audio,
					# so we just need to set the correct target sampling rate.
					__magic_name__							=    raw_datasets.cast_column(
					    data_args.audio_column_name					,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate				)				)

					__magic_name__							=    feature_extractor.model_input_names[0]

					def train_transforms(a_				:					Any				):
										__magic_name__							=    []
										for audio in batch[data_args.audio_column_name]:
															__magic_name__							=    random_subsample(
															    audio['array']					,max_length=data_args.max_length_seconds					,sample_rate=feature_extractor.sampling_rate				)
															subsampled_wavs.append(a_				)
										__magic_name__							=    feature_extractor(a_					,sampling_rate=feature_extractor.sampling_rate				)
										__magic_name__							=    {model_input_name: inputs.get(a_				)}
										__magic_name__							=    list(batch[data_args.label_column_name]				)

										return output_batch

					def val_transforms(a_				:					Tuple				):
										__magic_name__							=    [audio['array'] for audio in batch[data_args.audio_column_name]]
										__magic_name__							=    feature_extractor(a_					,sampling_rate=feature_extractor.sampling_rate				)
										__magic_name__							=    {model_input_name: inputs.get(a_				)}
										__magic_name__							=    list(batch[data_args.label_column_name]				)

										return output_batch

					# Prepare label mappings.
					# We'll include these in the model's config to get human readable labels in the Inference API.
					__magic_name__							=    raw_datasets['train'].features[data_args.label_column_name].names
					__magic_name__,	__magic_name__							=    {}, {}
					for i, label in enumerate(a_				):
										__magic_name__							=    str(a_				)
										__magic_name__							=    label

					# Load the accuracy metric from the datasets package
					__magic_name__							=    evaluate.load('accuracy'				)

					# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
					# `predictions` and `label_ids` fields) and has to return a dictionary string to float.
					def compute_metrics(a_				:					Tuple				):
										__magic_name__							=    np.argmax(eval_pred.predictions					,axis=1				)
										return metric.compute(predictions=a_					,references=eval_pred.label_ids				)

					__magic_name__							=    AutoConfig.from_pretrained(
					    model_args.config_name or model_args.model_name_or_path					,num_labels=len(a_				)					,labelaid=a_					,idalabel=a_					,finetuning_task='audio-classification'					,cache_dir=model_args.cache_dir					,revision=model_args.model_revision					,use_auth_token=True if model_args.use_auth_token else None					,)
					__magic_name__							=    AutoModelForAudioClassification.from_pretrained(
					    model_args.model_name_or_path					,from_tf=bool('.ckpt' in model_args.model_name_or_path				)					,config=a_					,cache_dir=model_args.cache_dir					,revision=model_args.model_revision					,use_auth_token=True if model_args.use_auth_token else None					,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes					,)

					# freeze the convolutional waveform encoder
					if model_args.freeze_feature_encoder:
										model.freeze_feature_encoder()

					if training_args.do_train:
										if data_args.max_train_samples is not None:
															__magic_name__							=    (
															    raw_datasets['train'].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
															)
										# Set the training transforms
										raw_datasets["train"].set_transform(a_					,output_all_columns=a_				)

					if training_args.do_eval:
										if data_args.max_eval_samples is not None:
															__magic_name__							=    (
															    raw_datasets['eval'].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
															)
										# Set the validation transforms
										raw_datasets["eval"].set_transform(a_					,output_all_columns=a_				)

					# Initialize our trainer
					__magic_name__							=    Trainer(
					    model=a_					,args=a_					,train_dataset=raw_datasets['train'] if training_args.do_train else None					,eval_dataset=raw_datasets['eval'] if training_args.do_eval else None					,compute_metrics=a_					,tokenizer=a_					,)

					# Training
					if training_args.do_train:
										__magic_name__							=    None
										if training_args.resume_from_checkpoint is not None:
															__magic_name__							=    training_args.resume_from_checkpoint
										elif last_checkpoint is not None:
															__magic_name__							=    last_checkpoint
										__magic_name__							=    trainer.train(resume_from_checkpoint=a_				)
										trainer.save_model()
										trainer.log_metrics('train'					,train_result.metrics				)
										trainer.save_metrics('train'					,train_result.metrics				)
										trainer.save_state()

					# Evaluation
					if training_args.do_eval:
										__magic_name__							=    trainer.evaluate()
										trainer.log_metrics('eval'					,a_				)
										trainer.save_metrics('eval'					,a_				)

					# Write model card and (optionally) push to hub
					__magic_name__							=    {
					    'finetuned_from': model_args.model_name_or_path,
					    'tasks': 'audio-classification',
					    'dataset': data_args.dataset_name,
					    'tags': ['audio-classification'],
					}
					if training_args.push_to_hub:
										trainer.push_to_hub(**a_				)
					else:
										trainer.create_model_card(**a_				)


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 					_lowercase     (				a_				:					Optional[Any]					,a_				:					Dict					,a_				:					Any					,a_				:					Any=None					,a_				:					Any=None					,a_				:					List[str]=None					,a_				:					Union[str, Any]=None					,a_				:					Dict=None					,)				->	Optional[Any]:




					'''simple docstring'''







					if attention_mask is None:
										__magic_name__							=    input_ids.ne(config.pad_token_id				)
					if decoder_attention_mask is None:
										__magic_name__							=    decoder_input_ids.ne(config.pad_token_id				)
					if head_mask is None:
										__magic_name__							=    torch.ones(config.encoder_layers					,config.encoder_attention_heads					,device=a_				)
					if decoder_head_mask is None:
										__magic_name__							=    torch.ones(config.decoder_layers					,config.decoder_attention_heads					,device=a_				)
					if cross_attn_head_mask is None:
										__magic_name__							=    torch.ones(config.decoder_layers					,config.decoder_attention_heads					,device=a_				)
					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 				__UpperCamelCase				:







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

						'''simple docstring'''





						__magic_name__							=    parent
						__magic_name__							=    batch_size
						__magic_name__							=    seq_length
						__magic_name__							=    is_training
						__magic_name__							=    use_labels
						__magic_name__							=    vocab_size
						__magic_name__							=    hidden_size
						__magic_name__							=    num_hidden_layers
						__magic_name__							=    num_attention_heads
						__magic_name__							=    intermediate_size
						__magic_name__							=    hidden_act
						__magic_name__							=    hidden_dropout_prob
						__magic_name__							=    attention_probs_dropout_prob
						__magic_name__							=    encoder_layerdrop
						__magic_name__							=    decoder_layerdrop
						__magic_name__							=    max_position_embeddings
						__magic_name__							=    eos_token_id
						__magic_name__							=    pad_token_id
						__magic_name__							=    bos_token_id







	def 	_SCREAMING_SNAKE_CASE							(   self: Dict      ):

						'''simple docstring'''





						__magic_name__							=    ids_tensor([self.batch_size, self.seq_length]  , self.vocab_size      )
						__magic_name__							=    self.eos_token_id  # Eos Token
						__magic_name__							=    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
						__magic_name__							=    input_ids.clamp(self.pad_token_id + 1      )
						__magic_name__							=    decoder_input_ids.clamp(self.pad_token_id + 1      )

						__magic_name__							=    self.get_config()
						__magic_name__							=    prepare_mam_aaa_inputs_dict(__UpperCamelCase  , __UpperCamelCase  , __UpperCamelCase      )
						return config, inputs_dict







	def 	_SCREAMING_SNAKE_CASE							(   self: Optional[int]      ):

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

						'''simple docstring'''





						__magic_name__,	__magic_name__							=    self.prepare_config_and_inputs()
						return config, inputs_dict







	def 	_SCREAMING_SNAKE_CASE							(   self: Tuple  , __UpperCamelCase: Tuple  , __UpperCamelCase: Union[str, Any]      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaModel(config=__UpperCamelCase      ).get_decoder().to(__UpperCamelCase      ).eval()
						__magic_name__							=    inputs_dict['input_ids']
						__magic_name__							=    inputs_dict['attention_mask']
						__magic_name__							=    inputs_dict['head_mask']

						# first forward pass
						__magic_name__							=    model(__UpperCamelCase  , attention_mask=__UpperCamelCase  , head_mask=__UpperCamelCase  , use_cache=__UpperCamelCase      )

						__magic_name__,	__magic_name__							=    outputs.to_tuple()

						# create hypothetical multiple next token and extent to next_input_ids
						__magic_name__							=    ids_tensor((self.batch_size, 3)  , config.vocab_size      )
						__magic_name__							=    ids_tensor((self.batch_size, 3)  , 2      )

						# append to next input_ids and
						__magic_name__							=    torch.cat([input_ids, next_tokens]  , dim=-1      )
						__magic_name__							=    torch.cat([attention_mask, next_attn_mask]  , dim=-1      )

						__magic_name__							=    model(__UpperCamelCase  , attention_mask=__UpperCamelCase      )['last_hidden_state']
						__magic_name__							=    model(__UpperCamelCase  , attention_mask=__UpperCamelCase  , past_key_values=__UpperCamelCase      )[
						    'last_hidden_state'
						]

						# select random slice
						__magic_name__							=    ids_tensor((1,)  , output_from_past.shape[-1]      ).item()
						__magic_name__							=    output_from_no_past[:, -3:, random_slice_idx].detach()
						__magic_name__							=    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(__UpperCamelCase  , __UpperCamelCase  , atol=1E-2      )      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Union[str, Any]  , __UpperCamelCase: Any  , __UpperCamelCase: int      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaModel(config=__UpperCamelCase      ).to(__UpperCamelCase      ).eval()
						__magic_name__							=    model(**__UpperCamelCase      )

						__magic_name__							=    outputs.encoder_last_hidden_state
						__magic_name__							=    outputs.last_hidden_state

						with tempfile.TemporaryDirectory() as tmpdirname:
											__magic_name__							=    model.get_encoder()
											encoder.save_pretrained(__UpperCamelCase      )
											__magic_name__							=    MaMaaaEncoder.from_pretrained(__UpperCamelCase      ).to(__UpperCamelCase      )

						__magic_name__							=    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:
											__magic_name__							=    model.get_decoder()
											decoder.save_pretrained(__UpperCamelCase      )
											__magic_name__							=    MaMaaaDecoder.from_pretrained(__UpperCamelCase      ).to(__UpperCamelCase      )

						__magic_name__							=    decoder(
						    input_ids=inputs_dict['decoder_input_ids']  , attention_mask=inputs_dict['decoder_attention_mask']  , encoder_hidden_states=__UpperCamelCase  , 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 				__UpperCamelCase				(					SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE  ,						unittest.TestCase			):
	_lowercase  :   Tuple       				=  (
	    (
	        MaMaaaModel,
	        MaMaaaForConditionalGeneration,
	    )
	    if is_torch_available()
	    else ()
	)
	_lowercase  :   Dict       				=  (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
	_lowercase  :   Tuple       				=  (
	    {
	        "conversational": MaMaaaForConditionalGeneration,
	        "feature-extraction": MaMaaaModel,
	        "summarization": MaMaaaForConditionalGeneration,
	        "text2text-generation": MaMaaaForConditionalGeneration,
	        "translation": MaMaaaForConditionalGeneration,
	    }
	    if is_torch_available()
	    else {}
	)
	_lowercase  :   List[str]       				=  True
	_lowercase  :   Dict       				=  True
	_lowercase  :   Union[str, Any]       				=  False
	_lowercase  :   List[Any]       				=  False







	def 	_SCREAMING_SNAKE_CASE							(   self: Dict  , __UpperCamelCase: Any  , __UpperCamelCase: Optional[Any]  , __UpperCamelCase: List[str]  , __UpperCamelCase: Optional[Any]  , __UpperCamelCase: Tuple      ):

						'''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 	_SCREAMING_SNAKE_CASE							(   self: Tuple      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaModelTester(self      )
						__magic_name__							=    ConfigTester(self  , config_class=__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						self.config_tester.run_common_tests()







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						__magic_name__,	__magic_name__							=    self.model_tester.prepare_config_and_inputs()
						for model_class in self.all_model_classes:
											__magic_name__							=    model_class(__UpperCamelCase      )

											with tempfile.TemporaryDirectory() as tmpdirname:
																model.save_pretrained(__UpperCamelCase      )
																__magic_name__,	__magic_name__							=    model_class.from_pretrained(__UpperCamelCase  , output_loading_info=__UpperCamelCase      )
											self.assertEqual(info['missing_keys']  , []      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						__magic_name__							=    self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_decoder_model_past_large_inputs(*__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[Any]      ):

						'''simple docstring'''





						__magic_name__							=    self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_encoder_decoder_model_standalone(*__UpperCamelCase      )







	def 	_SCREAMING_SNAKE_CASE							(   self: List[str]      ):

						'''simple docstring'''





						__magic_name__,	__magic_name__							=    self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
											__magic_name__							=    model_class(__UpperCamelCase      )
											model.to(__UpperCamelCase      )
											model.eval()

											__magic_name__							=    copy.deepcopy(self._prepare_for_class(__UpperCamelCase  , __UpperCamelCase      )      )

											if not self.is_encoder_decoder:
																__magic_name__							=    inputs['input_ids']
																del inputs["input_ids"]
											else:
																__magic_name__							=    inputs['input_ids']
																__magic_name__							=    inputs.get('decoder_input_ids'  , __UpperCamelCase      )
																del inputs["input_ids"]
																inputs.pop('decoder_input_ids'  , __UpperCamelCase      )

											__magic_name__							=    model.get_input_embeddings()
											if not self.is_encoder_decoder:
																__magic_name__							=    wte(__UpperCamelCase      )
											else:
																__magic_name__							=    wte(__UpperCamelCase      )
																__magic_name__							=    wte(__UpperCamelCase      )

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







	def 	_SCREAMING_SNAKE_CASE							(   self: Union[str, Any]      ):

						'''simple docstring'''





						__magic_name__,	__magic_name__							=    self.model_tester.prepare_config_and_inputs()
						__magic_name__							=    input_dict['input_ids']
						__magic_name__							=    input_ids.ne(1      ).to(__UpperCamelCase      )
						__magic_name__							=    MaMaaaForConditionalGeneration(__UpperCamelCase      ).eval().to(__UpperCamelCase      )
						if torch_device == "cuda":
											model.half()
						model.generate(__UpperCamelCase  , attention_mask=__UpperCamelCase      )
						model.generate(num_beams=4  , do_sample=__UpperCamelCase  , early_stopping=__UpperCamelCase  , num_return_sequences=3      )




def 					_lowercase     (				a_				:					List[Any]				)				->	Union[str, Any]:




					'''simple docstring'''







					return torch.tensor(a_					,dtype=torch.long					,device=a_				)


A__						=							1e-4


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







	@cached_property
	def 	_SCREAMING_SNAKE_CASE							(   self: Any      ):

						'''simple docstring'''





						return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'      )







	def 	_SCREAMING_SNAKE_CASE							(   self: int      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaModel.from_pretrained('facebook/m2m100_418M'      ).to(__UpperCamelCase      )
						__magic_name__							=    _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]      )
						__magic_name__							=    _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]      )
						__magic_name__							=    prepare_mam_aaa_inputs_dict(model.config  , __UpperCamelCase  , __UpperCamelCase      )
						with torch.no_grad():
											__magic_name__							=    model(**__UpperCamelCase      )[0]
						__magic_name__							=    torch.Size((1, 11, 10_24)      )
						self.assertEqual(output.shape  , __UpperCamelCase      )
						# change to expected output here
						__magic_name__							=    torch.tensor(
						    [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]]  , device=__UpperCamelCase      )
						self.assertTrue(torch.allclose(output[:, :3, :3]  , __UpperCamelCase  , atol=__UpperCamelCase      )      )







	def 	_SCREAMING_SNAKE_CASE							(   self: str      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'      ).to(__UpperCamelCase      )

						# change to intended input
						__magic_name__							=    _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]]      )
						__magic_name__							=    _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]]      )
						__magic_name__							=    prepare_mam_aaa_inputs_dict(model.config  , __UpperCamelCase  , __UpperCamelCase      )
						with torch.no_grad():
											__magic_name__							=    model(**__UpperCamelCase      )[0]
						__magic_name__							=    torch.Size((1, 11, model.config.vocab_size)      )
						self.assertEqual(output.shape  , __UpperCamelCase      )
						# change to expected output here
						__magic_name__							=    torch.tensor(
						    [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]]  , device=__UpperCamelCase      )
						self.assertTrue(torch.allclose(output[:, :3, :3]  , __UpperCamelCase  , atol=__UpperCamelCase      )      )







	def 	_SCREAMING_SNAKE_CASE							(   self: Union[str, Any]      ):

						'''simple docstring'''





						__magic_name__							=    MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M'      ).to(__UpperCamelCase      )
						__magic_name__							=    MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M'  , src_lang='fr'  , tgt_lang='en'      )

						__magic_name__							=    [
						    '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
						__magic_name__							=    tokenizer(__UpperCamelCase  , padding=__UpperCamelCase  , return_tensors='pt'      )

						__magic_name__							=    model.generate(
						    input_ids=dct['input_ids'].to(__UpperCamelCase      )  , attention_mask=dct['attention_mask'].to(__UpperCamelCase      )  , num_beams=5  , forced_bos_token_id=tokenizer.get_lang_id('en'      )  , )

						__magic_name__							=    [
						    '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.',
						]

						__magic_name__							=    tokenizer.batch_decode(
						    hypotheses_batch.tolist()  , clean_up_tokenization_spaces=__UpperCamelCase  , skip_special_tokens=__UpperCamelCase      )
						assert generated == expected_en




