|
| 1 | +# Copyright (c) 2024, NVIDIA CORPORATION. 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 | + |
| 15 | + |
| 16 | +"""HuggingFace model serialization support for NeMo's configuration system. |
| 17 | +
|
| 18 | +This module provides integration between NeMo's configuration system and HuggingFace's |
| 19 | +pretrained models. It enables automatic serialization and deserialization of HuggingFace |
| 20 | +models within NeMo's configuration framework. |
| 21 | +
|
| 22 | +The integration works by: |
| 23 | +1. Detecting HuggingFace models through their characteristic methods (save_pretrained/from_pretrained) |
| 24 | +2. Converting them to Fiddle configurations that preserve the model's class and path |
| 25 | +3. Providing an artifact handler (HFAutoArtifact) that manages the actual model files |
| 26 | +
|
| 27 | +Example: |
| 28 | + ```python |
| 29 | + from transformers import AutoModel |
| 30 | + |
| 31 | + # This model will be automatically handled by the HFAutoArtifact system |
| 32 | + model = AutoModel.from_pretrained("bert-base-uncased") |
| 33 | + |
| 34 | + # When serialized, the model files will be saved to the artifacts directory |
| 35 | + # When deserialized, the model will be loaded from the saved files |
| 36 | + ``` |
| 37 | +""" |
| 38 | + |
| 39 | +import contextlib |
| 40 | +import inspect |
| 41 | +import threading |
| 42 | +from pathlib import Path |
| 43 | + |
| 44 | +import fiddle as fdl |
| 45 | + |
| 46 | +from nemo.lightning.io.artifact import Artifact |
| 47 | +from nemo.lightning.io.to_config import to_config |
| 48 | + |
| 49 | +_local = threading.local() |
| 50 | + |
| 51 | + |
| 52 | +class HFAutoArtifact(Artifact): |
| 53 | + """Artifact handler for HuggingFace pretrained model/processor/tokenizer/etc.. |
| 54 | +
|
| 55 | + This handler manages the serialization and deserialization of HuggingFace models |
| 56 | + by utilizing their save_pretrained/from_pretrained methods. It saves models to |
| 57 | + an 'artifacts' subdirectory within the specified path. |
| 58 | + """ |
| 59 | + |
| 60 | + def dump(self, instance, value: Path, absolute_dir: Path, relative_dir: Path) -> Path: |
| 61 | + """Save a HuggingFace model to disk. |
| 62 | +
|
| 63 | + Args: |
| 64 | + instance: The HuggingFace model instance to save |
| 65 | + value: Original path value (unused) |
| 66 | + absolute_dir: Absolute path to the save directory |
| 67 | + relative_dir: Relative path from the config file to the save directory |
| 68 | +
|
| 69 | + Returns: |
| 70 | + str: The relative path to the saved model artifacts |
| 71 | + """ |
| 72 | + instance.save_pretrained(Path(absolute_dir) / "artifacts") |
| 73 | + return "./" + str(Path(relative_dir) / "artifacts") |
| 74 | + |
| 75 | + def load(self, path: Path) -> Path: |
| 76 | + """Return the path to load a HuggingFace model. |
| 77 | +
|
| 78 | + Args: |
| 79 | + path: Path to the saved model artifacts |
| 80 | +
|
| 81 | + Returns: |
| 82 | + Path: The same path, to be used with from_pretrained |
| 83 | + """ |
| 84 | + return path |
| 85 | + |
| 86 | + |
| 87 | +@contextlib.contextmanager |
| 88 | +def from_pretrained_kwargs(**kwargs): |
| 89 | + """Context manager for passing additional kwargs to from_pretrained. |
| 90 | +
|
| 91 | + Args: |
| 92 | + **kwargs: Keyword arguments to pass to from_pretrained |
| 93 | +
|
| 94 | + Example: |
| 95 | + with from_pretrained_kwargs(trust_remote_code=True): |
| 96 | + io.load_context("path/to/checkpoint") |
| 97 | + """ |
| 98 | + if not hasattr(_local, "kwargs"): |
| 99 | + _local.kwargs = {} |
| 100 | + previous = _local.kwargs.copy() |
| 101 | + _local.kwargs.update(kwargs) |
| 102 | + try: |
| 103 | + yield |
| 104 | + finally: |
| 105 | + _local.kwargs = previous |
| 106 | + |
| 107 | + |
| 108 | +def from_pretrained(auto_cls, pretrained_model_name_or_path="dummy"): |
| 109 | + """Factory function for loading HuggingFace pretrained models. |
| 110 | +
|
| 111 | + This function is used as the serialization target for HuggingFace models. |
| 112 | + When deserialized, it will recreate the model using its from_pretrained method. |
| 113 | +
|
| 114 | + Args: |
| 115 | + auto_cls: The HuggingFace model class (e.g., AutoModel, AutoTokenizer) |
| 116 | + pretrained_model_name_or_path: Path to the saved model or model identifier |
| 117 | +
|
| 118 | + Returns: |
| 119 | + The loaded HuggingFace model |
| 120 | + """ |
| 121 | + kwargs = getattr(_local, "kwargs", {}) |
| 122 | + return auto_cls.from_pretrained(pretrained_model_name_or_path, **kwargs) |
| 123 | + |
| 124 | + |
| 125 | +@to_config.register( |
| 126 | + lambda v: not inspect.isclass(v) |
| 127 | + and getattr(v, "__module__", "").startswith("transformers") |
| 128 | + and hasattr(v, "save_pretrained") |
| 129 | + and hasattr(v, "from_pretrained") |
| 130 | +) |
| 131 | +def handle_hf_pretrained(value): |
| 132 | + """Convert a HuggingFace model instance to a Fiddle configuration. |
| 133 | +
|
| 134 | + This handler detects HuggingFace model instances by checking for the presence |
| 135 | + of save_pretrained and from_pretrained methods. It converts them to a Fiddle |
| 136 | + configuration that will recreate the model using from_pretrained. |
| 137 | +
|
| 138 | + Args: |
| 139 | + value: A HuggingFace model instance |
| 140 | +
|
| 141 | + Returns: |
| 142 | + fdl.Config: A Fiddle configuration that will recreate the model |
| 143 | + """ |
| 144 | + return fdl.Config( |
| 145 | + from_pretrained, |
| 146 | + auto_cls=value.__class__, |
| 147 | + pretrained_model_name_or_path="dummy", |
| 148 | + ) |
| 149 | + |
| 150 | + |
| 151 | +# Register the HFAutoArtifact handler for the pretrained_model_name_or_path parameter |
| 152 | +from_pretrained.__io_artifacts__ = [HFAutoArtifact("pretrained_model_name_or_path")] |
0 commit comments