


'''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    __snake_case       :







    """simple docstring"""



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

    def __lowercase   (   self    :  Dict		)   ->  Optional[int]:
      lowerCAmelCase_			:      str			=   ids_tensor([self.batch_size, self.seq_length]    ,						self.vocab_size		)
      lowerCAmelCase_			:      str			=   random_attention_mask([self.batch_size, self.seq_length]		)

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

      lowerCAmelCase_			:      Optional[int]			=   None
      if self.use_token_type_ids:
        lowerCAmelCase_			:      str			=   ids_tensor([self.batch_size, self.seq_length]    ,						self.n_langs		)

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

      lowerCAmelCase_			:      List[str]			=   self.get_config()

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

    def __lowercase   (   self    :  Union[str, Any]		)   ->  Union[str, Any]:
      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 __lowercase   (   self    :  int    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  int    ,						)   ->  Tuple:
      lowerCAmelCase_			:      int			=   XLMModel(config=lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.eval()
      lowerCAmelCase_			:      int			=   model(lowerCamelCase    ,						lengths=lowerCamelCase    ,						langs=lowerCamelCase		)
      lowerCAmelCase_			:      List[Any]			=   model(lowerCamelCase    ,						langs=lowerCamelCase		)
      lowerCAmelCase_			:      Optional[int]			=   model(lowerCamelCase		)
      self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)		)

    def __lowercase   (   self    :  Optional[Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Union[str, Any]    ,						lowerCamelCase    :  Dict    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  Union[str, Any]    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  str    ,						)   ->  Dict:
      lowerCAmelCase_			:      str			=   XLMWithLMHeadModel(lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.eval()

      lowerCAmelCase_			:      Optional[Any]			=   model(lowerCamelCase    ,						token_type_ids=lowerCamelCase    ,						labels=lowerCamelCase		)
      self.parent.assertEqual(result.loss.shape    ,						()		)
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.seq_length, self.vocab_size)		)

    def __lowercase   (   self    :  str    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  Any    ,						lowerCamelCase    :  Any    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Dict    ,						)   ->  List[str]:
      lowerCAmelCase_			:      Optional[int]			=   XLMForQuestionAnsweringSimple(lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.eval()

      lowerCAmelCase_			:      Any			=   model(lowerCamelCase		)

      lowerCAmelCase_			:      Dict			=   model(lowerCamelCase    ,						start_positions=lowerCamelCase    ,						end_positions=lowerCamelCase		)
      lowerCAmelCase_			:      List[Any]			=   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 __lowercase   (   self    :  List[str]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  Dict    ,						lowerCamelCase    :  Dict    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  Tuple    ,						)   ->  Optional[Any]:
      lowerCAmelCase_			:      List[Any]			=   XLMForQuestionAnswering(lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.eval()

      lowerCAmelCase_			:      int			=   model(lowerCamelCase		)

      lowerCAmelCase_			:      Union[str, Any]			=   model(
          lowerCamelCase    ,						start_positions=lowerCamelCase    ,						end_positions=lowerCamelCase    ,						cls_index=lowerCamelCase    ,						is_impossible=lowerCamelCase    ,						p_mask=lowerCamelCase    ,						)

      lowerCAmelCase_			:      List[Any]			=   model(
          lowerCamelCase    ,						start_positions=lowerCamelCase    ,						end_positions=lowerCamelCase    ,						cls_index=lowerCamelCase    ,						is_impossible=lowerCamelCase    ,						)

      ((lowerCAmelCase_),							)			:      Any			=   result_with_labels.to_tuple()

      lowerCAmelCase_			:      Tuple			=   model(lowerCamelCase    ,						start_positions=lowerCamelCase    ,						end_positions=lowerCamelCase		)

      ((lowerCAmelCase_),							)			:      List[Any]			=   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 __lowercase   (   self    :  List[Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Union[str, Any]    ,						lowerCamelCase    :  Union[str, Any]    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  List[str]    ,						lowerCamelCase    :  str    ,						)   ->  Optional[int]:
      lowerCAmelCase_			:      Optional[int]			=   XLMForSequenceClassification(lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.eval()

      lowerCAmelCase_			:      str			=   model(lowerCamelCase		)
      lowerCAmelCase_			:      Optional[int]			=   model(lowerCamelCase    ,						labels=lowerCamelCase		)
      self.parent.assertEqual(result.loss.shape    ,						()		)
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.type_sequence_label_size)		)

    def __lowercase   (   self    :  Dict    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  List[str]    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  str    ,						)   ->  Union[str, Any]:
      lowerCAmelCase_			:      int			=   self.num_labels
      lowerCAmelCase_			:      str			=   XLMForTokenClassification(lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.eval()

      lowerCAmelCase_			:      List[str]			=   model(lowerCamelCase    ,						attention_mask=lowerCamelCase    ,						labels=lowerCamelCase		)
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.seq_length, self.num_labels)		)

    def __lowercase   (   self    :  int    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  Union[str, Any]    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  Any    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Union[str, Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[Any]    ,						)   ->  List[str]:
      lowerCAmelCase_			:      Optional[int]			=   self.num_choices
      lowerCAmelCase_			:      Union[str, Any]			=   XLMForMultipleChoice(config=lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.eval()
      lowerCAmelCase_			:      str			=   input_ids.unsqueeze(1		).expand(-1    ,						self.num_choices    ,						-1		).contiguous()
      lowerCAmelCase_			:      Optional[Any]			=   token_type_ids.unsqueeze(1		).expand(-1    ,						self.num_choices    ,						-1		).contiguous()
      lowerCAmelCase_			:      int			=   input_mask.unsqueeze(1		).expand(-1    ,						self.num_choices    ,						-1		).contiguous()
      lowerCAmelCase_			:      str			=   model(
          lowerCamelCase    ,						attention_mask=lowerCamelCase    ,						token_type_ids=lowerCamelCase    ,						labels=lowerCamelCase    ,						)
      self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_choices)		)





    def __lowercase   (   self    :  Optional[Any]		)   ->  Tuple:
      lowerCAmelCase_			:      Union[str, Any]			=   self.prepare_config_and_inputs()
      (
          (
          lowerCAmelCase_
      ),							(
          lowerCAmelCase_
      ),							(
          lowerCAmelCase_
      ),							(
          lowerCAmelCase_
      ),							(
          lowerCAmelCase_
      ),							(
          lowerCAmelCase_
      ),							(
          lowerCAmelCase_
      ),							(
          lowerCAmelCase_
      ),							(
          lowerCAmelCase_
      ),							
      )			:      Optional[Any]			=   config_and_inputs
      lowerCAmelCase_			:      Tuple			=   {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """lengths""": input_lengths}
      return config, inputs_dict







@require_torch
class    __snake_case       (   _SCREAMING_SNAKE_CASE	,_SCREAMING_SNAKE_CASE	,_SCREAMING_SNAKE_CASE	,unittest.TestCase):







    """simple docstring"""



    lowercase    =					(
        (
            XLMModel,
            XLMWithLMHeadModel,
            XLMForQuestionAnswering,
            XLMForSequenceClassification,
            XLMForQuestionAnsweringSimple,
            XLMForTokenClassification,
            XLMForMultipleChoice,
        )
        if is_torch_available()
        else ()
    )
    lowercase    =					(
        (XLMWithLMHeadModel,) if is_torch_available() else ()
    )  # TODO (PVP): Check other models whether language generation is also applicable
    lowercase    =					(
        {
            '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 __lowercase   (   self    :  int    ,						lowerCamelCase    :  Any    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  List[str]    ,						lowerCamelCase    :  Dict		)   ->  Any:
      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 __lowercase   (   self    :  Union[str, Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Any=False		)   ->  Union[str, Any]:
      lowerCAmelCase_			:      str			=   super()._prepare_for_class(lowerCamelCase    ,						lowerCamelCase    ,						return_labels=lowerCamelCase		)

      if return_labels:
        if model_class.__name__ == "XLMForQuestionAnswering":
          lowerCAmelCase_			:      List[Any]			=   torch.zeros(
              self.model_tester.batch_size    ,						dtype=torch.long    ,						device=lowerCamelCase		)
          lowerCAmelCase_			:      List[Any]			=   torch.zeros(
              self.model_tester.batch_size    ,						dtype=torch.long    ,						device=lowerCamelCase		)

      return inputs_dict

    def __lowercase   (   self    :  Optional[Any]		)   ->  Optional[int]:
      lowerCAmelCase_			:      Union[str, Any]			=   XLMModelTester(self		)
      lowerCAmelCase_			:      Tuple			=   ConfigTester(self    ,						config_class=lowerCamelCase    ,						emb_dim=37		)

    def __lowercase   (   self    :  Tuple		)   ->  Optional[int]:
      self.config_tester.run_common_tests()

    def __lowercase   (   self    :  Optional[int]		)   ->  List[str]:
      lowerCAmelCase_			:      Any			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_model(*lowerCamelCase		)

    def __lowercase   (   self    :  Optional[int]		)   ->  int:
      lowerCAmelCase_			:      Optional[Any]			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_lm_head(*lowerCamelCase		)

    def __lowercase   (   self    :  Tuple		)   ->  List[Any]:
      lowerCAmelCase_			:      Any			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_simple_qa(*lowerCamelCase		)

    def __lowercase   (   self    :  Tuple		)   ->  Optional[int]:
      lowerCAmelCase_			:      int			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_qa(*lowerCamelCase		)

    def __lowercase   (   self    :  Any		)   ->  Union[str, Any]:
      lowerCAmelCase_			:      Dict			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_sequence_classif(*lowerCamelCase		)

    def __lowercase   (   self    :  str		)   ->  Dict:
      lowerCAmelCase_			:      Union[str, Any]			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_token_classif(*lowerCamelCase		)

    def __lowercase   (   self    :  Tuple		)   ->  Optional[int]:
      lowerCAmelCase_			:      Optional[int]			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_xlm_for_multiple_choice(*lowerCamelCase		)

    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  int    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Tuple=False    ,						lowerCamelCase    :  Dict=1		)   ->  List[Any]:
      self.assertIsInstance(lowerCamelCase    ,						lowerCamelCase		)
      self.assertListEqual(
          [isinstance(lowerCamelCase    ,						lowerCamelCase		) for iter_attentions in attentions]    ,						[True] * len(lowerCamelCase		)		)
      self.assertEqual(len(lowerCamelCase		)    ,						(max_length - min_length) * num_beam_groups		)

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

        lowerCAmelCase_			:      str			=   (
            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(lowerCamelCase		)		)

    def __lowercase   (   self    :  List[Any]    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  Any    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  Union[str, Any]    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  Dict=False    ,						lowerCamelCase    :  Optional[int]=1		)   ->  Dict:
      self.assertIsInstance(lowerCamelCase    ,						lowerCamelCase		)
      self.assertListEqual(
          [isinstance(lowerCamelCase    ,						lowerCamelCase		) for iter_hidden_states in hidden_states]    ,						[True] * len(lowerCamelCase		)    ,						)
      self.assertEqual(len(lowerCamelCase		)    ,						(max_length - min_length) * num_beam_groups		)

      for idx, iter_hidden_states in enumerate(lowerCamelCase		):
        # adds PAD dummy token
        lowerCAmelCase_			:      str			=   min_length + idx + 1
        lowerCAmelCase_			:      Tuple			=   (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(lowerCamelCase		)    ,						)
      pass





    @slow
    def __lowercase   (   self    :  Optional[int]		)   ->  Tuple:
      for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCAmelCase_			:      Dict			=   XLMModel.from_pretrained(lowerCamelCase		)
        self.assertIsNotNone(lowerCamelCase		)







@require_torch
class    __snake_case       (   unittest.TestCase):







    """simple docstring"""



    @slow
    def __lowercase   (   self    :  Optional[int]		)   ->  Optional[int]:
      lowerCAmelCase_			:      Dict			=   XLMWithLMHeadModel.from_pretrained("""xlm-mlm-en-2048"""		)
      model.to(lowerCamelCase		)
      lowerCAmelCase_			:      str			=   torch.tensor([[14, 4_47]]    ,						dtype=torch.long    ,						device=lowerCamelCase		)  # the president
      lowerCAmelCase_			:      Any			=   [
          14,
          4_47,
          14,
          4_47,
          14,
          4_47,
          14,
          4_47,
          14,
          4_47,
          14,
          4_47,
          14,
          4_47,
          14,
          4_47,
          14,
          4_47,
          14,
          4_47,
      ]  # 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
      lowerCAmelCase_			:      Dict			=   model.generate(lowerCamelCase    ,						do_sample=lowerCamelCase		)
      self.assertListEqual(output_ids[0].cpu().numpy().tolist()    ,						lowerCamelCase		)







'''simple docstring'''






from sklearn.metrics import recall_score

import datasets


__A					:  Dict											=      "\nRecall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:\nRecall = TP / (TP + FN)\nWhere TP is the true positives and FN is the false negatives.\n"


__A					:  List[Any]											=      "\nArgs:\n- **predictions** (`list` of `int`): The predicted labels.\n- **references** (`list` of `int`): The ground truth labels.\n- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.\n- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.\n- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.\n    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.\n    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.\n    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.\n- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .\n    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.\n    - `0`: If there is a zero division, the return value is `0`.\n    - `1`: If there is a zero division, the return value is `1`.\n\nReturns:\n- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.\n\nExamples:\n\n    Example 1-A simple example with some errors\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])\n        >>> print(results)\n        {'recall': 0.6666666666666666}\n\n    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)\n        >>> print(results)\n        {'recall': 0.5}\n\n    Example 3-The same example as Example 1, but with `sample_weight` included.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]\n        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)\n        >>> print(results)\n        {'recall': 0.55}\n\n    Example 4-A multiclass example, using different averages.\n        >>> recall_metric = datasets.load_metric('recall')\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'recall': 0.3333333333333333}\n        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print(results)\n        {'recall': array([1., 0., 0.])}\n"


__A					:  str											=      "\n@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}\n"






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







    """simple docstring"""



    def __lowercase   (   self    :  str		)   ->  Dict:
      return datasets.MetricInfo(
          description=_DESCRIPTION    ,						citation=_CITATION    ,						inputs_description=_KWARGS_DESCRIPTION    ,						features=datasets.Features(
              {
                  """predictions""": datasets.Sequence(datasets.Value("""int32"""		)		),
                  """references""": datasets.Sequence(datasets.Value("""int32"""		)		),
              }
              if self.config_name == """multilabel"""
              else {
                  """predictions""": datasets.Value("""int32"""		),
                  """references""": datasets.Value("""int32"""		),
              }		)    ,						reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"""]    ,						)





    def __lowercase   (   self    :  Tuple    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[Any]=None    ,						lowerCamelCase    :  Optional[int]=1    ,						lowerCamelCase    :  Union[str, Any]="binary"    ,						lowerCamelCase    :  Any=None    ,						lowerCamelCase    :  str="warn"    ,						)   ->  List[Any]:
      lowerCAmelCase_			:      Optional[int]			=   recall_score(
          lowerCamelCase    ,						lowerCamelCase    ,						labels=lowerCamelCase    ,						pos_label=lowerCamelCase    ,						average=lowerCamelCase    ,						sample_weight=lowerCamelCase    ,						zero_division=lowerCamelCase    ,						)
      return {"recall": float(lowerCamelCase		) if score.size == 1 else score}



