



"""simple docstring"""
import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


A:     Union[str, Any]										=	re.compile(R"\b(a|an|the)\b", re.UNICODE)

A:     int										=	None

def    _snake_case		(		):
 UpperCAmelCase			:      List[str]			=			argparse.ArgumentParser("""Official evaluation script for SQuAD version 2.0."""		)
 parser.add_argument("""data_file"""    ,	metavar="""data.json"""    ,	help="""Input data JSON file."""		)
 parser.add_argument("""pred_file"""    ,	metavar="""pred.json"""    ,	help="""Model predictions."""		)
 parser.add_argument(
     """--out-file"""    ,	"""-o"""    ,	metavar="""eval.json"""    ,	help="""Write accuracy metrics to file (default is stdout)."""		)
 parser.add_argument(
     """--na-prob-file"""    ,	"""-n"""    ,	metavar="""na_prob.json"""    ,	help="""Model estimates of probability of no answer."""		)
 parser.add_argument(
     """--na-prob-thresh"""    ,	"""-t"""    ,	type=UpperCamelCase    ,	default=1.0    ,	help="""Predict \"\" if no-answer probability exceeds this (default = 1.0)."""    ,	)
 parser.add_argument(
     """--out-image-dir"""    ,	"""-p"""    ,	metavar="""out_images"""    ,	default=UpperCamelCase    ,	help="""Save precision-recall curves to directory."""		)
 parser.add_argument("""--verbose"""    ,	"""-v"""    ,	action="""store_true"""		)
 if len(sys.argv		) == 1:
  parser.print_help()
  sys.exit(1		)
 return parser.parse_args()

def    _snake_case		(		UpperCamelCase		:	str		):
 UpperCAmelCase			:      Optional[int]			=			{}
 for article in dataset:
  for p in article["paragraphs"]:
   for qa in p["qas"]:
    UpperCAmelCase			:      List[str]			=			bool(qa["""answers"""]["""text"""]		)
 return qid_to_has_ans

def    _snake_case		(		UpperCamelCase		:	Optional[Any]		):

 def remove_articles(UpperCamelCase		:	List[str]		):
  return ARTICLES_REGEX.sub(""" """    ,	UpperCamelCase		)

 def white_space_fix(UpperCamelCase		:	Any		):
  return " ".join(text.split()		)

 def remove_punc(UpperCamelCase		:	Optional[int]		):
  UpperCAmelCase			:      int			=			set(string.punctuation		)
  return "".join(ch for ch in text if ch not in exclude		)

 def lower(UpperCamelCase		:	str		):
  return text.lower()

 return white_space_fix(remove_articles(remove_punc(lower(UpperCamelCase		)		)		)		)

def    _snake_case		(		UpperCamelCase		:	Tuple		):
 if not s:
  return []
 return normalize_answer(UpperCamelCase		).split()

def    _snake_case		(		UpperCamelCase		:	Optional[Any]    ,	UpperCamelCase		:	List[Any]		):
 return int(normalize_answer(UpperCamelCase		) == normalize_answer(UpperCamelCase		)		)

def    _snake_case		(		UpperCamelCase		:	List[str]    ,	UpperCamelCase		:	Optional[Any]		):
 UpperCAmelCase			:      int			=			get_tokens(UpperCamelCase		)
 UpperCAmelCase			:      int			=			get_tokens(UpperCamelCase		)
 UpperCAmelCase			:      Tuple			=			collections.Counter(UpperCamelCase		) & collections.Counter(UpperCamelCase		)
 UpperCAmelCase			:      List[str]			=			sum(common.values()		)
 if len(UpperCamelCase		) == 0 or len(UpperCamelCase		) == 0:
  # If either is no-answer, then F1 is 1 if they agree, 0 otherwise
  return int(gold_toks == pred_toks		)
 if num_same == 0:
  return 0
 UpperCAmelCase			:      Any			=			1.0 * num_same / len(UpperCamelCase		)
 UpperCAmelCase			:      List[str]			=			1.0 * num_same / len(UpperCamelCase		)
 UpperCAmelCase			:      Optional[int]			=			(2 * precision * recall) / (precision + recall)
 return fa

