



"""simple docstring"""
import random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
       import os

       import jax.numpy as jnp
       from jax import jit

       from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
       from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

       UpperCAmelCase    :		Union[str, Any]      =			"0.12"  # assumed parallelism: 8


if is_torch_available():
       import torch


def       _SCREAMING_SNAKE_CASE    (__lowerCAmelCase			,	__lowerCAmelCase			,	__lowerCAmelCase=None				)			->    Any:







  '''simple docstring'''


  if rng is None:
    lowercase_             =			random.Random()

  lowercase_             =			1
  for dim in shape:
    total_dims *= dim

  lowercase_             =			[]
  for _ in range(_UpperCamelCase				):
    values.append(rng.randint(0			,	vocab_size - 1				)				)

  lowercase_             =			np.array(_UpperCamelCase			,	dtype=jnp.intaa				).reshape(_UpperCamelCase				)

  return output


def       _SCREAMING_SNAKE_CASE    (__lowerCAmelCase			,	__lowerCAmelCase=None				)			->    Union[str, Any]:







  '''simple docstring'''


  lowercase_             =			ids_tensor(_UpperCamelCase			,	vocab_size=2			,	rng=_UpperCamelCase				)
  # make sure that at least one token is attended to for each batch
  lowercase_             =			1
  return attn_mask


@require_flax
class  SCREAMING_SNAKE_CASE__			:
    lowercase__  			= None
    lowercase__  			= ()

    def        _UpperCAmelCase						(					self      :					Optional[int]):







      """simple docstring"""







      lowercase_       ,     lowercase_             =			self.model_tester.prepare_config_and_inputs_for_common()

      # cut to half length & take max batch_size 3
      lowercase_             =			2
      lowercase_             =			inputs["""input_ids"""].shape[-1] // 2
      lowercase_             =			inputs["""input_ids"""][:max_batch_size, :sequence_length]

      lowercase_             =			jnp.ones_like(__a)
      lowercase_             =			attention_mask[:max_batch_size, :sequence_length]

      # generate max 5 tokens
      lowercase_             =			input_ids.shape[-1] + 5
      if config.eos_token_id is not None and config.pad_token_id is None:
        # hack to allow generate for models such as GPT2 as is done in `generate()`
        lowercase_             =			config.eos_token_id
      return config, input_ids, attention_mask, max_length

    @is_pt_flax_cross_test
    def        _UpperCAmelCase						(					self      :					int):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()
      lowercase_             =			False
      lowercase_             =			max_length
      lowercase_             =			0

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model_class.__name__[4:]  # Skip the "Flax" at the beginning
        lowercase_             =			getattr(__a			,	__a)
        lowercase_             =			pt_model_class(__a).eval()
        lowercase_             =			load_flax_weights_in_pytorch_model(__a			,	flax_model.params)

        lowercase_             =			flax_model.generate(__a).sequences
        lowercase_             =			pt_model.generate(torch.tensor(__a			,	dtype=torch.long))

        if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
          lowercase_             =			flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

        self.assertListEqual(pt_generation_outputs.numpy().tolist()			,	flax_generation_outputs.tolist())

    def        _UpperCAmelCase						(					self      :					Tuple):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()
      lowercase_             =			False
      lowercase_             =			max_length

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())

    def        _UpperCAmelCase						(					self      :					Dict):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()
      lowercase_             =			True
      lowercase_             =			max_length

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())

    def        _UpperCAmelCase						(					self      :					Tuple):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()
      lowercase_             =			False
      lowercase_             =			max_length
      lowercase_             =			2

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())

    def        _UpperCAmelCase						(					self      :					str):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()
      lowercase_             =			False
      lowercase_             =			max_length
      lowercase_             =			2
      lowercase_             =			2

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a).sequences
        self.assertEqual(generation_outputs.shape[0]			,	input_ids.shape[0] * config.num_return_sequences)

    def        _UpperCAmelCase						(					self      :					Tuple):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()
      lowercase_             =			True
      lowercase_             =			max_length
      lowercase_             =			0.8
      lowercase_             =			1_0
      lowercase_             =			0.3
      lowercase_             =			1
      lowercase_             =			8
      lowercase_             =			9

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())

    def        _UpperCAmelCase						(					self      :					List[str]):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()
      lowercase_             =			max_length
      lowercase_             =			1
      lowercase_             =			8
      lowercase_             =			9

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())

    def        _UpperCAmelCase						(					self      :					List[Any]):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()
      lowercase_             =			max_length
      lowercase_             =			2
      lowercase_             =			1
      lowercase_             =			8
      lowercase_             =			9

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())

    def        _UpperCAmelCase						(					self      :					Optional[int]):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()

      # pad attention mask on the left
      lowercase_             =			attention_mask.at[(0, 0)].set(0)

      lowercase_             =			False
      lowercase_             =			max_length

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a			,	attention_mask=__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a			,	attention_mask=__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())

    def        _UpperCAmelCase						(					self      :					Optional[Any]):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()

      # pad attention mask on the left
      lowercase_             =			attention_mask.at[(0, 0)].set(0)

      lowercase_             =			True
      lowercase_             =			max_length

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a			,	attention_mask=__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a			,	attention_mask=__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())




    def        _UpperCAmelCase						(					self      :					Union[str, Any]):







      """simple docstring"""







      lowercase_       ,     lowercase_       ,     lowercase_       ,     lowercase_             =			self._get_input_ids_and_config()

      # pad attention mask on the left
      lowercase_             =			attention_mask.at[(0, 0)].set(0)

      lowercase_             =			2
      lowercase_             =			max_length

      for model_class in self.all_generative_model_classes:
        lowercase_             =			model_class(__a)

        lowercase_             =			model.generate(__a			,	attention_mask=__a).sequences
        self.assertEqual(generation_outputs.shape[-1]			,	__a)

        lowercase_             =			jit(model.generate)
        lowercase_             =			jit_generate(__a			,	attention_mask=__a).sequences

        self.assertListEqual(generation_outputs.tolist()			,	jit_generation_outputs.tolist())







