convert.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Copyright 2020 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from argparse import ArgumentParser, Namespace
  15. from ..utils import logging
  16. from . import BaseTransformersCLICommand
  17. def convert_command_factory(args: Namespace):
  18. """
  19. Factory function used to convert a model TF 1.0 checkpoint in a PyTorch checkpoint.
  20. Returns: ServeCommand
  21. """
  22. return ConvertCommand(
  23. args.model_type, args.tf_checkpoint, args.pytorch_dump_output, args.config, args.finetuning_task_name
  24. )
  25. IMPORT_ERROR_MESSAGE = """
  26. transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires
  27. TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.
  28. """
  29. class ConvertCommand(BaseTransformersCLICommand):
  30. @staticmethod
  31. def register_subcommand(parser: ArgumentParser):
  32. """
  33. Register this command to argparse so it's available for the transformer-cli
  34. Args:
  35. parser: Root parser to register command-specific arguments
  36. """
  37. train_parser = parser.add_parser(
  38. "convert",
  39. help="CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.",
  40. )
  41. train_parser.add_argument("--model_type", type=str, required=True, help="Model's type.")
  42. train_parser.add_argument(
  43. "--tf_checkpoint", type=str, required=True, help="TensorFlow checkpoint path or folder."
  44. )
  45. train_parser.add_argument(
  46. "--pytorch_dump_output", type=str, required=True, help="Path to the PyTorch saved model output."
  47. )
  48. train_parser.add_argument("--config", type=str, default="", help="Configuration file path or folder.")
  49. train_parser.add_argument(
  50. "--finetuning_task_name",
  51. type=str,
  52. default=None,
  53. help="Optional fine-tuning task name if the TF model was a finetuned model.",
  54. )
  55. train_parser.set_defaults(func=convert_command_factory)
  56. def __init__(
  57. self,
  58. model_type: str,
  59. tf_checkpoint: str,
  60. pytorch_dump_output: str,
  61. config: str,
  62. finetuning_task_name: str,
  63. *args,
  64. ):
  65. self._logger = logging.get_logger("transformers-cli/converting")
  66. self._logger.info(f"Loading model {model_type}")
  67. self._model_type = model_type
  68. self._tf_checkpoint = tf_checkpoint
  69. self._pytorch_dump_output = pytorch_dump_output
  70. self._config = config
  71. self._finetuning_task_name = finetuning_task_name
  72. def run(self):
  73. if self._model_type == "albert":
  74. try:
  75. from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
  76. convert_tf_checkpoint_to_pytorch,
  77. )
  78. except ImportError:
  79. raise ImportError(IMPORT_ERROR_MESSAGE)
  80. convert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
  81. elif self._model_type == "bert":
  82. try:
  83. from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
  84. convert_tf_checkpoint_to_pytorch,
  85. )
  86. except ImportError:
  87. raise ImportError(IMPORT_ERROR_MESSAGE)
  88. convert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
  89. elif self._model_type == "funnel":
  90. try:
  91. from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
  92. convert_tf_checkpoint_to_pytorch,
  93. )
  94. except ImportError:
  95. raise ImportError(IMPORT_ERROR_MESSAGE)
  96. convert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
  97. elif self._model_type == "t5":
  98. try:
  99. from ..models.t5.convert_t5_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
  100. except ImportError:
  101. raise ImportError(IMPORT_ERROR_MESSAGE)
  102. convert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
  103. elif self._model_type == "gpt":
  104. from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
  105. convert_openai_checkpoint_to_pytorch,
  106. )
  107. convert_openai_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
  108. elif self._model_type == "gpt2":
  109. try:
  110. from ..models.gpt2.convert_gpt2_original_tf_checkpoint_to_pytorch import (
  111. convert_gpt2_checkpoint_to_pytorch,
  112. )
  113. except ImportError:
  114. raise ImportError(IMPORT_ERROR_MESSAGE)
  115. convert_gpt2_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
  116. elif self._model_type == "xlnet":
  117. try:
  118. from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
  119. convert_xlnet_checkpoint_to_pytorch,
  120. )
  121. except ImportError:
  122. raise ImportError(IMPORT_ERROR_MESSAGE)
  123. convert_xlnet_checkpoint_to_pytorch(
  124. self._tf_checkpoint, self._config, self._pytorch_dump_output, self._finetuning_task_name
  125. )
  126. elif self._model_type == "xlm":
  127. from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
  128. convert_xlm_checkpoint_to_pytorch,
  129. )
  130. convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint, self._pytorch_dump_output)
  131. elif self._model_type == "lxmert":
  132. from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
  133. convert_lxmert_checkpoint_to_pytorch,
  134. )
  135. convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint, self._pytorch_dump_output)
  136. elif self._model_type == "rembert":
  137. from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
  138. convert_rembert_tf_checkpoint_to_pytorch,
  139. )
  140. convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint, self._config, self._pytorch_dump_output)
  141. else:
  142. raise ValueError("--model_type should be selected in the list [bert, gpt, gpt2, t5, xlnet, xlm, lxmert]")