def    _snake_case		(		UpperCamelCase		:	List[Any]    ,	UpperCamelCase		:	List[str]		):
 UpperCAmelCase			:      str			=			{}
 UpperCAmelCase			:      str			=			{}
 for article in dataset:
  for p in article["paragraphs"]:
   for qa in p["qas"]:
    UpperCAmelCase			:      str			=			qa["""id"""]
    UpperCAmelCase			:      List[Any]			=			[t for t in qa["""answers"""]["""text"""] if normalize_answer(UpperCamelCase		)]
    if not gold_answers:
     # For unanswerable questions, only correct answer is empty string
     UpperCAmelCase			:      Any			=			[""""""]
    if qid not in preds:
     print(F"Missing prediction for {qid}"		)
     continue
    UpperCAmelCase			:      Optional[int]			=			preds[qid]
    # Take max over all gold answers
    UpperCAmelCase			:      int			=			max(compute_exact(UpperCamelCase    ,	UpperCamelCase		) for a in gold_answers		)
    UpperCAmelCase			:      Optional[int]			=			max(compute_fa(UpperCamelCase    ,	UpperCamelCase		) for a in gold_answers		)
 return exact_scores, fa_scores

def    _snake_case		(		UpperCamelCase		:	Optional[Any]    ,	UpperCamelCase		:	str    ,	UpperCamelCase		:	List[Any]    ,	UpperCamelCase		:	int		):
 UpperCAmelCase			:      str			=			{}
 for qid, s in scores.items():
  UpperCAmelCase			:      str			=			na_probs[qid] > na_prob_thresh
  if pred_na:
   UpperCAmelCase			:      List[str]			=			float(not qid_to_has_ans[qid]		)
  else:
   UpperCAmelCase			:      Optional[int]			=			s
 return new_scores

def    _snake_case		(		UpperCamelCase		:	Optional[Any]    ,	UpperCamelCase		:	str    ,	UpperCamelCase		:	Optional[int]=None		):
 if not qid_list:
  UpperCAmelCase			:      Optional[Any]			=			len(UpperCamelCase		)
  return collections.OrderedDict(
      [
          ("""exact""", 100.0 * sum(exact_scores.values()		) / total),
          ("""f1""", 100.0 * sum(fa_scores.values()		) / total),
          ("""total""", total),
      ]		)
 else:
  UpperCAmelCase			:      Tuple			=			len(UpperCamelCase		)
  return collections.OrderedDict(
      [
          ("""exact""", 100.0 * sum(exact_scores[k] for k in qid_list		) / total),
          ("""f1""", 100.0 * sum(fa_scores[k] for k in qid_list		) / total),
          ("""total""", total),
      ]		)

def    _snake_case		(		UpperCamelCase		:	Tuple    ,	UpperCamelCase		:	Any    ,	UpperCamelCase		:	Dict		):
 for k in new_eval:
  UpperCAmelCase			:      List[Any]			=			new_eval[k]

def    _snake_case		(		UpperCamelCase		:	List[str]    ,	UpperCamelCase		:	Union[str, Any]    ,	UpperCamelCase		:	str    ,	UpperCamelCase		:	Any		):
 plt.step(UpperCamelCase    ,	UpperCamelCase    ,	color="""b"""    ,	alpha=0.2    ,	where="""post"""		)
 plt.fill_between(UpperCamelCase    ,	UpperCamelCase    ,	step="""post"""    ,	alpha=0.2    ,	color="""b"""		)
 plt.xlabel("""Recall"""		)
 plt.ylabel("""Precision"""		)
 plt.xlim([0.0, 1.05]		)
 plt.ylim([0.0, 1.05]		)
 plt.title(UpperCamelCase		)
 plt.savefig(UpperCamelCase		)
 plt.clf()

