




import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


_UpperCAmelCase		:  List[Any]	=   "\\n@INPROCEEDINGS{Papineni02bleu:a,\n    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n    booktitle = {},\n    year = {2002},\n    pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n    author = \"Lin, Chin-Yew  and\n      Och, Franz Josef\",\n    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n    month = \"aug 23{--}aug 27\",\n    year = \"2004\",\n    address = \"Geneva, Switzerland\",\n    publisher = \"COLING\",\n    url = \"https://www.aclweb.org/anthology/C04-1072\",\n    pages = \"501--507\",\n}\n"

_UpperCAmelCase		:  List[Any]	=   "\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n"

_UpperCAmelCase		:  Optional[int]	=   "\nComputes BLEU score of translated segments against one or more references.\nArgs:\n    predictions: list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    max_order: Maximum n-gram order to use when computing BLEU score.\n    smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n    'bleu': bleu score,\n    'precisions': geometric mean of n-gram precisions,\n    'brevity_penalty': brevity penalty,\n    'length_ratio': ratio of lengths,\n    'translation_length': translation_length,\n    'reference_length': reference_length\nExamples:\n\n    >>> predictions = [\n    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample\n    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample\n    ... ]\n    >>> references = [\n    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)\n    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)\n    ... ]\n    >>> bleu = datasets.load_metric(\"bleu\")\n    >>> results = bleu.compute(predictions=predictions, references=references)\n    >>> print(results[\"bleu\"])\n    1.0\n"




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					,       _KWARGS_DESCRIPTION)
class       __lowerCAmelCase				(							datasets.Metric):






       def     SCREAMING_SNAKE_CASE			(      self:    List[str] ):
         return datasets.MetricInfo(
             description=_DESCRIPTION				,    citation=_CITATION				,    inputs_description=_KWARGS_DESCRIPTION				,    features=datasets.Features(
                 {
                     "predictions": datasets.Sequence(datasets.Value("string"				,    id="token" )				,    id="sequence" ),
                     "references": datasets.Sequence(
                         datasets.Sequence(datasets.Value("string"				,    id="token" )				,    id="sequence" )				,    id="references" ),
                 } )				,    codebase_urls=["https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py"]				,    reference_urls=[
                 "https://en.wikipedia.org/wiki/BLEU",
                 "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213",
             ]				,    )






       def     SCREAMING_SNAKE_CASE			(      self:    Tuple				,    _lowerCAmelCase:    Any				,    _lowerCAmelCase:    List[Any]				,    _lowerCAmelCase:    Any=4				,    _lowerCAmelCase:    Tuple=False ):
         lowercase			:str							=  compute_bleu(
             reference_corpus=_lowerCAmelCase				,    translation_corpus=_lowerCAmelCase				,    max_order=_lowerCAmelCase				,    smooth=_lowerCAmelCase )
         ((lowercase)		,			(lowercase)		,			(lowercase)		,			(lowercase)		,			(lowercase)		,			(lowercase))			:Dict							=  score
         return {
             "bleu": bleu,
             "precisions": precisions,
             "brevity_penalty": bp,
             "length_ratio": ratio,
             "translation_length": translation_length,
             "reference_length": reference_length,
         }









import unittest

from transformers import GPTNeoXJapaneseConfig, is_torch_available
from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel




