


'''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()

lowerCAmelCase     :  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       lowercase					(_A ,    _A ,    _A ,    _A ,    _A=False ,    _A=True       ):







       """simple docstring"""







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

       _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				int       =							MODEL_CLASSES[model_type]

       # Initialise TF model
       if config_file in aws_config_map:
              _lowerCAmelCase     :				str       =							cached_file(_A ,    _A ,    force_download=not use_cached_models       )
       _lowerCAmelCase     :				Optional[int]       =							config_class.from_json_file(_A       )
       _lowerCAmelCase     :				List[str]       =							True
       _lowerCAmelCase     :				Optional[Any]       =							True
       print(f'Building TensorFlow model from configuration: {config}'       )
       _lowerCAmelCase     :				List[str]       =							model_class(_A       )

       # Load weights from tf checkpoint
       if pytorch_checkpoint_path in aws_config_map.keys():
              _lowerCAmelCase     :				List[str]       =							cached_file(
                  _A ,    _A ,    force_download=not use_cached_models       )
       # Load PyTorch checkpoint in tf2 model:
       _lowerCAmelCase     :				Optional[Any]       =							load_pytorch_checkpoint_in_tfa_model(_A ,    _A       )

       if compare_with_pt_model:
              _lowerCAmelCase     :				Dict       =							tf_model(tf_model.dummy_inputs ,    training=_A       )  # build the network

              _lowerCAmelCase     :				Optional[int]       =							torch.load(_A ,    map_location='cpu'       )
              _lowerCAmelCase     :				str       =							pt_model_class.from_pretrained(
                  pretrained_model_name_or_path=_A ,    config=_A ,    state_dict=_A       )

              with torch.no_grad():
                     _lowerCAmelCase     :				str       =							pt_model(**pt_model.dummy_inputs       )

              _lowerCAmelCase     :				List[Any]       =							pto[0].numpy()
              _lowerCAmelCase     :				str       =							tfo[0].numpy()
              _lowerCAmelCase     :				List[Any]       =							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(_A ,    save_format='h5'       )






def       lowercase					(_A ,    _A ,    _A=None ,    _A=None ,    _A=False ,    _A=False ,    _A=False ,    _A=False ,    ):







       """simple docstring"""







       if args_model_type is None:
              _lowerCAmelCase     :				List[Any]       =							list(MODEL_CLASSES.keys()       )
       else:
              _lowerCAmelCase     :				Union[str, Any]       =							[args_model_type]

       for j, model_type in enumerate(_A ,    start=1       ):
              print('=' * 1_0_0       )
              print(f' Converting model type {j}/{len(_A       )}: {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()       )}.'       )

              _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				str       =							MODEL_CLASSES[model_type]

              if model_shortcut_names_or_path is None:
                     _lowerCAmelCase     :				int       =							list(aws_model_maps.keys()       )
              if config_shortcut_names_or_path is None:
                     _lowerCAmelCase     :				Optional[int]       =							model_shortcut_names_or_path

              for i, (model_shortcut_name, config_shortcut_name) in enumerate(
                  zip(_A ,    _A       ) ,    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
                            _lowerCAmelCase     :				str       =							model_shortcut_name
                     elif only_convert_finetuned_models:
                            print(f'    Skipping not finetuned checkpoint {model_shortcut_name}'       )
                            continue
                     print(
                         f'    Converting checkpoint {i}/{len(_A       )}: {model_shortcut_name} - model_type {model_type}'       )
                     print('-' * 1_0_0       )

                     if config_shortcut_name in aws_config_map:
                            _lowerCAmelCase     :				str       =							cached_file(_A ,    _A ,    force_download=not use_cached_models       )
                     else:
                            _lowerCAmelCase     :				List[Any]       =							config_shortcut_name

                     if model_shortcut_name in aws_model_maps:
                            _lowerCAmelCase     :				str       =							cached_file(_A ,    _A ,    force_download=not use_cached_models       )
                     else:
                            _lowerCAmelCase     :				List[str]       =							model_shortcut_name

                     if os.path.isfile(_A       ):
                            _lowerCAmelCase     :				Optional[Any]       =							'converted_model'

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


if __name__ == "__main__":
       lowerCAmelCase     :  int											=    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.""")
       lowerCAmelCase     :  Optional[Any]											=    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'''







from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers.models.xglm.modeling_tf_xglm import (
           TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
           TFXGLMForCausalLM,
           TFXGLMModel,
       )