def    _snake_case		(		UpperCamelCase		:	Union[str, Any]    ,	UpperCamelCase		:	List[Any]    ,	UpperCamelCase		:	str    ,	UpperCamelCase		:	List[Any]    ,	UpperCamelCase		:	Dict=None    ,	UpperCamelCase		:	Tuple=None		):
 UpperCAmelCase			:      List[Any]			=			sorted(UpperCamelCase    ,	key=lambda UpperCamelCase		: na_probs[k]		)
 UpperCAmelCase			:      Dict			=			0.0
 UpperCAmelCase			:      Tuple			=			1.0
 UpperCAmelCase			:      Tuple			=			0.0
 UpperCAmelCase			:      Tuple			=			[1.0]
 UpperCAmelCase			:      Union[str, Any]			=			[0.0]
 UpperCAmelCase			:      List[Any]			=			0.0
 for i, qid in enumerate(UpperCamelCase		):
  if qid_to_has_ans[qid]:
   true_pos += scores[qid]
  UpperCAmelCase			:      Tuple			=			true_pos / float(i + 1		)
  UpperCAmelCase			:      Union[str, Any]			=			true_pos / float(UpperCamelCase		)
  if i == len(UpperCamelCase		) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
   # i.e., if we can put a threshold after this point
   avg_prec += cur_p * (cur_r - recalls[-1])
   precisions.append(UpperCamelCase		)
   recalls.append(UpperCamelCase		)
 if out_image:
  plot_pr_curve(UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase		)
 return {"ap": 100.0 * avg_prec}

def    _snake_case		(		UpperCamelCase		:	str    ,	UpperCamelCase		:	Union[str, Any]    ,	UpperCamelCase		:	List[Any]    ,	UpperCamelCase		:	Any    ,	UpperCamelCase		:	List[str]    ,	UpperCamelCase		:	Optional[int]		):
 if out_image_dir and not os.path.exists(UpperCamelCase		):
  os.makedirs(UpperCamelCase		)
 UpperCAmelCase			:      str			=			sum(1 for v in qid_to_has_ans.values() if v		)
 if num_true_pos == 0:
  return
 UpperCAmelCase			:      Tuple			=			make_precision_recall_eval(
     UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	out_image=os.path.join(UpperCamelCase    ,	"""pr_exact.png"""		)    ,	title="""Precision-Recall curve for Exact Match score"""    ,	)
 UpperCAmelCase			:      Union[str, Any]			=			make_precision_recall_eval(
     UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	out_image=os.path.join(UpperCamelCase    ,	"""pr_f1.png"""		)    ,	title="""Precision-Recall curve for F1 score"""    ,	)
 UpperCAmelCase			:      Union[str, Any]			=			{k: float(UpperCamelCase		) for k, v in qid_to_has_ans.items()}
 UpperCAmelCase			:      int			=			make_precision_recall_eval(
     UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	out_image=os.path.join(UpperCamelCase    ,	"""pr_oracle.png"""		)    ,	title="""Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"""    ,	)
 merge_eval(UpperCamelCase    ,	UpperCamelCase    ,	"""pr_exact"""		)
 merge_eval(UpperCamelCase    ,	UpperCamelCase    ,	"""pr_f1"""		)
 merge_eval(UpperCamelCase    ,	UpperCamelCase    ,	"""pr_oracle"""		)

def    _snake_case		(		UpperCamelCase		:	int    ,	UpperCamelCase		:	Tuple    ,	UpperCamelCase		:	Union[str, Any]    ,	UpperCamelCase		:	Optional[Any]		):
 if not qid_list:
  return
 UpperCAmelCase			:      Optional[Any]			=			[na_probs[k] for k in qid_list]
 UpperCAmelCase			:      Optional[Any]			=			np.ones_like(UpperCamelCase		) / float(len(UpperCamelCase		)		)
 plt.hist(UpperCamelCase    ,	weights=UpperCamelCase    ,	bins=20    ,	range=(0.0, 1.0)		)
 plt.xlabel("""Model probability of no-answer"""		)
 plt.ylabel("""Proportion of dataset"""		)
 plt.title(F"Histogram of no-answer probability: {name}"		)
 plt.savefig(os.path.join(UpperCamelCase    ,	F"na_prob_hist_{name}.png"		)		)
 plt.clf()

