


'''simple docstring'''


import unittest

from transformers import XLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, 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 (
				    XLMForMultipleChoice,
				    XLMForQuestionAnswering,
				    XLMForQuestionAnsweringSimple,
				    XLMForSequenceClassification,
				    XLMForTokenClassification,
				    XLMModel,
				    XLMWithLMHeadModel,
				)
				from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST





class     lowercase__  :





							'''simple docstring'''


							def __init__(    self    ,					__snake_case    ,					__snake_case=13    ,					__snake_case=7    ,					__snake_case=True    ,					__snake_case=True    ,					__snake_case=True    ,					__snake_case=True    ,					__snake_case=True    ,					__snake_case=False    ,					__snake_case=False    ,					__snake_case=False    ,					__snake_case=2    ,					__snake_case=99    ,					__snake_case=0    ,					__snake_case=32    ,					__snake_case=5    ,					__snake_case=4    ,					__snake_case=0.1    ,					__snake_case=0.1    ,					__snake_case=512    ,					__snake_case=2    ,					__snake_case=0.02    ,					__snake_case=2    ,					__snake_case=4    ,					__snake_case="last"    ,					__snake_case=True    ,					__snake_case=None    ,					__snake_case=0    ,					):
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      parent
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      batch_size
											_SCREAMING_SNAKE_CASE :       Dict     		=      seq_length
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      is_training
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      use_input_lengths
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      use_token_type_ids
											_SCREAMING_SNAKE_CASE :       Dict     		=      use_labels
											_SCREAMING_SNAKE_CASE :       Tuple     		=      gelu_activation
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      sinusoidal_embeddings
											_SCREAMING_SNAKE_CASE :       Tuple     		=      causal
											_SCREAMING_SNAKE_CASE :       Any     		=      asm
											_SCREAMING_SNAKE_CASE :       List[str]     		=      n_langs
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      vocab_size
											_SCREAMING_SNAKE_CASE :       Any     		=      n_special
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      hidden_size
											_SCREAMING_SNAKE_CASE :       str     		=      num_hidden_layers
											_SCREAMING_SNAKE_CASE :       str     		=      num_attention_heads
											_SCREAMING_SNAKE_CASE :       Any     		=      hidden_dropout_prob
											_SCREAMING_SNAKE_CASE :       str     		=      attention_probs_dropout_prob
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      max_position_embeddings
											_SCREAMING_SNAKE_CASE :       Any     		=      type_sequence_label_size
											_SCREAMING_SNAKE_CASE :       int     		=      initializer_range
											_SCREAMING_SNAKE_CASE :       Dict     		=      num_labels
											_SCREAMING_SNAKE_CASE :       int     		=      num_choices
											_SCREAMING_SNAKE_CASE :       int     		=      summary_type
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      use_proj
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      scope
											_SCREAMING_SNAKE_CASE :       Dict     		=      bos_token_id






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      ids_tensor([self.batch_size, self.seq_length]    ,					self.vocab_size  )
											_SCREAMING_SNAKE_CASE :       List[str]     		=      random_attention_mask([self.batch_size, self.seq_length]  )

											_SCREAMING_SNAKE_CASE :       int     		=      None
											if self.use_input_lengths:
															_SCREAMING_SNAKE_CASE :       str     		=      (
															    ids_tensor([self.batch_size]    ,					vocab_size=2  ) + self.seq_length - 2
															)  # small variation of seq_length

											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      None
											if self.use_token_type_ids:
															_SCREAMING_SNAKE_CASE :       List[Any]     		=      ids_tensor([self.batch_size, self.seq_length]    ,					self.n_langs  )

											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      None
											_SCREAMING_SNAKE_CASE :       Tuple     		=      None
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      None
											if self.use_labels:
															_SCREAMING_SNAKE_CASE :       str     		=      ids_tensor([self.batch_size]    ,					self.type_sequence_label_size  )
															_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      ids_tensor([self.batch_size, self.seq_length]    ,					self.num_labels  )
															_SCREAMING_SNAKE_CASE :       str     		=      ids_tensor([self.batch_size]    ,					2  ).float()
															_SCREAMING_SNAKE_CASE :       Tuple     		=      ids_tensor([self.batch_size]    ,					self.num_choices  )

											_SCREAMING_SNAKE_CASE :       List[Any]     		=      self.get_config()

											return (
											    config,
											    input_ids,
											    token_type_ids,
											    input_lengths,
											    sequence_labels,
											    token_labels,
											    is_impossible_labels,
											    choice_labels,
											    input_mask,
											)






							def UpperCAmelCase_	(    self  ):
											return XLMConfig(
											    vocab_size=self.vocab_size    ,					n_special=self.n_special    ,					emb_dim=self.hidden_size    ,					n_layers=self.num_hidden_layers    ,					n_heads=self.num_attention_heads    ,					dropout=self.hidden_dropout_prob    ,					attention_dropout=self.attention_probs_dropout_prob    ,					gelu_activation=self.gelu_activation    ,					sinusoidal_embeddings=self.sinusoidal_embeddings    ,					asm=self.asm    ,					causal=self.causal    ,					n_langs=self.n_langs    ,					max_position_embeddings=self.max_position_embeddings    ,					initializer_range=self.initializer_range    ,					summary_type=self.summary_type    ,					use_proj=self.use_proj    ,					num_labels=self.num_labels    ,					bos_token_id=self.bos_token_id    ,					)






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					):
											_SCREAMING_SNAKE_CASE :       Dict     		=      XLMModel(config=__snake_case  )
											model.to(__snake_case  )
											model.eval()
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      model(__snake_case    ,					lengths=__snake_case    ,					langs=__snake_case  )
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      model(__snake_case    ,					langs=__snake_case  )
											_SCREAMING_SNAKE_CASE :       str     		=      model(__snake_case  )
											self.parent.assertEqual(result.last_hidden_state.shape    ,					(self.batch_size, self.seq_length, self.hidden_size)  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					):
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      XLMWithLMHeadModel(__snake_case  )
											model.to(__snake_case  )
											model.eval()

											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      model(__snake_case    ,					token_type_ids=__snake_case    ,					labels=__snake_case  )
											self.parent.assertEqual(result.loss.shape    ,					()  )
											self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.seq_length, self.vocab_size)  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					):
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      XLMForQuestionAnsweringSimple(__snake_case  )
											model.to(__snake_case  )
											model.eval()

											_SCREAMING_SNAKE_CASE :       List[Any]     		=      model(__snake_case  )

											_SCREAMING_SNAKE_CASE :       int     		=      model(__snake_case    ,					start_positions=__snake_case    ,					end_positions=__snake_case  )
											_SCREAMING_SNAKE_CASE :       str     		=      outputs
											self.parent.assertEqual(result.start_logits.shape    ,					(self.batch_size, self.seq_length)  )
											self.parent.assertEqual(result.end_logits.shape    ,					(self.batch_size, self.seq_length)  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					):
											_SCREAMING_SNAKE_CASE :       int     		=      XLMForQuestionAnswering(__snake_case  )
											model.to(__snake_case  )
											model.eval()

											_SCREAMING_SNAKE_CASE :       int     		=      model(__snake_case  )

											_SCREAMING_SNAKE_CASE :       int     		=      model(
											    __snake_case    ,					start_positions=__snake_case    ,					end_positions=__snake_case    ,					cls_index=__snake_case    ,					is_impossible=__snake_case    ,					p_mask=__snake_case    ,					)

											_SCREAMING_SNAKE_CASE :       List[Any]     		=      model(
											    __snake_case    ,					start_positions=__snake_case    ,					end_positions=__snake_case    ,					cls_index=__snake_case    ,					is_impossible=__snake_case    ,					)

											((_SCREAMING_SNAKE_CASE)		,       ) :       List[str]     		=      result_with_labels.to_tuple()

											_SCREAMING_SNAKE_CASE :       Any     		=      model(__snake_case    ,					start_positions=__snake_case    ,					end_positions=__snake_case  )

											((_SCREAMING_SNAKE_CASE)		,       ) :       int     		=      result_with_labels.to_tuple()

											self.parent.assertEqual(result_with_labels.loss.shape    ,					()  )
											self.parent.assertEqual(result.start_top_log_probs.shape    ,					(self.batch_size, model.config.start_n_top)  )
											self.parent.assertEqual(result.start_top_index.shape    ,					(self.batch_size, model.config.start_n_top)  )
											self.parent.assertEqual(
											    result.end_top_log_probs.shape    ,					(self.batch_size, model.config.start_n_top * model.config.end_n_top)  )
											self.parent.assertEqual(
											    result.end_top_index.shape    ,					(self.batch_size, model.config.start_n_top * model.config.end_n_top)  )
											self.parent.assertEqual(result.cls_logits.shape    ,					(self.batch_size,)  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					):
											_SCREAMING_SNAKE_CASE :       Dict     		=      XLMForSequenceClassification(__snake_case  )
											model.to(__snake_case  )
											model.eval()

											_SCREAMING_SNAKE_CASE :       Tuple     		=      model(__snake_case  )
											_SCREAMING_SNAKE_CASE :       Tuple     		=      model(__snake_case    ,					labels=__snake_case  )
											self.parent.assertEqual(result.loss.shape    ,					()  )
											self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.type_sequence_label_size)  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					):
											_SCREAMING_SNAKE_CASE :       Dict     		=      self.num_labels
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      XLMForTokenClassification(__snake_case  )
											model.to(__snake_case  )
											model.eval()

											_SCREAMING_SNAKE_CASE :       int     		=      model(__snake_case    ,					attention_mask=__snake_case    ,					labels=__snake_case  )
											self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.seq_length, self.num_labels)  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					):
											_SCREAMING_SNAKE_CASE :       Any     		=      self.num_choices
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      XLMForMultipleChoice(config=__snake_case  )
											model.to(__snake_case  )
											model.eval()
											_SCREAMING_SNAKE_CASE :       Tuple     		=      input_ids.unsqueeze(1  ).expand(-1    ,					self.num_choices    ,					-1  ).contiguous()
											_SCREAMING_SNAKE_CASE :       Dict     		=      token_type_ids.unsqueeze(1  ).expand(-1    ,					self.num_choices    ,					-1  ).contiguous()
											_SCREAMING_SNAKE_CASE :       int     		=      input_mask.unsqueeze(1  ).expand(-1    ,					self.num_choices    ,					-1  ).contiguous()
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      model(
											    __snake_case    ,					attention_mask=__snake_case    ,					token_type_ids=__snake_case    ,					labels=__snake_case    ,					)
											self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.num_choices)  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      self.prepare_config_and_inputs()
											(
											    (
											    _SCREAMING_SNAKE_CASE
											)		,       (
											    _SCREAMING_SNAKE_CASE
											)		,       (
											    _SCREAMING_SNAKE_CASE
											)		,       (
											    _SCREAMING_SNAKE_CASE
											)		,       (
											    _SCREAMING_SNAKE_CASE
											)		,       (
											    _SCREAMING_SNAKE_CASE
											)		,       (
											    _SCREAMING_SNAKE_CASE
											)		,       (
											    _SCREAMING_SNAKE_CASE
											)		,       (
											    _SCREAMING_SNAKE_CASE
											)		,       
											) :       Tuple     		=      config_and_inputs
											_SCREAMING_SNAKE_CASE :       str     		=      {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths}
											return config, inputs_dict