@require_tf
class 						UpperCamelCase__       :



     """simple docstring"""






     __magic_name__           =     XGLMConfig
     __magic_name__           =     {}
     __magic_name__           =     "gelu"







     def __init__(			self   ,						snake_case__   ,						snake_case__=14   ,						snake_case__=7   ,						snake_case__=True   ,						snake_case__=True   ,						snake_case__=True   ,						snake_case__=99   ,						snake_case__=32   ,						snake_case__=2   ,						snake_case__=4   ,						snake_case__=37   ,						snake_case__="gelu"   ,						snake_case__=0.1   ,						snake_case__=0.1   ,						snake_case__=512   ,						snake_case__=0.02   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							parent
            _lowerCAmelCase     :				Tuple       =							batch_size
            _lowerCAmelCase     :				Optional[Any]       =							seq_length
            _lowerCAmelCase     :				Dict       =							is_training
            _lowerCAmelCase     :				str       =							use_input_mask
            _lowerCAmelCase     :				Tuple       =							use_labels
            _lowerCAmelCase     :				Union[str, Any]       =							vocab_size
            _lowerCAmelCase     :				Any       =							d_model
            _lowerCAmelCase     :				Dict       =							num_hidden_layers
            _lowerCAmelCase     :				Optional[Any]       =							num_attention_heads
            _lowerCAmelCase     :				Tuple       =							ffn_dim
            _lowerCAmelCase     :				Tuple       =							activation_function
            _lowerCAmelCase     :				int       =							activation_dropout
            _lowerCAmelCase     :				Optional[Any]       =							attention_dropout
            _lowerCAmelCase     :				Union[str, Any]       =							max_position_embeddings
            _lowerCAmelCase     :				List[Any]       =							initializer_range
            _lowerCAmelCase     :				List[str]       =							None
            _lowerCAmelCase     :				Any       =							0
            _lowerCAmelCase     :				Any       =							2
            _lowerCAmelCase     :				Optional[Any]       =							1







     def a						(			self ):

            '''simple docstring'''

            return XGLMConfig.from_pretrained('facebook/xglm-564M' )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[Any]       =							tf.clip_by_value(
                ids_tensor([self.batch_size, self.seq_length]   ,						self.vocab_size )   ,						clip_value_min=0   ,						clip_value_max=3 )

            _lowerCAmelCase     :				str       =							None
            if self.use_input_mask:
                   _lowerCAmelCase     :				int       =							random_attention_mask([self.batch_size, self.seq_length] )

            _lowerCAmelCase     :				str       =							self.get_config()

            _lowerCAmelCase     :				Union[str, Any]       =							floats_tensor([self.num_hidden_layers, self.num_attention_heads]   ,						2 )

            return (
                config,
                input_ids,
                input_mask,
                head_mask,
            )







     def a						(			self ):

            '''simple docstring'''

            return XGLMConfig(
                vocab_size=self.vocab_size   ,						d_model=self.hidden_size   ,						num_layers=self.num_hidden_layers   ,						attention_heads=self.num_attention_heads   ,						ffn_dim=self.ffn_dim   ,						activation_function=self.activation_function   ,						activation_dropout=self.activation_dropout   ,						attention_dropout=self.attention_dropout   ,						max_position_embeddings=self.max_position_embeddings   ,						initializer_range=self.initializer_range   ,						use_cache=snake_case__   ,						bos_token_id=self.bos_token_id   ,						eos_token_id=self.eos_token_id   ,						pad_token_id=self.pad_token_id   ,						return_dict=snake_case__   ,						)







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							self.prepare_config_and_inputs()

            (
                (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  
            )     :				Dict       =							config_and_inputs

            _lowerCAmelCase     :				Optional[int]       =							{
                'input_ids': input_ids,
                'head_mask': head_mask,
            }

            return config, inputs_dict
@require_tf
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_     ,       SCREAMING_SNAKE_CASE_     ,       unittest.TestCase						):



     """simple docstring"""






     __magic_name__           =     (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
     __magic_name__           =     (TFXGLMForCausalLM,) if is_tf_available() else ()
     __magic_name__           =     (
         {"feature-extraction": TFXGLMModel, "text-generation": TFXGLMForCausalLM} if is_tf_available() else {}
     )
     __magic_name__           =     False
     __magic_name__           =     False
     __magic_name__           =     False







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							TFXGLMModelTester(self )
            _lowerCAmelCase     :				Dict       =							ConfigTester(self   ,						config_class=snake_case__   ,						n_embd=37 )







     def a						(			self ):

            '''simple docstring'''

            self.config_tester.run_common_tests()







     @slow
     def a						(			self ):

            '''simple docstring'''

            for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _lowerCAmelCase     :				Optional[Any]       =							TFXGLMModel.from_pretrained(snake_case__ )
                   self.assertIsNotNone(snake_case__ )







     @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' )
     def a						(			self ):

            '''simple docstring'''

            super().test_resize_token_embeddings()
@require_tf
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     @slow
     def a						(			self   ,						snake_case__=True ):

            '''simple docstring'''

            _lowerCAmelCase     :				str       =							TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
            _lowerCAmelCase     :				str       =							tf.convert_to_tensor([[2, 268, 9865]]   ,						dtype=tf.intaa )  # The dog
            # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
            # fmt: off
            _lowerCAmelCase     :				str       =							[2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581]
            # fmt: on
            _lowerCAmelCase     :				Optional[int]       =							model.generate(snake_case__   ,						do_sample=snake_case__   ,						num_beams=1 )
            if verify_outputs:
                   self.assertListEqual(output_ids[0].numpy().tolist()   ,						snake_case__ )







     @slow
     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							XGLMTokenizer.from_pretrained('facebook/xglm-564M' )
            _lowerCAmelCase     :				int       =							TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )

            tf.random.set_seed(0 )
            _lowerCAmelCase     :				Optional[int]       =							tokenizer('Today is a nice day and'   ,						return_tensors='tf' )
            _lowerCAmelCase     :				Dict       =							tokenized.input_ids
            # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
            with tf.device(':/CPU:0' ):
                   _lowerCAmelCase     :				Dict       =							model.generate(snake_case__   ,						do_sample=snake_case__   ,						seed=[7, 0] )
            _lowerCAmelCase     :				List[Any]       =							tokenizer.decode(output_ids[0]   ,						skip_special_tokens=snake_case__ )

            _lowerCAmelCase     :				Tuple       =							(
                'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'
            )
            self.assertEqual(snake_case__   ,						snake_case__ )







     @slow
     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Any       =							TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' )
            _lowerCAmelCase     :				int       =							XGLMTokenizer.from_pretrained('facebook/xglm-564M' )

            _lowerCAmelCase     :				Tuple       =							'left'

            # use different length sentences to test batching
            _lowerCAmelCase     :				Optional[int]       =							[
                'This is an extremelly long sentence that only exists to test the ability of the model to cope with '
                'left-padding, such as in batched generation. The output for the sequence below should be the same '
                'regardless of whether left padding is applied or not. When',
                'Hello, my dog is a little',
            ]

            _lowerCAmelCase     :				Tuple       =							tokenizer(snake_case__   ,						return_tensors='tf'   ,						padding=snake_case__ )
            _lowerCAmelCase     :				Any       =							inputs['input_ids']

            _lowerCAmelCase     :				Any       =							model.generate(input_ids=snake_case__   ,						attention_mask=inputs['attention_mask']   ,						max_new_tokens=12 )

            _lowerCAmelCase     :				Dict       =							tokenizer(sentences[0]   ,						return_tensors='tf' ).input_ids
            _lowerCAmelCase     :				Union[str, Any]       =							model.generate(input_ids=snake_case__   ,						max_new_tokens=12 )

            _lowerCAmelCase     :				int       =							tokenizer(sentences[1]   ,						return_tensors='tf' ).input_ids
            _lowerCAmelCase     :				Optional[Any]       =							model.generate(input_ids=snake_case__   ,						max_new_tokens=12 )

            _lowerCAmelCase     :				Optional[Any]       =							tokenizer.batch_decode(snake_case__   ,						skip_special_tokens=snake_case__ )
            _lowerCAmelCase     :				Any       =							tokenizer.decode(output_non_padded[0]   ,						skip_special_tokens=snake_case__ )
            _lowerCAmelCase     :				Optional[Any]       =							tokenizer.decode(output_padded[0]   ,						skip_special_tokens=snake_case__ )

            _lowerCAmelCase     :				List[Any]       =							[
                'This is an extremelly long sentence that only exists to test the ability of the model to cope with '
                'left-padding, such as in batched generation. The output for the sequence below should be the same '
                'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '
                'a single',
                'Hello, my dog is a little bit of a shy one, but he is very friendly',
            ]
            self.assertListEqual(snake_case__   ,						snake_case__ )
            self.assertListEqual(snake_case__   ,						[non_padded_sentence, padded_sentence] )

