



'''simple docstring'''





import math
import unittest

from transformers import BioGptConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
   import torch

   from transformers import (
       BioGptForCausalLM,
       BioGptForSequenceClassification,
       BioGptForTokenClassification,
       BioGptModel,
       BioGptTokenizer,
   )
   from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST






class 					lowerCamelCase_    :
  """simple docstring"""




  def __init__( self      :	Tuple			,	_a      :	Optional[Any]			,	_a      :	str=13			,	_a      :	Any=7			,	_a      :	str=True			,	_a      :	List[Any]=True			,	_a      :	str=False			,	_a      :	Optional[int]=True			,	_a      :	str=99			,	_a      :	Optional[int]=32			,	_a      :	List[Any]=5			,	_a      :	str=4			,	_a      :	Any=37			,	_a      :	Tuple="gelu"			,	_a      :	Union[str, Any]=0.1			,	_a      :	Tuple=0.1			,	_a      :	Tuple=512			,	_a      :	Union[str, Any]=16			,	_a      :	Union[str, Any]=2			,	_a      :	str=0.02			,	_a      :	List[str]=3			,	_a      :	List[Any]=4			,	_a      :	Optional[int]=None			,	)					->					int:
    __lowerCamelCase       :       Any           = parent
    __lowerCamelCase       :       Optional[Any]           = batch_size
    __lowerCamelCase       :       int           = seq_length
    __lowerCamelCase       :       Optional[Any]           = is_training
    __lowerCamelCase       :       str           = use_input_mask
    __lowerCamelCase       :       Tuple           = use_token_type_ids
    __lowerCamelCase       :       Any           = use_labels
    __lowerCamelCase       :       Union[str, Any]           = vocab_size
    __lowerCamelCase       :       Optional[int]           = hidden_size
    __lowerCamelCase       :       str           = num_hidden_layers
    __lowerCamelCase       :       Any           = num_attention_heads
    __lowerCamelCase       :       int           = intermediate_size
    __lowerCamelCase       :       Tuple           = hidden_act
    __lowerCamelCase       :       Optional[int]           = hidden_dropout_prob
    __lowerCamelCase       :       Optional[int]           = attention_probs_dropout_prob
    __lowerCamelCase       :       Optional[Any]           = max_position_embeddings
    __lowerCamelCase       :       Any           = type_vocab_size
    __lowerCamelCase       :       str           = type_sequence_label_size
    __lowerCamelCase       :       Optional[Any]           = initializer_range
    __lowerCamelCase       :       Union[str, Any]           = num_labels
    __lowerCamelCase       :       Union[str, Any]           = num_choices
    __lowerCamelCase       :       Tuple           = scope




  def 						_lowercase     ( self      :	Tuple   )					->					Union[str, Any]:
    __lowerCamelCase       :       Optional[Any]           = ids_tensor([self.batch_size, self.seq_length]			,	self.vocab_size   )

    __lowerCamelCase       :       Optional[Any]           = None
    if self.use_input_mask:
      __lowerCamelCase       :       Optional[int]           = random_attention_mask([self.batch_size, self.seq_length]   )

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

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

    __lowerCamelCase       :       Optional[Any]           = self.get_config()

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




  def 						_lowercase     ( self      :	Optional[Any]   )					->					List[str]:
    return BioGptConfig(
        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=_a			,	initializer_range=self.initializer_range			,	)




  def 						_lowercase     ( self      :	Dict			,	_a      :	Any			,	_a      :	int			,	_a      :	int			,	_a      :	Union[str, Any]			,	_a      :	Any			,	_a      :	Optional[Any]			,	_a      :	Any   )					->					List[str]:
    __lowerCamelCase       :       Optional[Any]           = BioGptModel(config=_a   )
    model.to(_a   )
    model.eval()
    __lowerCamelCase       :       Dict           = model(_a			,	attention_mask=_a   )
    __lowerCamelCase       :       Optional[int]           = model(_a   )
    self.parent.assertEqual(result.last_hidden_state.shape			,	(self.batch_size, self.seq_length, self.hidden_size)   )




  def 						_lowercase     ( self      :	str			,	_a      :	Union[str, Any]			,	_a      :	Optional[Any]			,	_a      :	Optional[Any]			,	_a      :	Tuple			,	_a      :	Union[str, Any]			,	_a      :	int			,	_a      :	Any			,	_a      :	List[str]			,	_a      :	Tuple			,	)					->					List[str]:
    __lowerCamelCase       :       int           = BioGptForCausalLM(config=_a   )
    model.to(_a   )
    model.eval()
    __lowerCamelCase       :       int           = model(_a			,	attention_mask=_a			,	token_type_ids=_a			,	labels=_a   )
    self.parent.assertEqual(result.logits.shape			,	(self.batch_size, self.seq_length, self.vocab_size)   )




  def 						_lowercase     ( self      :	int			,	_a      :	int			,	_a      :	Tuple			,	_a      :	Union[str, Any]			,	_a      :	List[str]			,	_a      :	Optional[Any]			,	*_a      :	List[Any]   )					->					str:
    __lowerCamelCase       :       Optional[int]           = BioGptModel(config=_a   )
    model.to(_a   )
    model.eval()

    # create attention mask
    __lowerCamelCase       :       List[str]           = torch.ones(input_ids.shape			,	dtype=torch.long			,	device=_a   )
    __lowerCamelCase       :       List[Any]           = self.seq_length // 2
    __lowerCamelCase       :       Optional[Any]           = 0

    # first forward pass
    __lowerCamelCase       ,__lowerCamelCase       :       Any           = model(_a			,	attention_mask=_a   ).to_tuple()

    # create hypothetical next token and extent to next_input_ids
    __lowerCamelCase       :       Any           = ids_tensor((self.batch_size, 1)			,	config.vocab_size   )

    # change a random masked slice from input_ids
    __lowerCamelCase       :       int           = ids_tensor((1,)			,	_a   ).item() + 1
    __lowerCamelCase       :       Any           = ids_tensor((self.batch_size, 1)			,	config.vocab_size   ).squeeze(-1   )
    __lowerCamelCase       :       Tuple           = random_other_next_tokens

    # append to next input_ids and attn_mask
    __lowerCamelCase       :       Optional[Any]           = torch.cat([input_ids, next_tokens]			,	dim=-1   )
    __lowerCamelCase       :       Tuple           = torch.cat(
        [attn_mask, torch.ones((attn_mask.shape[0], 1)			,	dtype=torch.long			,	device=_a   )]			,	dim=1			,	)

    # get two different outputs
    __lowerCamelCase       :       Dict           = model(_a			,	attention_mask=_a   )['last_hidden_state']
    __lowerCamelCase       :       Optional[Any]           = model(_a			,	past_key_values=_a			,	attention_mask=_a   )['last_hidden_state']

    # select random slice
    __lowerCamelCase       :       Union[str, Any]           = ids_tensor((1,)			,	output_from_past.shape[-1]   ).item()
    __lowerCamelCase       :       List[Any]           = output_from_no_past[:, -1, random_slice_idx].detach()
    __lowerCamelCase       :       str           = output_from_past[:, 0, random_slice_idx].detach()

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




  def 						_lowercase     ( self      :	Union[str, Any]			,	_a      :	Optional[Any]			,	_a      :	Optional[int]			,	_a      :	str			,	_a      :	List[str]			,	_a      :	Any			,	*_a      :	Dict   )					->					Optional[Any]:
    __lowerCamelCase       :       Tuple           = BioGptModel(config=_a   ).to(_a   ).eval()

    __lowerCamelCase       :       List[str]           = torch.ones(input_ids.shape			,	dtype=torch.long			,	device=_a   )

    # first forward pass
    __lowerCamelCase       :       Tuple           = model(_a			,	attention_mask=_a			,	use_cache=_a   )

    __lowerCamelCase       ,__lowerCamelCase       :       Tuple           = outputs.to_tuple()

    # create hypothetical multiple next token and extent to next_input_ids
    __lowerCamelCase       :       Tuple           = ids_tensor((self.batch_size, 3)			,	config.vocab_size   )
    __lowerCamelCase       :       Tuple           = ids_tensor((self.batch_size, 3)			,	2   )

    # append to next input_ids and
    __lowerCamelCase       :       Tuple           = torch.cat([input_ids, next_tokens]			,	dim=-1   )
    __lowerCamelCase       :       Tuple           = torch.cat([attention_mask, next_attn_mask]			,	dim=-1   )

    __lowerCamelCase       :       int           = model(_a			,	attention_mask=_a   )['last_hidden_state']
    __lowerCamelCase       :       List[str]           = model(_a			,	attention_mask=_a			,	past_key_values=_a   )[
        'last_hidden_state'
    ]

    # select random slice
    __lowerCamelCase       :       Optional[Any]           = ids_tensor((1,)			,	output_from_past.shape[-1]   ).item()
    __lowerCamelCase       :       List[str]           = output_from_no_past[:, -3:, random_slice_idx].detach()
    __lowerCamelCase       :       Union[str, Any]           = 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(_a			,	_a			,	atol=1e-3   )   )




  def 						_lowercase     ( self      :	List[str]			,	_a      :	List[Any]			,	_a      :	Any			,	_a      :	Dict			,	_a      :	int			,	_a      :	List[Any]			,	*_a      :	List[Any]			,	_a      :	Optional[Any]=False   )					->					Optional[Any]:
    __lowerCamelCase       :       List[Any]           = BioGptForCausalLM(_a   )
    model.to(_a   )
    if gradient_checkpointing:
      model.gradient_checkpointing_enable()

    __lowerCamelCase       :       Any           = model(_a			,	labels=_a   )
    self.parent.assertEqual(result.loss.shape			,	()   )
    self.parent.assertEqual(result.logits.shape			,	(self.batch_size, self.seq_length, self.vocab_size)   )
    result.loss.backward()




  def 						_lowercase     ( self      :	Any			,	_a      :	str			,	*_a      :	List[Any]   )					->					str:
    __lowerCamelCase       :       List[Any]           = BioGptModel(_a   )
    __lowerCamelCase       :       Tuple           = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers   )
    for key in model.state_dict().keys():
      if "c_proj" in key and "weight" in key:
        self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]   ) - model_std   )			,	0.001   )
        self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]   ) - 0.0   )			,	0.01   )




  def 						_lowercase     ( self      :	Any			,	_a      :	List[Any]			,	_a      :	List[Any]			,	_a      :	List[str]			,	_a      :	List[str]			,	_a      :	str			,	*_a      :	Optional[Any]   )					->					Dict:
    __lowerCamelCase       :       List[str]           = self.num_labels
    __lowerCamelCase       :       Any           = BioGptForTokenClassification(_a   )
    model.to(_a   )
    model.eval()
    __lowerCamelCase       :       str           = model(_a			,	attention_mask=_a			,	token_type_ids=_a   )
    self.parent.assertEqual(result.logits.shape			,	(self.batch_size, self.seq_length, self.num_labels)   )




  def 						_lowercase     ( self      :	Optional[Any]   )					->					int:
    __lowerCamelCase       :       Optional[Any]           = self.prepare_config_and_inputs()
    (
        (
        __lowerCamelCase
    )       ,(
        __lowerCamelCase
    )       ,(
        __lowerCamelCase
    )       ,(
        __lowerCamelCase
    )       ,(
        __lowerCamelCase
    )       ,(
        __lowerCamelCase
    )       ,(
        __lowerCamelCase
    )       ,
    )       :       List[Any]           = config_and_inputs
    __lowerCamelCase       :       Union[str, Any]           = {'input_ids': input_ids, 'attention_mask': input_mask}
    return config, inputs_dict






