


"""simple docstring"""







import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union

import numpy as np
import regex

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy


a__       :							Dict        =  logging.get_logger(__name__)

a__       :							Any        =  {
    "artists_file": "artists.json",
    "lyrics_file": "lyrics.json",
    "genres_file": "genres.json",
}

a__       :							Optional[int]        =  {
    "artists_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json",
    },
    "genres_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json",
    },
    "lyrics_file": {
        "jukebox": "https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json",
    },
}

a__       :							Dict        =  {
    "jukebox": 5_1_2,
}




class 				UpperCamelCase_			(				_SCREAMING_SNAKE_CASE):

	"""simple docstring"""





	snake_case__       :						Optional[Any]					      =    VOCAB_FILES_NAMES
	snake_case__       :						Tuple					      =    PRETRAINED_VOCAB_FILES_MAP
	snake_case__       :						str					      =    PRETRAINED_LYRIC_TOKENS_SIZES
	snake_case__       :						Union[str, Any]					      =    ["input_ids", "attention_mask"]




	def __init__(				self    :       Tuple    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       int    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Dict=["v3", "v2", "v2"]    ,    UpperCAmelCase__    :       Tuple=5_1_2    ,    UpperCAmelCase__    :       Tuple=5    ,    UpperCAmelCase__    :       Any="<|endoftext|>"    ,    **UpperCAmelCase__    :       Union[str, Any]    ,    ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       AddedToken(A_    ,    lstrip=A_    ,    rstrip=A_     ) if isinstance(A_    ,    A_     ) else unk_token
						super().__init__(
						    unk_token=A_    ,    n_genres=A_    ,    version=A_    ,    max_n_lyric_tokens=A_    ,    **A_    ,    )
						__SCREAMING_SNAKE_CASE		     =       version
						__SCREAMING_SNAKE_CASE		     =       max_n_lyric_tokens
						__SCREAMING_SNAKE_CASE		     =       n_genres

						with open(A_    ,    encoding="utf-8"     ) as vocab_handle:
											__SCREAMING_SNAKE_CASE		     =       json.load(A_     )

						with open(A_    ,    encoding="utf-8"     ) as vocab_handle:
											__SCREAMING_SNAKE_CASE		     =       json.load(A_     )

						with open(A_    ,    encoding="utf-8"     ) as vocab_handle:
											__SCREAMING_SNAKE_CASE		     =       json.load(A_     )

						__SCREAMING_SNAKE_CASE		     =       R"[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+"
						# In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
						if len(self.lyrics_encoder     ) == 7_9:
											__SCREAMING_SNAKE_CASE		     =       oov.replace(R"\-\'"    ,    R"\-+\'"     )

						__SCREAMING_SNAKE_CASE		     =       regex.compile(A_     )
						__SCREAMING_SNAKE_CASE		     =       {v: k for k, v in self.artists_encoder.items()}
						__SCREAMING_SNAKE_CASE		     =       {v: k for k, v in self.genres_encoder.items()}
						__SCREAMING_SNAKE_CASE		     =       {v: k for k, v in self.lyrics_encoder.items()}




	@property
	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			str:
						return len(self.artists_encoder     ) + len(self.genres_encoder     ) + len(self.lyrics_encoder     )




	def 						UpperCAmelCase_   (				self    :       Any     ) ->			Tuple:
						return dict(self.artists_encoder    ,    self.genres_encoder    ,    self.lyrics_encoder     )




	def 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       List[str]     ) ->			Optional[Any]:
						__SCREAMING_SNAKE_CASE		     =       [self.artists_encoder.get(A_    ,    0     ) for artist in list_artists]
						for genres in range(len(A_     )     ):
											__SCREAMING_SNAKE_CASE		     =       [self.genres_encoder.get(A_    ,    0     ) for genre in list_genres[genres]]
											__SCREAMING_SNAKE_CASE		     =       list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]     ))

						__SCREAMING_SNAKE_CASE		     =       [[self.lyrics_encoder.get(A_    ,    0     ) for character in list_lyrics[0]], [], []]
						return artists_id, list_genres, lyric_ids




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]    ,    UpperCAmelCase__    :       int     ) ->			Optional[Any]:
						return list(A_     )




	def 						UpperCAmelCase_   (				self    :       str    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Dict    ,    **UpperCAmelCase__    :       Optional[int]     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.prepare_for_tokenization(A_    ,    A_    ,    A_     )
						__SCREAMING_SNAKE_CASE		     =       self._tokenize(A_     )
						return artist, genre, lyrics




	def 						UpperCAmelCase_   (				self    :       Any    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       Tuple = False     ) ->			Tuple[str, str, str, Dict[str, Any]]:
						for idx in range(len(self.version     )     ):
											if self.version[idx] == "v3":
																__SCREAMING_SNAKE_CASE		     =       artists[idx].lower()
																__SCREAMING_SNAKE_CASE		     =       [genres[idx].lower()]
											else:
																__SCREAMING_SNAKE_CASE		     =       self._normalize(artists[idx]     ) + ".v2"
																__SCREAMING_SNAKE_CASE		     =       [
																    self._normalize(A_     ) + ".v2" for genre in genres[idx].split("_"     )
																]  # split is for the full dictionary with combined genres

						if self.version[0] == "v2":
											__SCREAMING_SNAKE_CASE		     =       regex.compile(R"[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+"     )
											__SCREAMING_SNAKE_CASE		     =       "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n"
											__SCREAMING_SNAKE_CASE		     =       {vocab[index]: index + 1 for index in range(len(A_     )     )}
											__SCREAMING_SNAKE_CASE		     =       0
											__SCREAMING_SNAKE_CASE		     =       len(A_     ) + 1
											__SCREAMING_SNAKE_CASE		     =       self.vocab
											__SCREAMING_SNAKE_CASE		     =       {v: k for k, v in self.vocab.items()}
											__SCREAMING_SNAKE_CASE		     =       ""
						else:
											__SCREAMING_SNAKE_CASE		     =       regex.compile(R"[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+"     )

						__SCREAMING_SNAKE_CASE		     =       self._run_strip_accents(A_     )
						__SCREAMING_SNAKE_CASE		     =       lyrics.replace("\\"    ,    "\n"     )
						__SCREAMING_SNAKE_CASE		     =       self.out_of_vocab.sub(""    ,    A_     ), [], []
						return artists, genres, lyrics




	def 						UpperCAmelCase_   (				self    :       str    ,    UpperCAmelCase__    :       Optional[Any]     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE		     =       unicodedata.normalize("NFD"    ,    A_     )
						__SCREAMING_SNAKE_CASE		     =       []
						for char in text:
											__SCREAMING_SNAKE_CASE		     =       unicodedata.category(A_     )
											if cat == "Mn":
																continue
											output.append(A_     )
						return "".join(A_     )




	def 						UpperCAmelCase_   (				self    :       Any    ,    UpperCAmelCase__    :       List[str]     ) ->			str:
						__SCREAMING_SNAKE_CASE		     =       (
						    [chr(A_     ) for i in range(ord("a"     )    ,    ord("z"     ) + 1     )]
						    + [chr(A_     ) for i in range(ord("A"     )    ,    ord("Z"     ) + 1     )]
						    + [chr(A_     ) for i in range(ord("0"     )    ,    ord("9"     ) + 1     )]
						    + ["."]
						)
						__SCREAMING_SNAKE_CASE		     =       frozenset(A_     )
						__SCREAMING_SNAKE_CASE		     =       re.compile(R"_+"     )
						__SCREAMING_SNAKE_CASE		     =       "".join([c if c in accepted else "_" for c in text.lower()]     )
						__SCREAMING_SNAKE_CASE		     =       pattern.sub("_"    ,    A_     ).strip("_"     )
						return text




	def 						UpperCAmelCase_   (				self    :       Tuple    ,    UpperCAmelCase__    :       Dict     ) ->			str:
						return " ".join(A_     )




	def 						UpperCAmelCase_   (				self    :       int    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       Any = None    ,    UpperCAmelCase__    :       List[Any] = False     ) ->			Optional[int]:
						# Convert to TensorType
						if not isinstance(A_    ,    A_     ):
											__SCREAMING_SNAKE_CASE		     =       TensorType(A_     )

						# Get a function reference for the correct framework
						if tensor_type == TensorType.TENSORFLOW:
											if not is_tf_available():
																raise ImportError(
																    "Unable to convert output to TensorFlow tensors format, TensorFlow is not installed."     )
											import tensorflow as tf

											__SCREAMING_SNAKE_CASE		     =       tf.constant
											__SCREAMING_SNAKE_CASE		     =       tf.is_tensor
						elif tensor_type == TensorType.PYTORCH:
											if not is_torch_available():
																raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed."     )
											import torch

											__SCREAMING_SNAKE_CASE		     =       torch.tensor
											__SCREAMING_SNAKE_CASE		     =       torch.is_tensor
						elif tensor_type == TensorType.JAX:
											if not is_flax_available():
																raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed."     )
											import jax.numpy as jnp  # noqa: F811

											__SCREAMING_SNAKE_CASE		     =       jnp.array
											__SCREAMING_SNAKE_CASE		     =       _is_jax
						else:
											__SCREAMING_SNAKE_CASE		     =       np.asarray
											__SCREAMING_SNAKE_CASE		     =       _is_numpy

						# Do the tensor conversion in batch

						try:
											if prepend_batch_axis:
																__SCREAMING_SNAKE_CASE		     =       [inputs]

											if not is_tensor(A_     ):
																__SCREAMING_SNAKE_CASE		     =       as_tensor(A_     )
						except:  # noqa E722
											raise ValueError(
											    "Unable to create tensor, you should probably activate truncation and/or padding "
											    "with \'padding=True\' \'truncation=True\' to have batched tensors with the same length."     )

						return inputs




	def __call__(				self    :       Dict    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Optional[Any]=""    ,    UpperCAmelCase__    :       List[str]="pt"     ) ->			BatchEncoding:
						__SCREAMING_SNAKE_CASE		     =       [0, 0, 0]
						__SCREAMING_SNAKE_CASE		     =       [artist] * len(self.version     )
						__SCREAMING_SNAKE_CASE		     =       [genres] * len(self.version     )

						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.tokenize(A_    ,    A_    ,    A_     )
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self._convert_token_to_id(A_    ,    A_    ,    A_     )

						__SCREAMING_SNAKE_CASE		     =       [-INFINITY] * len(full_tokens[-1]     )
						__SCREAMING_SNAKE_CASE		     =       [
						    self.convert_to_tensors(
						        [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]]    ,    tensor_type=A_     )
						    for i in range(len(self.version     )     )
						]
						return BatchEncoding({"input_ids": input_ids, "attention_masks": attention_masks}     )




	def 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       List[Any] = None     ) ->			Tuple[str]:
						if not os.path.isdir(A_     ):
											logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""     )
											return

						__SCREAMING_SNAKE_CASE		     =       os.path.join(
						    A_    ,    (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["artists_file"]     )
						with open(A_    ,    "w"    ,    encoding="utf-8"     ) as f:
											f.write(json.dumps(self.artists_encoder    ,    ensure_ascii=A_     )     )

						__SCREAMING_SNAKE_CASE		     =       os.path.join(
						    A_    ,    (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["genres_file"]     )
						with open(A_    ,    "w"    ,    encoding="utf-8"     ) as f:
											f.write(json.dumps(self.genres_encoder    ,    ensure_ascii=A_     )     )

						__SCREAMING_SNAKE_CASE		     =       os.path.join(
						    A_    ,    (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["lyrics_file"]     )
						with open(A_    ,    "w"    ,    encoding="utf-8"     ) as f:
											f.write(json.dumps(self.lyrics_encoder    ,    ensure_ascii=A_     )     )

						return (artists_file, genres_file, lyrics_file)




	def 						UpperCAmelCase_   (				self    :       str    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       int     ) ->			str:
						__SCREAMING_SNAKE_CASE		     =       self.artists_decoder.get(A_     )
						__SCREAMING_SNAKE_CASE		     =       [self.genres_decoder.get(A_     ) for genre in genres_index]
						__SCREAMING_SNAKE_CASE		     =       [self.lyrics_decoder.get(A_     ) for character in lyric_index]
						return artist, genres, lyrics








"""simple docstring"""







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      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_=None						,		lowerCAmelCase_=None						,		lowerCAmelCase_=None						,		lowerCAmelCase_=None						,		lowerCAmelCase_=None						,		):




					'''simple docstring'''


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

	"""simple docstring"""





	def __init__(				self    :       Dict    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Dict=1_3    ,    UpperCAmelCase__    :       List[str]=7    ,    UpperCAmelCase__    :       Any=True    ,    UpperCAmelCase__    :       Any=False    ,    UpperCAmelCase__    :       Optional[int]=9_9    ,    UpperCAmelCase__    :       Dict=1_6    ,    UpperCAmelCase__    :       List[str]=2    ,    UpperCAmelCase__    :       str=4    ,    UpperCAmelCase__    :       str=4    ,    UpperCAmelCase__    :       Optional[int]="relu"    ,    UpperCAmelCase__    :       int=0.1    ,    UpperCAmelCase__    :       List[str]=0.1    ,    UpperCAmelCase__    :       List[Any]=0.0    ,    UpperCAmelCase__    :       Union[str, Any]=0.0    ,    UpperCAmelCase__    :       List[str]=2_0    ,    UpperCAmelCase__    :       List[str]=2    ,    UpperCAmelCase__    :       Any=1    ,    UpperCAmelCase__    :       Union[str, Any]=0    ,    ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       parent
						__SCREAMING_SNAKE_CASE		     =       batch_size
						__SCREAMING_SNAKE_CASE		     =       seq_length
						__SCREAMING_SNAKE_CASE		     =       is_training
						__SCREAMING_SNAKE_CASE		     =       use_labels
						__SCREAMING_SNAKE_CASE		     =       vocab_size
						__SCREAMING_SNAKE_CASE		     =       hidden_size
						__SCREAMING_SNAKE_CASE		     =       num_hidden_layers
						__SCREAMING_SNAKE_CASE		     =       num_attention_heads
						__SCREAMING_SNAKE_CASE		     =       intermediate_size
						__SCREAMING_SNAKE_CASE		     =       hidden_act
						__SCREAMING_SNAKE_CASE		     =       hidden_dropout_prob
						__SCREAMING_SNAKE_CASE		     =       attention_probs_dropout_prob
						__SCREAMING_SNAKE_CASE		     =       encoder_layerdrop
						__SCREAMING_SNAKE_CASE		     =       decoder_layerdrop
						__SCREAMING_SNAKE_CASE		     =       max_position_embeddings
						__SCREAMING_SNAKE_CASE		     =       eos_token_id
						__SCREAMING_SNAKE_CASE		     =       pad_token_id
						__SCREAMING_SNAKE_CASE		     =       bos_token_id




	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size, self.seq_length]    ,    self.vocab_size     )
						__SCREAMING_SNAKE_CASE		     =       self.eos_token_id  # Eos Token
						__SCREAMING_SNAKE_CASE		     =       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
						__SCREAMING_SNAKE_CASE		     =       input_ids.clamp(self.pad_token_id + 1     )
						__SCREAMING_SNAKE_CASE		     =       decoder_input_ids.clamp(self.pad_token_id + 1     )

						__SCREAMING_SNAKE_CASE		     =       self.get_config()
						__SCREAMING_SNAKE_CASE		     =       prepare_mam_aaa_inputs_dict(UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__     )
						return config, inputs_dict




	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			Any:
						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 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			int:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.prepare_config_and_inputs()
						return config, inputs_dict




	def 						UpperCAmelCase_   (				self    :       str    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       Optional[Any]     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE		     =       MaMaaaModel(config=UpperCAmelCase__     ).get_decoder().to(UpperCAmelCase__     ).eval()
						__SCREAMING_SNAKE_CASE		     =       inputs_dict["input_ids"]
						__SCREAMING_SNAKE_CASE		     =       inputs_dict["attention_mask"]
						__SCREAMING_SNAKE_CASE		     =       inputs_dict["head_mask"]

						# first forward pass
						__SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    head_mask=UpperCAmelCase__    ,    use_cache=UpperCAmelCase__     )

						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       outputs.to_tuple()

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

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

						__SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__     )["last_hidden_state"]
						__SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    past_key_values=UpperCAmelCase__     )[
						    "last_hidden_state"
						]

						# select random slice
						__SCREAMING_SNAKE_CASE		     =       ids_tensor((1,)    ,    output_from_past.shape[-1]     ).item()
						__SCREAMING_SNAKE_CASE		     =       output_from_no_past[:, -3:, random_slice_idx].detach()
						__SCREAMING_SNAKE_CASE		     =       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 						UpperCAmelCase_   (				self    :       Tuple    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Union[str, Any]     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE		     =       MaMaaaModel(config=UpperCAmelCase__     ).to(UpperCAmelCase__     ).eval()
						__SCREAMING_SNAKE_CASE		     =       model(**UpperCAmelCase__     )

						__SCREAMING_SNAKE_CASE		     =       outputs.encoder_last_hidden_state
						__SCREAMING_SNAKE_CASE		     =       outputs.last_hidden_state

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

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

						__SCREAMING_SNAKE_CASE		     =       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_			(				UpperCamelCase    ,						UpperCamelCase    ,						UpperCamelCase    ,						unittest.TestCase):

	"""simple docstring"""





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




	def 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       Dict     ) ->			Optional[Any]:
						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 						UpperCAmelCase_   (				self    :       Dict     ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       MaMaaaModelTester(self     )
						__SCREAMING_SNAKE_CASE		     =       ConfigTester(self    ,    config_class=UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			Tuple:
						self.config_tester.run_common_tests()




	def 						UpperCAmelCase_   (				self    :       Dict     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
						for model_class in self.all_model_classes:
											__SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )

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




	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			Optional[Any]:
						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_encoder_decoder_model_standalone(*UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       str     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
											__SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )
											model.to(UpperCAmelCase__     )
											model.eval()

											__SCREAMING_SNAKE_CASE		     =       copy.deepcopy(self._prepare_for_class(UpperCAmelCase__    ,    UpperCAmelCase__     )     )

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

											__SCREAMING_SNAKE_CASE		     =       model.get_input_embeddings()
											if not self.is_encoder_decoder:
																__SCREAMING_SNAKE_CASE		     =       wte(UpperCAmelCase__     )
											else:
																__SCREAMING_SNAKE_CASE		     =       wte(UpperCAmelCase__     )
																__SCREAMING_SNAKE_CASE		     =       wte(UpperCAmelCase__     )

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




	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
						__SCREAMING_SNAKE_CASE		     =       input_dict["input_ids"]
						__SCREAMING_SNAKE_CASE		     =       input_ids.ne(1     ).to(UpperCAmelCase__     )
						__SCREAMING_SNAKE_CASE		     =       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      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


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


a__       :							Union[str, Any]        =  1E-4




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

	"""simple docstring"""





	@cached_property
	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			List[str]:
						return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"     )




	def 						UpperCAmelCase_   (				self    :       Dict     ) ->			List[Any]:
						__SCREAMING_SNAKE_CASE		     =       MaMaaaModel.from_pretrained("facebook/m2m100_418M"     ).to(UpperCAmelCase__     )
						__SCREAMING_SNAKE_CASE		     =       _long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]     )
						__SCREAMING_SNAKE_CASE		     =       _long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]     )
						__SCREAMING_SNAKE_CASE		     =       prepare_mam_aaa_inputs_dict(model.config    ,    UpperCAmelCase__    ,    UpperCAmelCase__     )
						with torch.no_grad():
											__SCREAMING_SNAKE_CASE		     =       model(**UpperCAmelCase__     )[0]
						__SCREAMING_SNAKE_CASE		     =       torch.Size((1, 1_1, 1_0_2_4)     )
						self.assertEqual(output.shape    ,    UpperCAmelCase__     )
						# change to expected output here
						__SCREAMING_SNAKE_CASE		     =       torch.tensor(
						    [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]]    ,    device=UpperCAmelCase__     )
						self.assertTrue(torch.allclose(output[:, :3, :3]    ,    UpperCAmelCase__    ,    atol=UpperCAmelCase__     )     )




	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			str:
						__SCREAMING_SNAKE_CASE		     =       MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"     ).to(UpperCAmelCase__     )

						# change to intended input
						__SCREAMING_SNAKE_CASE		     =       _long_tensor([[1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8, 2]]     )
						__SCREAMING_SNAKE_CASE		     =       _long_tensor([[2, 1_2_8_0_2_8, 9_8, 1_2, 3_0_5_2_7, 2_7_3_2, 1_5_9, 7_7_5_5, 6_1_9_0_4, 3_9_1_4_4, 3_8]]     )
						__SCREAMING_SNAKE_CASE		     =       prepare_mam_aaa_inputs_dict(model.config    ,    UpperCAmelCase__    ,    UpperCAmelCase__     )
						with torch.no_grad():
											__SCREAMING_SNAKE_CASE		     =       model(**UpperCAmelCase__     )[0]
						__SCREAMING_SNAKE_CASE		     =       torch.Size((1, 1_1, model.config.vocab_size)     )
						self.assertEqual(output.shape    ,    UpperCAmelCase__     )
						# change to expected output here
						__SCREAMING_SNAKE_CASE		     =       torch.tensor(
						    [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]]    ,    device=UpperCAmelCase__     )
						self.assertTrue(torch.allclose(output[:, :3, :3]    ,    UpperCAmelCase__    ,    atol=UpperCAmelCase__     )     )




	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"     ).to(UpperCAmelCase__     )
						__SCREAMING_SNAKE_CASE		     =       MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"    ,    src_lang="fr"    ,    tgt_lang="en"     )

						__SCREAMING_SNAKE_CASE		     =       [
						    "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
						__SCREAMING_SNAKE_CASE		     =       tokenizer(UpperCAmelCase__    ,    padding=UpperCAmelCase__    ,    return_tensors="pt"     )

						__SCREAMING_SNAKE_CASE		     =       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"     )    ,    )

						__SCREAMING_SNAKE_CASE		     =       [
						    "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.",
						]

						__SCREAMING_SNAKE_CASE		     =       tokenizer.batch_decode(
						    hypotheses_batch.tolist()    ,    clean_up_tokenization_spaces=UpperCAmelCase__    ,    skip_special_tokens=UpperCAmelCase__     )
						assert generated == expected_en