@require_flax
class  SCREAMING_SNAKE_CASE__			(				unittest.TestCase ):

    def        _UpperCAmelCase						(					self      :					List[str]):







      """simple docstring"""







      lowercase_             =			AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""")
      lowercase_             =			FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""")

      lowercase_             =			"""Hello world"""
      lowercase_             =			tokenizer(__a			,	return_tensors="""np""").input_ids

      # typos are quickly detected (the correct argument is `do_sample`)
      with self.assertRaisesRegex(__a			,	"""do_samples"""):
        model.generate(__a			,	do_samples=__a)

      # arbitrary arguments that will not be used anywhere are also not accepted
      with self.assertRaisesRegex(__a			,	"""foo"""):
        lowercase_             =			{"""foo""": """bar"""}
        model.generate(__a			,	**__a)





"""simple docstring"""


import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
A	:  List[str]            =     pytest.mark.integration


A	:  Optional[Any]            =     {"comet"}
A	:  int            =     importlib.util.find_spec("fairseq") is not None

A	:  Union[str, Any]            =     {"code_eval"}
A	:  Dict            =     os.name == "nt"

A	:  Dict            =     {"bertscore", "frugalscore", "perplexity"}
A	:  Any            =     importlib.util.find_spec("transformers") is not None


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
									self.skipTest("\"test requires Fairseq\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
									self.skipTest("\"test requires transformers\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			@wraps(_UpperCamelCase )
			def wrapper(self       ,					_UpperCamelCase ):
						if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
									self.skipTest("\"test not supported on Windows\"" )
						else:
									test_case(self       ,					_UpperCamelCase )

			return wrapper


def _lowerCamelCase      (						):

			'''simple docstring'''




			__lowerCAmelCase							       =     [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )]
			return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished
@parameterized.named_parameters(get_local_metric_names()						)
@for_all_test_methods(
    lowerCAmelCase__			,lowerCAmelCase__			,lowerCAmelCase__						)
@local
class     _UpperCamelCase    (  parameterized.TestCase						):
							'''simple docstring'''







							__UpperCAmelCase		:       Any							 ={}
							__UpperCAmelCase		:       List[str]							 =None

							@pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning"      )
							@pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning"      )
							def      snake_case							(	self       ,  __a      ):
										__lowerCAmelCase							       =     "[...]"
										__lowerCAmelCase							       =     importlib.import_module(
										    datasets.load.metric_module_factory(os.path.join("metrics"       ,  __a      )      ).module_path      )
										__lowerCAmelCase							       =     datasets.load.import_main_class(metric_module.__name__       ,  dataset=__a      )
										# check parameters
										__lowerCAmelCase							       =     inspect.signature(metric._compute      ).parameters
										self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()      )      )  # no **kwargs
										# run doctest
										with self.patch_intensive_calls(__a       ,  metric_module.__name__      ):
													with self.use_local_metrics():
																try:
																			__lowerCAmelCase							       =     doctest.testmod(__a       ,  verbose=__a       ,  raise_on_error=__a      )
																except doctest.UnexpectedException as e:
																			raise e.exc_info[1]  # raise the exception that doctest caught
										self.assertEqual(results.failed       ,  0      )
										self.assertGreater(results.attempted       ,  1      )

							@slow
							def      snake_case							(	self       ,  __a      ):
										__lowerCAmelCase							       =     "[...]"
										__lowerCAmelCase							       =     importlib.import_module(
										    datasets.load.metric_module_factory(os.path.join("metrics"       ,  __a      )      ).module_path      )
										# run doctest
										with self.use_local_metrics():
													__lowerCAmelCase							       =     doctest.testmod(__a       ,  verbose=__a       ,  raise_on_error=__a      )
										self.assertEqual(results.failed       ,  0      )
										self.assertGreater(results.attempted       ,  1      )

							@contextmanager
							def      snake_case							(	self       ,  __a       ,  __a      ):
										if metric_name in self.INTENSIVE_CALLS_PATCHER:
													with self.INTENSIVE_CALLS_PATCHER[metric_name](__a      ):
																yield
										else:
													yield

							@contextmanager
							def      snake_case							(	self      ):
										def load_local_metric(__a       ,  *__a       ,  **__a      ):
													return load_metric(os.path.join("metrics"       ,  __a      )       ,  *__a       ,  **__a      )

										with patch("datasets.load_metric"      ) as mock_load_metric:
													__lowerCAmelCase							       =     load_local_metric
													yield



							@classmethod
							def      snake_case							(	cls       ,  __a      ):
										def wrapper(__a      ):
													__lowerCAmelCase							       =     contextmanager(__a      )
													__lowerCAmelCase							       =     patcher
													return patcher

										return wrapper


