diff --git a/aspec/commands/convert_to_hf.py b/aspec/commands/convert_to_hf.py index 9149047..391c7e7 100644 --- a/aspec/commands/convert_to_hf.py +++ b/aspec/commands/convert_to_hf.py @@ -203,6 +203,21 @@ def _serving_config(raw_config: dict) -> dict: raise ValueError("SGLang Domino serving requires a boolean shift_label") return config + if raw_config.get("architectures") == ["JetSpecDraftModel"]: + from aspec.models.draft.jetspec import JetSpecConfig, official_jetspec_config + + effective = JetSpecConfig.from_dict(raw_config).to_dict() + config = official_jetspec_config(effective) + if effective.get("fc_norm"): + raise NotImplementedError( + "SGLang JetSpec export cannot represent per-layer fc_norm; " + "use --format aspec" + ) + # SGLang 0.5.21 reads top-level is_causal for DFlash full-attention + # layers; it does not read dflash_config.causal_head. + config["is_causal"] = True + return config + if raw_config.get("architectures") == ["MedusaDraftModel"]: raise NotImplementedError( "Medusa heads require native --format aspec export; " @@ -213,10 +228,6 @@ def _serving_config(raw_config: dict) -> dict: native["architectures"] = ["Qwen3_5ForCausalLMMTP"] native["mtp_num_hidden_layers"] = 1 return native - if raw_config.get("architectures") == ["JetSpecDraftModel"]: - raise NotImplementedError( - "JetSpec requires --format aspec; SGLang 0.5.21 has no JetSpec serving loader" - ) attention = resolve_draft_attention(raw_config) if attention["csa"] is not None: raise NotImplementedError( @@ -372,7 +383,7 @@ def _draft_structure_manifest(raw_config: dict) -> dict: "runtime": "sglang", "validated_version": "0.5.21", "speculative_algorithm": ( - "DFLASH" if algorithm in {"dflash2", "domino"} else + "DFLASH" if algorithm in {"dflash2", "domino", "jetspec"} else "EAGLE" if algorithm == "mtp" else algorithm.upper() ), "required_patch_features": ( diff --git a/aspec/commands/evaluate_draft.py b/aspec/commands/evaluate_draft.py index c8dac16..15fee0b 100644 --- a/aspec/commands/evaluate_draft.py +++ b/aspec/commands/evaluate_draft.py @@ -28,6 +28,7 @@ "dflash": "DFLASH", "dflash2": "DFLASH", "domino": "DFLASH", + "jetspec": "DFLASH", "eagle3": "EAGLE3", "mtp": "EAGLE", } diff --git a/configs/recipes/jetspec_qwen3_8b.yaml b/configs/recipes/jetspec_qwen3_8b.yaml index 5ef8e31..80d54de 100644 --- a/configs/recipes/jetspec_qwen3_8b.yaml +++ b/configs/recipes/jetspec_qwen3_8b.yaml @@ -1,5 +1,5 @@ # Formal single-node JetSpec recipe: causal parallel Draft training, exact -# recovery and native export. Hyperparameters are a starting point, not a +# recovery and SGLang/native export. Hyperparameters are a starting point, not a # convergence or acceptance claim. model: target_model_path: ${oc.env:ASPEC_TARGET_MODEL,Qwen/Qwen3-8B} diff --git a/docs/benchmarks/jetspec-decode.md b/docs/benchmarks/jetspec-decode.md new file mode 100644 index 0000000..8058047 --- /dev/null +++ b/docs/benchmarks/jetspec-decode.md @@ -0,0 +1,73 @@ +# JetSpec bounded decode compatibility + +This is a bounded decode integration check, not a throughput benchmark, convergence +result or serving-quality claim. It verifies that an ASpec-exported JetSpec asset is +loaded by official SGLang 0.5.21, that the causal head is active, and that exporting +the published checkpoint through ASpec preserves the decode result. + +## Setup + +- Host: one H100 PCIe 80GB, `sglang==0.5.21`, torch 2.13.0+cu130. +- Target: `Qwen/Qwen3-8B` (`/public/models/Qwen3-8B`). +- Data: 16 prompts from the held-out validation split. +- Decode: greedy, 32 new tokens, two complete repeats, normal radix cache. +- Draft: JetSpec block size 16, five Target feature layers `[1, 9, 17, 25, 33]`. +- Export: `aspec export` default SGLang layout with top-level `is_causal=true` and + `dflash_config.causal_head=true`. + +SGLang 0.5.21 reads the top-level `is_causal` flag for DFlash full-attention layers; +`dflash_config.causal_head` alone leaves those layers bidirectional. + +## Results + +| Draft | Acceptance length | Verifications | Median speedup | Greedy equal | Repeats stable | +| --- | ---: | ---: | ---: | --- | --- | +| ASpec 8-step checkpoint | 1.032 | 992 | 0.795x | yes | yes | +| Published `JetSpec/jetspec-qwen3-8b` loaded directly | 2.723 | 376 | 1.823x | yes | yes | +| Published checkpoint exported through ASpec | 2.723 | 376 | 1.823x | yes | yes | + +Acceptance length follows `aspec evaluate`: completion tokens divided by real +verifier calls, including Target tokens. Each repeat produced 512 completion tokens; +the two repeats produced 1024 tokens total, which is the numerator used above. + +The ASpec-exported published checkpoint matched the directly loaded checkpoint's +acceptance length, verification count and speedup in this bounded setup. That checks +config/weight/layout compatibility; it does not establish convergence or a trained +quality comparison. + +Timing is fixed-order: the evaluator completes all Target-only repeats before all +speculative repeats. Two repeats do not counterbalance that order, so the speedup +column is a bounded decode observation with an uncontrolled order-dependent +limitation, not an unbiased throughput result. + +The 8-step ASpec checkpoint was trained only as a functional smoke test on synthetic +data. Its lower acceptance and slower speculative decode are expected and are not +evidence against the method. + +## Reproduction + +```bash +aspec export --input-dir outputs/jetspec/checkpoints/iter_0000009 \ + --output-dir outputs/jetspec-sglang + +CUDA_VISIBLE_DEVICES=0 aspec evaluate \ + --target /models/Qwen3-8B --draft outputs/jetspec-sglang \ + --data held-out.jsonl --output outputs/jetspec-decode.json \ + --samples 16 --max-new-tokens 32 --repeats 2 +``` + +The command above applies to an ASpec FSDP training checkpoint. For the published +draft head, use the reproducible validation harness: + +```bash +python -m tools.validation.jetspec_published_export \ + --checkpoint /models/jetspec-qwen3-8b \ + --target-model /models/Qwen3-8B \ + --output outputs/jetspec-official-sglang +``` + +The harness loads the published tensors through `load_initial_draft_weights`, writes +the minimal distributed-checkpoint layout the converter expects, and calls +`convert_checkpoint(..., artifact_format="sglang")`. The published checkpoint omits +`embed_tokens`, so `--target-model` supplies the borrowed embedding; converting only +the config is not sufficient. diff --git a/docs/contributing/validation.md b/docs/contributing/validation.md index 954a5ef..34b91ec 100644 --- a/docs/contributing/validation.md +++ b/docs/contributing/validation.md @@ -109,6 +109,28 @@ python -m tools.validation.domino_anchor_protocol verify \ its source sample. Consuming the same file in both trainers is still required before claiming a matched loss-curve comparison; an identical seed alone is not enough. +## JetSpec decode acceptance + +Export a JetSpec checkpoint for SGLang and run the bounded greedy decode check: + +```bash +aspec export --input-dir outputs/jetspec/checkpoints/iter_0000009 \ + --output-dir outputs/jetspec-sglang + +aspec evaluate --target /models/Qwen3-8B --draft outputs/jetspec-sglang \ + --data held-out.jsonl --output outputs/jetspec-decode.json \ + --samples 16 --max-new-tokens 32 --repeats 2 +``` + +SGLang 0.5.21 needs the exported config to carry top-level `is_causal=true`; the +published `dflash_config.causal_head` field alone leaves DFlash full-attention layers +bidirectional. The evaluator checks greedy equality against Target-only decoding and +repeat stability, and reports acceptance length including Target tokens. Exporting the +published `JetSpec/jetspec-qwen3-8b` checkpoint with +`python -m tools.validation.jetspec_published_export --checkpoint ... --target-model ...` +reproduced the direct checkpoint's bounded acceptance and fixed-order timing; this is a +decode integration check, not throughput or convergence evidence. + ## Algorithm, capacity and fault checks | Scope | Required additional evidence | diff --git a/docs/support.md b/docs/support.md index ee34c00..07fbd44 100644 --- a/docs/support.md +++ b/docs/support.md @@ -16,7 +16,7 @@ and tests do not imply CPU training support. | Medusa heads-only | Parallel full-vocabulary future-token heads on the frozen Target post-norm state; training, exact recovery and native export; greedy and typical/nucleus sampling candidate-tree acceptance via a standalone Hugging Face evaluator; SDPA CP1, MBS1, non-packing, REPLICATE, one node | No packing/CP or warmstart; no SGLang Medusa integration or production-serving claim; see [scope](user-guide/medusa.md) | | EAGLE4 | Dense and selected upstream MoE; Draft/candidate stages; packing/CP and native assets | Candidate Top-K forward-KL is explicitly implemented from public semantics, not an unpublished official recipe; no serving integration | | DFlash2 | Experimental full/causal/SWA training with Flex, cuDNN THD or FA4 packing/CP | Experimental objective; no claim to reproduce an official training recipe | -| JetSpec | Qwen3-style causal parallel Draft head and temperature-scaled forward-KL objective, reused DFlash block machinery; chunked full-vocabulary KL, explicit causal visibility, exact recovery with FlexAttention, CP1, padded/non-packing, native export/strict reload and a proposal consumer | No SGLang export, tree builder or real decoding-acceptance claim yet; CPU causal packing and direct unmasked Draft calls fail closed; see [scope](user-guide/jetspec.md) | +| JetSpec | Qwen3-style causal parallel Draft head and temperature-scaled forward-KL objective, reused DFlash block machinery; chunked full-vocabulary KL, explicit causal visibility, exact recovery with FlexAttention, CP1, padded/non-packing, SGLang/native export, strict reload and a proposal consumer | No tree builder or long-run convergence claim; CPU causal packing and direct unmasked Draft calls fail closed; see [scope](user-guide/jetspec.md) | | MTP-conditioned DSpark / DFlash | Target-side frozen native Qwen3.5 features, token/hidden dual-anchor training, exact recovery and strict native assets; legacy Draft-side assets retained | Dense full GQA, CP1, MBS1, REPLICATE, one node, non-packing, decay objective; Target capture PP1/unquantized; no generic serving consumer | | Native MTP | Qwen3.5-9B native single predictor, same-Target frozen embedding/head, multi-step training, recovery and export/stitch | Text-only Dense MTP; SDPA CP1 or independently validated FA4 packing/CP; no generic multi-layer/MoE MTP | | Dense / Qwen MoE / Ling MoE | Structure-specific FFNs, routing state, checkpointing and strict assets | No promise of every algorithm × structure combination | diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index 7d433e4..e6414e0 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -123,9 +123,9 @@ frozen Target features. `JetSpecConfig` forces that causal contract and rejects incompatible structures. The ASpec training CLI selects the algorithm through a shipped Qwen3-8B Draft config and a JetSpec trainer that reuses the DFlash optimizer/checkpoint path. FlexAttention, CP1, padded/non-packing execution and -exact recovery are the initial scope. Native export, strict reload and a proposal -consumer are supported; tree construction, SGLang export and verifier-acceptance -runs remain pending. +exact recovery are the initial scope. SGLang/native export, strict reload, a +proposal consumer and bounded verifier-acceptance runs are supported; tree +construction and long-run convergence evidence remain pending. ## Native MTP conditioning for DSpark/DFlash diff --git a/docs/user-guide/jetspec.md b/docs/user-guide/jetspec.md index ba76fb0..d125c75 100644 --- a/docs/user-guide/jetspec.md +++ b/docs/user-guide/jetspec.md @@ -17,8 +17,8 @@ Target GPU plus two Draft GPUs at 4K (three GPUs total). `block_size=16`, `is_causal=true`). - Formal recipe: `configs/recipes/jetspec_qwen3_8b.yaml` (FlexAttention, CP1, non-packing, REPLICATE, Store/TCP transport, held-out evaluation and - `inference.store_last_hidden_states=true`). It is catalogued as `jetspec`; its - export boundary is native-only. + `inference.store_last_hidden_states=true`). It is catalogued as `jetspec`; both + SGLang and native export are validated. - Smoke example: `configs/examples/jetspec_qwen3_8b_4k_tcp.yaml` (shorter functional run with bundled data). - The supported path fails closed outside dense full attention, padded inputs, @@ -76,18 +76,27 @@ and exact resume still need a hardware run before making quality claims. ## Export and strict reload -Export a trained checkpoint with the native ASpec artifact format: +Export a trained checkpoint for SGLang serving (default) or as a native ASpec +artifact: ```bash +aspec export \ + --input-dir outputs/jetspec_qwen3_8b_4k_tcp_resumed/checkpoints/iter_0000009 \ + --output-dir outputs/jetspec-qwen3-8b-sglang + aspec export \ --input-dir outputs/jetspec_qwen3_8b_4k_tcp_resumed/checkpoints/iter_0000009 \ --output-dir outputs/jetspec-qwen3-8b-asset --format aspec ``` -JetSpec deliberately rejects the SGLang artifact format: SGLang 0.5.21 has no -validated JetSpec loader, so a DFlash-style serving export could silently lose the -causal block contract. The native manifest records the JetSpec algorithm, trained -`block_size`, Target feature layers, temperature, KL chunk size and weighting. +The SGLang export maps JetSpec to the published DFlash draft layout and sets both +`dflash_config.causal_head=true` and top-level `is_causal=true`. SGLang 0.5.21 reads +the top-level flag for DFlash full-attention layers; `causal_head` alone would leave +the draft bidirectional. The manifest records runtime `DFLASH`; SGLang loads the +exported `fc`/`hidden_norm`/`norm`/`layers.*` tensors. + +The native manifest records the JetSpec algorithm, trained `block_size`, Target +feature layers, temperature, KL chunk size and weighting. `aspec.draft_artifact.load_native_draft` validates the checksums and semantics, then loads every tensor strictly and preserves dtypes. @@ -102,6 +111,21 @@ produces the flat `JetSpecDraftModel`/`model_type="jetspec"` config. The publish weight layout matches ASpec's export names; `load_initial_draft_weights` loads the draft tensors strictly and borrows the missing Target embedding. +### Decode acceptance + +Run real decode acceptance against the SGLang export with `aspec evaluate`: + +```bash +aspec evaluate --target /path/to/Qwen3-8B \ + --draft outputs/jetspec-qwen3-8b-sglang \ + --data /path/to/held-out-prompts.jsonl --output outputs/jetspec-decode.json +``` + +The evaluator reports measured acceptance length (including Target tokens), checks +greedy equality against Target-only decoding and verifies repeat stability. A +16-prompt, 32-new-token, two-repeat check on one H100 loaded the asset and produced stable greedy output; the bounded run is a +decode integration check, not throughput or convergence evidence. + ### Native proposal component `aspec.draft_artifact.JetSpecConsumer` loads a native JetSpec asset and proposes one @@ -119,8 +143,14 @@ against independent equations, explicit-mask and packed fail-closed paths, anchor/loss-mask exclusion, empty supervision and next-token label/teacher alignment. Native export, strict reload and the proposal consumer have focused CPU coverage, including causal visibility and anchor-feature isolation. GPU attention -execution, convergence, acceptance length and serving performance are not certified -by those checks. +execution, convergence and serving throughput are not certified by those checks. +Bounded SGLang decode was run on 16 held-out prompts (32 new tokens, greedy, two +repeats): the 8-step checkpoint produced greedy-equal, repeat-stable output. The published `JetSpec/jetspec-qwen3-8b` checkpoint measured 2.723 +tokens/verification and 1.823x fixed-order median speedup in the same bounded setup; exporting +that checkpoint through ASpec reproduced the same numbers, confirming tensor/layout +compatibility. The 8-step checkpoint measured 1.032 +tokens/verification and 0.795x, so this is not a convergence or quality claim. See +[bounded decode compatibility](../benchmarks/jetspec-decode.md). ## Reference and selected method @@ -238,9 +268,12 @@ denominator. Per-position loss now reports KL rather than CE. - Native export, strict reload and a native proposal consumer are supported; the published Qwen3-8B config/weight layout maps into ASpec. -- This integration does not provide tree construction, SGLang serving export, a - real verifier-acceptance run or a same-budget comparison with the official - implementation. Those remain follow-up work under the issue's expected outcomes. +- SGLang serving export, native export/strict reload and a bounded real + verifier-acceptance run are supported. +- This integration does not provide tree construction or a same-budget trained + comparison with the official implementation. The official repository publishes an + inference checkpoint but no comparable training loop; the bounded check therefore + compares asset loading and decode acceptance rather than training curves. - The default tests are in `tests/cpu/test_jetspec.py`, `tests/cpu/test_jetspec_integration.py`, `tests/cpu/test_jetspec_export.py`, `tests/cpu/test_jetspec_consumer.py` and `tests/cpu/test_jetspec_official.py`. diff --git a/docs/user-guide/recipes.md b/docs/user-guide/recipes.md index 4b98ed0..0b7c797 100644 --- a/docs/user-guide/recipes.md +++ b/docs/user-guide/recipes.md @@ -19,7 +19,7 @@ connections on your hardware before training. | `dspark` | Qwen3-8B / Dense DSpark | 1 node, 8 GPUs: 4T + 4D; 4K | Train on your data with packing and NVLink | | `dflash` | Qwen3-8B / DFlash | 1 node, 3 GPUs: 1T + 2D; 4K | Train a block-parallel DFlash Draft | | `domino` | Qwen3-8B / Domino | 1 node, 3 GPUs: 1T + 2D; 4K | Train a DFlash backbone with a GRU correction head | -| `jetspec` | Qwen3-8B / JetSpec | 1 node, 3 GPUs: 1T + 2D; 4K | Train a causal parallel block Draft and export a native asset | +| `jetspec` | Qwen3-8B / JetSpec | 1 node, 3 GPUs: 1T + 2D; 4K | Train a causal parallel block Draft and export for SGLang or native use | | `medusa` | Qwen3-8B / heads-only Medusa | 1 node, 2 GPUs: 1T + 1D; 4K | Train parallel future-token heads and export a native heads asset | | `eagle3` | Qwen3-8B / EAGLE3 | 1 node, 3 GPUs: 1T + 2D; 4K | Train a recurrent EAGLE3 Draft | | `eagle4` | Qwen3-8B / EAGLE4 | 1 node, 3 GPUs: 1T + 2D; 4K; sequential stages | Train a Draft, then candidate retrieval projections | diff --git a/tests/cpu/test_jetspec_export.py b/tests/cpu/test_jetspec_export.py index a576b55..a839cfc 100644 --- a/tests/cpu/test_jetspec_export.py +++ b/tests/cpu/test_jetspec_export.py @@ -166,9 +166,36 @@ def test_jetspec_native_export_rejects_block_size_that_disagrees_with_checkpoint ) -def test_jetspec_has_no_serving_export(): - with pytest.raises(NotImplementedError, match="--format aspec"): - convert_to_hf._serving_config(_raw_config()) +def test_jetspec_serving_export_uses_causal_dflash_layout(): + config = convert_to_hf._serving_config(_raw_config()) + + assert config["architectures"] == ["DFlashDraftModel"] + assert config["model_type"] == "qwen3" + assert config["is_causal"] is True + assert config["block_size"] == 5 + assert config["num_target_layers"] == 6 + assert config["dflash_config"]["causal_head"] is True + assert config["dflash_config"]["target_layer_ids"] == [1, 4] + assert config["dflash_config"]["mask_token_id"] == 31 + + +def test_jetspec_sglang_export_manifest_uses_dflash_runtime(tmp_path, monkeypatch): + raw = _raw_config() + _monkeypatch_checkpoint(monkeypatch, _model(raw)) + source = _prepare_source(tmp_path, raw) + output = tmp_path / "sglang-asset" + + manifest = convert_to_hf.convert_checkpoint( + input_dir=source, output_dir=output, artifact_format="sglang" + ) + + assert manifest["storage_format"] == "sglang" + assert manifest["algorithm"] == "jetspec" + assert manifest["draft_structure"]["loader_contract"]["speculative_algorithm"] == "DFLASH" + exported = json.loads((output / "config.json").read_text()) + assert exported["architectures"] == ["DFlashDraftModel"] + assert exported["is_causal"] is True + assert exported["dflash_config"]["causal_head"] is True def _write_config(tmp_path, raw): diff --git a/tests/cpu/test_jetspec_integration.py b/tests/cpu/test_jetspec_integration.py index 3127ec8..e30ec71 100644 --- a/tests/cpu/test_jetspec_integration.py +++ b/tests/cpu/test_jetspec_integration.py @@ -102,10 +102,12 @@ def test_registration_resolves_jetspec(): assert semantics["block_size"] == 5 -def test_sglang_serving_export_rejects_jetspec(): +def test_sglang_serving_export_uses_causal_dflash_layout(): raw = json.loads(_DRAFT_JSON.read_text()) - with pytest.raises(NotImplementedError, match="--format aspec"): - _serving_config(raw) + config = _serving_config(raw) + assert config["architectures"] == ["DFlashDraftModel"] + assert config["is_causal"] is True + assert config["dflash_config"]["causal_head"] is True diff --git a/tests/test_decode_evaluation.py b/tests/test_decode_evaluation.py index c8545f1..0d24a43 100644 --- a/tests/test_decode_evaluation.py +++ b/tests/test_decode_evaluation.py @@ -118,3 +118,7 @@ def test_equality_between_frameworks_does_not_hide_repeat_instability(): def test_empty_or_incomplete_repeats_cannot_pass_equality(baseline, candidate): with pytest.raises(ValueError, match="complete decode repeats"): output_checks(baseline, candidate) + + +def test_jetspec_uses_the_dflash_serving_runtime(): + assert serving_algorithm("jetspec") == "DFLASH" diff --git a/tools/recipe_catalog.json b/tools/recipe_catalog.json index e7c2b28..d37dab7 100644 --- a/tools/recipe_catalog.json +++ b/tools/recipe_catalog.json @@ -52,7 +52,7 @@ "gpus": 3, "target_gpus": 1, "draft_gpus": 2, - "native_only_export": true + "native_only_export": false }, "eagle3": { "configs": [ diff --git a/tools/validation/jetspec_published_export.py b/tools/validation/jetspec_published_export.py new file mode 100644 index 0000000..aad8300 --- /dev/null +++ b/tools/validation/jetspec_published_export.py @@ -0,0 +1,117 @@ +# Copyright 2026 Ant Group Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 + +"""Export the published JetSpec head through the ASpec checkpoint exporter. + +The published ``JetSpec/jetspec-qwen3-8b`` repository is an HF draft-head asset, +not an ASpec FSDP training checkpoint. This validation harness loads its tensors +into an ASpec draft model, writes the minimal distributed-checkpoint layout the +exporter expects, and then runs the normal ``convert_checkpoint`` path. + +This is a reproducibility tool for the bounded published-checkpoint comparison, +not a training or serving entry point. +""" + +from __future__ import annotations + +import argparse +import json +import tempfile +from pathlib import Path + +import torch + +from aspec.config.draft_algorithm import draft_model_semantics +from aspec.models.draft import AutoDraftModelConfig, AutoEagle3DraftModel +from aspec.training.checkpoint import load_initial_draft_weights +from tools import convert_to_hf + + +def export_published_jetspec( + checkpoint: Path, + output: Path, + *, + target_model: str | None = None, + artifact_format: str = "sglang", + force: bool = False, +) -> dict: + """Load a published JetSpec head and export it through ASpec's converter.""" + if target_model is None: + raise ValueError( + "published JetSpec checkpoints omit embed_tokens; pass --target-model " + "so the export borrows the matching Target embedding" + ) + checkpoint = checkpoint.expanduser().resolve() + output = output.expanduser().resolve() + config_path = checkpoint / "config.json" + weights_path = checkpoint / "model.safetensors" + if not config_path.is_file() or not weights_path.is_file(): + raise FileNotFoundError( + "published checkpoint must contain config.json and model.safetensors" + ) + + raw = json.loads(config_path.read_text(encoding="utf-8")) + config = AutoDraftModelConfig.from_dict(raw) + model = AutoEagle3DraftModel.from_config(config, torch_dtype=torch.bfloat16) + load_initial_draft_weights(model, str(checkpoint), allow_target_embedding=True) + state = { + "model_state.model.draft_model." + key: value.detach().clone() + for key, value in model.state_dict().items() + if key != "embed_tokens.weight" + } + + with tempfile.TemporaryDirectory(prefix="aspec-jetspec-published-") as directory: + source = Path(directory) / "iter_0000001" + (source / "model").mkdir(parents=True) + (source / "model/.metadata").write_bytes(b"validation-stub") + (source / "draft_config.json").write_text(json.dumps(raw)) + (source / "meta.json").write_text(json.dumps({ + "training_topology": { + "draft_algorithm": "jetspec", + "training_objective": {"block_size": config.block_size}, + "draft_model_semantics": draft_model_semantics(config), + } + })) + + original = convert_to_hf._load_fsdp_state_dict + convert_to_hf._load_fsdp_state_dict = lambda _: state + try: + return convert_to_hf.convert_checkpoint( + input_dir=source, + output_dir=output, + target_model_path=target_model, + artifact_format=artifact_format, + force=force, + ) + finally: + convert_to_hf._load_fsdp_state_dict = original + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--target-model", default=None, + help="optional Target path for a borrowed embedding") + parser.add_argument("--format", choices=("sglang", "aspec"), default="sglang", + dest="artifact_format") + parser.add_argument("--force", action="store_true") + args = parser.parse_args() + + manifest = export_published_jetspec( + args.checkpoint, + args.output, + target_model=args.target_model, + artifact_format=args.artifact_format, + force=args.force, + ) + print(json.dumps({ + "algorithm": manifest["algorithm"], + "storage_format": manifest["storage_format"], + "tensor_count": manifest["tensor_count"], + "output": str(args.output.resolve()), + }, indent=2)) + + +if __name__ == "__main__": + main()