mirror of
https://github.com/NVIDIA/Model-Optimizer.git
synced 2026-12-06 04:57:17 +08:00
fix(speculative): one label alignment per projector_type; DSpark and Domino export the head they built (#2762)
### What does this PR do? Type of change: Bug fix A DFlash-family drafter's label alignment belongs to its algorithm. DSpark and Domino train block position `k` on the token at `anchor + k + 1`: next-token, so the anchor is itself a prediction. DFlash, DFlash2 and LiLiCorr train it on `anchor + k`: each masked position predicts itself. Since #2757 the class constant `_label_shift` drives the training targets, but on `main` the same fact is still written in four more places, and the exports read it from the user's config: - `DSparkModule.shift_label`, hard-coded `True`. - `DominoModule.shift_label`, read from the config. - A `NotImplementedError` in `HFDominoModel.modify`. - The exporters' `getattr(draft_config, "shift_label", True)`, plus a literal `sample_from_anchor: True` in the vanilla DSpark export. Three bugs follow: 1. **`shift_label` in the config is ignored or contradicted.** - DSpark with `shift_label: false` trains next-token alignment anyway and exports `shift_label: false`, so a loader that honors the field reads every drafted position one token off. - Domino refuses it, but only after building the draft. - DFlash, DFlash2 and LiLiCorr accept the field and ignore it. 2. **The exporters re-read head fields from the raw config.** - `DSparkModule` casts `markov_rank` to int, so a rank written as `64.0` trains a rank-64 head and exports `64.0`. - The vanilla export copies that value to the top level, where vLLM's `Qwen3DSparkModel` sizes its Markov table. - `use_confidence_head` and Domino's `pure_draft_prefix_len` are re-read with defaults of their own. 3. **Domino's HF AR validation drafts one position off, without its head.** `HFDominoModel` inherits DFlash's `pseudo_speculative_generate`, which decodes block positions `1..bs-1` with the backbone alone, so every draft is scored against the wrong target. Shipped training is unaffected: `domino.yaml` keeps AR validation off. The fixes: - **The alignment comes from `projector_type` alone.** - `shift_label` is deprecated and will be removed in 0.50. Before converting the model, `convert_to_dflash_model` compares it with the wrapper class's `_label_shift`: - A matching value is dropped with a `FutureWarning`. Configs copied from the old Domino recipe (`shift_label: true`) keep working through the migration window in the README's deprecation policy. - A contradicting value raises, because it never took effect. - Why the check does not warn and override, as `HFDFlashModel.modify` does for RoPE: on `main` a contradicting value was already ignored or refused. DFlash, DFlash2 and LiLiCorr ignored it, DSpark trained next-token anyway, and Domino refused `false`. Overriding it with a warning would let a run go on that does not train what its config says. - Why it is not a `DFlashConfig` validator: the alignment lives on the plugin's wrapper class, which the config layer does not import. A validator would also run on restore, where old checkpoints carry contradicting values. - `restore_dflash_model` drops the key unchecked before replaying convert, so checkpoints that carry it still load. DSpark ones saved with `shift_label: false` now re-export `true`. - Both halves read one table, `_DEPRECATED_ARCHITECTURE_KEYS` in `dflash/conversion.py`. It pairs each key with the model attribute that now fixes its value, and the reason, so the check and the restore filter cannot drift apart. - The exports write `shift_label`, and DSpark's `sample_from_anchor` (vLLM's name for the same alignment), from `_label_shift`. - The modules' `shift_label` attributes and Domino's own check are gone. The Domino recipe, the skill sheets and the test configs no longer set the key. - **The exporters read the built head** for `markov_rank`, `markov_head_type`, `use_confidence_head`, `pure_draft_prefix_len`, `gru_hidden_dim` and `emb_dim`, as `LiLiCorrExporter` already does. - **Domino's `pseudo_speculative_generate` raises `NotImplementedError`.** - HF AR validation is being deprecated (#3107), so Domino gets no decode of its own. - Domino acceptance cannot be measured anywhere yet: - The inherited decode drafts with the backbone alone, one block position off. - The export declares `DFlashDraftModel`, so vLLM would serve it the same way. - `examples/specdec_bench` has no Domino route. The error, the changelog and the skill sheet now say so, matching the launcher example's note. - The eval-time warning that called acceptance rates "backbone-only" is removed. The `forward` docstring and the skill sheet now note that eval loss and accuracy exclude the correction head; the recipe sets `do_eval: false`. - During training, the AR callback already catches the error and logs `AR validation not available.` - **Changelog (0.49.0):** a Deprecations entry for `shift_label`, and a Bug Fixes entry for the exports and Domino's AR validation. ### Usage Remove `shift_label` from DFlash-family configs, since `projector_type` fixes the alignment. Until 0.50 a value that matches the variant only warns: ```yaml dflash: dflash_architecture_config: projector_type: domino # shift_label: true # deprecated: warns until 0.50; false raises ``` ### Testing - New and changed tests: - `test_deprecated_shift_label[dflash|dspark|domino x true|false]` restores a modelopt_state that carries `shift_label`, then converts with it. A matching value warns, converts, and is not saved in the new modelopt_state. A contradicting one raises and leaves the model unconverted. - All 6 cases fail on `main` (09a14b9ae8). - With the previous revision's refusal (39ffc25218), the 3 matching cases fail. - Without the restore filter, the 3 contradicting cases fail at restore. - `test_export_config_has_dspark_fields` converts with `markov_rank` given as a float and expects an int at both config levels. All 8 cases fail without the exporter change. - `TestDominoForward::test_ar_validation_is_refused` fails without the override, because the inherited decode then runs. - Rebased onto `main` (ef893e7708) asbd19e2d81b. `git range-diff` shows the same changes commit for commit; only the skill sheets' new location under `skills/modelopt-speculative-decoding/` and CHANGELOG context differ. - Atbd19e2d81b, Python 3.12, transformers 5.18.0, torch 2.13: `test_hf_{dflash,dflash2,dspark,domino,lilicorr}.py`, `tests/unit/recipe`, `tests/unit/torch/export/test_hf_spec_rope_export.py`, `tests/unit/examples/test_deepseek_v4_recipe.py` and `tools/launcher/tests/test_examples_resolve.py`: 987 passed. - Before the rebase, ata944d85bb7, Python 3.12, transformers 5.18.0, torch 2.10: `test_hf_{dflash,dflash2,dspark,domino,lilicorr}.py`, 318 passed. - At39ffc25218, which differs from the head only in the `shift_label` check, Domino's error text and docs: - Those five files plus `tests/unit/recipe/test_loader.py`, `tests/unit/torch/export/test_hf_spec_rope_export.py` and `tests/unit/examples/test_deepseek_v4_recipe.py`: 834 passed. - `tools/launcher/tests/test_examples_resolve.py`: 75 passed. - `tests/gpu/torch/speculative/plugins/test_hf_dflash.py` on 2 GPUs (torch 2.13): 16 passed. - Not run: - transformers 5.5 and 5.12, which CI's multi-version job covers. An earlier revision passed 792 of these tests on 5.5.4, 5.12.1 and 5.18.0. - A bitwise A/B, because no training code changes. ### Before your PR is "*Ready for review*" Make sure you read and follow [Contributor guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md) and your commits are signed (`git commit -s -S`). Make sure you read and follow the [Security Best Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors) (e.g. avoiding hardcoded `trust_remote_code=True`, `torch.load(..., weights_only=False)`, `pickle`, etc.). - Is this change backward compatible?: - ✅ for a `shift_label` that matches the variant, including the shipped Domino recipe's `true`. Such configs convert as before, with a deprecation warning. - ❌ for a contradicting `shift_label`, which now raises at convert: it never took effect. That is DFlash, DFlash2 or LiLiCorr with `true`, and DSpark or Domino with `false`. - Existing checkpoints still load. - Domino with `shift_label: false` raises `ValueError` instead of `NotImplementedError`. - Domino's HF AR validation raises instead of returning misaligned drafts. - If you copied code from any other sources or added a new PIP dependency, did you follow guidance in `CONTRIBUTING.md`: N/A - Did you write any new necessary tests?: ✅ - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ✅ 0.49.0: a Deprecations entry for `shift_label`, and a Bug Fixes entry, since DSpark and Domino have shipped since 0.46.0. - Did you get Claude approval on this PR?: ✅ Approved at39ffc25218. Its one suggestion is addressed at the head. ### Additional Information Follow-up to #2757, now merged. The shared-forward PRs, #2989 [1/2] and then #2990 [2/2], build on this branch and will be restacked onto it. Found while testing and not fixed here; it fails the same way on `main`: with `DFlashModule` as its own FSDP2 unit, DSpark and Domino training fails with `got mixed torch.Tensor and DTensor`, because their heads run outside `DFlashModule.forward`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Corrected DSpark and Domino export settings to reflect the built model configuration. * Fixed a validation error in Domino’s Hugging Face autoregressive validation; this validation is not supported for Domino. * **Deprecations** * `shift_label` is deprecated and planned for removal in version 0.50. Matching values are ignored with a warning; conflicting values cause an error. Existing checkpoints containing the setting can still be loaded. * **Documentation** * Updated speculative decoding guidance to reflect the deprecation and Domino’s evaluation limitations. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: h-guo18 <67671475+h-guo18@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
d9ff11fb8d
commit
9047bbd418
@@ -105,6 +105,7 @@ Changelog
|
||||
- ``modelopt.torch.export.copy_non_safetensor_files_from_ckpt`` is deprecated; use ``copy_non_model_files``.
|
||||
- ``modelopt.torch.sparsity.attention_sparsity.sparsify`` (``mtsa.sparsify``) is deprecated; use ``mts.sparsify(model, config, forward_loop=forward_loop)``.
|
||||
- PyTorch 2.10 support is deprecated and will be dropped in a future release.
|
||||
- ``dflash_architecture_config.shift_label`` is deprecated and will be removed in 0.50, since ``projector_type`` fixes the label alignment (DSpark and Domino predict the next token): remove it from DFlash-family configs. Until then a value matching ``projector_type`` is ignored with a warning and any other raises, as it never took effect; checkpoints saved with it still load.
|
||||
|
||||
**Bug Fixes**
|
||||
|
||||
@@ -131,6 +132,7 @@ Changelog
|
||||
- Fix GPT-OSS draft training with pre-normalization teacher hidden states by enabling the target model's final normalization.
|
||||
- Fix vanilla DSpark exports to use the Qwen3 DSpark architecture, head names and configuration expected by vLLM. Re-export existing training checkpoints to use this format.
|
||||
- ``mtq.fold_weight`` now folds sequential weight quantizers (e.g. W4A8 INT4 + FP8 weights) into the weights; it used to leave them unfolded and enabled.
|
||||
- DSpark and Domino exports now write the ``shift_label``, ``markov_rank`` and other head fields they were trained with. Domino's HF AR validation (``pseudo_speculative_generate``) now raises instead of scoring the backbone one block position off; Domino acceptance cannot be measured until a runtime applies its correction head.
|
||||
- Fix ONNX quantization placing a per-tensor Q/DQ pair on a rank-0 (scalar) constant input, which TensorRT's ONNX parser rejects (``convertAxis`` asserts the quantization axis lies in ``[0, nbDims]`` but ``nbDims == 0``). Rank-0 constant operands are now kept unquantized in the int8, fp8, and autotune export paths; the existing single-element Mul/Div/Pad stripping stays gated under ``target_dla``.
|
||||
- Fix the diffusers skip-softmax HF export to emit the schema TensorRT-LLM VisualGen loads (``threshold_scale_factor.coefficients`` and a scalar ``target_sparsity``). Re-export checkpoints that failed to load.
|
||||
- Fix PTQ of native Transformers FP8 experts to apply source weight scales during calibration and export. Re-quantize affected checkpoints from the original FP8 source.
|
||||
|
||||
@@ -522,19 +522,19 @@ class DominoExporter(DFlashExporter):
|
||||
"""Extend the DFlash config with the Domino head fields."""
|
||||
config = super()._export_config()
|
||||
draft_config = self.model.dflash_config
|
||||
# Read off the built head rather than the config dict, so the export describes the
|
||||
# head these weights belong to.
|
||||
head = self.model.dflash_module
|
||||
|
||||
# Present because HFDominoModel.modify validates them at convert time.
|
||||
emb_dim = draft_config.emb_dim
|
||||
gru_hidden_dim = draft_config.gru_hidden_dim
|
||||
# Mirror the reference checkpoint: emb_dim also appears at the top level.
|
||||
config["emb_dim"] = emb_dim
|
||||
config["emb_dim"] = head.emb_dim
|
||||
config["dflash_config"].update(
|
||||
{
|
||||
"projector_type": getattr(draft_config, "projector_type", "domino"),
|
||||
"shift_label": getattr(draft_config, "shift_label", True),
|
||||
"pure_draft_prefix_len": getattr(draft_config, "pure_draft_prefix_len", 1),
|
||||
"gru_hidden_dim": gru_hidden_dim,
|
||||
"emb_dim": emb_dim,
|
||||
"shift_label": bool(self.model._label_shift),
|
||||
"pure_draft_prefix_len": head.pure_draft_prefix_len,
|
||||
"gru_hidden_dim": head.gru_hidden_dim,
|
||||
"emb_dim": head.emb_dim,
|
||||
}
|
||||
)
|
||||
return config
|
||||
@@ -616,14 +616,17 @@ class DSparkExporter(DFlashExporter):
|
||||
"""Extend the DFlash config with the DSpark head fields."""
|
||||
config = super()._export_config()
|
||||
draft_config = self.model.dflash_config
|
||||
# Read off the built head, not the config dict: DSparkModule casts markov_rank to int
|
||||
# and lower-cases markov_head_type, and the export must describe what was trained.
|
||||
head = self.model.dflash_module
|
||||
|
||||
config["dflash_config"].update(
|
||||
{
|
||||
"projector_type": getattr(draft_config, "projector_type", "dspark"),
|
||||
"shift_label": getattr(draft_config, "shift_label", True),
|
||||
"markov_rank": draft_config.markov_rank,
|
||||
"markov_head_type": self.model.dflash_module.markov_head_type,
|
||||
"use_confidence_head": bool(getattr(draft_config, "use_confidence_head", False)),
|
||||
"shift_label": bool(self.model._label_shift),
|
||||
"markov_rank": head.markov_rank,
|
||||
"markov_head_type": head.markov_head_type,
|
||||
"use_confidence_head": head.use_confidence_head,
|
||||
}
|
||||
)
|
||||
if config["dflash_config"]["markov_head_type"] == "vanilla":
|
||||
@@ -635,7 +638,7 @@ class DSparkExporter(DFlashExporter):
|
||||
"mask_token_id": config["dflash_config"]["mask_token_id"],
|
||||
"target_layer_ids": config["dflash_config"]["target_layer_ids"],
|
||||
"markov_rank": config["dflash_config"]["markov_rank"],
|
||||
"sample_from_anchor": True,
|
||||
"sample_from_anchor": bool(self.model._label_shift),
|
||||
"enable_confidence_head": config["dflash_config"]["use_confidence_head"],
|
||||
"confidence_head_with_markov": config["dflash_config"]["use_confidence_head"],
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
|
||||
"""DFlash conversion/restore utilities."""
|
||||
|
||||
import warnings
|
||||
|
||||
from torch import nn
|
||||
|
||||
from modelopt.torch.opt.conversion import ModelLikeModule
|
||||
@@ -58,6 +60,40 @@ _REGISTRY_BY_PROJECTOR_TYPE = {
|
||||
"lilicorr": LiLiCorrDMRegistry,
|
||||
}
|
||||
|
||||
# Deprecated dflash_architecture_config keys (removed in 0.50), each with the model attribute
|
||||
# that now fixes its value, and why.
|
||||
_DEPRECATED_ARCHITECTURE_KEYS = {
|
||||
"shift_label": (
|
||||
"_label_shift",
|
||||
(
|
||||
"projector_type fixes the label alignment (dspark and domino predict the token at "
|
||||
"anchor + k + 1, the others the token at anchor + k)"
|
||||
),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _drop_deprecated_keys(arch_config: dict, dm_cls: type) -> dict:
|
||||
"""Return ``arch_config`` without the deprecated keys, warning on each value ``dm_cls`` matches.
|
||||
|
||||
A value ``dm_cls`` contradicts raises instead: it never took effect, so the run would not
|
||||
train what its config says.
|
||||
"""
|
||||
for key in sorted(_DEPRECATED_ARCHITECTURE_KEYS.keys() & arch_config.keys()):
|
||||
attr, reason = _DEPRECATED_ARCHITECTURE_KEYS[key]
|
||||
if arch_config[key] != getattr(dm_cls, attr):
|
||||
raise ValueError(
|
||||
f"dflash_architecture_config.{key}={arch_config[key]!r} contradicts the model: "
|
||||
f"{reason}. Remove it."
|
||||
)
|
||||
warnings.warn(
|
||||
f"dflash_architecture_config.{key} is deprecated and will be removed in 0.50: "
|
||||
f"{reason}. Remove it.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return {k: v for k, v in arch_config.items() if k not in _DEPRECATED_ARCHITECTURE_KEYS}
|
||||
|
||||
|
||||
def convert_to_dflash_model(model: nn.Module, config: DFlashConfig) -> ConvertReturnType:
|
||||
"""Convert the model to a DFlash (or Domino) model as per `config`."""
|
||||
@@ -79,6 +115,9 @@ def convert_to_dflash_model(model: nn.Module, config: DFlashConfig) -> ConvertRe
|
||||
)
|
||||
|
||||
registry.register_subclass(type(model), "base_model_class")
|
||||
config.dflash_architecture_config = _drop_deprecated_keys(
|
||||
config.dflash_architecture_config, registry[type(model)]
|
||||
)
|
||||
|
||||
dflash_model = registry.convert(model)
|
||||
dflash_model.modify(config)
|
||||
@@ -95,4 +134,10 @@ def restore_dflash_model(
|
||||
# Warm start is a one-time training-time init; the restored weights would overwrite it
|
||||
# anyway, and replaying it on the meta device would raise.
|
||||
config = config.model_copy(update={"dflash_init_checkpoint": None})
|
||||
# Unchecked: checkpoints saved before the deprecation carry values that never took effect.
|
||||
config.dflash_architecture_config = {
|
||||
k: v
|
||||
for k, v in config.dflash_architecture_config.items()
|
||||
if k not in _DEPRECATED_ARCHITECTURE_KEYS
|
||||
}
|
||||
return convert_to_dflash_model(model, config)[0]
|
||||
|
||||
@@ -133,10 +133,6 @@ class HFDominoModel(HFDFlashModel):
|
||||
self.dflash_lambda_base_start = config.dflash_lambda_base_start
|
||||
self.dflash_lambda_base_decay_ratio = config.dflash_lambda_base_decay_ratio
|
||||
self._lambda_base = self.dflash_lambda_base_start
|
||||
if not getattr(self.dflash_module, "shift_label", True):
|
||||
raise NotImplementedError(
|
||||
"Domino currently supports shift_label=True (next-token alignment) only."
|
||||
)
|
||||
|
||||
def get_exporter(self):
|
||||
"""Get the exporter for the Domino draft model."""
|
||||
@@ -264,17 +260,10 @@ class HFDominoModel(HFDFlashModel):
|
||||
|
||||
Mirrors ``HFDFlashModel.forward`` for data preparation (reusing the inherited
|
||||
anchor/noise/mask/position helpers), then applies the Domino head and the
|
||||
two-term loss. Eval/offline-eval is delegated to the DFlash parent.
|
||||
two-term loss. Eval/offline-eval is delegated to the DFlash parent, so eval loss and
|
||||
accuracy exclude the correction head.
|
||||
"""
|
||||
if not self.training:
|
||||
# Eval delegates to the DFlash backbone; the correction head is not
|
||||
# applied yet, so warn once that acceptance rates are backbone-only.
|
||||
if not getattr(self, "_warned_eval_head_bypass", False):
|
||||
logger.warning(
|
||||
"Domino eval uses the DFlash backbone only (correction head not "
|
||||
"applied yet); reported acceptance rates are backbone-only."
|
||||
)
|
||||
self._warned_eval_head_bypass = True
|
||||
return super().forward(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask,
|
||||
@@ -366,6 +355,14 @@ class HFDominoModel(HFDFlashModel):
|
||||
|
||||
return ModelOutput(loss=loss, logits=None, train_acc=[[accuracy]], domino_metrics=metrics)
|
||||
|
||||
def pseudo_speculative_generate(self, input_ids, steps=1):
|
||||
"""Refused: DFlash's decode would draft with the backbone alone, one block position off."""
|
||||
raise NotImplementedError(
|
||||
"Domino acceptance cannot be measured until a runtime applies its correction head: "
|
||||
"the inherited DFlash decode would draft with the backbone alone, one block position "
|
||||
"off. Set ar_validate_steps to 0."
|
||||
)
|
||||
|
||||
|
||||
class DominoLambdaCallback(TrainerCallback):
|
||||
"""Update the model's ``lambda_base`` from the HF Trainer global step.
|
||||
|
||||
@@ -82,7 +82,6 @@ class DominoModule(DFlashModule):
|
||||
f"pure_draft_prefix_len must be in [0, {self.block_size - 1}] "
|
||||
f"(block_size={self.block_size}), got {self.pure_draft_prefix_len}."
|
||||
)
|
||||
self.shift_label = getattr(config, "shift_label", True)
|
||||
|
||||
# Causal state over the block's token embeddings. bias=False matches the
|
||||
# reference checkpoint (only weight_ih_l0 / weight_hh_l0 are stored).
|
||||
|
||||
@@ -89,10 +89,6 @@ class DSparkModule(DFlashModule):
|
||||
self.projector_type = getattr(config, "projector_type", "dspark")
|
||||
self.markov_rank = int(config.markov_rank)
|
||||
self.markov_head_type = str(getattr(config, "markov_head_type", "vanilla")).lower()
|
||||
# DSpark treats the anchor as the first prediction position (next-token
|
||||
# alignment), matching Domino's shift_label path; kept as an attribute so
|
||||
# the wrapper and exporter can read it uniformly.
|
||||
self.shift_label = True
|
||||
if self.markov_rank <= 0:
|
||||
raise ValueError(f"DSpark requires markov_rank > 0, got {self.markov_rank}.")
|
||||
if self.markov_head_type not in ("vanilla", "gated", "rnn"):
|
||||
|
||||
@@ -37,9 +37,8 @@ training:
|
||||
cp_size: 1
|
||||
dp_shard_size: 1
|
||||
disable_tqdm: true
|
||||
# Keep off: eval runs the DFlash backbone only (correction head not applied
|
||||
# yet), so AR would reflect the backbone alone, not the trained model.
|
||||
estimate_ar: false
|
||||
# Keep off: Domino has no HF AR validation (pseudo_speculative_generate raises).
|
||||
ar_validate_steps: 0
|
||||
answer_only_loss: true
|
||||
|
||||
@@ -87,4 +86,3 @@ dflash:
|
||||
emb_dim: 256
|
||||
gru_hidden_dim: 1024
|
||||
pure_draft_prefix_len: 1
|
||||
shift_label: true
|
||||
|
||||
@@ -49,7 +49,6 @@ Everything in `dflash.md` applies. Domino adds:
|
||||
| `dflash.dflash_architecture_config.emb_dim` | 256 | GRU head embedding dim. **Required** |
|
||||
| `dflash.dflash_architecture_config.gru_hidden_dim` | 1024 | GRU hidden dim. **Required** |
|
||||
| `dflash.dflash_architecture_config.pure_draft_prefix_len` | 1 | Positions at block start kept as base logits only (no causal correction). Must be in `[0, block_size-1]` |
|
||||
| `dflash.dflash_architecture_config.shift_label` | true | Next-token alignment — **only `true` is supported** |
|
||||
| `dflash.dflash_lambda_base_start` | 1.0 | Curriculum start weight on the base loss |
|
||||
| `dflash.dflash_lambda_base_decay_ratio` | 1.0 | Fraction of training over which `lambda_base` decays to 0 |
|
||||
|
||||
@@ -87,10 +86,9 @@ export is the whole in-pipeline signal.
|
||||
|
||||
## Quality gate
|
||||
|
||||
**Do not trust in-training AR for Domino.** The recipe pins `estimate_ar: false` and
|
||||
`ar_validate_steps: 0` deliberately: eval delegates to the DFlash backbone with the
|
||||
correction head not applied, so reported acceptance rates are backbone-only. The code
|
||||
logs this once as a warning — treat that warning as expected, not as a defect.
|
||||
**Domino has no acceptance evaluation yet.** `pseudo_speculative_generate` raises and no
|
||||
runtime applies the correction head, so keep the recipe's `ar_validate_steps: 0`. Eval
|
||||
loss and accuracy (`do_eval`, off in the recipe) exclude the head too.
|
||||
|
||||
The training-regression gate from `dflash.md` applies and the Qwen3-8B example sets
|
||||
it: `MAX_FINAL_LOSS=5.0`, `MIN_FINAL_ACC=0.15`, checked by `check_regression.py`
|
||||
@@ -107,9 +105,9 @@ failures (`seq_len` divisibility, offline eval, mask token, chat template) are i
|
||||
| Error pattern | Root cause | Fix |
|
||||
| --- | --- | --- |
|
||||
| `Domino (projector_type='domino') requires ['emb_dim', 'gru_hidden_dim'] in dflash_architecture_config` | GRU head dims missing | Set both in `dflash_architecture_config` |
|
||||
| `Domino currently supports shift_label=True (next-token alignment) only` | `shift_label=false` | Leave it at `true` |
|
||||
| `dflash_architecture_config.shift_label` deprecation warning, or `... contradicts the model` | `shift_label` in the config (the old recipe set it) | Remove it; Domino always trains next-token alignment |
|
||||
| `pure_draft_prefix_len must be in [0, N] (block_size=B), got X` | Prefix length >= block size | Lower it below `block_size` |
|
||||
| `DominoLambdaCallback: state.max_steps unset (<=0); lambda_base curriculum disabled` (warning) | `training.max_steps` not set | Set `training.max_steps`, else the curriculum never runs |
|
||||
| `Domino eval uses the DFlash backbone only ...` (warning) | Correction head not applied at eval | Expected — do not chase it; evaluate after export once the inference path lands |
|
||||
| `Domino acceptance cannot be measured until a runtime applies its correction head` | `ar_validate.py`, or `ar_validate_steps > 0` (training logs `AR validation not available.`) | Keep `ar_validate_steps: 0`; there is no Domino acceptance evaluation yet |
|
||||
| DDP error about unused parameters | `ddp_find_unused_parameters` turned off | Keep it `true` |
|
||||
| Draft trains but quality is poor | Draft dims left at `Qwen3Config` defaults instead of matching the base | Set the GQA/FFN dims explicitly |
|
||||
|
||||
@@ -151,6 +151,7 @@ failures (`seq_len` divisibility, offline eval, mask token, chat template) are i
|
||||
| `DSpark (projector_type='dspark') requires 'markov_rank' (> 0) in dflash_architecture_config` | Markov head dimension missing | Set `dflash_architecture_config.markov_rank` |
|
||||
| `DSpark requires markov_rank > 0, got N` | Non-positive value | Set a positive rank |
|
||||
| `Unsupported markov_head_type: '...'. Expected 'vanilla', 'gated' or 'rnn'` | Typo or unsupported head | Use one of the three |
|
||||
| `dflash_architecture_config.shift_label` deprecation warning, or `... contradicts the model` | `shift_label` in the config | Remove it; DSpark always trains next-token alignment |
|
||||
| `dflash_confidence_head_alpha > 0 but the confidence head was not built` | Loss term enabled without the head | Set `dflash_architecture_config.use_confidence_head=true`, or set the alpha to 0 |
|
||||
| `DSpark offline model cannot run AR validation / pseudo_speculative_generate` | Offline/streaming conversion deleted base layers | Keep `estimate_ar=false` and `ar_validate_steps=0`; evaluate after export |
|
||||
| Draft trains but acceptance length is poor | Draft dims left at defaults instead of matching the base | Set the GQA/FFN dims explicitly (see *Per-model adjustments*) |
|
||||
|
||||
@@ -1597,6 +1597,49 @@ def test_a_step_with_nothing_to_train_reaches_every_draft_parameter(head, draft_
|
||||
assert all(output.grad is not None for output in outputs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shift_label", [True, False])
|
||||
@pytest.mark.parametrize(
|
||||
"head_fields",
|
||||
[
|
||||
{},
|
||||
{"projector_type": "dspark", "markov_rank": 4},
|
||||
{"projector_type": "domino", "emb_dim": 8, "gru_hidden_dim": 8},
|
||||
],
|
||||
ids=["dflash", "dspark", "domino"],
|
||||
)
|
||||
def test_deprecated_shift_label(head_fields, shift_label):
|
||||
"""projector_type fixes the label alignment, so convert drops a shift_label matching it with
|
||||
a warning and refuses any other, which never took effect.
|
||||
|
||||
Restore drops either unchecked: DSpark used to accept the field and ignore it in training,
|
||||
and the Domino recipe set it, so checkpoints carry it in their modelopt_state.
|
||||
"""
|
||||
config = get_dflash_config()
|
||||
config["dflash_architecture_config"].update(head_fields)
|
||||
model = get_tiny_llama(num_hidden_layers=4)
|
||||
mtsp.convert(model, [("dflash", config)])
|
||||
|
||||
state = mto.modelopt_state(model)
|
||||
saved_config = state["modelopt_state_dict"][0][1]["config"]
|
||||
saved_config["dflash_architecture_config"]["shift_label"] = shift_label
|
||||
restored = mto.restore_from_modelopt_state(get_tiny_llama(num_hidden_layers=4), state)
|
||||
assert restored._label_shift == model._label_shift
|
||||
|
||||
config["dflash_architecture_config"]["shift_label"] = shift_label
|
||||
legacy = get_tiny_llama(num_hidden_layers=4)
|
||||
if shift_label != bool(model._label_shift):
|
||||
base_cls = type(legacy)
|
||||
with pytest.raises(ValueError, match="shift_label"):
|
||||
mtsp.convert(legacy, [("dflash", config)])
|
||||
assert type(legacy) is base_cls # refused before converting
|
||||
return
|
||||
with pytest.warns(FutureWarning, match="shift_label"):
|
||||
mtsp.convert(legacy, [("dflash", config)])
|
||||
assert legacy._label_shift == model._label_shift
|
||||
legacy_config = mto.modelopt_state(legacy)["modelopt_state_dict"][0][1]["config"]
|
||||
assert "shift_label" not in legacy_config["dflash_architecture_config"]
|
||||
|
||||
|
||||
class TestTeacherLogits:
|
||||
"""The base distribution is projected only at the rows, and vocab entries, asked for.
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ layout (``prefix_gru.*`` / ``embed_proj.*``).
|
||||
import json
|
||||
from copy import deepcopy
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from _test_utils.torch.transformers_models import get_tiny_llama
|
||||
from safetensors.torch import load_file
|
||||
@@ -58,7 +59,6 @@ def _get_domino_config(block_size=BLOCK_SIZE, num_layers=NUM_DRAFT_LAYERS):
|
||||
"gru_hidden_dim": GRU_HIDDEN_DIM,
|
||||
"emb_dim": EMB_DIM,
|
||||
"pure_draft_prefix_len": 1,
|
||||
"shift_label": True,
|
||||
}
|
||||
return config
|
||||
|
||||
@@ -156,6 +156,14 @@ class TestDominoForward:
|
||||
out = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
|
||||
assert abs(out.loss.item() - out.domino_metrics["final_loss"]) < 1e-4
|
||||
|
||||
def test_ar_validation_is_refused(self):
|
||||
"""DFlash's decode would draft Domino's block one position off and without its head."""
|
||||
model = get_tiny_llama(num_hidden_layers=4)
|
||||
mtsp.convert(model, [("dflash", _get_domino_config())])
|
||||
input_ids, _, _ = self._make_batch(model.dflash_config.vocab_size)
|
||||
with pytest.raises(NotImplementedError):
|
||||
model.pseudo_speculative_generate(input_ids, steps=2)
|
||||
|
||||
|
||||
class TestDominoSwa:
|
||||
"""Domino honors dflash_swa_window_size (regression: the window was silently ignored)."""
|
||||
|
||||
@@ -60,6 +60,7 @@ def _get_dspark_config(
|
||||
confidence_alpha=0.0,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_layers=NUM_DRAFT_LAYERS,
|
||||
markov_rank=MARKOV_RANK,
|
||||
):
|
||||
"""Create a DSpark config for testing (dflash mode + projector_type=dspark)."""
|
||||
config = deepcopy(DFLASH_DEFAULT_CFG["config"])
|
||||
@@ -71,11 +72,10 @@ def _get_dspark_config(
|
||||
config["dflash_architecture_config"] = {
|
||||
"num_hidden_layers": num_layers,
|
||||
"projector_type": "dspark",
|
||||
"markov_rank": MARKOV_RANK,
|
||||
"markov_rank": markov_rank,
|
||||
"markov_head_type": head_type,
|
||||
"use_confidence_head": use_confidence_head,
|
||||
"pure_draft_prefix_len": 1,
|
||||
"shift_label": True,
|
||||
}
|
||||
return config
|
||||
|
||||
@@ -270,7 +270,9 @@ class TestDSparkSwa:
|
||||
class TestDSparkExporter:
|
||||
"""Test vanilla serving exports and the native gated/recurrent formats."""
|
||||
|
||||
def _export(self, tmp_path, head_type="vanilla", use_confidence_head=False):
|
||||
def _export(
|
||||
self, tmp_path, head_type="vanilla", use_confidence_head=False, markov_rank=MARKOV_RANK
|
||||
):
|
||||
model = get_tiny_llama(num_hidden_layers=4)
|
||||
mtsp.convert(
|
||||
model,
|
||||
@@ -278,7 +280,9 @@ class TestDSparkExporter:
|
||||
(
|
||||
"dflash",
|
||||
_get_dspark_config(
|
||||
head_type=head_type, use_confidence_head=use_confidence_head
|
||||
head_type=head_type,
|
||||
use_confidence_head=use_confidence_head,
|
||||
markov_rank=markov_rank,
|
||||
),
|
||||
)
|
||||
],
|
||||
@@ -312,8 +316,12 @@ class TestDSparkExporter:
|
||||
@pytest.mark.parametrize("use_confidence_head", [False, True])
|
||||
def test_export_config_has_dspark_fields(self, tmp_path, head_type, use_confidence_head):
|
||||
"""Vanilla exports select the runtime and preserve the trained head settings."""
|
||||
# DSparkModule casts markov_rank to int; vLLM sizes its Markov table from the export.
|
||||
export_dir = self._export(
|
||||
tmp_path, head_type=head_type, use_confidence_head=use_confidence_head
|
||||
tmp_path,
|
||||
head_type=head_type,
|
||||
use_confidence_head=use_confidence_head,
|
||||
markov_rank=float(MARKOV_RANK),
|
||||
)
|
||||
with open(export_dir / "config.json") as f:
|
||||
cfg = json.load(f)
|
||||
@@ -323,6 +331,7 @@ class TestDSparkExporter:
|
||||
dc = cfg["dflash_config"]
|
||||
assert dc["projector_type"] == "dspark"
|
||||
assert dc["markov_rank"] == MARKOV_RANK
|
||||
assert type(dc["markov_rank"]) is int
|
||||
assert dc["markov_head_type"] == head_type.lower()
|
||||
assert dc["use_confidence_head"] is use_confidence_head
|
||||
assert dc["shift_label"] is True
|
||||
@@ -331,6 +340,7 @@ class TestDSparkExporter:
|
||||
if vanilla:
|
||||
assert cfg["model_type"] == "qwen3"
|
||||
assert cfg["markov_rank"] == MARKOV_RANK
|
||||
assert type(cfg["markov_rank"]) is int
|
||||
assert cfg["sample_from_anchor"] is True
|
||||
assert cfg["enable_confidence_head"] is use_confidence_head
|
||||
assert cfg["confidence_head_with_markov"] is use_confidence_head
|
||||
|
||||
@@ -10,10 +10,9 @@
|
||||
# task_0: Build training conversations (Daring-Anteater multi-turn SFT, 50K)
|
||||
# task_1: Online Domino training + export of the drafter checkpoint
|
||||
#
|
||||
# NOTE: the inference side (vLLM / AR evaluation) is intentionally not wired up
|
||||
# yet — the Domino correction head is not applied in pseudo_speculative_generate
|
||||
# or in the serving stack. Add the vLLM smoke-test / MT-Bench AR-eval steps
|
||||
# (see hf_online_dflash.yaml task_1/task_2) once the inference path lands.
|
||||
# NOTE: no evaluation step yet. Domino has no HF AR validation
|
||||
# (pseudo_speculative_generate raises), and no serving stack applies its correction
|
||||
# head. Add a vLLM smoke test (see hf_online_dflash.yaml task_1) once one does.
|
||||
#
|
||||
# Reference: SpecForge PR #571 (z-lab) | drafter format:
|
||||
# huggingface.co/Huang2020/Qwen3-8B-Domino-b16
|
||||
|
||||
Reference in New Issue
Block a user