@require_torch
class     lowercase__  (						_snake_case     ,     _snake_case     ,     _snake_case     ,     unittest.TestCase					):





							'''simple docstring'''


							A_							:      str      	=  (
							    (
							        XLMModel,
							        XLMWithLMHeadModel,
							        XLMForQuestionAnswering,
							        XLMForSequenceClassification,
							        XLMForQuestionAnsweringSimple,
							        XLMForTokenClassification,
							        XLMForMultipleChoice,
							    )
							    if is_torch_available()
							    else ()
							)
							A_							:      Any      	=  (
							    (XLMWithLMHeadModel,) if is_torch_available() else ()
							)  # TODO (PVP): Check other models whether language generation is also applicable
							A_							:      Optional[Any]      	=  (
							    {
							        """feature-extraction""": XLMModel,
							        """fill-mask""": XLMWithLMHeadModel,
							        """question-answering""": XLMForQuestionAnsweringSimple,
							        """text-classification""": XLMForSequenceClassification,
							        """text-generation""": XLMWithLMHeadModel,
							        """token-classification""": XLMForTokenClassification,
							        """zero-shot""": XLMForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case  ):
											if (
											    pipeline_test_casse_name == "QAPipelineTests"
											    and tokenizer_name is not None
											    and not tokenizer_name.endswith("""Fast"""  )
											):
															# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
															# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
															# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
															return True

											return False






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case=False  ):
											_SCREAMING_SNAKE_CASE :       List[str]     		=      super()._prepare_for_class(__snake_case    ,					__snake_case    ,					return_labels=__snake_case  )

											if return_labels:
															if model_class.__name__ == "XLMForQuestionAnswering":
																			_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      torch.zeros(
																			    self.model_tester.batch_size    ,					dtype=torch.long    ,					device=__snake_case  )
																			_SCREAMING_SNAKE_CASE :       Dict     		=      torch.zeros(
																			    self.model_tester.batch_size    ,					dtype=torch.long    ,					device=__snake_case  )

											return inputs_dict






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      XLMModelTester(self  )
											_SCREAMING_SNAKE_CASE :       Dict     		=      ConfigTester(self    ,					config_class=__snake_case    ,					emb_dim=37  )






							def UpperCAmelCase_	(    self  ):
											self.config_tester.run_common_tests()






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       str     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_xlm_model(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Dict     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_xlm_lm_head(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_xlm_simple_qa(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_xlm_qa(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Dict     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_xlm_sequence_classif(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_xlm_token_classif(*__snake_case  )






							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Tuple     		=      self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_xlm_for_multiple_choice(*__snake_case  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case=False    ,					__snake_case=1  ):
											self.assertIsInstance(__snake_case    ,					__snake_case  )
											self.assertListEqual(
											    [isinstance(__snake_case    ,					__snake_case  ) for iter_attentions in attentions]    ,					[True] * len(__snake_case  )  )
											self.assertEqual(len(__snake_case  )    ,					(max_length - min_length) * num_beam_groups  )

											for idx, iter_attentions in enumerate(__snake_case  ):
															# adds PAD dummy token
															_SCREAMING_SNAKE_CASE :       Any     		=      min_length + idx + 1
															_SCREAMING_SNAKE_CASE :       List[str]     		=      min_length + idx + 1

															_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      (
															    batch_size * num_beam_groups,
															    config.num_attention_heads,
															    tgt_len,
															    src_len,
															)
															# check attn size
															self.assertListEqual(
															    [layer_attention.shape for layer_attention in iter_attentions]    ,					[expected_shape] * len(__snake_case  )  )






							def UpperCAmelCase_	(    self    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case    ,					__snake_case=False    ,					__snake_case=1  ):
											self.assertIsInstance(__snake_case    ,					__snake_case  )
											self.assertListEqual(
											    [isinstance(__snake_case    ,					__snake_case  ) for iter_hidden_states in hidden_states]    ,					[True] * len(__snake_case  )    ,					)
											self.assertEqual(len(__snake_case  )    ,					(max_length - min_length) * num_beam_groups  )

											for idx, iter_hidden_states in enumerate(__snake_case  ):
															# adds PAD dummy token
															_SCREAMING_SNAKE_CASE :       int     		=      min_length + idx + 1
															_SCREAMING_SNAKE_CASE :       Any     		=      (batch_size * num_beam_groups, seq_len, config.hidden_size)
															# check hidden size
															self.assertListEqual(
															    [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states]    ,					[expected_shape] * len(__snake_case  )    ,					)
											pass






							@slow
							def UpperCAmelCase_	(    self  ):
											for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE :       Any     		=      XLMModel.from_pretrained(__snake_case  )
															self.assertIsNotNone(__snake_case  )





@require_torch
class     lowercase__  (						unittest.TestCase					):





							'''simple docstring'''


							@slow
							def UpperCAmelCase_	(    self  ):
											_SCREAMING_SNAKE_CASE :       Tuple     		=      XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048"""  )
											model.to(__snake_case  )
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      torch.tensor([[14, 447]]    ,					dtype=torch.long    ,					device=__snake_case  )  # the president
											_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      [
											    14,
											    447,
											    14,
											    447,
											    14,
											    447,
											    14,
											    447,
											    14,
											    447,
											    14,
											    447,
											    14,
											    447,
											    14,
											    447,
											    14,
											    447,
											    14,
											    447,
											]  # the president the president the president the president the president the president the president the president the president the president
											# TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      model.generate(__snake_case    ,					do_sample=__snake_case  )
											self.assertListEqual(output_ids[0].cpu().numpy().tolist()    ,					__snake_case  )








'''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
UpperCAmelCase_		:   Union[str, Any]							   =		pytest.mark.integration


UpperCAmelCase_		:   List[Any]							   =		{'comet'}
UpperCAmelCase_		:   int							   =		importlib.util.find_spec('fairseq') is not None

UpperCAmelCase_		:   Optional[Any]							   =		{'code_eval'}
UpperCAmelCase_		:   Optional[int]							   =		os.name == 'nt'

UpperCAmelCase_		:   Dict							   =		{'bertscore', 'frugalscore', 'perplexity'}
UpperCAmelCase_		:   Dict							   =		importlib.util.find_spec('transformers') is not None







def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





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

				return wrapper







def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





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

				return wrapper







def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





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

				return wrapper







def 			snake_case_   (  ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE :       Dict     		=      [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(
    _snake_case     ,     _snake_case     ,     _snake_case					)
@local
class     lowercase__  (						parameterized.TestCase					):





							'''simple docstring'''


							A_							:      Optional[int]      	=  {}
							A_							:      Union[str, Any]      	=  None






							@pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning"""  )
							@pytest.mark.filterwarnings("""ignore:load_metric is deprecated:FutureWarning"""  )
							def UpperCAmelCase_	(    self    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       str     		=      """[...]"""
											_SCREAMING_SNAKE_CASE :       Any     		=      importlib.import_module(
											    datasets.load.metric_module_factory(os.path.join("""metrics"""    ,					__snake_case  )  ).module_path  )
											_SCREAMING_SNAKE_CASE :       Optional[int]     		=      datasets.load.import_main_class(metric_module.__name__    ,					dataset=__snake_case  )
											# check parameters
											_SCREAMING_SNAKE_CASE :       Tuple     		=      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(__snake_case    ,					metric_module.__name__  ):
															with self.use_local_metrics():
																			try:
																							_SCREAMING_SNAKE_CASE :       int     		=      doctest.testmod(__snake_case    ,					verbose=__snake_case    ,					raise_on_error=__snake_case  )
																			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 UpperCAmelCase_	(    self    ,					__snake_case  ):
											_SCREAMING_SNAKE_CASE :       List[Any]     		=      """[...]"""
											_SCREAMING_SNAKE_CASE :       Optional[Any]     		=      importlib.import_module(
											    datasets.load.metric_module_factory(os.path.join("""metrics"""    ,					__snake_case  )  ).module_path  )
											# run doctest
											with self.use_local_metrics():
															_SCREAMING_SNAKE_CASE :       List[str]     		=      doctest.testmod(__snake_case    ,					verbose=__snake_case    ,					raise_on_error=__snake_case  )
											self.assertEqual(results.failed    ,					0  )
											self.assertGreater(results.attempted    ,					1  )






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






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

											with patch("""datasets.load_metric"""  ) as mock_load_metric:
															_SCREAMING_SNAKE_CASE :       Union[str, Any]     		=      load_local_metric
															yield






							@classmethod
							def UpperCAmelCase_	(    cls    ,					__snake_case  ):
											def wrapper(__snake_case  ):
															_SCREAMING_SNAKE_CASE :       Any     		=      contextmanager(__snake_case  )
															_SCREAMING_SNAKE_CASE :       int     		=      patcher
															return patcher

											return wrapper







@LocalMetricTest.register_intensive_calls_patcher("""bleurt"""     )
def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





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

				tf.flags.DEFINE_string("""sv"""							,      """"""							,      """"""     )  # handle pytest cli flags





				class     lowercase__  (						_snake_case					):





											'''simple docstring'''


											def UpperCAmelCase_	(    self    ,					__snake_case  ):
															assert len(input_dict["""input_ids"""]  ) == 2
															return np.array([1.03, 1.04]  )

    # 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:
								_SCREAMING_SNAKE_CASE :       Any     		=      MockedPredictor()
								yield







@LocalMetricTest.register_intensive_calls_patcher("""bertscore"""     )
def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				import torch

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

				# 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:
								_SCREAMING_SNAKE_CASE :       Any     		=      bert_cos_score_idf
								yield







@LocalMetricTest.register_intensive_calls_patcher("""comet"""     )
def 			snake_case_   (  SCREAMING_SNAKE_CASE__     ):







				"""simple docstring"""





				def load_from_checkpoint(SCREAMING_SNAKE_CASE__     ):





								class     lowercase__  :





															'''simple docstring'''


															def UpperCAmelCase_	(    self    ,					__snake_case    ,					*__snake_case    ,					**__snake_case  ):
																			assert len(__snake_case  ) == 2
																			_SCREAMING_SNAKE_CASE :       Dict     		=      [0.19, 0.92]
																			return scores, sum(__snake_case  ) / len(__snake_case  )



								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:
								_SCREAMING_SNAKE_CASE :       Any     		=      None
								with patch("""comet.load_from_checkpoint"""     ) as mock_load_from_checkpoint:
												_SCREAMING_SNAKE_CASE :       List[str]     		=      load_from_checkpoint
												yield







def 			snake_case_   (  ):







				"""simple docstring"""





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