class       __lowerCAmelCase				:






       def __init__(      self:    List[str]				,    _lowerCAmelCase:    Dict				,    _lowerCAmelCase:    List[str]=13				,    _lowerCAmelCase:    Dict=7				,    _lowerCAmelCase:    Tuple=True				,    _lowerCAmelCase:    Dict=True				,    _lowerCAmelCase:    Optional[Any]=True				,    _lowerCAmelCase:    Union[str, Any]=True				,    _lowerCAmelCase:    str=99				,    _lowerCAmelCase:    Dict=32				,    _lowerCAmelCase:    Dict=5				,    _lowerCAmelCase:    int=4				,    _lowerCAmelCase:    Optional[Any]=4				,    _lowerCAmelCase:    Any="gelu"				,    _lowerCAmelCase:    Any=0.0				,    _lowerCAmelCase:    List[Any]=0.1				,    _lowerCAmelCase:    Optional[int]=True				,    _lowerCAmelCase:    Any=5_12				,    _lowerCAmelCase:    Optional[Any]=16				,    _lowerCAmelCase:    str=2				,    _lowerCAmelCase:    Tuple=0.02				,    _lowerCAmelCase:    str=3				,    _lowerCAmelCase:    List[str]=4				,    _lowerCAmelCase:    Optional[Any]=None				,    ):
         lowercase			:List[str]							=  parent
         lowercase			:List[str]							=  batch_size
         lowercase			:List[str]							=  seq_length
         lowercase			:Dict							=  is_training
         lowercase			:Union[str, Any]							=  use_input_mask
         lowercase			:Optional[int]							=  use_token_type_ids
         lowercase			:Dict							=  use_labels
         lowercase			:Any							=  vocab_size
         lowercase			:List[Any]							=  hidden_size
         lowercase			:Optional[int]							=  num_hidden_layers
         lowercase			:Union[str, Any]							=  num_attention_heads
         lowercase			:Any							=  intermediate_multiple_size
         lowercase			:str							=  hidden_act
         lowercase			:List[Any]							=  hidden_dropout
         lowercase			:Optional[Any]							=  attention_dropout
         lowercase			:int							=  weight_tying
         lowercase			:Tuple							=  max_position_embeddings
         lowercase			:str							=  type_vocab_size
         lowercase			:Union[str, Any]							=  type_sequence_label_size
         lowercase			:Dict							=  initializer_range
         lowercase			:Dict							=  num_labels
         lowercase			:Dict							=  num_choices
         lowercase			:Any							=  scope






       def     SCREAMING_SNAKE_CASE			(      self:    str ):
         lowercase			:List[Any]							=  ids_tensor([self.batch_size, self.seq_length]				,    self.vocab_size )

         lowercase			:Optional[Any]							=  None
         if self.use_input_mask:
           lowercase			:str							=  random_attention_mask([self.batch_size, self.seq_length] )

         lowercase			:int							=  None
         if self.use_labels:
           lowercase			:Dict							=  ids_tensor([self.batch_size, self.seq_length]				,    self.num_labels )

         lowercase			:Tuple							=  self.get_config()

         return config, input_ids, input_mask, token_labels






       def     SCREAMING_SNAKE_CASE			(      self:    str ):
         return GPTNeoXJapaneseConfig(
             vocab_size=self.vocab_size				,    hidden_size=self.hidden_size				,    num_hidden_layers=self.num_hidden_layers				,    num_attention_heads=self.num_attention_heads				,    intermediate_multiple_size=self.intermediate_multiple_size				,    hidden_act=self.hidden_act				,    hidden_dropout=self.hidden_dropout				,    attention_dropout=self.attention_dropout				,    weight_tying=self.weight_tying				,    max_position_embeddings=self.max_position_embeddings				,    type_vocab_size=self.type_vocab_size				,    is_decoder=_lowerCAmelCase				,    initializer_range=self.initializer_range				,    )






       def     SCREAMING_SNAKE_CASE			(      self:    Optional[int] ):
         lowercase		,			lowercase		,			lowercase		,			lowercase			:Any							=  self.prepare_config_and_inputs()

         lowercase			:Tuple							=  True

         return config, input_ids, input_mask, token_labels






       def     SCREAMING_SNAKE_CASE			(      self:    List[Any]				,    _lowerCAmelCase:    Optional[Any]				,    _lowerCAmelCase:    Dict				,    _lowerCAmelCase:    List[str] ):
         lowercase			:List[str]							=  GPTNeoXJapaneseModel(config=_lowerCAmelCase )
         model.to(_lowerCAmelCase )
         model.eval()
         lowercase			:Optional[int]							=  model(_lowerCAmelCase				,    attention_mask=_lowerCAmelCase )
         lowercase			:Dict							=  model(_lowerCAmelCase )
         self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, self.seq_length, self.hidden_size) )






       def     SCREAMING_SNAKE_CASE			(      self:    Optional[int]				,    _lowerCAmelCase:    Dict				,    _lowerCAmelCase:    List[Any]				,    _lowerCAmelCase:    int ):
         lowercase			:Dict							=  True
         lowercase			:Optional[Any]							=  GPTNeoXJapaneseModel(_lowerCAmelCase )
         model.to(_lowerCAmelCase )
         model.eval()
         lowercase			:List[str]							=  model(_lowerCAmelCase				,    attention_mask=_lowerCAmelCase )
         self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, self.seq_length, self.hidden_size) )






       def     SCREAMING_SNAKE_CASE			(      self:    int				,    _lowerCAmelCase:    str				,    _lowerCAmelCase:    Dict				,    _lowerCAmelCase:    int				,    _lowerCAmelCase:    List[Any] ):
         lowercase			:str							=  GPTNeoXJapaneseForCausalLM(config=_lowerCAmelCase )
         model.to(_lowerCAmelCase )
         model.eval()
         lowercase			:Tuple							=  model(_lowerCAmelCase				,    attention_mask=_lowerCAmelCase				,    labels=_lowerCAmelCase )
         self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.seq_length, self.vocab_size) )






       def     SCREAMING_SNAKE_CASE			(      self:    Dict				,    _lowerCAmelCase:    List[Any]				,    _lowerCAmelCase:    int				,    _lowerCAmelCase:    Any ):
         lowercase			:Optional[Any]							=  True
         lowercase			:List[str]							=  GPTNeoXJapaneseForCausalLM(config=_lowerCAmelCase )
         model.to(_lowerCAmelCase )
         model.eval()

         # first forward pass
         lowercase			:str							=  model(_lowerCAmelCase				,    attention_mask=_lowerCAmelCase				,    use_cache=_lowerCAmelCase )
         lowercase			:Tuple							=  outputs.past_key_values

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

         # append to next input_ids and
         lowercase			:Tuple							=  torch.cat([input_ids, next_tokens]				,    dim=-1 )
         lowercase			:List[Any]							=  torch.cat([input_mask, next_mask]				,    dim=-1 )

         lowercase			:Dict							=  model(_lowerCAmelCase				,    attention_mask=_lowerCAmelCase				,    output_hidden_states=_lowerCAmelCase )
         lowercase			:List[str]							=  output_from_no_past["hidden_states"][0]
         lowercase			:str							=  model(
             _lowerCAmelCase				,    attention_mask=_lowerCAmelCase				,    past_key_values=_lowerCAmelCase				,    output_hidden_states=_lowerCAmelCase				,    )["hidden_states"][0]

         # select random slice
         lowercase			:Dict							=  ids_tensor((1,)				,    output_from_past.shape[-1] ).item()
         lowercase			:str							=  output_from_no_past[:, -3:, random_slice_idx].detach()
         lowercase			:List[str]							=  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(_lowerCAmelCase				,    _lowerCAmelCase				,    atol=1e-3 ) )






       def     SCREAMING_SNAKE_CASE			(      self:    Dict ):
         lowercase			:str							=  self.prepare_config_and_inputs()
         lowercase		,			lowercase		,			lowercase		,			lowercase			:Tuple							=  config_and_inputs
         lowercase			:Union[str, Any]							=  {"input_ids": input_ids, "attention_mask": input_mask}
         return config, inputs_dict







