






"""simple docstring"""
import argparse
import os

from . import (
    ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AlbertConfig,
    BartConfig,
    BertConfig,
    CamembertConfig,
    CTRLConfig,
    DistilBertConfig,
    DPRConfig,
    ElectraConfig,
    FlaubertConfig,
    GPTaConfig,
    LayoutLMConfig,
    LxmertConfig,
    OpenAIGPTConfig,
    RobertaConfig,
    TaConfig,
    TFAlbertForPreTraining,
    TFBartForConditionalGeneration,
    TFBartForSequenceClassification,
    TFBertForPreTraining,
    TFBertForQuestionAnswering,
    TFBertForSequenceClassification,
    TFCamembertForMaskedLM,
    TFCTRLLMHeadModel,
    TFDistilBertForMaskedLM,
    TFDistilBertForQuestionAnswering,
    TFDPRContextEncoder,
    TFDPRQuestionEncoder,
    TFDPRReader,
    TFElectraForPreTraining,
    TFFlaubertWithLMHeadModel,
    TFGPTaLMHeadModel,
    TFLayoutLMForMaskedLM,
    TFLxmertForPreTraining,
    TFLxmertVisualFeatureEncoder,
    TFOpenAIGPTLMHeadModel,
    TFRobertaForCausalLM,
    TFRobertaForMaskedLM,
    TFRobertaForSequenceClassification,
    TFTaForConditionalGeneration,
    TFTransfoXLLMHeadModel,
    TFWavaVecaModel,
    TFXLMRobertaForMaskedLM,
    TFXLMWithLMHeadModel,
    TFXLNetLMHeadModel,
    TransfoXLConfig,
    WavaVecaConfig,
    WavaVecaModel,
    XLMConfig,
    XLMRobertaConfig,
    XLNetConfig,
    is_torch_available,
    load_pytorch_checkpoint_in_tfa_model,
)
from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging


if is_torch_available():
 import numpy as np
 import torch

 from . import (
     AlbertForPreTraining,
     BartForConditionalGeneration,
     BertForPreTraining,
     BertForQuestionAnswering,
     BertForSequenceClassification,
     CamembertForMaskedLM,
     CTRLLMHeadModel,
     DistilBertForMaskedLM,
     DistilBertForQuestionAnswering,
     DPRContextEncoder,
     DPRQuestionEncoder,
     DPRReader,
     ElectraForPreTraining,
     FlaubertWithLMHeadModel,
     GPTaLMHeadModel,
     LayoutLMForMaskedLM,
     LxmertForPreTraining,
     LxmertVisualFeatureEncoder,
     OpenAIGPTLMHeadModel,
     RobertaForMaskedLM,
     RobertaForSequenceClassification,
     TaForConditionalGeneration,
     TransfoXLLMHeadModel,
     XLMRobertaForMaskedLM,
     XLMWithLMHeadModel,
     XLNetLMHeadModel,
 )


logging.set_verbosity_info()

