
"""simple docstring"""




import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel


class       __magic_name__							:
       def __init__(  self			,					A_			,					A_=13			,					A_=7			,					A_=True			,					A_=True			,					A_=False			,					A_=True			,					A_=99			,					A_=32			,					A_=5			,					A_=4			,					A_=37			,					A_="gelu"			,					A_=0.1			,					A_=0.1			,					A_=512			,					A_=16			,					A_=2			,					A_=0.02			,					A_=3			,					A_=4			,					A_=None			,					)  ->						int:





         """simple docstring"""




         _lowercase:      List[Any]   			=  parent
         _lowercase:      Any   			=  batch_size
         _lowercase:      List[str]   			=  seq_length
         _lowercase:      str   			=  is_training
         _lowercase:      List[str]   			=  use_input_mask
         _lowercase:      Optional[int]   			=  use_token_type_ids
         _lowercase:      Tuple   			=  use_labels
         _lowercase:      Tuple   			=  vocab_size
         _lowercase:      List[Any]   			=  hidden_size
         _lowercase:      str   			=  num_hidden_layers
         _lowercase:      Optional[int]   			=  num_attention_heads
         _lowercase:      Optional[Any]   			=  intermediate_size
         _lowercase:      Optional[Any]   			=  hidden_act
         _lowercase:      int   			=  hidden_dropout_prob
         _lowercase:      Optional[int]   			=  attention_probs_dropout_prob
         _lowercase:      Optional[Any]   			=  max_position_embeddings
         _lowercase:      Optional[int]   			=  type_vocab_size
         _lowercase:      List[str]   			=  type_sequence_label_size
         _lowercase:      Any   			=  initializer_range
         _lowercase:      Union[str, Any]   			=  num_labels
         _lowercase:      int   			=  num_choices
         _lowercase:      List[str]   			=  scope
       def 				lowercase_				(  self							)  ->						int:





         """simple docstring"""




         _lowercase:      Optional[int]   			=  ids_tensor([self.batch_size, self.seq_length]			,					self.vocab_size							)

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

         _lowercase:      int   			=  None
         if self.use_token_type_ids:
           _lowercase:      Dict   			=  ids_tensor([self.batch_size, self.seq_length]			,					self.type_vocab_size							)

         _lowercase:      Dict   			=  None
         _lowercase:      Optional[Any]   			=  None
         _lowercase:      List[Any]   			=  None
         if self.use_labels:
           _lowercase:      int   			=  ids_tensor([self.batch_size]			,					self.type_sequence_label_size							)
           _lowercase:      Union[str, Any]   			=  ids_tensor([self.batch_size, self.seq_length]			,					self.num_labels							)
           _lowercase:      Union[str, Any]   			=  ids_tensor([self.batch_size]			,					self.num_choices							)

         _lowercase:      Optional[Any]   			=  self.get_config()

         return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
       def 				lowercase_				(  self							)  ->						Dict:





         """simple docstring"""




         return OpenLlamaConfig(
             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_size=self.intermediate_size			,					hidden_act=self.hidden_act			,					hidden_dropout_prob=self.hidden_dropout_prob			,					attention_probs_dropout_prob=self.attention_probs_dropout_prob			,					max_position_embeddings=self.max_position_embeddings			,					type_vocab_size=self.type_vocab_size			,					is_decoder=A_			,					initializer_range=self.initializer_range			,					use_stable_embedding=A_			,					)
       def 				lowercase_				(  self			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_							)  ->						Optional[int]:





         """simple docstring"""




         _lowercase:      Dict   			=  OpenLlamaModel(config=A_							)
         model.to(A_							)
         model.eval()
         _lowercase:      Dict   			=  model(A_			,					attention_mask=A_							)
         _lowercase:      Any   			=  model(A_							)
         self.parent.assertEqual(result.last_hidden_state.shape			,					(self.batch_size, self.seq_length, self.hidden_size)							)
       def 				lowercase_				(  self			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					)  ->						str:





         """simple docstring"""




         _lowercase:      List[Any]   			=  True
         _lowercase:      Optional[int]   			=  OpenLlamaModel(A_							)
         model.to(A_							)
         model.eval()
         _lowercase:      Tuple   			=  model(
             A_			,					attention_mask=A_			,					encoder_hidden_states=A_			,					encoder_attention_mask=A_			,					)
         _lowercase:      List[str]   			=  model(
             A_			,					attention_mask=A_			,					encoder_hidden_states=A_			,					)
         _lowercase:      Dict   			=  model(A_			,					attention_mask=A_							)
         self.parent.assertEqual(result.last_hidden_state.shape			,					(self.batch_size, self.seq_length, self.hidden_size)							)
       def 				lowercase_				(  self			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					)  ->						Any:





         """simple docstring"""




         _lowercase:      Dict   			=  OpenLlamaForCausalLM(config=A_							)
         model.to(A_							)
         model.eval()
         _lowercase:      List[str]   			=  model(A_			,					attention_mask=A_			,					labels=A_							)
         self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.seq_length, self.vocab_size)							)
       def 				lowercase_				(  self			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					A_			,					)  ->						List[Any]:





         """simple docstring"""




         _lowercase:      int   			=  True
         _lowercase:      str   			=  True
         _lowercase:      int   			=  OpenLlamaForCausalLM(config=A_							)
         model.to(A_							)
         model.eval()

         # first forward pass
         _lowercase:      int   			=  model(
             A_			,					attention_mask=A_			,					encoder_hidden_states=A_			,					encoder_attention_mask=A_			,					use_cache=A_			,					)
         _lowercase:      Optional[Any]   			=  outputs.past_key_values

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

         # append to next input_ids and
         _lowercase:      Any   			=  torch.cat([input_ids, next_tokens]			,					dim=-1							)
         _lowercase:      Union[str, Any]   			=  torch.cat([input_mask, next_mask]			,					dim=-1							)

         _lowercase:      Union[str, Any]   			=  model(
             A_			,					attention_mask=A_			,					encoder_hidden_states=A_			,					encoder_attention_mask=A_			,					output_hidden_states=A_			,					)['''hidden_states'''][0]
         _lowercase:      List[Any]   			=  model(
             A_			,					attention_mask=A_			,					encoder_hidden_states=A_			,					encoder_attention_mask=A_			,					past_key_values=A_			,					output_hidden_states=A_			,					)['''hidden_states'''][0]

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



       def 				lowercase_				(  self							)  ->						Tuple:





         """simple docstring"""




         _lowercase:      Optional[int]   			=  self.prepare_config_and_inputs()
         (
             (
             _lowercase
         )			,					(
             _lowercase
         )			,					(
             _lowercase
         )			,					(
             _lowercase
         )			,					(
             _lowercase
         )			,					(
             _lowercase
         )			,					(
             _lowercase
         )			,					
         ):      Optional[Any]   			=  config_and_inputs
         _lowercase:      List[str]   			=  {'''input_ids''': input_ids, '''attention_mask''': input_mask}
         return config, inputs_dict


