-
Notifications
You must be signed in to change notification settings - Fork 184
Add DFlash model converter #617
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
shanjiaz
merged 7 commits into
vllm-project:main
from
guan404ming:feat/dflash-converter
Jun 24, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1f472cf
Add DFlash model converter
guan404ming 0e37073
Flag any missing draft weight in DFlash converter
guan404ming e2dbd64
Auto-convert external checkpoints in from_pretrained
guan404ming 4676344
Fix ci error
guan404ming 3496fd2
Refactor external checkpoint conversion logic in SpeculatorModel
guan404ming 9234240
Merge branch 'main' into feat/dflash-converter
shanjiaz 1fe674b
Merge branch 'main' into feat/dflash-converter
shanjiaz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| """DFlash checkpoint conversion utilities.""" | ||
|
|
||
| from speculators.convert.dflash.converter import DFlashConverter | ||
|
|
||
| __all__ = ["DFlashConverter"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| """DFlash checkpoint converter. | ||
|
|
||
| Converts an external DFlash checkpoint (e.g. ``z-lab/*-DFlash``) to a Speculators | ||
| checkpoint that loads with ``DFlashDraftModel.from_pretrained(path)``. | ||
|
|
||
| The draft transformer body (``layers.*``, ``fc``, ``hidden_norm``, ``norm``) already | ||
| matches ``DFlashDraftModel`` so weights are copied as-is. The external checkpoint | ||
| borrows the verifier's embedding and LM head at runtime, so ``embed_tokens`` / | ||
| ``lm_head`` / ``verifier_lm_head`` / ``verifier_norm`` are loaded from the verifier | ||
| before saving. | ||
| """ | ||
|
|
||
| from pathlib import Path | ||
|
|
||
| import torch | ||
| from loguru import logger | ||
| from transformers import PretrainedConfig | ||
|
|
||
| from speculators.config import SpeculatorsConfig, VerifierConfig | ||
| from speculators.convert.utils import ( | ||
| ensure_checkpoint_is_local, | ||
| load_checkpoint_config, | ||
| load_checkpoint_weights, | ||
| ) | ||
| from speculators.models.dflash import DFlashDraftModel, DFlashSpeculatorConfig | ||
| from speculators.proposals.greedy import GreedyTokenProposalConfig | ||
|
|
||
| __all__ = ["DFlashConverter"] | ||
|
|
||
| # config.json keys that are not part of the draft transformer (Qwen3) config | ||
| _NON_TRANSFORMER_KEYS = frozenset( | ||
| {"architectures", "auto_map", "block_size", "dflash_config", "num_target_layers"} | ||
| ) | ||
|
|
||
| # state dict keys that are filled from the verifier (not the source checkpoint), so | ||
| # their absence from the source weights is expected, not a conversion error | ||
| _VERIFIER_FILLED_KEYS = frozenset( | ||
| { | ||
| "embed_tokens.weight", | ||
| "lm_head.weight", | ||
| "verifier_lm_head.weight", | ||
| "verifier_norm.weight", | ||
| "t2d", | ||
| "d2t", | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| class DFlashConverter: | ||
| """Convert an external DFlash checkpoint to speculators format. | ||
|
|
||
| Copies the draft transformer body as-is and fills the embedding, LM head, and | ||
| verifier norm from the verifier model so the saved checkpoint is self-contained. | ||
| """ | ||
|
|
||
| def convert( | ||
| self, | ||
| input_path: str | Path, | ||
| output_path: str | Path, | ||
| base_model: str, | ||
| validate: bool = True, | ||
| aux_hidden_state_layer_ids: list[int] | None = None, | ||
| cache_dir: str | Path | None = None, | ||
| ) -> None: | ||
| logger.info(f"Converting DFlash checkpoint: {input_path}") | ||
|
|
||
| local_checkpoint_path = ensure_checkpoint_is_local(input_path, cache_dir) | ||
| source_config = load_checkpoint_config(local_checkpoint_path) | ||
| weights = load_checkpoint_weights(local_checkpoint_path) | ||
| logger.info(f"Loaded {len(weights)} weights") | ||
|
|
||
| config = self._build_config( | ||
| source_config, base_model, aux_hidden_state_layer_ids | ||
| ) | ||
| saved_path = self._save(config, weights, output_path) | ||
| logger.success(f"Saved to: {saved_path}") | ||
|
|
||
| if validate: | ||
| self._validate(saved_path) | ||
|
|
||
| def _build_config( | ||
| self, | ||
| source_config: dict, | ||
| base_model: str, | ||
| aux_hidden_state_layer_ids: list[int] | None, | ||
| ) -> DFlashSpeculatorConfig: | ||
| dflash = source_config.get("dflash_config", {}) | ||
| transformer_config = { | ||
| k: v for k, v in source_config.items() if k not in _NON_TRANSFORMER_KEYS | ||
| } | ||
|
|
||
| verifier_config_dict, _ = PretrainedConfig.get_config_dict(base_model) | ||
| source_hidden = transformer_config.get("hidden_size") | ||
| target_hidden = verifier_config_dict.get("hidden_size") | ||
| if source_hidden and target_hidden and source_hidden != target_hidden: | ||
| raise ValueError( | ||
| f"Architecture mismatch: source DFlash checkpoint has " | ||
| f"hidden_size={source_hidden} but base_model '{base_model}' has " | ||
| f"hidden_size={target_hidden}. Dimensions must match." | ||
| ) | ||
|
|
||
| if aux_hidden_state_layer_ids is None: | ||
| target_layer_ids = dflash.get("target_layer_ids") | ||
| if target_layer_ids is None: | ||
| raise ValueError( | ||
| "Checkpoint config has no `dflash_config.target_layer_ids`; " | ||
| "pass `aux_hidden_state_layer_ids` explicitly." | ||
| ) | ||
| # z-lab reads hidden_states[layer_id + 1] (index 0 is the embedding | ||
| # output) while speculators uses the layer id directly. | ||
| # Source: z-lab utils.extract_context_feature. | ||
| aux_hidden_state_layer_ids = [i + 1 for i in target_layer_ids] | ||
|
|
||
| speculators_config = SpeculatorsConfig( | ||
| algorithm="dflash", | ||
| proposal_methods=[ | ||
| GreedyTokenProposalConfig( | ||
| speculative_tokens=source_config["block_size"] - 1, | ||
|
shanjiaz marked this conversation as resolved.
|
||
| ) | ||
| ], | ||
| default_proposal_method="greedy", | ||
| verifier=VerifierConfig( | ||
| name_or_path=base_model, | ||
| architectures=verifier_config_dict.get("architectures", []), | ||
| ), | ||
| ) | ||
|
|
||
| return DFlashSpeculatorConfig( | ||
| transformer_layer_config=transformer_config, # type: ignore[arg-type] | ||
| draft_vocab_size=transformer_config["vocab_size"], | ||
| block_size=source_config["block_size"], | ||
| aux_hidden_state_layer_ids=aux_hidden_state_layer_ids, | ||
| mask_token_id=dflash.get("mask_token_id"), | ||
| speculators_config=speculators_config, | ||
| ) | ||
|
|
||
| def _save( | ||
| self, | ||
| config: DFlashSpeculatorConfig, | ||
| weights: dict[str, torch.Tensor], | ||
| output_path: str | Path, | ||
| ) -> Path: | ||
| model = DFlashDraftModel(config=config) | ||
|
|
||
| body = {k: v for k, v in weights.items() if k not in ("t2d", "d2t")} | ||
| missing, unexpected = model.load_state_dict(body, strict=False) | ||
| if unexpected: | ||
| raise ValueError( | ||
| "Unexpected keys in checkpoint -- the structure does not match " | ||
| f"DFlashDraftModel. Unexpected keys: {unexpected}" | ||
| ) | ||
| critical_missing = [k for k in missing if k not in _VERIFIER_FILLED_KEYS] | ||
| if critical_missing: | ||
| raise ValueError(f"Draft weights missing after load: {critical_missing}") | ||
| logger.debug(f"Keys loaded from verifier at save time: {missing}") | ||
|
|
||
| # embed_tokens / lm_head / verifier_lm_head / verifier_norm come from the | ||
| # verifier; without this they would be saved as NaN. | ||
| model.load_verifier_weights() | ||
|
shanjiaz marked this conversation as resolved.
|
||
|
|
||
| model.to(dtype=next(iter(body.values())).dtype) # type: ignore[call-arg] | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| model.save_pretrained(str(output_path)) | ||
| return Path(output_path) | ||
|
|
||
| def _validate(self, output_path: Path) -> None: | ||
| logger.info("Validating converted DFlash checkpoint...") | ||
| try: | ||
| model = DFlashDraftModel.from_pretrained(str(output_path)) | ||
| except (OSError, ValueError, RuntimeError) as exc: | ||
| logger.error(f"Validation failed: {exc}") | ||
| raise | ||
| for name in ("fc.weight", "lm_head.weight", "embed_tokens.weight"): | ||
| if torch.isnan(model.state_dict()[name]).any(): | ||
| raise ValueError(f"Converted checkpoint has NaN in {name}") | ||
| logger.success("Validation succeeded") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.