|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Shared mixin for HuggingFace speculative decoding model classes.""" |
| 17 | + |
| 18 | +# mypy: disable-error-code="attr-defined,misc" |
| 19 | + |
| 20 | +import contextlib |
| 21 | + |
| 22 | +import torch |
| 23 | +from torch.nn import CrossEntropyLoss |
| 24 | + |
| 25 | +from .modeling_fakebase import _BASE_MODEL_PATHS, _EMBED_TOKENS_PATHS, _LM_HEAD_PATHS |
| 26 | + |
| 27 | +__all__ = ["HFSpecDecMixin"] |
| 28 | + |
| 29 | + |
| 30 | +class HFSpecDecMixin: |
| 31 | + """Mixin providing HuggingFace base-model discovery for speculative decoding plugins. |
| 32 | +
|
| 33 | + Provides shared properties and methods for locating base-model submodules |
| 34 | + (backbone, embeddings, lm_head) and running the base-model forward pass. |
| 35 | +
|
| 36 | + Must be used with multiple inheritance alongside an algorithm-specific base |
| 37 | + (EagleModel, DFlashModel, etc.) that inherits from DynamicModule. |
| 38 | +
|
| 39 | + Example:: |
| 40 | +
|
| 41 | + @EagleDMRegistry.register({PreTrainedModel: "hf.PreTrainedModel"}) |
| 42 | + class HFEagleModel(HFSpecDecMixin, EagleModel): ... |
| 43 | + """ |
| 44 | + |
| 45 | + # -- Class attributes (subclasses may override) -- |
| 46 | + |
| 47 | + # List of (method_name, compile_kwargs) for _activate_torch_compile(). |
| 48 | + # Example: [("_eagle_forward", {"mode": "max-autotune"}), ("_eagle_loss", {"fullgraph": True})] |
| 49 | + _compile_targets: list[tuple[str, dict]] = [] |
| 50 | + |
| 51 | + # -- Properties: base model access -- |
| 52 | + |
| 53 | + @property |
| 54 | + def _base_model(self): |
| 55 | + return self.get_submodule(self.base_model_path) |
| 56 | + |
| 57 | + @property |
| 58 | + def _base_model_embeddings(self): |
| 59 | + return self.get_submodule(self.base_model_embeddings_path) |
| 60 | + |
| 61 | + @property |
| 62 | + def _base_model_lm_head(self): |
| 63 | + return self.get_submodule(self.base_model_lm_head_path) |
| 64 | + |
| 65 | + @property |
| 66 | + def _base_llm_config(self): |
| 67 | + """Return the LLM config for the base model, handling VLM nesting.""" |
| 68 | + return ( |
| 69 | + getattr(self.config, "text_config", None) |
| 70 | + or getattr(self.config, "llm_config", None) |
| 71 | + or self.config |
| 72 | + ) |
| 73 | + |
| 74 | + # -- Methods: model discovery -- |
| 75 | + |
| 76 | + def _find_base_model_parts(self): |
| 77 | + """Find model parts from different models and set base_{part}_path attributes. |
| 78 | +
|
| 79 | + Iterates over candidate submodule paths from modeling_fakebase to locate the |
| 80 | + base model backbone, embedding layer, and LM head. |
| 81 | +
|
| 82 | + Raises: |
| 83 | + ValueError: If any required model part cannot be found. |
| 84 | + """ |
| 85 | + for name, paths in { |
| 86 | + "base_model_path": _BASE_MODEL_PATHS, |
| 87 | + "base_model_embeddings_path": _EMBED_TOKENS_PATHS, |
| 88 | + "base_model_lm_head_path": _LM_HEAD_PATHS, |
| 89 | + }.items(): |
| 90 | + for path in paths: |
| 91 | + try: |
| 92 | + submodule = self.get_submodule(path) |
| 93 | + assert isinstance(submodule, torch.nn.Module) |
| 94 | + setattr(self, name, path) |
| 95 | + break |
| 96 | + except Exception: |
| 97 | + continue |
| 98 | + else: |
| 99 | + raise ValueError(f"Part {name} not found in model") |
| 100 | + |
| 101 | + # -- Methods: base model forward -- |
| 102 | + |
| 103 | + def _base_model_forward(self, input_ids, attention_mask, freeze=True, labels=None, **kwargs): |
| 104 | + """Run the base model forward pass with optional freeze and base-model loss. |
| 105 | +
|
| 106 | + Args: |
| 107 | + input_ids: Input token IDs. |
| 108 | + attention_mask: Attention mask. |
| 109 | + freeze: If True, run under torch.no_grad(). |
| 110 | + labels: Optional labels for computing base model CE loss. |
| 111 | + **kwargs: Additional keyword arguments forwarded to the base model. |
| 112 | +
|
| 113 | + Returns: |
| 114 | + (outputs, base_loss) tuple where outputs is the raw model output and |
| 115 | + base_loss is the cross-entropy loss (None if freeze=True or labels=None). |
| 116 | + """ |
| 117 | + ctx = torch.no_grad() if freeze else contextlib.nullcontext() |
| 118 | + with ctx: |
| 119 | + outputs = super().forward( |
| 120 | + input_ids=input_ids, |
| 121 | + attention_mask=attention_mask, |
| 122 | + output_hidden_states=True, |
| 123 | + **kwargs, |
| 124 | + ) |
| 125 | + base_loss = None |
| 126 | + if not freeze and labels is not None: |
| 127 | + loss_fct = CrossEntropyLoss() |
| 128 | + base_loss = loss_fct( |
| 129 | + outputs.logits.view(-1, outputs.logits.shape[-1]), |
| 130 | + labels.view(-1), |
| 131 | + ) |
| 132 | + return outputs, base_loss |
| 133 | + |
| 134 | + # -- Methods: profiling & compilation -- |
| 135 | + |
| 136 | + def _nvtx_range(self, name): |
| 137 | + """Optionally create an NVTX range for profiling. |
| 138 | +
|
| 139 | + Enabled when the subclass sets ``self._enable_nvtx = True`` in ``modify()``. |
| 140 | + """ |
| 141 | + if not getattr(self, "_enable_nvtx", False): |
| 142 | + return contextlib.nullcontext() |
| 143 | + try: |
| 144 | + import torch.cuda.nvtx as nvtx |
| 145 | + |
| 146 | + return nvtx.range(name) |
| 147 | + except Exception as e: |
| 148 | + print(f"Failed to create NVTX range {name}: {e}") |
| 149 | + return contextlib.nullcontext() |
| 150 | + |
| 151 | + def _activate_torch_compile(self): |
| 152 | + """Apply ``torch.compile`` to methods listed in ``_compile_targets``. |
| 153 | +
|
| 154 | + Each entry is ``(method_name, extra_kwargs)`` passed to ``torch.compile(..., dynamic=False)``. |
| 155 | + Failures fall back to eager mode silently. |
| 156 | + """ |
| 157 | + import torch._dynamo |
| 158 | + |
| 159 | + torch._dynamo.config.suppress_errors = True # Allow fallback to eager mode |
| 160 | + |
| 161 | + for name, kwargs in self._compile_targets: |
| 162 | + try: |
| 163 | + setattr(self, name, torch.compile(getattr(self, name), dynamic=False, **kwargs)) |
| 164 | + except Exception: # noqa: PERF203 |
| 165 | + print(f"Disabling torch.compile for {name} due to compilation error.") |
| 166 | + |
| 167 | + # -- Methods: export interface (subclasses must override) -- |
| 168 | + |
| 169 | + def get_dummy_inputs(self) -> dict: |
| 170 | + """Construct dummy inputs for export forward pass. Subclasses must override.""" |
| 171 | + raise NotImplementedError |
| 172 | + |
| 173 | + def get_exporter(self): |
| 174 | + """Return the exporter for the draft model. Subclasses must override.""" |
| 175 | + raise NotImplementedError |
0 commit comments