@require_torch
class       __magic_name__							(							SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__ ,       unittest.TestCase			):
       UpperCamelCase_ =		(
           (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
       )
       UpperCamelCase_ =		(OpenLlamaForCausalLM,) if is_torch_available() else ()
       UpperCamelCase_ =		(
           {
               '''feature-extraction''': OpenLlamaModel,
               '''text-classification''': OpenLlamaForSequenceClassification,
               '''text-generation''': OpenLlamaForCausalLM,
               '''zero-shot''': OpenLlamaForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       UpperCamelCase_ =		False
       UpperCamelCase_ =		False
       def 				lowercase_				(  self							)  ->						List[str]:





         """simple docstring"""




         _lowercase:      int   			=  OpenLlamaModelTester(self							)
         _lowercase:      int   			=  ConfigTester(self			,					config_class=A_			,					hidden_size=37							)
       def 				lowercase_				(  self							)  ->						Optional[Any]:





         """simple docstring"""




         self.config_tester.run_common_tests()
       def 				lowercase_				(  self							)  ->						Union[str, Any]:





         """simple docstring"""




         _lowercase:      Optional[Any]   			=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A_							)
       def 				lowercase_				(  self							)  ->						str:





         """simple docstring"""




         _lowercase:      Tuple   			=  self.model_tester.prepare_config_and_inputs()
         for type in ["absolute", "relative_key", "relative_key_query"]:
           _lowercase:      Dict   			=  type
           self.model_tester.create_and_check_model(*A_							)
       def 				lowercase_				(  self							)  ->						Optional[Any]:





         """simple docstring"""




         _lowercase			,					_lowercase:      List[str]   			=  self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase:      int   			=  3
         _lowercase:      str   			=  input_dict['''input_ids''']
         _lowercase:      Union[str, Any]   			=  input_ids.ne(1							).to(A_							)
         _lowercase:      int   			=  ids_tensor([self.model_tester.batch_size]			,					self.model_tester.type_sequence_label_size							)
         _lowercase:      Any   			=  OpenLlamaForSequenceClassification(A_							)
         model.to(A_							)
         model.eval()
         _lowercase:      int   			=  model(A_			,					attention_mask=A_			,					labels=A_							)
         self.assertEqual(result.logits.shape			,					(self.model_tester.batch_size, self.model_tester.num_labels)							)
       def 				lowercase_				(  self							)  ->						Union[str, Any]:





         """simple docstring"""




         _lowercase			,					_lowercase:      List[Any]   			=  self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase:      List[Any]   			=  3
         _lowercase:      Union[str, Any]   			=  '''single_label_classification'''
         _lowercase:      Union[str, Any]   			=  input_dict['''input_ids''']
         _lowercase:      str   			=  input_ids.ne(1							).to(A_							)
         _lowercase:      int   			=  ids_tensor([self.model_tester.batch_size]			,					self.model_tester.type_sequence_label_size							)
         _lowercase:      int   			=  OpenLlamaForSequenceClassification(A_							)
         model.to(A_							)
         model.eval()
         _lowercase:      List[Any]   			=  model(A_			,					attention_mask=A_			,					labels=A_							)
         self.assertEqual(result.logits.shape			,					(self.model_tester.batch_size, self.model_tester.num_labels)							)
       def 				lowercase_				(  self							)  ->						Tuple:





         """simple docstring"""




         _lowercase			,					_lowercase:      Any   			=  self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase:      Union[str, Any]   			=  3
         _lowercase:      List[str]   			=  '''multi_label_classification'''
         _lowercase:      Union[str, Any]   			=  input_dict['''input_ids''']
         _lowercase:      Optional[Any]   			=  input_ids.ne(1							).to(A_							)
         _lowercase:      List[str]   			=  ids_tensor(
             [self.model_tester.batch_size, config.num_labels]			,					self.model_tester.type_sequence_label_size							).to(torch.float							)
         _lowercase:      Any   			=  OpenLlamaForSequenceClassification(A_							)
         model.to(A_							)
         model.eval()
         _lowercase:      Optional[int]   			=  model(A_			,					attention_mask=A_			,					labels=A_							)
         self.assertEqual(result.logits.shape			,					(self.model_tester.batch_size, self.model_tester.num_labels)							)
       @unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test'''							)
       def 				lowercase_				(  self							)  ->						int:





         """simple docstring"""




         pass



       @parameterized.expand([('''linear''',), ('''dynamic''',)]							)
       def 				lowercase_				(  self			,					A_							)  ->						Any:





         """simple docstring"""




         _lowercase			,					_lowercase:      int   			=  self.model_tester.prepare_config_and_inputs_for_common()
         _lowercase:      int   			=  ids_tensor([1, 10]			,					config.vocab_size							)
         _lowercase:      int   			=  ids_tensor([1, int(config.max_position_embeddings * 1.5							)]			,					config.vocab_size							)

         set_seed(42							)  # Fixed seed at init time so the two models get the same random weights
         _lowercase:      Optional[int]   			=  OpenLlamaModel(A_							)
         original_model.to(A_							)
         original_model.eval()
         _lowercase:      Any   			=  original_model(A_							).last_hidden_state
         _lowercase:      Optional[int]   			=  original_model(A_							).last_hidden_state

         set_seed(42							)  # Fixed seed at init time so the two models get the same random weights
         _lowercase:      List[str]   			=  {'''type''': scaling_type, '''factor''': 10.0}
         _lowercase:      List[str]   			=  OpenLlamaModel(A_							)
         scaled_model.to(A_							)
         scaled_model.eval()
         _lowercase:      Tuple   			=  scaled_model(A_							).last_hidden_state
         _lowercase:      Optional[Any]   			=  scaled_model(A_							).last_hidden_state

         # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
         # maximum sequence length, so the outputs for the short input should match.
         if scaling_type == "dynamic":
           self.assertTrue(torch.allclose(A_			,					A_			,					atol=1E-5							)							)
         else:
           self.assertFalse(torch.allclose(A_			,					A_			,					atol=1E-5							)							)

         # The output should be different for long inputs
         self.assertFalse(torch.allclose(A_			,					A_			,					atol=1E-5							)							)


"""simple docstring"""




from collections import defaultdict
from pathlib import Path

import pandas as pd
from rouge_cli import calculate_rouge_path

from utils import calculate_rouge


A__ :       Any				= [
    'Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the'
    ' final seconds on board Flight 9525. The Germanwings co-pilot says he had a "previous episode of severe'
    ' depression\" German airline confirms it knew of Andreas Lubitz\'s depression years before he took control.',
    'The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal'
    ' accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC\'s'
    ' founding Rome Statute in January. Israel and the United States opposed the Palestinians\' efforts to join the'
    ' body.',
    'Amnesty International releases its annual report on the death penalty. The report catalogs the use of'
    ' state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the'
    ' world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital'
    ' punishment.',
]

A__ :       Tuple				= [
    'Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .'
    ' Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz'
    ' had informed his Lufthansa training school of an episode of severe depression, airline says .',
    'Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June .'
    ' Israel and the United States opposed the move, which could open the door to war crimes investigations against'
    ' Israelis .',
    'Amnesty\'s annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to'
    ' death . Organization claims that governments around the world are using the threat of terrorism to advance'
    ' executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death'
    ' sentences up by 28% .',
]




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      Any   			=  calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					bootstrap_aggregation=_UpperCamelCase			,					rouge_keys=['''rouge2''', '''rougeL''']    )
  assert isinstance(_UpperCamelCase			,					_UpperCamelCase    )
  _lowercase:      List[Any]   			=  calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					bootstrap_aggregation=_UpperCamelCase			,					rouge_keys=['''rouge2''']    )
  assert (
      pd.DataFrame(no_aggregation['''rouge2''']    ).fmeasure.mean()
      == pd.DataFrame(no_aggregation_just_ra['''rouge2''']    ).fmeasure.mean()
  )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      Dict   			=  '''rougeLsum'''
  _lowercase:      Dict   			=  calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					newline_sep=_UpperCamelCase			,					rouge_keys=[k]    )[k]
  _lowercase:      List[str]   			=  calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					newline_sep=_UpperCamelCase			,					rouge_keys=[k]    )[k]
  assert score > score_no_sep




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      Tuple   			=  ['''rouge1''', '''rouge2''', '''rougeL''']
  _lowercase:      Dict   			=  calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					newline_sep=_UpperCamelCase			,					rouge_keys=_UpperCamelCase    )
  _lowercase:      Optional[int]   			=  calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					newline_sep=_UpperCamelCase			,					rouge_keys=_UpperCamelCase    )
  assert score_sep == score_no_sep




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      Union[str, Any]   			=  [
      '''Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.''',
      '''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .''',
  ]
  _lowercase:      Union[str, Any]   			=  [
      '''Margot Frank, died in 1945, a month earlier than previously thought.''',
      '''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of'''
      ''' the final seconds on board Flight 9525.''',
  ]
  assert calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					newline_sep=_UpperCamelCase    ) == calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					newline_sep=_UpperCamelCase    )




def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      int   			=  [
      '''" "a person who has such a video needs to immediately give it to the investigators," prosecutor says .<n> "it is a very disturbing scene," editor-in-chief of bild online tells "erin burnett: outfront" '''
  ]
  _lowercase:      Union[str, Any]   			=  [
      ''' Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports . Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says .'''
  ]

  _lowercase:      List[Any]   			=  calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					rouge_keys=['''rougeLsum''']			,					newline_sep=_UpperCamelCase    )['''rougeLsum''']
  _lowercase:      Union[str, Any]   			=  calculate_rouge(_UpperCamelCase			,					_UpperCamelCase			,					rouge_keys=['''rougeLsum''']    )['''rougeLsum''']
  assert new_score > prev_score







def 			_lowerCAmelCase		(		):






  """simple docstring"""



  _lowercase:      List[str]   			=  Path('''examples/seq2seq/test_data/wmt_en_ro'''    )
  _lowercase:      int   			=  calculate_rouge_path(data_dir.joinpath('''test.source'''    )			,					data_dir.joinpath('''test.target'''    )    )
  assert isinstance(_UpperCamelCase			,					_UpperCamelCase    )
  _lowercase:      Optional[int]   			=  calculate_rouge_path(
      data_dir.joinpath('''test.source'''    )			,					data_dir.joinpath('''test.target'''    )			,					bootstrap_aggregation=_UpperCamelCase    )
  assert isinstance(_UpperCamelCase			,					_UpperCamelCase    )
