

import argparse

import torch
from torch import nn

from transformers import PLBartConfig, PLBartForConditionalGeneration, PLBartForSequenceClassification





def 	snake_case_      (__A     :						Dict     )			->	List[Any]:
   __lowerCAmelCase  :			int					    =						[
       """encoder.version""",
       """decoder.version""",
       """model.encoder.version""",
       """model.decoder.version""",
       """_float_tensor""",
       """decoder.output_projection.weight""",
   ]
   for k in ignore_keys:
      state_dict.pop(__A					,   __A     )





def 	snake_case_      (__A     :						Any     )			->	Union[str, Any]:
   __lowerCAmelCase    ,__lowerCAmelCase  :			Dict					    =						emb.weight.shape
   __lowerCAmelCase  :			List[Any]					    =						nn.Linear(__A					,   __A					,   bias=__A     )
   __lowerCAmelCase  :			str					    =						emb.weight.data
   return lin_layer





def 	snake_case_      (__A     :						str					,   __A     :						Dict="uclanlp/plbart-base"					,   __A     :						Optional[Any]=False					,   __A     :						Optional[int]=False     )			->	Union[str, Any]:
   __lowerCAmelCase  :			Any					    =						torch.load(__A					,   map_location="""cpu"""     )["""model"""]
   remove_ignore_keys_(__A     )
   __lowerCAmelCase  :			List[str]					    =						state_dict["""encoder.embed_tokens.weight"""].shape[0]

   __lowerCAmelCase  :			Optional[Any]					    =						PLBartConfig.from_pretrained(__A					,   vocab_size=__A     )

   __lowerCAmelCase  :			Any					    =						state_dict["""decoder.embed_tokens.weight"""]
   if not classification:
      __lowerCAmelCase  :			Any					    =						PLBartForConditionalGeneration(__A     )
      model.model.load_state_dict(__A     )
      if finetuned:
         __lowerCAmelCase  :			List[Any]					    =						make_linear_from_emb(model.model.shared     )

   else:
      __lowerCAmelCase  :			Any					    =						{}
      for key, value in state_dict.copy().items():
         if key.startswith("""classification_heads.sentence_classification_head"""     ):
            __lowerCAmelCase  :			Tuple					    =						value
            state_dict.pop(__A     )
      __lowerCAmelCase  :			str					    =						PLBartForSequenceClassification(__A     )
      model.model.load_state_dict(__A     )
      model.classification_head.load_state_dict(__A     )

   return model


if __name__ == "__main__":
   __UpperCAmelCase      = argparse.ArgumentParser()
   # Required parameters
   parser.add_argument("""fairseq_path""", type=str, help="""model.pt on local filesystem.""")
   parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
   parser.add_argument(
       """--hf_config""",
       default="""uclanlp/plbart-base""",
       type=str,
       help="""Which huggingface architecture to use: plbart-base""",
   )
   parser.add_argument("""--finetuned""", action="""store_true""", help="""whether the model is a fine-tuned checkpoint""")
   parser.add_argument(
       """--classification""", action="""store_true""", help="""whether the model is a classification checkpoint"""
   )
   __UpperCAmelCase      = parser.parse_args()
   __UpperCAmelCase      = convert_fairseq_plbart_checkpoint_from_disk(
       args.fairseq_path,
       hf_config_path=args.hf_config,
       finetuned=args.finetuned,
       classification=args.classification,
   )
   model.save_pretrained(args.pytorch_dump_folder_path)





import importlib.metadata
import subprocess
import sys





def 	snake_case_      (__A     :						bool = False     )			->	str:
   __lowerCAmelCase  :			Any					    =						False
   if "IPython" in sys.modules:
      __lowerCAmelCase  :			Optional[int]					    =						"""google.colab""" in str(sys.modules["""IPython"""].get_ipython()     )

   if in_colab:
      if upgrade:
         __lowerCAmelCase  :			int					    =						["""pip""", """install""", """-U""", """torch"""]
         subprocess.run(__A					,   check=__A     )
      # get the current version of torch
      __lowerCAmelCase  :			List[Any]					    =						importlib.metadata.version("""torch"""     )
      __lowerCAmelCase  :			List[Any]					    =						torch_version[: torch_version.rindex("""."""     )]
      __lowerCAmelCase  :			int					    =						f'''https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-{torch_version_trunc}-cp37-cp37m-linux_x86_64.whl'''
      __lowerCAmelCase  :			List[Any]					    =						["""pip""", """install""", xla_wheel]
      subprocess.run(__A					,   check=__A     )
   else:
      raise RuntimeError("""`install_xla` utility works only on google colab."""     )


