



"""simple docstring"""







from sklearn.metrics import recall_score

import datasets


lowercase__		:    Any				   =     """
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


lowercase__		:    Any				   =     """
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **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.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **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'`.
    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
    - `'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.
    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **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.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


lowercase__		:    Dict				   =     """
@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}
"""







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




      """simple docstring"""




      def 					SCREAMING_SNAKE_CASE__			(				self    :				int	):
        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 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				int=None   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=1   ,      SCREAMING_SNAKE_CASE_    :				str="binary"   ,      SCREAMING_SNAKE_CASE_    :				Tuple=None   ,      SCREAMING_SNAKE_CASE_    :				Tuple="warn"   ,      ):
        lowerCAmelCase_       :    Dict								=			recall_score(
            SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_   ,      pos_label=SCREAMING_SNAKE_CASE_   ,      average=SCREAMING_SNAKE_CASE_   ,      sample_weight=SCREAMING_SNAKE_CASE_   ,      zero_division=SCREAMING_SNAKE_CASE_   ,      )
        return {"recall": float(SCREAMING_SNAKE_CASE_	) if score.size == 1 else score}










"""simple docstring"""







import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

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


if is_torch_available():
     import torch

     from transformers import (
         FlaubertForMultipleChoice,
         FlaubertForQuestionAnswering,
         FlaubertForQuestionAnsweringSimple,
         FlaubertForSequenceClassification,
         FlaubertForTokenClassification,
         FlaubertModel,
         FlaubertWithLMHeadModel,
     )
     from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=1_3   ,      SCREAMING_SNAKE_CASE_    :				Dict=7   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=True   ,      SCREAMING_SNAKE_CASE_    :				List[str]=True   ,      SCREAMING_SNAKE_CASE_    :				Dict=True   ,      SCREAMING_SNAKE_CASE_    :				Dict=True   ,      SCREAMING_SNAKE_CASE_    :				List[str]=True   ,      SCREAMING_SNAKE_CASE_    :				str=False   ,      SCREAMING_SNAKE_CASE_    :				str=False   ,      SCREAMING_SNAKE_CASE_    :				Any=False   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=2   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=9_9   ,      SCREAMING_SNAKE_CASE_    :				Dict=0   ,      SCREAMING_SNAKE_CASE_    :				int=3_2   ,      SCREAMING_SNAKE_CASE_    :				Dict=5   ,      SCREAMING_SNAKE_CASE_    :				Dict=4   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=0.1   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=0.1   ,      SCREAMING_SNAKE_CASE_    :				List[str]=5_1_2   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=1_2   ,      SCREAMING_SNAKE_CASE_    :				Tuple=2   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=0.02   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=3   ,      SCREAMING_SNAKE_CASE_    :				int=4   ,      SCREAMING_SNAKE_CASE_    :				List[Any]="last"   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=None   ,      SCREAMING_SNAKE_CASE_    :				str=None   ,      ):
        lowerCAmelCase_       :    Tuple								=			parent
        lowerCAmelCase_       :    Tuple								=			batch_size
        lowerCAmelCase_       :    str								=			seq_length
        lowerCAmelCase_       :    List[Any]								=			is_training
        lowerCAmelCase_       :    Optional[int]								=			use_input_lengths
        lowerCAmelCase_       :    Union[str, Any]								=			use_token_type_ids
        lowerCAmelCase_       :    str								=			use_labels
        lowerCAmelCase_       :    str								=			gelu_activation
        lowerCAmelCase_       :    str								=			sinusoidal_embeddings
        lowerCAmelCase_       :    List[Any]								=			causal
        lowerCAmelCase_       :    Union[str, Any]								=			asm
        lowerCAmelCase_       :    Union[str, Any]								=			n_langs
        lowerCAmelCase_       :    Optional[Any]								=			vocab_size
        lowerCAmelCase_       :    Any								=			n_special
        lowerCAmelCase_       :    Union[str, Any]								=			hidden_size
        lowerCAmelCase_       :    str								=			num_hidden_layers
        lowerCAmelCase_       :    Tuple								=			num_attention_heads
        lowerCAmelCase_       :    Optional[Any]								=			hidden_dropout_prob
        lowerCAmelCase_       :    List[Any]								=			attention_probs_dropout_prob
        lowerCAmelCase_       :    Dict								=			max_position_embeddings
        lowerCAmelCase_       :    Union[str, Any]								=			type_vocab_size
        lowerCAmelCase_       :    List[Any]								=			type_sequence_label_size
        lowerCAmelCase_       :    str								=			initializer_range
        lowerCAmelCase_       :    Dict								=			num_labels
        lowerCAmelCase_       :    Union[str, Any]								=			num_choices
        lowerCAmelCase_       :    Union[str, Any]								=			summary_type
        lowerCAmelCase_       :    Optional[Any]								=			use_proj
        lowerCAmelCase_       :    List[Any]								=			scope



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    List[Any]								=			ids_tensor([self.batch_size, self.seq_length]   ,      self.vocab_size	)
        lowerCAmelCase_       :    str								=			random_attention_mask([self.batch_size, self.seq_length]	)

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

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

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

        lowerCAmelCase_       :    Union[str, 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 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        return FlaubertConfig(
            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   ,      )



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				str   ,      ):
        lowerCAmelCase_       :    Union[str, Any]								=			FlaubertModel(config=SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()
        lowerCAmelCase_       :    Any								=			model(SCREAMING_SNAKE_CASE_   ,      lengths=SCREAMING_SNAKE_CASE_   ,      langs=SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Any								=			model(SCREAMING_SNAKE_CASE_   ,      langs=SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Optional[Any]								=			model(SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.last_hidden_state.shape   ,      (self.batch_size, self.seq_length, self.hidden_size)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      ):
        lowerCAmelCase_       :    Any								=			FlaubertWithLMHeadModel(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    Dict								=			model(SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.loss.shape   ,      ()	)
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.seq_length, self.vocab_size)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				int   ,      ):
        lowerCAmelCase_       :    Tuple								=			FlaubertForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    Union[str, Any]								=			model(SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    Optional[int]								=			model(SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_	)
        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 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      ):
        lowerCAmelCase_       :    Optional[int]								=			FlaubertForQuestionAnswering(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    int								=			model(SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    Any								=			model(
            SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_   ,      cls_index=SCREAMING_SNAKE_CASE_   ,      is_impossible=SCREAMING_SNAKE_CASE_   ,      p_mask=SCREAMING_SNAKE_CASE_   ,      )

        lowerCAmelCase_       :    Optional[int]								=			model(
            SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_   ,      cls_index=SCREAMING_SNAKE_CASE_   ,      is_impossible=SCREAMING_SNAKE_CASE_   ,      )

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

        lowerCAmelCase_       :    int								=			model(SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_	)

        ((lowerCAmelCase_)						,)       :    Dict								=			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 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      ):
        lowerCAmelCase_       :    Optional[int]								=			FlaubertForSequenceClassification(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    Any								=			model(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    List[Any]								=			model(SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)

        self.parent.assertEqual(result.loss.shape   ,      ()	)
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.type_sequence_label_size)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      ):
        lowerCAmelCase_       :    List[Any]								=			self.num_labels
        lowerCAmelCase_       :    Optional[Any]								=			FlaubertForTokenClassification(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

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



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





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
        lowerCAmelCase_       :    List[Any]								=			self.prepare_config_and_inputs()
        (
            (
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,
        )       :    Dict								=			config_and_inputs
        lowerCAmelCase_       :    List[str]								=			{
            'input_ids': input_ids,
            'token_type_ids': token_type_ids,
            'lengths': input_lengths,
            'attention_mask': input_mask,
        }
        return config, inputs_dict







@require_torch
class 				UpperCamelCase__       (     lowercase_, lowercase_, unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					(
          (
              FlaubertModel,
              FlaubertWithLMHeadModel,
              FlaubertForQuestionAnswering,
              FlaubertForQuestionAnsweringSimple,
              FlaubertForSequenceClassification,
              FlaubertForTokenClassification,
              FlaubertForMultipleChoice,
          )
          if is_torch_available()
          else ()
      )
      _SCREAMING_SNAKE_CASE      =					(
          {
              """feature-extraction""": FlaubertModel,
              """fill-mask""": FlaubertWithLMHeadModel,
              """question-answering""": FlaubertForQuestionAnsweringSimple,
              """text-classification""": FlaubertForSequenceClassification,
              """token-classification""": FlaubertForTokenClassification,
              """zero-shot""": FlaubertForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Union[str, 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 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=False	):
        lowerCAmelCase_       :    Any								=			super()._prepare_for_class(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      return_labels=SCREAMING_SNAKE_CASE_	)

        if return_labels:
          if model_class.__name__ == "FlaubertForQuestionAnswering":
            lowerCAmelCase_       :    Tuple								=			torch.zeros(
                self.model_tester.batch_size   ,      dtype=torch.long   ,      device=SCREAMING_SNAKE_CASE_	)
            lowerCAmelCase_       :    int								=			torch.zeros(
                self.model_tester.batch_size   ,      dtype=torch.long   ,      device=SCREAMING_SNAKE_CASE_	)

        return inputs_dict



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        lowerCAmelCase_       :    Tuple								=			FlaubertModelTester(self	)
        lowerCAmelCase_       :    str								=			ConfigTester(self   ,      config_class=SCREAMING_SNAKE_CASE_   ,      emb_dim=3_7	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        self.config_tester.run_common_tests()



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
        lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_model(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
        lowerCAmelCase_       :    str								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_lm_head(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
        lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_simple_qa(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
        lowerCAmelCase_       :    List[str]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_qa(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):
        lowerCAmelCase_       :    Optional[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_sequence_classif(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        lowerCAmelCase_       :    Dict								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_token_classif(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
        lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_multiple_choice(*SCREAMING_SNAKE_CASE_	)



      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_       :    Optional[Any]								=			FlaubertModel.from_pretrained(SCREAMING_SNAKE_CASE_	)
          self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)





      @slow
      @require_torch_gpu
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        lowerCAmelCase_						,lowerCAmelCase_       :    Any								=			self.model_tester.prepare_config_and_inputs_for_common()
        for model_class in self.all_model_classes:
          # FlauBertForMultipleChoice behaves incorrectly in JIT environments.
          if model_class == FlaubertForMultipleChoice:
            return

          lowerCAmelCase_       :    int								=			True
          lowerCAmelCase_       :    Union[str, Any]								=			model_class(config=SCREAMING_SNAKE_CASE_	)

          lowerCAmelCase_       :    Any								=			self._prepare_for_class(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
          lowerCAmelCase_       :    int								=			torch.jit.trace(
              SCREAMING_SNAKE_CASE_   ,      (inputs_dict['input_ids'].to('cpu'	), inputs_dict['attention_mask'].to('cpu'	))	)

          with tempfile.TemporaryDirectory() as tmp:
            torch.jit.save(SCREAMING_SNAKE_CASE_   ,      os.path.join(SCREAMING_SNAKE_CASE_   ,      'traced_model.pt'	)	)
            lowerCAmelCase_       :    Optional[Any]								=			torch.jit.load(os.path.join(SCREAMING_SNAKE_CASE_   ,      'traced_model.pt'	)   ,      map_location=SCREAMING_SNAKE_CASE_	)
            loaded(inputs_dict['input_ids'].to(SCREAMING_SNAKE_CASE_	)   ,      inputs_dict['attention_mask'].to(SCREAMING_SNAKE_CASE_	)	)







@require_torch
class 				UpperCamelCase__       (     unittest.TestCase  ):




      """simple docstring"""




      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        lowerCAmelCase_       :    int								=			FlaubertModel.from_pretrained('flaubert/flaubert_base_cased'	)
        lowerCAmelCase_       :    List[Any]								=			torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]	)
        with torch.no_grad():
          lowerCAmelCase_       :    Optional[Any]								=			model(SCREAMING_SNAKE_CASE_	)[0]
        lowerCAmelCase_       :    Optional[Any]								=			torch.Size((1, 1_1, 7_6_8)	)
        self.assertEqual(output.shape   ,      SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Optional[int]								=			torch.tensor(
            [[[-2.62_51, -1.42_98, -0.02_27], [-2.85_10, -1.63_87, 0.22_58], [-2.81_14, -1.18_32, -0.30_66]]]	)

        self.assertTrue(torch.allclose(output[:, :3, :3]   ,      SCREAMING_SNAKE_CASE_   ,      atol=1E-4	)	)





