





import unittest

from parameterized import parameterized

from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
    import torch

    from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer





class 			A__   :




   """simple docstring"""



   def __init__( self ,  lowercase ,  lowercase=13 ,  lowercase=7 ,  lowercase=True ,  lowercase=True ,  lowercase=False ,  lowercase=True ,  lowercase=99 ,  lowercase=32 ,  lowercase=5 ,  lowercase=4 ,  lowercase=37 ,  lowercase="gelu" ,  lowercase=0.1 ,  lowercase=0.1 ,  lowercase=512 ,  lowercase=16 ,  lowercase=2 ,  lowercase=0.02 ,  lowercase=3 ,  lowercase=4 ,  lowercase=None ,  )      ->						Tuple:







          '''simple docstring'''

          a__						:     Any			=    parent
          a__						:     Tuple			=    batch_size
          a__						:     int			=    seq_length
          a__						:     Tuple			=    is_training
          a__						:     List[Any]			=    use_input_mask
          a__						:     Optional[Any]			=    use_token_type_ids
          a__						:     List[Any]			=    use_labels
          a__						:     Optional[int]			=    vocab_size
          a__						:     Any			=    hidden_size
          a__						:     Union[str, Any]			=    num_hidden_layers
          a__						:     Optional[Any]			=    num_attention_heads
          a__						:     str			=    intermediate_size
          a__						:     List[Any]			=    hidden_act
          a__						:     Any			=    hidden_dropout_prob
          a__						:     List[Any]			=    attention_probs_dropout_prob
          a__						:     Union[str, Any]			=    max_position_embeddings
          a__						:     Any			=    type_vocab_size
          a__						:     int			=    type_sequence_label_size
          a__						:     Tuple			=    initializer_range
          a__						:     Optional[Any]			=    num_labels
          a__						:     str			=    num_choices
          a__						:     Any			=    scope

   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          a__						:     List[Any]			=    ids_tensor([self.batch_size, self.seq_length] ,  self.vocab_size)

          a__						:     List[Any]			=    None
          if self.use_input_mask:
                 a__						:     Any			=    random_attention_mask([self.batch_size, self.seq_length])

          a__						:     Dict			=    None
          if self.use_token_type_ids:
                 a__						:     Any			=    ids_tensor([self.batch_size, self.seq_length] ,  self.type_vocab_size)

          a__						:     Dict			=    None
          a__						:     str			=    None
          a__						:     str			=    None
          if self.use_labels:
                 a__						:     Dict			=    ids_tensor([self.batch_size] ,  self.type_sequence_label_size)
                 a__						:     List[str]			=    ids_tensor([self.batch_size, self.seq_length] ,  self.num_labels)
                 a__						:     List[str]			=    ids_tensor([self.batch_size] ,  self.num_choices)

          a__						:     int			=    self.get_config()

          return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          return LlamaConfig(
              vocab_size=self.vocab_size ,  hidden_size=self.hidden_size ,  num_hidden_layers=self.num_hidden_layers ,  num_attention_heads=self.num_attention_heads ,  intermediate_size=self.intermediate_size ,  hidden_act=self.hidden_act ,  hidden_dropout_prob=self.hidden_dropout_prob ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob ,  max_position_embeddings=self.max_position_embeddings ,  type_vocab_size=self.type_vocab_size ,  is_decoder=lowercase ,  initializer_range=self.initializer_range ,  )

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase)      ->						List[str]:







          '''simple docstring'''

          a__						:     str			=    LlamaModel(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:     List[Any]			=    model(lowercase ,  attention_mask=lowercase)
          a__						:     List[str]			=    model(lowercase)
          self.parent.assertEqual(result.last_hidden_state.shape ,  (self.batch_size, self.seq_length, self.hidden_size))

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  )      ->						Tuple:







          '''simple docstring'''

          a__						:     int			=    True
          a__						:     Optional[Any]			=    LlamaModel(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:     Union[str, Any]			=    model(
              lowercase ,  attention_mask=lowercase ,  encoder_hidden_states=lowercase ,  encoder_attention_mask=lowercase ,  )
          a__						:     Dict			=    model(
              lowercase ,  attention_mask=lowercase ,  encoder_hidden_states=lowercase ,  )
          a__						:     List[Any]			=    model(lowercase ,  attention_mask=lowercase)
          self.parent.assertEqual(result.last_hidden_state.shape ,  (self.batch_size, self.seq_length, self.hidden_size))

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  )      ->						List[Any]:







          '''simple docstring'''

          a__						:     Optional[Any]			=    LlamaForCausalLM(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:     Optional[Any]			=    model(lowercase ,  attention_mask=lowercase ,  labels=lowercase)
          self.parent.assertEqual(result.logits.shape ,  (self.batch_size, self.seq_length, self.vocab_size))

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  )      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     int			=    True
          a__						:     Dict			=    True
          a__						:     Optional[int]			=    LlamaForCausalLM(config=lowercase)
          model.to(lowercase)
          model.eval()

          # first forward pass
          a__						:     Dict			=    model(
              lowercase ,  attention_mask=lowercase ,  encoder_hidden_states=lowercase ,  encoder_attention_mask=lowercase ,  use_cache=lowercase ,  )
          a__						:     Tuple			=    outputs.past_key_values

          # create hypothetical multiple next token and extent to next_input_ids
          a__						:     int			=    ids_tensor((self.batch_size, 3) ,  config.vocab_size)
          a__						:     Optional[int]			=    ids_tensor((self.batch_size, 3) ,  vocab_size=2)

          # append to next input_ids and
          a__						:     str			=    torch.cat([input_ids, next_tokens] ,  dim=-1)
          a__						:     Optional[int]			=    torch.cat([input_mask, next_mask] ,  dim=-1)

          a__						:     Union[str, Any]			=    model(
              lowercase ,  attention_mask=lowercase ,  encoder_hidden_states=lowercase ,  encoder_attention_mask=lowercase ,  output_hidden_states=lowercase ,  )['hidden_states'][0]
          a__						:     str			=    model(
              lowercase ,  attention_mask=lowercase ,  encoder_hidden_states=lowercase ,  encoder_attention_mask=lowercase ,  past_key_values=lowercase ,  output_hidden_states=lowercase ,  )['hidden_states'][0]

          # select random slice
          a__						:     List[Any]			=    ids_tensor((1,) ,  output_from_past.shape[-1]).item()
          a__						:     int			=    output_from_no_past[:, -3:, random_slice_idx].detach()
          a__						:     Optional[int]			=    output_from_past[:, :, random_slice_idx].detach()

          self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])

          # test that outputs are equal for slice
          self.parent.assertTrue(torch.allclose(lowercase ,  lowercase ,  atol=1e-3))

   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     Tuple			=    self.prepare_config_and_inputs()
          (
              (
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							
          )						:     int			=    config_and_inputs
          a__						:     Optional[Any]			=    {'input_ids': input_ids, 'attention_mask': input_mask}
          return config, inputs_dict





@require_torch
class 			A__   (							__UpperCAmelCase			,  __UpperCAmelCase			,  __UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



   __A       :    List[Any]	  =  (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
   __A       :    Union[str, Any]	  =  (LlamaForCausalLM,) if is_torch_available() else ()
   __A       :    List[str]	  =  (
       {
           '''feature-extraction''': LlamaModel,
           '''text-classification''': LlamaForSequenceClassification,
           '''text-generation''': LlamaForCausalLM,
           '''zero-shot''': LlamaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   __A       :    Dict	  =  False
   __A       :    Optional[int]	  =  False

   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          a__						:     int			=    LlamaModelTester(self)
          a__						:     Union[str, Any]			=    ConfigTester(self ,  config_class=lowercase ,  hidden_size=37)

   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          self.config_tester.run_common_tests()

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Tuple			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase)

   def 							__lowercase		( self)      ->						List[str]:







          '''simple docstring'''

          a__						:     List[Any]			=    self.model_tester.prepare_config_and_inputs()
          for type in ["absolute", "relative_key", "relative_key_query"]:
                 a__						:     List[Any]			=    type
                 self.model_tester.create_and_check_model(*lowercase)

   def 							__lowercase		( self)      ->						Optional[int]:







          '''simple docstring'''

          a__			,							a__						:     List[str]			=    self.model_tester.prepare_config_and_inputs_for_common()
          a__						:     Tuple			=    3
          a__						:     Dict			=    input_dict['input_ids']
          a__						:     str			=    input_ids.ne(1).to(lowercase)
          a__						:     Optional[Any]			=    ids_tensor([self.model_tester.batch_size] ,  self.model_tester.type_sequence_label_size)
          a__						:     Any			=    LlamaForSequenceClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:     Optional[int]			=    model(lowercase ,  attention_mask=lowercase ,  labels=lowercase)
          self.assertEqual(result.logits.shape ,  (self.model_tester.batch_size, self.model_tester.num_labels))

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__			,							a__						:     List[Any]			=    self.model_tester.prepare_config_and_inputs_for_common()
          a__						:     Tuple			=    3
          a__						:     Any			=    'single_label_classification'
          a__						:     Any			=    input_dict['input_ids']
          a__						:     Tuple			=    input_ids.ne(1).to(lowercase)
          a__						:     int			=    ids_tensor([self.model_tester.batch_size] ,  self.model_tester.type_sequence_label_size)
          a__						:     List[str]			=    LlamaForSequenceClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:     Any			=    model(lowercase ,  attention_mask=lowercase ,  labels=lowercase)
          self.assertEqual(result.logits.shape ,  (self.model_tester.batch_size, self.model_tester.num_labels))

   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          a__			,							a__						:     Any			=    self.model_tester.prepare_config_and_inputs_for_common()
          a__						:     Dict			=    3
          a__						:     str			=    'multi_label_classification'
          a__						:     Any			=    input_dict['input_ids']
          a__						:     Any			=    input_ids.ne(1).to(lowercase)
          a__						:     Optional[int]			=    ids_tensor(
              [self.model_tester.batch_size, config.num_labels] ,  self.model_tester.type_sequence_label_size).to(torch.float)
          a__						:     Dict			=    LlamaForSequenceClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:     int			=    model(lowercase ,  attention_mask=lowercase ,  labels=lowercase)
          self.assertEqual(result.logits.shape ,  (self.model_tester.batch_size, self.model_tester.num_labels))

   @unittest.skip('LLaMA buffers include complex numbers, which breaks this test')
   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          pass

   @parameterized.expand([('linear',), ('dynamic',)])
   def 							__lowercase		( self ,  lowercase)      ->						str:







          '''simple docstring'''

          a__			,							a__						:     Any			=    self.model_tester.prepare_config_and_inputs_for_common()
          a__						:     Dict			=    ids_tensor([1, 10] ,  config.vocab_size)
          a__						:     List[str]			=    ids_tensor([1, int(config.max_position_embeddings * 1.5)] ,  config.vocab_size)

          set_seed(42)  # Fixed seed at init time so the two models get the same random weights
          a__						:     str			=    LlamaModel(lowercase)
          original_model.to(lowercase)
          original_model.eval()
          a__						:     Dict			=    original_model(lowercase).last_hidden_state
          a__						:     List[Any]			=    original_model(lowercase).last_hidden_state

          set_seed(42)  # Fixed seed at init time so the two models get the same random weights
          a__						:     Union[str, Any]			=    {'type': scaling_type, 'factor': 10.0}
          a__						:     List[Any]			=    LlamaModel(lowercase)
          scaled_model.to(lowercase)
          scaled_model.eval()
          a__						:     str			=    scaled_model(lowercase).last_hidden_state
          a__						:     Union[str, Any]			=    scaled_model(lowercase).last_hidden_state

          # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
          # maximum sequence length, so the outputs for the short input should match.
          if scaling_type == "dynamic":
                 self.assertTrue(torch.allclose(lowercase ,  lowercase ,  atol=1e-5))
          else:
                 self.assertFalse(torch.allclose(lowercase ,  lowercase ,  atol=1e-5))

          # The output should be different for long inputs
          self.assertFalse(torch.allclose(lowercase ,  lowercase ,  atol=1e-5))





@require_torch
class 			A__   (							unittest.TestCase     ):




   """simple docstring"""



   @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!')
   @slow
   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          a__						:     Dict			=    [1, 306, 4658, 278, 6593, 310, 2834, 338]
          a__						:     int			=    LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' ,  device_map='auto')
          a__						:     Any			=    model(torch.tensor([input_ids]))
          # Expected mean on dim = -1
          a__						:     str			=    torch.tensor([[-6.65_50, -4.12_27, -4.98_59, -3.24_06, 0.82_62, -3.00_33, 1.29_64, -3.36_99]])
          torch.testing.assert_close(out.mean(-1) ,  lowercase ,  atol=1e-2 ,  rtol=1e-2)
          # slicing logits[0, 0, 0:30]
          # fmt: off
          a__						:     Dict			=    torch.tensor([-12.82_81, -7.44_53, -0.46_39, -8.06_25, -7.25_00, -8.00_00, -6.48_83, -7.76_95, -7.84_38, -7.03_12, -6.21_88, -7.13_28, -1.84_96, 1.99_61, -8.62_50, -6.72_27, -12.82_81, -6.94_92, -7.07_42, -7.78_52, -7.58_20, -7.90_62, -6.93_75, -7.98_05, -8.34_38, -8.15_62, -8.04_69, -7.62_50, -7.74_22, -7.33_98,])
          # fmt: on
          torch.testing.assert_close(out[0, 0, :30] ,  lowercase ,  atol=1e-5 ,  rtol=1e-5)

   @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!')
   @slow
   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Union[str, Any]			=    [1, 306, 4658, 278, 6593, 310, 2834, 338]
          a__						:     Optional[int]			=    LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' ,  device_map='auto')
          a__						:     List[str]			=    model(torch.tensor(lowercase))
          # Expected mean on dim = -1
          a__						:     List[str]			=    torch.tensor([[-2.06_22, -1.27_94, -1.16_38, -0.97_88, -1.46_03, -1.02_38, -1.78_93, -1.44_11]])
          torch.testing.assert_close(out.mean(-1) ,  lowercase ,  atol=1e-2 ,  rtol=1e-2)
          # slicing logits[0, 0, 0:30]
          # fmt: off
          a__						:     Tuple			=    torch.tensor([-8.14_06, -8.05_47, 2.74_61, -1.23_44, -0.14_48, -1.82_62, -1.00_20, -1.81_54, -1.68_95, -1.85_16, -2.35_74, -0.92_77, 3.75_98, 6.57_42, -1.29_98, -0.11_77, -8.14_06, -2.96_88, -2.91_99, -3.16_99, -3.52_54, -2.35_55, -2.79_88, -3.41_41, -2.82_62, -4.51_95, -3.33_79, -3.31_64, -2.78_32, -3.02_73])
          # fmt: on
          torch.testing.assert_close(out[0, 0, :30] ,  lowercase ,  atol=1e-5 ,  rtol=1e-5)

   @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!')
   @slow
   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     int			=    [1, 306, 4658, 278, 6593, 310, 2834, 338]
          a__						:     int			=    LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ,  device_map='auto')
          a__						:     List[Any]			=    model(torch.tensor(lowercase))
          # Expected mean on dim = -1
          a__						:     Dict			=    torch.tensor([[-0.85_62, -1.85_20, -0.75_51, -0.41_62, -1.51_61, -1.20_38, -2.48_23, -2.32_54]])
          torch.testing.assert_close(out.mean(-1) ,  lowercase ,  atol=1e-2 ,  rtol=1e-2)
          # slicing logits[0, 0, 0:30]
          # fmt: off
          a__						:     Tuple			=    torch.tensor([-2.22_27, 4.88_28, 0.90_23, -0.45_78, -0.78_71, -0.10_33, -0.62_21, -0.57_86, -0.78_03, -1.06_74, -1.29_20, -0.15_70, 0.80_08, 2.07_23, -0.94_97, 0.27_71, -2.22_27, -0.76_12, -1.43_46, -1.20_61, -1.64_26, -0.30_00, -0.71_39, -1.19_34, -1.86_91, -1.69_73, -1.59_47, -1.27_05, -0.35_23, -0.55_13])
          # fmt: on
          torch.testing.assert_close(out.mean(-1) ,  lowercase ,  atol=1e-2 ,  rtol=1e-2)

   @unittest.skip(
       'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test')
   @slow
   def 							__lowercase		( self)      ->						Optional[int]:







          '''simple docstring'''

          a__						:     str			=    [1, 306, 4658, 278, 6593, 310, 2834, 338]
          a__						:     Any			=    LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' ,  device_map='auto')
          a__						:     str			=    model(torch.tensor(lowercase))

          a__						:     List[str]			=    torch.tensor(
              [[-4.23_27, -3.33_60, -4.66_65, -4.76_31, -1.81_80, -3.41_70, -1.42_11, -3.18_10]] ,  dtype=torch.floataa)
          torch.testing.assert_close(out.mean(-1) ,  lowercase ,  atol=1e-2 ,  rtol=1e-2)
          # fmt: off
          a__						:     List[str]			=    torch.tensor([-9.49_22, -3.95_51, 1.79_98, -5.67_58, -5.10_55, -5.89_84, -4.83_20, -6.80_86, -6.53_91, -5.61_72, -5.58_20, -5.53_52, 1.78_81, 3.62_89, -6.51_17, -3.47_85, -9.50_00, -6.03_52, -6.81_25, -6.01_95, -6.68_36, -5.47_27, -6.28_12, -6.03_91, -7.33_98, -7.42_97, -7.48_44, -6.58_20, -5.87_89, -5.53_12])
          # fmt: on
          torch.testing.assert_close(out[0, 0, :30] ,  lowercase ,  atol=1e-5 ,  rtol=1e-5)

   @unittest.skip('Model is curently gated')
   @slow
   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     List[Any]			=    'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi'
          a__						:     str			=    'Simply put, the theory of relativity states that '
          a__						:     int			=    LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf')
          a__						:     Tuple			=    tokenizer.encode(lowercase ,  return_tensors='pt')
          a__						:     Any			=    LlamaForCausalLM.from_pretrained(
              'meta-llama/Llama-2-13b-chat-hf' ,  device_map='sequential' ,  use_safetensors=lowercase)

          # greedy generation outputs
          a__						:     int			=    model.generate(lowercase ,  max_new_tokens=64 ,  top_p=lowercase ,  temperature=1 ,  do_sample=lowercase)
          a__						:     Optional[int]			=    tokenizer.decode(generated_ids[0] ,  skip_special_tokens=lowercase)
          self.assertEqual(lowercase ,  lowercase)









import argparse
import os
import pickle
import sys

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
lowercase				:	Union[str, Any]      						=  data_utils.TransfoXLTokenizer
lowercase				:	Optional[int]      						=  data_utils.TransfoXLCorpus
lowercase				:	List[Any]      						=  data_utils
lowercase				:	Tuple      						=  data_utils



def A_     (		A__		,				A__		,				A__		,				A__    )  ->		Optional[Any]:
       if transfo_xl_dataset_file:
              # Convert a pre-processed corpus (see original TensorFlow repo)
              with open(A__		,				'rb'    ) as fp:
                     a__						:     int			=    pickle.load(A__		,				encoding='latin1'    )
              # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
              a__						:     int			=    pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file']
              print(F'Save vocabulary to {pytorch_vocab_dump_path}'    )
              a__						:     List[Any]			=    corpus.vocab.__dict__
              torch.save(A__		,				A__    )

              a__						:     Dict			=    corpus.__dict__
              corpus_dict_no_vocab.pop('vocab'		,				A__    )
              a__						:     Optional[int]			=    pytorch_dump_folder_path + '/' + CORPUS_NAME
              print(F'Save dataset to {pytorch_dataset_dump_path}'    )
              torch.save(A__		,				A__    )

       if tf_checkpoint_path:
              # Convert a pre-trained TensorFlow model
              a__						:     Union[str, Any]			=    os.path.abspath(A__    )
              a__						:     Optional[Any]			=    os.path.abspath(A__    )

              print(F'Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.'    )
              # Initialise PyTorch model
              if transfo_xl_config_file == "":
                     a__						:     Dict			=    TransfoXLConfig()
              else:
                     a__						:     Dict			=    TransfoXLConfig.from_json_file(A__    )
              print(F'Building PyTorch model from configuration: {config}'    )
              a__						:     Optional[int]			=    TransfoXLLMHeadModel(A__    )

              a__						:     int			=    load_tf_weights_in_transfo_xl(A__		,				A__		,				A__    )
              # Save pytorch-model
              a__						:     Any			=    os.path.join(A__		,				A__    )
              a__						:     Dict			=    os.path.join(A__		,				A__    )
              print(F'Save PyTorch model to {os.path.abspath(A__    )}'    )
              torch.save(model.state_dict()		,				A__    )
              print(F'Save configuration file to {os.path.abspath(A__    )}'    )
              with open(A__		,				'w'		,				encoding='utf-8'    ) as f:
                     f.write(config.to_json_string()    )


if __name__ == "__main__":
    lowercase				:	List[Any]      						=  argparse.ArgumentParser()
    parser.add_argument(
        """--pytorch_dump_folder_path""",
        default=None,
        type=str,
        required=True,
        help="""Path to the folder to store the PyTorch model or dataset/vocab.""",
    )
    parser.add_argument(
        """--tf_checkpoint_path""",
        default="""""",
        type=str,
        help="""An optional path to a TensorFlow checkpoint path to be converted.""",
    )
    parser.add_argument(
        """--transfo_xl_config_file""",
        default="""""",
        type=str,
        help=(
            """An optional config json file corresponding to the pre-trained BERT model. \n"""
            """This specifies the model architecture."""
        ),
    )
    parser.add_argument(
        """--transfo_xl_dataset_file""",
        default="""""",
        type=str,
        help="""An optional dataset file to be converted in a vocabulary.""",
    )
    lowercase				:	Any      						=  parser.parse_args()
    convert_transfo_xl_checkpoint_to_pytorch(
        args.tf_checkpoint_path,
        args.transfo_xl_config_file,
        args.pytorch_dump_folder_path,
        args.transfo_xl_dataset_file,
    )