@require_torch
class 					lowerCamelCase_    (				SCREAMING_SNAKE_CASE_   ,   SCREAMING_SNAKE_CASE_   ,   SCREAMING_SNAKE_CASE_   ,   unittest.TestCase     ):
  """simple docstring"""




  a_												=(
      (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
      if is_torch_available()
      else ()
  )
  a_												=(BioGptForCausalLM,) if is_torch_available() else ()
  a_												=(
      {
          """feature-extraction""": BioGptModel,
          """text-classification""": BioGptForSequenceClassification,
          """text-generation""": BioGptForCausalLM,
          """token-classification""": BioGptForTokenClassification,
          """zero-shot""": BioGptForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  a_												=False




  def 						_lowercase     ( self      :	Dict   )					->					List[Any]:
    __lowerCamelCase       :       Any           = BioGptModelTester(self   )
    __lowerCamelCase       :       Union[str, Any]           = ConfigTester(self			,	config_class=_a			,	hidden_size=37   )




  def 						_lowercase     ( self      :	Optional[int]   )					->					str:
    self.config_tester.run_common_tests()




  def 						_lowercase     ( self      :	Optional[Any]   )					->					List[str]:
    __lowerCamelCase       :       Dict           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*_a   )




  def 						_lowercase     ( self      :	Tuple   )					->					Dict:
    __lowerCamelCase       :       Optional[int]           = self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
      __lowerCamelCase       :       Dict           = type
      self.model_tester.create_and_check_model(*_a   )




  def 						_lowercase     ( self      :	Optional[Any]   )					->					int:
    __lowerCamelCase       :       int           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_biogpt_model_attention_mask_past(*_a   )




  def 						_lowercase     ( self      :	str   )					->					Optional[int]:
    __lowerCamelCase       :       Tuple           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_forward_and_backwards(*_a			,	gradient_checkpointing=_a   )




  def 						_lowercase     ( self      :	Tuple   )					->					Dict:
    __lowerCamelCase       :       Tuple           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_biogpt_model_past_large_inputs(*_a   )




  def 						_lowercase     ( self      :	str   )					->					int:
    __lowerCamelCase       :       Optional[Any]           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_biogpt_weight_initialization(*_a   )




  def 						_lowercase     ( self      :	Optional[int]   )					->					int:
    __lowerCamelCase       :       str           = self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_biogpt_for_token_classification(*_a   )




  @slow
  def 						_lowercase     ( self      :	Optional[int]   )					->					int:
    __lowerCamelCase       :       Any           = BioGptForCausalLM.from_pretrained('microsoft/biogpt'   )
    model.to(_a   )
    __lowerCamelCase       :       Tuple           = BioGptTokenizer.from_pretrained('microsoft/biogpt'   )

    __lowerCamelCase       :       str           = 'left'

    # Define PAD Token = EOS Token = 50256
    __lowerCamelCase       :       Union[str, Any]           = tokenizer.eos_token
    __lowerCamelCase       :       int           = model.config.eos_token_id

    # use different length sentences to test batching
    __lowerCamelCase       :       int           = [
        'Hello, my dog is a little',
        'Today, I',
    ]

    __lowerCamelCase       :       Dict           = tokenizer(_a			,	return_tensors='pt'			,	padding=_a   )
    __lowerCamelCase       :       str           = inputs['input_ids'].to(_a   )

    __lowerCamelCase       :       List[str]           = model.generate(
        input_ids=_a			,	attention_mask=inputs['attention_mask'].to(_a   )			,	)

    __lowerCamelCase       :       Tuple           = tokenizer(sentences[0]			,	return_tensors='pt'   ).input_ids.to(_a   )
    __lowerCamelCase       :       Dict           = model.generate(input_ids=_a   )

    __lowerCamelCase       :       Optional[int]           = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item()
    __lowerCamelCase       :       int           = tokenizer(sentences[1]			,	return_tensors='pt'   ).input_ids.to(_a   )
    __lowerCamelCase       :       Optional[Any]           = model.generate(input_ids=_a			,	max_length=model.config.max_length - num_paddings   )

    __lowerCamelCase       :       Optional[Any]           = tokenizer.batch_decode(_a			,	skip_special_tokens=_a   )
    __lowerCamelCase       :       Dict           = tokenizer.decode(output_non_padded[0]			,	skip_special_tokens=_a   )
    __lowerCamelCase       :       List[Any]           = tokenizer.decode(output_padded[0]			,	skip_special_tokens=_a   )

    __lowerCamelCase       :       Any           = [
        'Hello, my dog is a little bit bigger than a little bit.',
        'Today, I have a good idea of how to use the information',
    ]
    self.assertListEqual(_a			,	_a   )
    self.assertListEqual(_a			,	[non_padded_sentence, padded_sentence]   )




  @slow
  def 						_lowercase     ( self      :	Tuple   )					->					int:
    for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __lowerCamelCase       :       Optional[Any]           = BioGptModel.from_pretrained(_a   )
      self.assertIsNotNone(_a   )




  def 						_lowercase     ( self      :	Union[str, Any]   )					->					List[str]:
    __lowerCamelCase       ,__lowerCamelCase       :       Tuple           = self.model_tester.prepare_config_and_inputs_for_common()
    __lowerCamelCase       :       Union[str, Any]           = 3
    __lowerCamelCase       :       Dict           = input_dict['input_ids']
    __lowerCamelCase       :       List[Any]           = input_ids.ne(1   ).to(_a   )
    __lowerCamelCase       :       Optional[int]           = ids_tensor([self.model_tester.batch_size]			,	self.model_tester.type_sequence_label_size   )
    __lowerCamelCase       :       List[str]           = BioGptForSequenceClassification(_a   )
    model.to(_a   )
    model.eval()
    __lowerCamelCase       :       Optional[int]           = model(_a			,	attention_mask=_a			,	labels=_a   )
    self.assertEqual(result.logits.shape			,	(self.model_tester.batch_size, self.model_tester.num_labels)   )




  def 						_lowercase     ( self      :	List[Any]   )					->					Optional[Any]:
    __lowerCamelCase       ,__lowerCamelCase       :       str           = self.model_tester.prepare_config_and_inputs_for_common()
    __lowerCamelCase       :       Dict           = 3
    __lowerCamelCase       :       List[Any]           = 'multi_label_classification'
    __lowerCamelCase       :       Union[str, Any]           = input_dict['input_ids']
    __lowerCamelCase       :       int           = input_ids.ne(1   ).to(_a   )
    __lowerCamelCase       :       Optional[int]           = ids_tensor(
        [self.model_tester.batch_size, config.num_labels]			,	self.model_tester.type_sequence_label_size   ).to(torch.float   )
    __lowerCamelCase       :       Optional[Any]           = BioGptForSequenceClassification(_a   )
    model.to(_a   )
    model.eval()
    __lowerCamelCase       :       Optional[Any]           = model(_a			,	attention_mask=_a			,	labels=_a   )
    self.assertEqual(result.logits.shape			,	(self.model_tester.batch_size, self.model_tester.num_labels)   )






@require_torch
class 					lowerCamelCase_    (				unittest.TestCase     ):
  """simple docstring"""




  @slow
  def 						_lowercase     ( self      :	int   )					->					Dict:
    __lowerCamelCase       :       Union[str, Any]           = BioGptForCausalLM.from_pretrained('microsoft/biogpt'   )
    __lowerCamelCase       :       Optional[Any]           = torch.tensor([[2, 4805, 9, 656, 21]]   )
    __lowerCamelCase       :       Optional[int]           = model(_a   )[0]

    __lowerCamelCase       :       int           = 4_2384

    __lowerCamelCase       :       Any           = torch.Size((1, 5, vocab_size)   )
    self.assertEqual(output.shape			,	_a   )

    __lowerCamelCase       :       Union[str, Any]           = torch.tensor(
        [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]]   )

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




  @slow
  def 						_lowercase     ( self      :	Dict   )					->					Dict:
    __lowerCamelCase       :       Any           = BioGptTokenizer.from_pretrained('microsoft/biogpt'   )
    __lowerCamelCase       :       Optional[Any]           = BioGptForCausalLM.from_pretrained('microsoft/biogpt'   )
    model.to(_a   )

    torch.manual_seed(0   )
    __lowerCamelCase       :       Optional[int]           = tokenizer('COVID-19 is'			,	return_tensors='pt'   ).to(_a   )
    __lowerCamelCase       :       Tuple           = model.generate(
        **_a			,	min_length=100			,	max_length=1024			,	num_beams=5			,	early_stopping=_a			,	)
    __lowerCamelCase       :       Optional[Any]           = tokenizer.decode(output_ids[0]			,	skip_special_tokens=_a   )

    __lowerCamelCase       :       int           = (
        'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the'
        ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and'
        ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),'
        ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and'
        ' more than 800,000 deaths.'
    )
    self.assertEqual(_a			,	_a   )











'''simple docstring'''





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
_UpperCamelCase											=						data_utils.TransfoXLTokenizer
_UpperCamelCase											=						data_utils.TransfoXLCorpus
_UpperCamelCase											=						data_utils
_UpperCamelCase											=						data_utils

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

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

  if tf_checkpoint_path:
    # Convert a pre-trained TensorFlow model
    __lowerCamelCase       :       int           = os.path.abspath(_lowerCAmelCase       )
    __lowerCamelCase       :       Any           = os.path.abspath(_lowerCAmelCase       )

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

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


if __name__ == "__main__":
   _UpperCamelCase											=						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.',
   )
   _UpperCamelCase											=						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,
   )