snake_case : Dict     		=		{
    """bart""": (
        BartConfig,
        TFBartForConditionalGeneration,
        TFBartForSequenceClassification,
        BartForConditionalGeneration,
        BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    """bert""": (
        BertConfig,
        TFBertForPreTraining,
        BertForPreTraining,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """bert-large-uncased-whole-word-masking-finetuned-squad""": (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """bert-large-cased-whole-word-masking-finetuned-squad""": (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """bert-base-cased-finetuned-mrpc""": (
        BertConfig,
        TFBertForSequenceClassification,
        BertForSequenceClassification,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """dpr""": (
        DPRConfig,
        TFDPRQuestionEncoder,
        TFDPRContextEncoder,
        TFDPRReader,
        DPRQuestionEncoder,
        DPRContextEncoder,
        DPRReader,
        DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    """gpt2""": (
        GPTaConfig,
        TFGPTaLMHeadModel,
        GPTaLMHeadModel,
        GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """xlnet""": (
        XLNetConfig,
        TFXLNetLMHeadModel,
        XLNetLMHeadModel,
        XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """xlm""": (
        XLMConfig,
        TFXLMWithLMHeadModel,
        XLMWithLMHeadModel,
        XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """xlm-roberta""": (
        XLMRobertaConfig,
        TFXLMRobertaForMaskedLM,
        XLMRobertaForMaskedLM,
        XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """transfo-xl""": (
        TransfoXLConfig,
        TFTransfoXLLMHeadModel,
        TransfoXLLMHeadModel,
        TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """openai-gpt""": (
        OpenAIGPTConfig,
        TFOpenAIGPTLMHeadModel,
        OpenAIGPTLMHeadModel,
        OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """roberta""": (
        RobertaConfig,
        TFRobertaForCausalLM,
        TFRobertaForMaskedLM,
        RobertaForMaskedLM,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """layoutlm""": (
        LayoutLMConfig,
        TFLayoutLMForMaskedLM,
        LayoutLMForMaskedLM,
        LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    """roberta-large-mnli""": (
        RobertaConfig,
        TFRobertaForSequenceClassification,
        RobertaForSequenceClassification,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """camembert""": (
        CamembertConfig,
        TFCamembertForMaskedLM,
        CamembertForMaskedLM,
        CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """flaubert""": (
        FlaubertConfig,
        TFFlaubertWithLMHeadModel,
        FlaubertWithLMHeadModel,
        FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """distilbert""": (
        DistilBertConfig,
        TFDistilBertForMaskedLM,
        DistilBertForMaskedLM,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """distilbert-base-distilled-squad""": (
        DistilBertConfig,
        TFDistilBertForQuestionAnswering,
        DistilBertForQuestionAnswering,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """lxmert""": (
        LxmertConfig,
        TFLxmertForPreTraining,
        LxmertForPreTraining,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """lxmert-visual-feature-encoder""": (
        LxmertConfig,
        TFLxmertVisualFeatureEncoder,
        LxmertVisualFeatureEncoder,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """ctrl""": (
        CTRLConfig,
        TFCTRLLMHeadModel,
        CTRLLMHeadModel,
        CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """albert""": (
        AlbertConfig,
        TFAlbertForPreTraining,
        AlbertForPreTraining,
        ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """t5""": (
        TaConfig,
        TFTaForConditionalGeneration,
        TaForConditionalGeneration,
        T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """electra""": (
        ElectraConfig,
        TFElectraForPreTraining,
        ElectraForPreTraining,
        ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    """wav2vec2""": (
        WavaVecaConfig,
        TFWavaVecaModel,
        WavaVecaModel,
        WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
}


def 							A						(				__snake_case: Tuple ,     __snake_case: str ,     __snake_case: List[Any] ,     __snake_case: int ,     __snake_case: Dict=False ,     __snake_case: int=True  )    ->		List[str]:

       """simple docstring"""





       if model_type not in MODEL_CLASSES:
              raise ValueError(F"""Unrecognized model type, should be one of {list(MODEL_CLASSES.keys()  )}."""  )

       __magic_name__				,  __magic_name__				,  __magic_name__				,  __magic_name__      				=    MODEL_CLASSES[model_type]

       # Initialise TF model
       if config_file in aws_config_map:
              __magic_name__      				=    cached_file(__snake_case ,     __snake_case ,     force_download=not use_cached_models  )
       __magic_name__      				=    config_class.from_json_file(__snake_case  )
       __magic_name__      				=    True
       __magic_name__      				=    True
       print(F"""Building TensorFlow model from configuration: {config}"""  )
       __magic_name__      				=    model_class(__snake_case  )

       # Load weights from tf checkpoint
       if pytorch_checkpoint_path in aws_config_map.keys():
              __magic_name__      				=    cached_file(
                  __snake_case ,     __snake_case ,     force_download=not use_cached_models  )
       # Load PyTorch checkpoint in tf2 model:
       __magic_name__      				=    load_pytorch_checkpoint_in_tfa_model(__snake_case ,     __snake_case  )

       if compare_with_pt_model:
              __magic_name__      				=    tf_model(tf_model.dummy_inputs ,     training=__snake_case  )  # build the network

              __magic_name__      				=    torch.load(__snake_case ,     map_location='cpu'  )
              __magic_name__      				=    pt_model_class.from_pretrained(
                  pretrained_model_name_or_path=__snake_case ,     config=__snake_case ,     state_dict=__snake_case  )

              with torch.no_grad():
                     __magic_name__      				=    pt_model(**pt_model.dummy_inputs  )

              __magic_name__      				=    pto[0].numpy()
              __magic_name__      				=    tfo[0].numpy()
              __magic_name__      				=    np.amax(np.abs(np_pt - np_tf  )  )
              print(F"""Max absolute difference between models outputs {diff}"""  )
              assert diff <= 2E-2, F"""Error, model absolute difference is >2e-2: {diff}"""

       # Save pytorch-model
       print(F"""Save TensorFlow model to {tf_dump_path}"""  )
       tf_model.save_weights(__snake_case ,     save_format='h5'  )


def 							A						(				__snake_case: Dict ,     __snake_case: int ,     __snake_case: Union[str, Any]=None ,     __snake_case: Any=None ,     __snake_case: Union[str, Any]=False ,     __snake_case: List[Any]=False ,     __snake_case: Union[str, Any]=False ,     __snake_case: Dict=False ,     )    ->		Tuple:

       """simple docstring"""





       if args_model_type is None:
              __magic_name__      				=    list(MODEL_CLASSES.keys()  )
       else:
              __magic_name__      				=    [args_model_type]

       for j, model_type in enumerate(__snake_case ,     start=1  ):
              print('=' * 1_0_0  )
              print(F""" Converting model type {j}/{len(__snake_case  )}: {model_type}"""  )
              print('=' * 1_0_0  )
              if model_type not in MODEL_CLASSES:
                     raise ValueError(F"""Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys()  )}."""  )

              __magic_name__				,  __magic_name__				,  __magic_name__				,  __magic_name__				,  __magic_name__      				=    MODEL_CLASSES[model_type]

              if model_shortcut_names_or_path is None:
                     __magic_name__      				=    list(aws_model_maps.keys()  )
              if config_shortcut_names_or_path is None:
                     __magic_name__      				=    model_shortcut_names_or_path

              for i, (model_shortcut_name, config_shortcut_name) in enumerate(
                  zip(__snake_case ,     __snake_case  ) ,     start=1  ):
                     print('-' * 1_0_0  )
                     if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name:
                            if not only_convert_finetuned_models:
                                   print(F"""    Skipping finetuned checkpoint {model_shortcut_name}"""  )
                                   continue
                            __magic_name__      				=    model_shortcut_name
                     elif only_convert_finetuned_models:
                            print(F"""    Skipping not finetuned checkpoint {model_shortcut_name}"""  )
                            continue
                     print(
                         F"""    Converting checkpoint {i}/{len(__snake_case  )}: {model_shortcut_name} - model_type {model_type}"""  )
                     print('-' * 1_0_0  )

                     if config_shortcut_name in aws_config_map:
                            __magic_name__      				=    cached_file(__snake_case ,     __snake_case ,     force_download=not use_cached_models  )
                     else:
                            __magic_name__      				=    config_shortcut_name

                     if model_shortcut_name in aws_model_maps:
                            __magic_name__      				=    cached_file(__snake_case ,     __snake_case ,     force_download=not use_cached_models  )
                     else:
                            __magic_name__      				=    model_shortcut_name

                     if os.path.isfile(__snake_case  ):
                            __magic_name__      				=    'converted_model'

                     convert_pt_checkpoint_to_tf(
                         model_type=__snake_case ,     pytorch_checkpoint_path=__snake_case ,     config_file=__snake_case ,     tf_dump_path=os.path.join(__snake_case ,     model_shortcut_name + '-tf_model.h5'  ) ,     compare_with_pt_model=__snake_case ,     )
                     if remove_cached_files:
                            os.remove(__snake_case  )
                            os.remove(__snake_case  )


if __name__ == "__main__":
 snake_case : Union[str, Any]     		=		argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     """--tf_dump_path""", default=None, type=str, required=True, help="""Path to the output Tensorflow dump file."""
 )
 parser.add_argument(
     """--model_type""",
     default=None,
     type=str,
     help=(
         f"""Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and """
         """convert all the models from AWS."""
     ),
 )
 parser.add_argument(
     """--pytorch_checkpoint_path""",
     default=None,
     type=str,
     help=(
         """Path to the PyTorch checkpoint path or shortcut name to download from AWS. """
         """If not given, will download and convert all the checkpoints from AWS."""
     ),
 )
 parser.add_argument(
     """--config_file""",
     default=None,
     type=str,
     help=(
         """The config json file corresponding to the pre-trained model. \n"""
         """This specifies the model architecture. If not given and """
         """--pytorch_checkpoint_path is not given or is a shortcut name """
         """use the configuration associated to the shortcut name on the AWS"""
     ),
 )
 parser.add_argument(
     """--compare_with_pt_model""", action="""store_true""", help="""Compare Tensorflow and PyTorch model predictions."""
 )
 parser.add_argument(
     """--use_cached_models""",
     action="""store_true""",
     help="""Use cached models if possible instead of updating to latest checkpoint versions.""",
 )
 parser.add_argument(
     """--remove_cached_files""",
     action="""store_true""",
     help="""Remove pytorch models after conversion (save memory when converting in batches).""",
 )
 parser.add_argument("""--only_convert_finetuned_models""", action="""store_true""", help="""Only convert finetuned models.""")
 snake_case : Dict     		=		parser.parse_args()

 # if args.pytorch_checkpoint_path is not None:
 #     convert_pt_checkpoint_to_tf(args.model_type.lower(),
 #                                 args.pytorch_checkpoint_path,
 #                                 args.config_file if args.config_file is not None else args.pytorch_checkpoint_path,
 #                                 args.tf_dump_path,
 #                                 compare_with_pt_model=args.compare_with_pt_model,
 #                                 use_cached_models=args.use_cached_models)
 # else:
 convert_all_pt_checkpoints_to_tf(
     args.model_type.lower() if args.model_type is not None else None,
     args.tf_dump_path,
     model_shortcut_names_or_path=[args.pytorch_checkpoint_path]
     if args.pytorch_checkpoint_path is not None
     else None,
     config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None,
     compare_with_pt_model=args.compare_with_pt_model,
     use_cached_models=args.use_cached_models,
     remove_cached_files=args.remove_cached_files,
     only_convert_finetuned_models=args.only_convert_finetuned_models,
 )







"""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__ (				a_):







    """simple docstring"""







    def __init__(		self :	List[str]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Optional[int]=1_3				,    UpperCamelCase_ :	Dict=7				,    UpperCamelCase_ :	Dict=True				,    UpperCamelCase_ :	Optional[Any]=True				,    UpperCamelCase_ :	Union[str, Any]=True				,    UpperCamelCase_ :	Dict=True				,    UpperCamelCase_ :	Optional[int]=True				,    UpperCamelCase_ :	Tuple=False				,    UpperCamelCase_ :	Union[str, Any]=False				,    UpperCamelCase_ :	Any=False				,    UpperCamelCase_ :	Tuple=2				,    UpperCamelCase_ :	List[Any]=9_9				,    UpperCamelCase_ :	List[Any]=0				,    UpperCamelCase_ :	Tuple=3_2				,    UpperCamelCase_ :	Any=5				,    UpperCamelCase_ :	Dict=4				,    UpperCamelCase_ :	Tuple=0.1				,    UpperCamelCase_ :	Any=0.1				,    UpperCamelCase_ :	Optional[Any]=5_1_2				,    UpperCamelCase_ :	Union[str, Any]=1_2				,    UpperCamelCase_ :	List[str]=2				,    UpperCamelCase_ :	str=0.02				,    UpperCamelCase_ :	List[str]=3				,    UpperCamelCase_ :	Dict=4				,    UpperCamelCase_ :	Optional[int]="last"				,    UpperCamelCase_ :	List[str]=None				,    UpperCamelCase_ :	Tuple=None				,    ):





           '''simple docstring'''

           __magic_name__      				=    parent
           __magic_name__      				=    batch_size
           __magic_name__      				=    seq_length
           __magic_name__      				=    is_training
           __magic_name__      				=    use_input_lengths
           __magic_name__      				=    use_token_type_ids
           __magic_name__      				=    use_labels
           __magic_name__      				=    gelu_activation
           __magic_name__      				=    sinusoidal_embeddings
           __magic_name__      				=    causal
           __magic_name__      				=    asm
           __magic_name__      				=    n_langs
           __magic_name__      				=    vocab_size
           __magic_name__      				=    n_special
           __magic_name__      				=    hidden_size
           __magic_name__      				=    num_hidden_layers
           __magic_name__      				=    num_attention_heads
           __magic_name__      				=    hidden_dropout_prob
           __magic_name__      				=    attention_probs_dropout_prob
           __magic_name__      				=    max_position_embeddings
           __magic_name__      				=    type_vocab_size
           __magic_name__      				=    type_sequence_label_size
           __magic_name__      				=    initializer_range
           __magic_name__      				=    num_labels
           __magic_name__      				=    num_choices
           __magic_name__      				=    summary_type
           __magic_name__      				=    use_proj
           __magic_name__      				=    scope







    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           __magic_name__      				=    ids_tensor([self.batch_size, self.seq_length]				,    self.vocab_size )
           __magic_name__      				=    random_attention_mask([self.batch_size, self.seq_length] )

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

           __magic_name__      				=    None
           if self.use_token_type_ids:
                  __magic_name__      				=    ids_tensor([self.batch_size, self.seq_length]				,    self.n_langs )

           __magic_name__      				=    None
           __magic_name__      				=    None
           __magic_name__      				=    None
           if self.use_labels:
                  __magic_name__      				=    ids_tensor([self.batch_size]				,    self.type_sequence_label_size )
                  __magic_name__      				=    ids_tensor([self.batch_size, self.seq_length]				,    self.num_labels )
                  __magic_name__      				=    ids_tensor([self.batch_size]				,    2 ).float()
                  __magic_name__      				=    ids_tensor([self.batch_size]				,    self.num_choices )

           __magic_name__      				=    self.get_config()

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







    def 				a__			(		self :	int ):





           '''simple docstring'''

           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 				a__			(		self :	Dict				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Optional[int]				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertModel(config=UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           __magic_name__      				=    model(UpperCamelCase_				,    lengths=UpperCamelCase_				,    langs=UpperCamelCase_ )
           __magic_name__      				=    model(UpperCamelCase_				,    langs=UpperCamelCase_ )
           __magic_name__      				=    model(UpperCamelCase_ )
           self.parent.assertEqual(result.last_hidden_state.shape				,    (self.batch_size, self.seq_length, self.hidden_size) )







    def 				a__			(		self :	Dict				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	str				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertWithLMHeadModel(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_				,    token_type_ids=UpperCamelCase_				,    labels=UpperCamelCase_ )
           self.parent.assertEqual(result.loss.shape				,    () )
           self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.seq_length, self.vocab_size) )







    def 				a__			(		self :	Union[str, Any]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	str				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertForQuestionAnsweringSimple(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_ )

           __magic_name__      				=    model(UpperCamelCase_				,    start_positions=UpperCamelCase_				,    end_positions=UpperCamelCase_ )
           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 				a__			(		self :	str				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Union[str, Any]				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertForQuestionAnswering(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_ )

           __magic_name__      				=    model(
               UpperCamelCase_				,    start_positions=UpperCamelCase_				,    end_positions=UpperCamelCase_				,    cls_index=UpperCamelCase_				,    is_impossible=UpperCamelCase_				,    p_mask=UpperCamelCase_				,    )

           __magic_name__      				=    model(
               UpperCamelCase_				,    start_positions=UpperCamelCase_				,    end_positions=UpperCamelCase_				,    cls_index=UpperCamelCase_				,    is_impossible=UpperCamelCase_				,    )

           ((__magic_name__)				,  )      				=    result_with_labels.to_tuple()

           __magic_name__      				=    model(UpperCamelCase_				,    start_positions=UpperCamelCase_				,    end_positions=UpperCamelCase_ )

           ((__magic_name__)				,  )      				=    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 				a__			(		self :	str				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Union[str, Any]				,    UpperCamelCase_ :	List[str]				,    ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertForSequenceClassification(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_ )
           __magic_name__      				=    model(UpperCamelCase_				,    labels=UpperCamelCase_ )

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







    def 				a__			(		self :	Optional[int]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	str				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Tuple				,    ):





           '''simple docstring'''

           __magic_name__      				=    self.num_labels
           __magic_name__      				=    FlaubertForTokenClassification(UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()

           __magic_name__      				=    model(UpperCamelCase_				,    attention_mask=UpperCamelCase_				,    labels=UpperCamelCase_ )
           self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.seq_length, self.num_labels) )







    def 				a__			(		self :	str				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Tuple				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	Tuple				,    ):





           '''simple docstring'''

           __magic_name__      				=    self.num_choices
           __magic_name__      				=    FlaubertForMultipleChoice(config=UpperCamelCase_ )
           model.to(UpperCamelCase_ )
           model.eval()
           __magic_name__      				=    input_ids.unsqueeze(1 ).expand(-1				,    self.num_choices				,    -1 ).contiguous()
           __magic_name__      				=    token_type_ids.unsqueeze(1 ).expand(-1				,    self.num_choices				,    -1 ).contiguous()
           __magic_name__      				=    input_mask.unsqueeze(1 ).expand(-1				,    self.num_choices				,    -1 ).contiguous()
           __magic_name__      				=    model(
               UpperCamelCase_				,    attention_mask=UpperCamelCase_				,    token_type_ids=UpperCamelCase_				,    labels=UpperCamelCase_				,    )
           self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.num_choices) )







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





           '''simple docstring'''

           __magic_name__      				=    self.prepare_config_and_inputs()
           (
               (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  (
               __magic_name__
           )				,  
           )      				=    config_and_inputs
           __magic_name__      				=    {
               '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__ (				a_							,	a_							,	unittest.TestCase):







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







    def 				a__			(		self :	List[str]				,    UpperCamelCase_ :	Any				,    UpperCamelCase_ :	List[str]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	Dict ):





           '''simple docstring'''

           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 				a__			(		self :	List[Any]				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Dict				,    UpperCamelCase_ :	Optional[Any]=False ):





           '''simple docstring'''

           __magic_name__      				=    super()._prepare_for_class(UpperCamelCase_				,    UpperCamelCase_				,    return_labels=UpperCamelCase_ )

           if return_labels:
                  if model_class.__name__ == "FlaubertForQuestionAnswering":
                         __magic_name__      				=    torch.zeros(
                             self.model_tester.batch_size				,    dtype=torch.long				,    device=UpperCamelCase_ )
                         __magic_name__      				=    torch.zeros(
                             self.model_tester.batch_size				,    dtype=torch.long				,    device=UpperCamelCase_ )

           return inputs_dict







    def 				a__			(		self :	List[str] ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertModelTester(self )
           __magic_name__      				=    ConfigTester(self				,    config_class=UpperCamelCase_				,    emb_dim=3_7 )







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           self.config_tester.run_common_tests()







    def 				a__			(		self :	Optional[Any] ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_model(*UpperCamelCase_ )







    def 				a__			(		self :	Dict ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_lm_head(*UpperCamelCase_ )







    def 				a__			(		self :	int ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_simple_qa(*UpperCamelCase_ )







    def 				a__			(		self :	int ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_qa(*UpperCamelCase_ )







    def 				a__			(		self :	Optional[int] ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCamelCase_ )







    def 				a__			(		self :	str ):





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_token_classif(*UpperCamelCase_ )







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





           '''simple docstring'''

           __magic_name__      				=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_multiple_choice(*UpperCamelCase_ )







    @slow
    def 				a__			(		self :	Any ):





           '''simple docstring'''

           for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  __magic_name__      				=    FlaubertModel.from_pretrained(UpperCamelCase_ )
                  self.assertIsNotNone(UpperCamelCase_ )







    @slow
    @require_torch_gpu
    def 				a__			(		self :	str ):





           '''simple docstring'''

           __magic_name__				,  __magic_name__      				=    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

                  __magic_name__      				=    True
                  __magic_name__      				=    model_class(config=UpperCamelCase_ )

                  __magic_name__      				=    self._prepare_for_class(UpperCamelCase_				,    UpperCamelCase_ )
                  __magic_name__      				=    torch.jit.trace(
                      UpperCamelCase_				,    (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) )

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



@require_torch
class        UpperCamelCase__ (				unittest.TestCase):







    """simple docstring"""







    @slow
    def 				a__			(		self :	Dict ):





           '''simple docstring'''

           __magic_name__      				=    FlaubertModel.from_pretrained('flaubert/flaubert_base_cased' )
           __magic_name__      				=    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():
                  __magic_name__      				=    model(UpperCamelCase_ )[0]
           __magic_name__      				=    torch.Size((1, 1_1, 7_6_8) )
           self.assertEqual(output.shape				,    UpperCamelCase_ )
           __magic_name__      				=    torch.tensor(
               [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]] )

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