def    _snake_case		(		UpperCamelCase		:	List[str]    ,	UpperCamelCase		:	Optional[Any]    ,	UpperCamelCase		:	Optional[Any]    ,	UpperCamelCase		:	int		):
 UpperCAmelCase			:      List[str]			=			sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]		)
 UpperCAmelCase			:      Optional[Any]			=			num_no_ans
 UpperCAmelCase			:      Any			=			cur_score
 UpperCAmelCase			:      List[str]			=			0.0
 UpperCAmelCase			:      Any			=			sorted(UpperCamelCase    ,	key=lambda UpperCamelCase		: na_probs[k]		)
 for i, qid in enumerate(UpperCamelCase		):
  if qid not in scores:
   continue
  if qid_to_has_ans[qid]:
   UpperCAmelCase			:      List[str]			=			scores[qid]
  else:
   if preds[qid]:
    UpperCAmelCase			:      List[Any]			=			-1
   else:
    UpperCAmelCase			:      str			=			0
  cur_score += diff
  if cur_score > best_score:
   UpperCAmelCase			:      Union[str, Any]			=			cur_score
   UpperCAmelCase			:      Dict			=			na_probs[qid]
 return 100.0 * best_score / len(UpperCamelCase		), best_thresh

def    _snake_case		(		UpperCamelCase		:	Dict    ,	UpperCamelCase		:	int    ,	UpperCamelCase		:	Union[str, Any]    ,	UpperCamelCase		:	Tuple    ,	UpperCamelCase		:	Optional[int]    ,	UpperCamelCase		:	Union[str, Any]		):
 UpperCAmelCase			,	UpperCAmelCase			:      Tuple			=			find_best_thresh(UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase		)
 UpperCAmelCase			,	UpperCAmelCase			:      Optional[Any]			=			find_best_thresh(UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase		)
 UpperCAmelCase			:      Optional[int]			=			best_exact
 UpperCAmelCase			:      int			=			exact_thresh
 UpperCAmelCase			:      Tuple			=			best_fa
 UpperCAmelCase			:      str			=			fa_thresh