@require_torch
class       __lowerCAmelCase				(							lowerCAmelCase					,       lowerCAmelCase					,       unittest.TestCase):
       _a           =  (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
       _a           =  (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
       _a           =  (
           {'''feature-extraction''': GPTNeoXJapaneseModel, '''text-generation''': GPTNeoXJapaneseForCausalLM}
           if is_torch_available()
           else {}
       )
       _a           =  False
       _a           =  False
       _a           =  False
       _a           =  False






       def     SCREAMING_SNAKE_CASE			(      self:    List[str] ):
         lowercase			:Any							=  GPTNeoXJapaneseModelTester(self )
         lowercase			:List[str]							=  ConfigTester(self				,    config_class=_lowerCAmelCase				,    hidden_size=37 )






       def     SCREAMING_SNAKE_CASE			(      self:    Tuple ):
         self.config_tester.run_common_tests()






       def     SCREAMING_SNAKE_CASE			(      self:    Dict ):
         lowercase		,			lowercase		,			lowercase		,			lowercase			:Tuple							=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(_lowerCAmelCase				,    _lowerCAmelCase				,    _lowerCAmelCase )






       def     SCREAMING_SNAKE_CASE			(      self:    Tuple ):
         lowercase		,			lowercase		,			lowercase		,			lowercase			:Optional[Any]							=  self.model_tester.prepare_config_and_inputs_for_decoder()
         self.model_tester.create_and_check_model_as_decoder(_lowerCAmelCase				,    _lowerCAmelCase				,    _lowerCAmelCase )






       def     SCREAMING_SNAKE_CASE			(      self:    Optional[int] ):
         # This regression test was failing with PyTorch < 1.3
         lowercase		,			lowercase		,			lowercase		,			lowercase			:Tuple							=  self.model_tester.prepare_config_and_inputs_for_decoder()

         lowercase			:Union[str, Any]							=  None

         self.model_tester.create_and_check_model_as_decoder(_lowerCAmelCase				,    _lowerCAmelCase				,    _lowerCAmelCase )






       def     SCREAMING_SNAKE_CASE			(      self:    Union[str, Any] ):
         lowercase		,			lowercase		,			lowercase		,			lowercase			:List[str]							=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_decoder_model_past_large_inputs(_lowerCAmelCase				,    _lowerCAmelCase				,    _lowerCAmelCase )






       def     SCREAMING_SNAKE_CASE			(      self:    str ):
         lowercase			:Optional[int]							=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_causal_lm(*_lowerCAmelCase )






       @slow
       def     SCREAMING_SNAKE_CASE			(      self:    str ):
         lowercase			:int							=  "abeja/gpt-neox-japanese-2.7b"

         lowercase			:Optional[int]							=  ["データサイエンティストとは、", "100年後に必要とされる会社は、", "フルリモートの環境で働くために必要なことは、", "国境の長いトンネルを抜けると", "美味しい日本食といえば、"]

         lowercase			:int							=  [
             "データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。",
             "100年後に必要とされる会社は、「人」が中心の会社です。",
             "フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。",
             "国境の長いトンネルを抜けると、そこは雪国だった。",
             "美味しい日本食といえば、やっぱりお寿司ですよね。",
         ]

         lowercase			:List[str]							=  GPTNeoXJapaneseTokenizer.from_pretrained(_lowerCAmelCase )
         lowercase			:Tuple							=  GPTNeoXJapaneseForCausalLM.from_pretrained(_lowerCAmelCase )

         lowercase			:List[str]							=  []
         for prompt in prompts:
           lowercase			:Optional[int]							=  tokenizer(_lowerCAmelCase				,    return_tensors="pt" ).input_ids
           lowercase			:Union[str, Any]							=  model.generate(_lowerCAmelCase				,    max_length=50 )
           lowercase			:List[str]							=  tokenizer.batch_decode(_lowerCAmelCase				,    skip_special_tokens=_lowerCAmelCase )
           predicted_outputs += generated_string
         self.assertListEqual(_lowerCAmelCase				,    _lowerCAmelCase )