@LocalMetricTest.register_intensive_calls_patcher("bleurt" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			import tensorflow.compat.va as tf
			from bleurt.score import Predictor

			tf.flags.DEFINE_string("sv"       ,					""       ,					"" )  # handle pytest cli flags
			class     _UpperCamelCase    (  lowerCAmelCase__						):
										'''simple docstring'''







										def      snake_case							(	self       ,  __a      ):
													assert len(input_dict["input_ids"]      ) == 2
													return np.array([1.0_3, 1.0_4]      )

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
			with patch("bleurt.score._create_predictor" ) as mock_create_predictor:
						__lowerCAmelCase							       =     MockedPredictor()
						yield


@LocalMetricTest.register_intensive_calls_patcher("bertscore" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			import torch

			def bert_cos_score_idf(_UpperCamelCase       ,					_UpperCamelCase       ,					*_UpperCamelCase       ,					**_UpperCamelCase ):
						return torch.tensor([[1.0, 1.0, 1.0]] * len(_UpperCamelCase ) )

			# mock get_model which is supposed to do download a bert model
			# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
			with patch("bert_score.scorer.get_model" ), patch(
			    "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf:
						__lowerCAmelCase							       =     bert_cos_score_idf
						yield


@LocalMetricTest.register_intensive_calls_patcher("comet" )
def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			def load_from_checkpoint(_UpperCamelCase ):
						class     _UpperCamelCase    :
													'''simple docstring'''







													def      snake_case							(	self       ,  __a       ,  *__a       ,  **__a      ):
																assert len(__a      ) == 2
																__lowerCAmelCase							       =     [0.1_9, 0.9_2]
																return scores, sum(__a      ) / len(__a      )
						return Model()

			# mock load_from_checkpoint which is supposed to do download a bert model
			# mock load_from_checkpoint which is supposed to do download a bert model
			with patch("comet.download_model" ) as mock_download_model:
						__lowerCAmelCase							       =     None
						with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint:
									__lowerCAmelCase							       =     load_from_checkpoint
									yield


def _lowerCamelCase      (						):

			'''simple docstring'''




			__lowerCAmelCase							       =     load_metric(os.path.join("metrics"       ,					"seqeval" ) )
			__lowerCAmelCase							       =     "ERROR"
			__lowerCAmelCase							       =     f"Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"
			with pytest.raises(_UpperCamelCase       ,					match=re.escape(_UpperCamelCase ) ):
						metric.compute(predictions=[]       ,					references=[]       ,					scheme=_UpperCamelCase )




