


"""simple docstring"""







# Copyright (c) 2021-, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

####################################################################################################

#
# Note: If when running this conversion script you're getting an exception:
#     ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#

import argparse
import os
import re
import zipfile

import torch

from transformers import AutoTokenizer, GPTaConfig




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_=0     ):




					'''simple docstring'''


					if name is None:
										__SCREAMING_SNAKE_CASE		     =       None
					else:
										__SCREAMING_SNAKE_CASE		     =       "." * max(0						,		spaces - 2     ) + "# {:" + str(50 - spaces     ) + "s}"
										__SCREAMING_SNAKE_CASE		     =       fmt.format(lowerCAmelCase_     )

					# Print and recurse (if needed).
					if isinstance(lowerCAmelCase_						,		lowerCAmelCase_     ):
										if msg is not None:
															print(lowerCAmelCase_     )
										for k in val.keys():
															recursive_print(lowerCAmelCase_						,		val[k]						,		spaces + 2     )
					elif isinstance(lowerCAmelCase_						,		torch.Tensor     ):
										print(lowerCAmelCase_						,		":"						,		val.size()     )
					else:
										print(lowerCAmelCase_						,		":"						,		lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       param.size()
					if checkpoint_version == 1.0:
										# version 1.0 stores [num_heads * hidden_size * num_splits, :]
										__SCREAMING_SNAKE_CASE		     =       (num_heads, hidden_size, num_splits) + input_shape[1:]
										__SCREAMING_SNAKE_CASE		     =       param.view(*lowerCAmelCase_     )
										__SCREAMING_SNAKE_CASE		     =       param.transpose(0						,		2     )
										__SCREAMING_SNAKE_CASE		     =       param.transpose(1						,		2     ).contiguous()
					elif checkpoint_version >= 2.0:
										# other versions store [num_heads * num_splits * hidden_size, :]
										__SCREAMING_SNAKE_CASE		     =       (num_heads, num_splits, hidden_size) + input_shape[1:]
										__SCREAMING_SNAKE_CASE		     =       param.view(*lowerCAmelCase_     )
										__SCREAMING_SNAKE_CASE		     =       param.transpose(0						,		1     ).contiguous()
					__SCREAMING_SNAKE_CASE		     =       param.view(*lowerCAmelCase_     )
					return param




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       {}

					# old versions did not store training args
					__SCREAMING_SNAKE_CASE		     =       input_state_dict.get("args"						,		lowerCAmelCase_     )
					if ds_args is not None:
										# do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
										# from pprint import pprint
										# pprint(vars(ds_args))

										__SCREAMING_SNAKE_CASE		     =       ds_args.padded_vocab_size
										__SCREAMING_SNAKE_CASE		     =       ds_args.max_position_embeddings
										__SCREAMING_SNAKE_CASE		     =       ds_args.hidden_size
										__SCREAMING_SNAKE_CASE		     =       ds_args.num_layers
										__SCREAMING_SNAKE_CASE		     =       ds_args.num_attention_heads
										__SCREAMING_SNAKE_CASE		     =       ds_args.ffn_hidden_size
										# pprint(config)

					# The number of heads.
					__SCREAMING_SNAKE_CASE		     =       config.n_head
					# The hidden_size per head.
					__SCREAMING_SNAKE_CASE		     =       config.n_embd // config.n_head
					# Megatron-LM checkpoint version
					if "checkpoint_version" in input_state_dict.keys():
										__SCREAMING_SNAKE_CASE		     =       input_state_dict["checkpoint_version"]
					else:
										__SCREAMING_SNAKE_CASE		     =       0.0

					# The model.
					__SCREAMING_SNAKE_CASE		     =       input_state_dict["model"]
					# The language model.
					__SCREAMING_SNAKE_CASE		     =       model["language_model"]
					# The embeddings.
					__SCREAMING_SNAKE_CASE		     =       lm["embedding"]

					# The word embeddings.
					__SCREAMING_SNAKE_CASE		     =       embeddings["word_embeddings"]["weight"]
					# Truncate the embedding table to vocab_size rows.
					__SCREAMING_SNAKE_CASE		     =       word_embeddings[: config.vocab_size, :]
					__SCREAMING_SNAKE_CASE		     =       word_embeddings

					# The position embeddings.
					__SCREAMING_SNAKE_CASE		     =       embeddings["position_embeddings"]["weight"]
					# Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size]
					__SCREAMING_SNAKE_CASE		     =       pos_embeddings.size(0     )
					if n_positions != config.n_positions:
										raise ValueError(
										    f"""pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match"""     )
					# Store the position embeddings.
					__SCREAMING_SNAKE_CASE		     =       pos_embeddings

					# The transformer.
					__SCREAMING_SNAKE_CASE		     =       lm["transformer"] if "transformer" in lm.keys() else lm["encoder"]

					# The regex to extract layer names.
					__SCREAMING_SNAKE_CASE		     =       re.compile(R"layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)"     )

					# The simple map of names for "automated" rules.
					__SCREAMING_SNAKE_CASE		     =       {
					    "attention.dense": ".attn.c_proj.",
					    "self_attention.dense": ".attn.c_proj.",
					    "mlp.dense_h_to_4h": ".mlp.c_fc.",
					    "mlp.dense_4h_to_h": ".mlp.c_proj.",
					}

					# Extract the layers.
					for key, val in transformer.items():
										# Match the name.
										__SCREAMING_SNAKE_CASE		     =       layer_re.match(lowerCAmelCase_     )

										# Stop if that's not a layer
										if m is None:
															break

										# The index of the layer.
										__SCREAMING_SNAKE_CASE		     =       int(m.group(1     )     )
										# The name of the operation.
										__SCREAMING_SNAKE_CASE		     =       m.group(2     )
										# Is it a weight or a bias?
										__SCREAMING_SNAKE_CASE		     =       m.group(3     )

										# The name of the layer.
										__SCREAMING_SNAKE_CASE		     =       f"""transformer.h.{layer_idx}"""

										# For layernorm(s), simply store the layer norm.
										if op_name.endswith("layernorm"     ):
															__SCREAMING_SNAKE_CASE		     =       "ln_1" if op_name.startswith("input"     ) else "ln_2"
															__SCREAMING_SNAKE_CASE		     =       val

										# Transpose the QKV matrix.
										elif (
										    op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
										) and weight_or_bias == "weight":
															# Insert a tensor of 1x1xDxD bias.
															__SCREAMING_SNAKE_CASE		     =       torch.tril(torch.ones((n_positions, n_positions)						,		dtype=torch.floataa     )     ).view(
															    1						,		1						,		lowerCAmelCase_						,		lowerCAmelCase_     )
															__SCREAMING_SNAKE_CASE		     =       causal_mask

															# Insert a "dummy" tensor for masked_bias.
															__SCREAMING_SNAKE_CASE		     =       torch.tensor(-1E4						,		dtype=torch.floataa     )
															__SCREAMING_SNAKE_CASE		     =       masked_bias

															__SCREAMING_SNAKE_CASE		     =       fix_query_key_value_ordering(lowerCAmelCase_						,		lowerCAmelCase_						,		3						,		lowerCAmelCase_						,		lowerCAmelCase_     )
															# Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D.
															__SCREAMING_SNAKE_CASE		     =       out_val.transpose(0						,		1     ).contiguous()
															# Store.
															__SCREAMING_SNAKE_CASE		     =       out_val

										# Transpose the bias.
										elif (
										    op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
										) and weight_or_bias == "bias":
															__SCREAMING_SNAKE_CASE		     =       fix_query_key_value_ordering(lowerCAmelCase_						,		lowerCAmelCase_						,		3						,		lowerCAmelCase_						,		lowerCAmelCase_     )
															# Store. No change of shape.
															__SCREAMING_SNAKE_CASE		     =       out_val

										# Transpose the weights.
										elif weight_or_bias == "weight":
															__SCREAMING_SNAKE_CASE		     =       megatron_to_transformers[op_name]
															__SCREAMING_SNAKE_CASE		     =       val.transpose(0						,		1     )

										# Copy the bias.
										elif weight_or_bias == "bias":
															__SCREAMING_SNAKE_CASE		     =       megatron_to_transformers[op_name]
															__SCREAMING_SNAKE_CASE		     =       val

    # DEBUG.
					assert config.n_layer == layer_idx + 1

					# The final layernorm.
					__SCREAMING_SNAKE_CASE		     =       transformer["final_layernorm.weight"]
					__SCREAMING_SNAKE_CASE		     =       transformer["final_layernorm.bias"]

					# For LM head, transformers' wants the matrix to weight embeddings.
					__SCREAMING_SNAKE_CASE		     =       word_embeddings

					# It should be done!
					return output_state_dict




def      UpperCAmelCase__ ():




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       argparse.ArgumentParser()
					parser.add_argument("--print-checkpoint-structure"						,		action="store_true"     )
					parser.add_argument(
					    "path_to_checkpoint"						,		type=lowerCAmelCase_						,		help="Path to the checkpoint file (.zip archive or direct .pt file)"						,		)
					parser.add_argument(
					    "--config_file"						,		default=""						,		type=lowerCAmelCase_						,		help="An optional config json file describing the pre-trained model."						,		)
					__SCREAMING_SNAKE_CASE		     =       parser.parse_args()

					# Extract the basename.
					__SCREAMING_SNAKE_CASE		     =       os.path.dirname(args.path_to_checkpoint     )

					# Load the model.
					# the .zip is very optional, let's keep it for backward compatibility
					print(f"""Extracting PyTorch state dictionary from {args.path_to_checkpoint}"""     )
					if args.path_to_checkpoint.endswith(".zip"     ):
										with zipfile.ZipFile(args.path_to_checkpoint						,		"r"     ) as checkpoint:
															with checkpoint.open("release/mp_rank_00/model_optim_rng.pt"     ) as pytorch_dict:
																				__SCREAMING_SNAKE_CASE		     =       torch.load(lowerCAmelCase_						,		map_location="cpu"     )
					else:
										__SCREAMING_SNAKE_CASE		     =       torch.load(args.path_to_checkpoint						,		map_location="cpu"     )

					__SCREAMING_SNAKE_CASE		     =       input_state_dict.get("args"						,		lowerCAmelCase_     )

					# Read the config, or default to the model released by NVIDIA.
					if args.config_file == "":
										if ds_args is not None:
															if ds_args.bias_gelu_fusion:
																				__SCREAMING_SNAKE_CASE		     =       "gelu_fast"
															elif ds_args.openai_gelu:
																				__SCREAMING_SNAKE_CASE		     =       "gelu_new"
															else:
																				__SCREAMING_SNAKE_CASE		     =       "gelu"
										else:
															# in the very early days this used to be "gelu_new"
															__SCREAMING_SNAKE_CASE		     =       "gelu_new"

										# Spell out all parameters in case the defaults change.
										__SCREAMING_SNAKE_CASE		     =       GPTaConfig(
										    vocab_size=5_0257						,		n_positions=1024						,		n_embd=1024						,		n_layer=24						,		n_head=16						,		n_inner=4096						,		activation_function=lowerCAmelCase_						,		resid_pdrop=0.1						,		embd_pdrop=0.1						,		attn_pdrop=0.1						,		layer_norm_epsilon=1E-5						,		initializer_range=0.02						,		summary_type="cls_index"						,		summary_use_proj=lowerCAmelCase_						,		summary_activation=lowerCAmelCase_						,		summary_proj_to_labels=lowerCAmelCase_						,		summary_first_dropout=0.1						,		scale_attn_weights=lowerCAmelCase_						,		use_cache=lowerCAmelCase_						,		bos_token_id=5_0256						,		eos_token_id=5_0256						,		)
					else:
										__SCREAMING_SNAKE_CASE		     =       GPTaConfig.from_json_file(args.config_file     )

					__SCREAMING_SNAKE_CASE		     =       ["GPT2LMHeadModel"]

					# Convert.
					print("Converting"     )
					__SCREAMING_SNAKE_CASE		     =       convert_megatron_checkpoint(lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_     )

					# Print the structure of converted state dict.
					if args.print_checkpoint_structure:
										recursive_print(lowerCAmelCase_						,		lowerCAmelCase_     )

					# Add tokenizer class info to config
					# see https://github.com/huggingface/transformers/issues/13906)
					if ds_args is not None:
										__SCREAMING_SNAKE_CASE		     =       ds_args.tokenizer_type
										if tokenizer_type == "GPT2BPETokenizer":
															__SCREAMING_SNAKE_CASE		     =       "gpt2"
										elif tokenizer_type == "PretrainedFromHF":
															__SCREAMING_SNAKE_CASE		     =       ds_args.tokenizer_name_or_path
										else:
															raise ValueError(f"""Unrecognized tokenizer_type {tokenizer_type}"""     )
					else:
										__SCREAMING_SNAKE_CASE		     =       "gpt2"

					__SCREAMING_SNAKE_CASE		     =       AutoTokenizer.from_pretrained(lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE		     =       type(lowerCAmelCase_     ).__name__
					__SCREAMING_SNAKE_CASE		     =       tokenizer_class

					# Store the config to file.
					print("Saving config"     )
					config.save_pretrained(lowerCAmelCase_     )

					# Save tokenizer based on args
					print(f"""Adding {tokenizer_class} tokenizer files"""     )
					tokenizer.save_pretrained(lowerCAmelCase_     )

					# Store the state_dict to file.
					__SCREAMING_SNAKE_CASE		     =       os.path.join(lowerCAmelCase_						,		"pytorch_model.bin"     )
					print(f"""Saving checkpoint to \"{output_checkpoint_file}\""""     )
					torch.save(lowerCAmelCase_						,		lowerCAmelCase_     )


####################################################################################################

if __name__ == "__main__":
		main()

####################################################################################################




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