def    _snake_case		(		):
 with open(OPTS.data_file		) as f:
  UpperCAmelCase			:      Union[str, Any]			=			json.load(UpperCamelCase		)
  UpperCAmelCase			:      List[Any]			=			dataset_json["""data"""]
 with open(OPTS.pred_file		) as f:
  UpperCAmelCase			:      str			=			json.load(UpperCamelCase		)
 if OPTS.na_prob_file:
  with open(OPTS.na_prob_file		) as f:
   UpperCAmelCase			:      Dict			=			json.load(UpperCamelCase		)
 else:
  UpperCAmelCase			:      Optional[int]			=			{k: 0.0 for k in preds}
 UpperCAmelCase			:      List[str]			=			make_qid_to_has_ans(UpperCamelCase		)  # maps qid to True/False
 UpperCAmelCase			:      Optional[int]			=			[k for k, v in qid_to_has_ans.items() if v]
 UpperCAmelCase			:      List[str]			=			[k for k, v in qid_to_has_ans.items() if not v]
 UpperCAmelCase			,	UpperCAmelCase			:      Union[str, Any]			=			get_raw_scores(UpperCamelCase    ,	UpperCamelCase		)
 UpperCAmelCase			:      Optional[Any]			=			apply_no_ans_threshold(UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	OPTS.na_prob_thresh		)
 UpperCAmelCase			:      List[str]			=			apply_no_ans_threshold(UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	OPTS.na_prob_thresh		)
 UpperCAmelCase			:      Optional[Any]			=			make_eval_dict(UpperCamelCase    ,	UpperCamelCase		)
 if has_ans_qids:
  UpperCAmelCase			:      List[Any]			=			make_eval_dict(UpperCamelCase    ,	UpperCamelCase    ,	qid_list=UpperCamelCase		)
  merge_eval(UpperCamelCase    ,	UpperCamelCase    ,	"""HasAns"""		)
 if no_ans_qids:
  UpperCAmelCase			:      Dict			=			make_eval_dict(UpperCamelCase    ,	UpperCamelCase    ,	qid_list=UpperCamelCase		)
  merge_eval(UpperCamelCase    ,	UpperCamelCase    ,	"""NoAns"""		)
 if OPTS.na_prob_file:
  find_all_best_thresh(UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase		)
 if OPTS.na_prob_file and OPTS.out_image_dir:
  run_precision_recall_analysis(UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	UpperCamelCase    ,	OPTS.out_image_dir		)
  histogram_na_prob(UpperCamelCase    ,	UpperCamelCase    ,	OPTS.out_image_dir    ,	"""hasAns"""		)
  histogram_na_prob(UpperCamelCase    ,	UpperCamelCase    ,	OPTS.out_image_dir    ,	"""noAns"""		)
 if OPTS.out_file:
  with open(OPTS.out_file    ,	"""w"""		) as f:
   json.dump(UpperCamelCase    ,	UpperCamelCase		)
 else:
  print(json.dumps(UpperCamelCase    ,	indent=2		)		)


