



"""simple docstring"""





import argparse
import os

import torch

from transformers import (
    XLNetConfig,
    XLNetForQuestionAnswering,
    XLNetForSequenceClassification,
    XLNetLMHeadModel,
    load_tf_weights_in_xlnet,
)
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


lowerCamelCase  			=		{
    """cola""": 2,
    """mnli""": 3,
    """mrpc""": 2,
    """sst-2""": 2,
    """sts-b""": 1,
    """qqp""": 2,
    """qnli""": 2,
    """rte""": 2,
    """wnli""": 2,
}


logging.set_verbosity_info()
def   a__      ( lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__=None ):
      # Initialise PyTorch model
      UpperCAmelCase_     					=				XLNetConfig.from_json_file(lowerCAmelCase__ )

      UpperCAmelCase_     					=				finetuning_task.lower() if finetuning_task is not None else ""
      if finetuning_task in GLUE_TASKS_NUM_LABELS:
            print(f"""Building PyTorch XLNetForSequenceClassification model from configuration: {config}""" )
            UpperCAmelCase_     					=				finetuning_task
            UpperCAmelCase_     					=				GLUE_TASKS_NUM_LABELS[finetuning_task]
            UpperCAmelCase_     					=				XLNetForSequenceClassification(lowerCAmelCase__ )
      elif "squad" in finetuning_task:
            UpperCAmelCase_     					=				finetuning_task
            UpperCAmelCase_     					=				XLNetForQuestionAnswering(lowerCAmelCase__ )
      else:
            UpperCAmelCase_     					=				XLNetLMHeadModel(lowerCAmelCase__ )

      # Load weights from tf checkpoint
      load_tf_weights_in_xlnet(lowerCAmelCase__      ,     lowerCAmelCase__      ,     lowerCAmelCase__ )

      # Save pytorch-model
      UpperCAmelCase_     					=				os.path.join(lowerCAmelCase__      ,     lowerCAmelCase__ )
      UpperCAmelCase_     					=				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__":
  lowerCamelCase  			=		argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
  )
  parser.add_argument(
      """--xlnet_config_file""",
      default=None,
      type=str,
      required=True,
      help=(
          """The config json file corresponding to the pre-trained XLNet model. \n"""
          """This specifies the model architecture."""
      ),
  )
  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(
      """--finetuning_task""",
      default=None,
      type=str,
      help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""",
  )
  lowerCamelCase  			=		parser.parse_args()
  print(args)

  convert_xlnet_checkpoint_to_pytorch(
      args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task
  )








'''simple docstring'''


import argparse

import torch

from transformers import GPTaLMHeadModel, RobertaForMaskedLM


if __name__ == "__main__":
      _UpperCamelCase 							=  argparse.ArgumentParser(
          description=(
              """Extraction some layers of the full RobertaForMaskedLM or GPT2LMHeadModel for Transfer Learned"""
              """ Distillation"""
          )
      )
      parser.add_argument("""--model_type""", default="""roberta""", choices=["""roberta""", """gpt2"""])
      parser.add_argument("""--model_name""", default="""roberta-large""", type=str)
      parser.add_argument("""--dump_checkpoint""", default="""serialization_dir/tf_roberta_048131723.pth""", type=str)
      parser.add_argument("""--vocab_transform""", action="""store_true""")
      _UpperCamelCase 							=  parser.parse_args()

      if args.model_type == "roberta":
            _UpperCamelCase 							=  RobertaForMaskedLM.from_pretrained(args.model_name)
            _UpperCamelCase 							=  """roberta"""
      elif args.model_type == "gpt2":
            _UpperCamelCase 							=  GPTaLMHeadModel.from_pretrained(args.model_name)
            _UpperCamelCase 							=  """transformer"""

      _UpperCamelCase 							=  model.state_dict()
      _UpperCamelCase 							=  {}

      # Embeddings #
      if args.model_type == "gpt2":
            for param_name in ["wte.weight", "wpe.weight"]:
                  _UpperCamelCase 							=  state_dict[F"""{prefix}.{param_name}"""]
      else:
            for w in ["word_embeddings", "position_embeddings", "token_type_embeddings"]:
                  _UpperCamelCase 							=  F"""{prefix}.embeddings.{w}.weight"""
                  _UpperCamelCase 							=  state_dict[param_name]
            for w in ["weight", "bias"]:
                  _UpperCamelCase 							=  F"""{prefix}.embeddings.LayerNorm.{w}"""
                  _UpperCamelCase 							=  state_dict[param_name]

    # Transformer Blocks #
      _UpperCamelCase 							=  0
      for teacher_idx in [0, 2, 4, 7, 9, 11]:
            if args.model_type == "gpt2":
                  for layer in ["ln_1", "attn.c_attn", "attn.c_proj", "ln_2", "mlp.c_fc", "mlp.c_proj"]:
                        for w in ["weight", "bias"]:
                              _UpperCamelCase 							=  state_dict[
                                  F"""{prefix}.h.{teacher_idx}.{layer}.{w}"""
                              ]
                  _UpperCamelCase 							=  state_dict[F"""{prefix}.h.{teacher_idx}.attn.bias"""]
            else:
                  for layer in [
                      "attention.self.query",
                      "attention.self.key",
                      "attention.self.value",
                      "attention.output.dense",
                      "attention.output.LayerNorm",
                      "intermediate.dense",
                      "output.dense",
                      "output.LayerNorm",
                  ]:
                        for w in ["weight", "bias"]:
                              _UpperCamelCase 							=  state_dict[
                                  F"""{prefix}.encoder.layer.{teacher_idx}.{layer}.{w}"""
                              ]
            std_idx += 1

      # Language Modeling Head ###s
      if args.model_type == "roberta":
            for layer in ["lm_head.decoder.weight", "lm_head.bias"]:
                  _UpperCamelCase 							=  state_dict[F"""{layer}"""]
            if args.vocab_transform:
                  for w in ["weight", "bias"]:
                        _UpperCamelCase 							=  state_dict[F"""lm_head.dense.{w}"""]
                        _UpperCamelCase 							=  state_dict[F"""lm_head.layer_norm.{w}"""]
      elif args.model_type == "gpt2":
            for w in ["weight", "bias"]:
                  _UpperCamelCase 							=  state_dict[F"""{prefix}.ln_f.{w}"""]
            _UpperCamelCase 							=  state_dict["""lm_head.weight"""]

      print(F"""N layers selected for distillation: {std_idx}""")
      print(F"""Number of params transferred for distillation: {len(compressed_sd.keys())}""")

      print(F"""Save transferred checkpoint to {args.dump_checkpoint}.""")
      torch.save(compressed_sd, args.dump_checkpoint)