if __name__ == "__main__":
      A:     List[str]										=	parse_args()
      if OPTS.out_image_dir:
            import matplotlib

            matplotlib.use("Agg")
            import matplotlib.pyplot as plt
      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    _snake_case		(		UpperCamelCase		:	List[Any]    ,	UpperCamelCase		:	List[Any]    ,	UpperCamelCase		:	Any    ,	UpperCamelCase		:	Any=None    ,	UpperCamelCase		:	Union[str, Any]=None    ,	UpperCamelCase		:	Tuple=None    ,	UpperCamelCase		:	Optional[int]=None    ,	UpperCamelCase		:	int=None    ,	):
 if attention_mask is None:
  UpperCAmelCase			:      Optional[int]			=			input_ids.ne(config.pad_token_id		)
 if decoder_attention_mask is None:
  UpperCAmelCase			:      int			=			decoder_input_ids.ne(config.pad_token_id		)
 if head_mask is None:
  UpperCAmelCase			:      Union[str, Any]			=			torch.ones(config.encoder_layers    ,	config.encoder_attention_heads    ,	device=UpperCamelCase		)
 if decoder_head_mask is None:
  UpperCAmelCase			:      List[str]			=			torch.ones(config.decoder_layers    ,	config.decoder_attention_heads    ,	device=UpperCamelCase		)
 if cross_attn_head_mask is None:
  UpperCAmelCase			:      Any			=			torch.ones(config.decoder_layers    ,	config.decoder_attention_heads    ,	device=UpperCamelCase		)
 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    SCREAMING_SNAKE_CASE__						:

   def __init__(     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE=13   ,  _SCREAMING_SNAKE_CASE=7   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE=False   ,  _SCREAMING_SNAKE_CASE=99   ,  _SCREAMING_SNAKE_CASE=16   ,  _SCREAMING_SNAKE_CASE=2   ,  _SCREAMING_SNAKE_CASE=4   ,  _SCREAMING_SNAKE_CASE=4   ,  _SCREAMING_SNAKE_CASE="relu"   ,  _SCREAMING_SNAKE_CASE=0.1   ,  _SCREAMING_SNAKE_CASE=0.1   ,  _SCREAMING_SNAKE_CASE=0.0   ,  _SCREAMING_SNAKE_CASE=0.0   ,  _SCREAMING_SNAKE_CASE=20   ,  _SCREAMING_SNAKE_CASE=2   ,  _SCREAMING_SNAKE_CASE=1   ,  _SCREAMING_SNAKE_CASE=0   ,  )						->   Optional[int]:





    '''simple docstring'''




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

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   List[str]:





    '''simple docstring'''




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

    UpperCAmelCase			:      Optional[Any]			=			self.get_config()
    UpperCAmelCase			:      int			=			prepare_mam_aaa_inputs_dict(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)
    return config, inputs_dict

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''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		)						->   List[str]:





    '''simple docstring'''




    UpperCAmelCase			,	UpperCAmelCase			:      Dict			=			self.prepare_config_and_inputs()
    return config, inputs_dict

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			MaMaaaModel(config=_SCREAMING_SNAKE_CASE		).get_decoder().to(_SCREAMING_SNAKE_CASE		).eval()
    UpperCAmelCase			:      str			=			inputs_dict["""input_ids"""]
    UpperCAmelCase			:      Tuple			=			inputs_dict["""attention_mask"""]
    UpperCAmelCase			:      Dict			=			inputs_dict["""head_mask"""]

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

    UpperCAmelCase			,	UpperCAmelCase			:      Dict			=			outputs.to_tuple()

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

    # append to next input_ids and
    UpperCAmelCase			:      Union[str, Any]			=			torch.cat([input_ids, next_tokens]   ,  dim=-1		)
    UpperCAmelCase			:      Tuple			=			torch.cat([attention_mask, next_attn_mask]   ,  dim=-1		)

    UpperCAmelCase			:      Optional[int]			=			model(_SCREAMING_SNAKE_CASE   ,  attention_mask=_SCREAMING_SNAKE_CASE		)["""last_hidden_state"""]
    UpperCAmelCase			:      Tuple			=			model(_SCREAMING_SNAKE_CASE   ,  attention_mask=_SCREAMING_SNAKE_CASE   ,  past_key_values=_SCREAMING_SNAKE_CASE		)[
        """last_hidden_state"""
    ]

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

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

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




   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      str			=			MaMaaaModel(config=_SCREAMING_SNAKE_CASE		).to(_SCREAMING_SNAKE_CASE		).eval()
    UpperCAmelCase			:      Any			=			model(**_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Dict			=			outputs.encoder_last_hidden_state
    UpperCAmelCase			:      List[str]			=			outputs.last_hidden_state

    with tempfile.TemporaryDirectory() as tmpdirname:
     UpperCAmelCase			:      Tuple			=			model.get_encoder()
     encoder.save_pretrained(_SCREAMING_SNAKE_CASE		)
     UpperCAmelCase			:      List[str]			=			MaMaaaEncoder.from_pretrained(_SCREAMING_SNAKE_CASE		).to(_SCREAMING_SNAKE_CASE		)

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

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

    with tempfile.TemporaryDirectory() as tmpdirname:
     UpperCAmelCase			:      Optional[int]			=			model.get_decoder()
     decoder.save_pretrained(_SCREAMING_SNAKE_CASE		)
     UpperCAmelCase			:      Tuple			=			MaMaaaDecoder.from_pretrained(_SCREAMING_SNAKE_CASE		).to(_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      List[str]			=			decoder(
        input_ids=inputs_dict["""decoder_input_ids"""]   ,  attention_mask=inputs_dict["""decoder_attention_mask"""]   ,  encoder_hidden_states=_SCREAMING_SNAKE_CASE   ,  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    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__   ,    UpperCAmelCase__   ,    UpperCAmelCase__   ,    unittest.TestCase				):
   __lowerCAmelCase						:     Optional[int]		=		(
       (
           MaMaaaModel,
           MaMaaaForConditionalGeneration,
       )
       if is_torch_available()
       else ()
   )
   __lowerCAmelCase						:     Tuple		=		(MaMaaaForConditionalGeneration,) if is_torch_available() else ()
   __lowerCAmelCase						:     str		=		(
       {
           'conversational': MaMaaaForConditionalGeneration,
           'feature-extraction': MaMaaaModel,
           'summarization': MaMaaaForConditionalGeneration,
           'text2text-generation': MaMaaaForConditionalGeneration,
           'translation': MaMaaaForConditionalGeneration,
       }
       if is_torch_available()
       else {}
   )
   __lowerCAmelCase						:     str		=		True
   __lowerCAmelCase						:     Tuple		=		True
   __lowerCAmelCase						:     Tuple		=		False
   __lowerCAmelCase						:     int		=		False

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   List[Any]:





    '''simple docstring'''




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

    return False

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





    '''simple docstring'''




    UpperCAmelCase			:      Optional[int]			=			MaMaaaModelTester(self		)
    UpperCAmelCase			:      List[str]			=			ConfigTester(self   ,  config_class=_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    self.config_tester.run_common_tests()

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   List[str]:





    '''simple docstring'''




    UpperCAmelCase			,	UpperCAmelCase			:      Union[str, Any]			=			self.model_tester.prepare_config_and_inputs()
    for model_class in self.all_model_classes:
     UpperCAmelCase			:      Dict			=			model_class(_SCREAMING_SNAKE_CASE		)

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

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      str			=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_decoder_model_past_large_inputs(*_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   str:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[Any]			=			self.model_tester.prepare_config_and_inputs_for_common()
    self.model_tester.check_encoder_decoder_model_standalone(*_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			,	UpperCAmelCase			:      Dict			=			self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
     UpperCAmelCase			:      List[Any]			=			model_class(_SCREAMING_SNAKE_CASE		)
     model.to(_SCREAMING_SNAKE_CASE		)
     model.eval()

     UpperCAmelCase			:      str			=			copy.deepcopy(self._prepare_for_class(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)		)

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

     UpperCAmelCase			:      Dict			=			model.get_input_embeddings()
     if not self.is_encoder_decoder:
      UpperCAmelCase			:      Union[str, Any]			=			wte(_SCREAMING_SNAKE_CASE		)
     else:
      UpperCAmelCase			:      List[str]			=			wte(_SCREAMING_SNAKE_CASE		)
      UpperCAmelCase			:      Optional[Any]			=			wte(_SCREAMING_SNAKE_CASE		)

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




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




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

def    _snake_case		(		UpperCamelCase		:	Any		):
 return torch.tensor(UpperCamelCase    ,	dtype=torch.long    ,	device=UpperCamelCase		)


A:     int										=	1E-4



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

   @cached_property
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[int]:





    '''simple docstring'''




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

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




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

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





    '''simple docstring'''




    UpperCAmelCase			:      List[str]			=			MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""		).to(_SCREAMING_SNAKE_CASE		)

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




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			:      Union[str, Any]			=			MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M"""		).to(_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      Optional[int]			=			MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M"""   ,  src_lang="""fr"""   ,  tgt_lang="""en"""		)

    UpperCAmelCase			:      List[Any]			=			[
        """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
    UpperCAmelCase			:      Any			=			tokenizer(_SCREAMING_SNAKE_CASE   ,  padding=_SCREAMING_SNAKE_CASE   ,  return_tensors="""pt"""		)

    UpperCAmelCase			:      str			=			model.generate(
        input_ids=dct["""input_ids"""].to(_SCREAMING_SNAKE_CASE		)   ,  attention_mask=dct["""attention_mask"""].to(_SCREAMING_SNAKE_CASE		)   ,  num_beams=5   ,  forced_bos_token_id=tokenizer.get_lang_id("""en"""		)   ,  )

    UpperCAmelCase			:      Tuple			=			[
        """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.""",
    ]

    UpperCAmelCase			:      str			=			tokenizer.batch_decode(
        hypotheses_batch.tolist()   ,  clean_up_tokenization_spaces=_SCREAMING_SNAKE_CASE   ,  skip_special_tokens=_SCREAMING_SNAKE_CASE		)
    assert generated == expected_en
