From 5a96c33ac2c029f3bd31bc6f65e1e392a0ba349d Mon Sep 17 00:00:00 2001 From: bohaotu Date: Fri, 27 Nov 2026 14:32:00 +0800 Subject: [PATCH 1/9] feat(ling3): add Ling-3.0-tiny DFlash recipe Add a five-layer dense DFlash draft config and `ling-tiny-dflash` recipe bound to Ling-3.0-tiny capture layers and frozen embedding/head/norm keys. Register the 1T+2D starting allocation and cover the Plan/config contract with CPU tests. --- .../dflash_ling3_tiny_draft_config.json | 20 ++++ configs/recipes/ling3_tiny_dflash.yaml | 103 ++++++++++++++++++ docs/user-guide/algorithms.md | 4 + docs/user-guide/ling.md | 1 + docs/user-guide/recipes.md | 1 + tests/cpu/test_release_recipes.py | 2 +- tests/test_ling3_recipe.py | 31 ++++++ tools/recipe_catalog.json | 11 ++ 8 files changed, 172 insertions(+), 1 deletion(-) create mode 100644 aspec/config/dflash_ling3_tiny_draft_config.json create mode 100644 configs/recipes/ling3_tiny_dflash.yaml diff --git a/aspec/config/dflash_ling3_tiny_draft_config.json b/aspec/config/dflash_ling3_tiny_draft_config.json new file mode 100644 index 0000000..ac91f61 --- /dev/null +++ b/aspec/config/dflash_ling3_tiny_draft_config.json @@ -0,0 +1,20 @@ +{ + "architectures": ["DFlashDraftModel"], + "model_type": "dflash", + "hidden_size": 1536, + "intermediate_size": 4608, + "num_hidden_layers": 5, + "num_attention_heads": 12, + "num_key_value_heads": 4, + "head_dim": 128, + "vocab_size": 157184, + "rms_norm_eps": 1e-6, + "max_position_embeddings": 131072, + "rope_theta": 6000000.0, + "num_target_layers": 5, + "target_hidden_size": 1536, + "target_num_hidden_layers": 24, + "target_layer_ids": [1, 6, 11, 16, 21], + "mask_token_id": 156894, + "tie_word_embeddings": false +} diff --git a/configs/recipes/ling3_tiny_dflash.yaml b/configs/recipes/ling3_tiny_dflash.yaml new file mode 100644 index 0000000..66542db --- /dev/null +++ b/configs/recipes/ling3_tiny_dflash.yaml @@ -0,0 +1,103 @@ +# Release training starting point: three passes, held-out eval and checkpoints. +# Hyperparameters are not a convergence/quality claim; see docs/user-guide/recipes.md. +# Ling-3.0-tiny BF16 Target + five-layer dense DFlash Draft. +# Data must use Ling's checkpoint chat template; see the recipe document. +# Initial three-GPU validation plan. Scale replicas from measured service rates. +model: + target_model_path: ${oc.env:ASPEC_TARGET_MODEL,inclusionAI/Ling-3.0-tiny} + native_context_length: 131072 + trust_remote_code: true + draft_model_config: aspec/config/dflash_ling3_tiny_draft_config.json + embedding_key: model.word_embeddings.weight + lm_head_key: lm_head.weight + norm_key: model.norm.weight + +dataset: + eval_interval: 100 + eval_micro_batch_size: 1 + train_data_path: ${oc.env:ASPEC_TRAIN_DATA} + eval_data_path: ${oc.env:ASPEC_EVAL_DATA} + chat_template: ling3 + prompt_key: conversations + min_loss_tokens: 32 + shuffle_dataset: true + dataset_seed: 42 + +training: + attention_backend: flex_attention + draft_context_parallel_size: 1 + micro_batch_size: 1 + draft_accumulation_steps: 2 + learning_rate: 6e-4 + min_lr: 6e-5 + weight_decay: 0.0 + max_grad_norm: 1.0 + max_seq_length: 4096 + num_epochs: 3 + warmup_ratio: 0.04 + seed: 42 + continual_training: false + deterministic_anchor_sampling: false + training_num_gpus_per_node: 2 + training_num_nodes: 1 + placement_strategy: inference_first + fsdp_strategy: REPLICATE + fsdp_reduce_dtype: bfloat16 + compile_model: false + max_concurrent_batches: 1 + streaming_dispatch_with_training: true + pipeline_dispatch_with_training: true + prefetch_depth: 1 + save_interval: 100 + save_per_epoch: false + save_final_checkpoint: true + max_checkpoints: 2 + dflash_block_size: 7 + dflash_packing: false + dflash_num_target_layers: 5 + dflash_num_anchors: 512 + dflash_loss_objective: decay + dflash_ce_loss_alpha: 1.0 + dflash_l1_loss_alpha: 0.0 + +inference: + inference_engine_type: sgl + store_last_hidden_states: true + # Native Ling runtime publishes GPU features through its forward-hook API. + # Normal Target attention state is retained; optimized direct prefill is disabled. + target_prefill_memory_optimized: false + inference_num_gpus: 1 + inference_num_gpus_per_engine: 1 + inference_num_gpus_per_node: 3 + inference_fetch_batch: 4 + inference_buffer_threshold: 4 + max_sample_pool_size: 8 + inference_batch_size: 2 + sglang: + tp_size: 1 + mem_fraction_static: 0.6 + +mooncake: + data_plane: transfer_engine + protocol: nvlink_intra + require_nvlink: true + enable_gpu_direct: true + allow_host_fallback: false + enable_hard_pin: true + max_seq_len: 4096 + hidden_dim: 1536 + global_segment_size: 16GB + local_buffer_size: 4GB + host_buffer_size: 1GB + gpu_ring_slots: 32 + source_gpu_ring_slots: 32 + destination_gpu_ring_slots: 1 + kv_lease_ttl_s: 600 + get_retry_max_wait_seconds: 600 + +logging: + report_to: none +debug: + enable_perf_metrics: true +output_dir: outputs/ling3-tiny-dflash +cache_dir: cache/ling3-tiny-dflash diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index 7d433e4..36dec12 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -25,6 +25,10 @@ EAGLE3 uses recurrent TTT and its selected distillation objective. Its pruned vo the checkpoint's `d2t/t2d` mapping across recovery/export. Teacher argmax outside the selected vocabulary is filtered; omitted probability mass is not reassigned to the reduced head. +Ling targets reuse the same DFlash trainer. `configs/recipes/ling3_tiny_dflash.yaml` binds +Ling-3.0-tiny's capture layers `[1, 6, 11, 16, 21]`, frozen embedding/head/norm keys, the `ling3` +template and gMASK 156894; it starts with one Target and two Draft GPUs. + The full-vocabulary recipe sets `training.eagle3_target_cache=logits`. This projects the frozen Target head once per microbatch and reuses the resulting BF16 logits across TTT depths and checkpoint recomputation; each depth still performs the same FP32 softmax and distillation loss. diff --git a/docs/user-guide/ling.md b/docs/user-guide/ling.md index 7ed7146..65752b5 100644 --- a/docs/user-guide/ling.md +++ b/docs/user-guide/ling.md @@ -7,6 +7,7 @@ tokens or feature-layer offsets. Model/dataset licenses are independent of ASpec | Target | YAML | Starting allocation | Draft | | --- | --- | --- | --- | | Ling-3.0-tiny | `configs/recipes/ling3_tiny_dspark.yaml` | 1 Target + 1 Draft GPU | Two-layer Dense DSpark | +| Ling-3.0-tiny DFlash | `configs/recipes/ling3_tiny_dflash.yaml` | 1 Target + 2 Draft GPUs | Five-layer Dense DFlash | | Ling-3.0-flash BF16 | `configs/recipes/ling3_flash_dspark.yaml` | TP2 Target + 1 Draft GPU | Five-layer Dense DSpark | | Ling-3.1-flash FP8 | `configs/recipes/ling31_flash_mla_moe_dspark.yaml` | TP4/EP4 Target + 4 Draft GPUs | Five-layer BF16 materialized MLA + Ling MoE | diff --git a/docs/user-guide/recipes.md b/docs/user-guide/recipes.md index 4b98ed0..3c83afb 100644 --- a/docs/user-guide/recipes.md +++ b/docs/user-guide/recipes.md @@ -26,6 +26,7 @@ connections on your hardware before training. | `dmtp` | Qwen3.5-9B / MTP-conditioned DSpark | 1 node, 8 GPUs: 4T + 4D; 4K, CP1 | Train a Draft conditioned on the frozen native predictor; native assets | | `native-mtp` | Qwen3.5-9B / native predictor | 1 node, 3 GPUs: 1T + 2D; 4K | Fine-tune the Target's native predictor | | `ling-tiny` | Ling-3.0-tiny / Dense DSpark | 1 node, 2 GPUs: 1T + 1D; 4K | Train a small Ling Draft | +| `ling-tiny-dflash` | Ling-3.0-tiny / DFlash | 1 node, 3 GPUs: 1T + 2D; 4K | Train a block-parallel DFlash Draft against Ling-3.0-tiny | | `ling-flash` | Ling-3.0-flash / Dense DSpark | 1 node, 3 GPUs: 2T (TP2) + 1D; 4K | Train against a larger Ling Target | | `ling-flash31` | Ling-3.1-flash / MLA + LingMoE DSpark | 1 node, 8 GPUs: 4T (TP4/EP4) + 4D; 4K | Train a structured Draft against the FP8 Ling Target | | `shared-target` | Qwen3-8B / two independent DSpark Drafts | 1 node, 8 GPUs: 4T + 2D × 2; 4K | Compare independent Drafts sharing Target features | diff --git a/tests/cpu/test_release_recipes.py b/tests/cpu/test_release_recipes.py index 364e244..4dc5df9 100644 --- a/tests/cpu/test_release_recipes.py +++ b/tests/cpu/test_release_recipes.py @@ -83,7 +83,7 @@ def test_qwen8b_recipes_plan_without_target_override(name, monkeypatch): def test_catalog_exactly_covers_formal_files(): entries = recipes.catalog() - assert len(entries) == 16 + assert len(entries) == 17 declared = {p for entry in entries.values() for p in entry["configs"]} assert declared == { str(p.relative_to(recipes.ROOT)) for p in (recipes.ROOT / "configs/recipes").glob("*.yaml") diff --git a/tests/test_ling3_recipe.py b/tests/test_ling3_recipe.py index 00103aa..4a16446 100644 --- a/tests/test_ling3_recipe.py +++ b/tests/test_ling3_recipe.py @@ -25,6 +25,8 @@ ROOT = Path(__file__).parents[1] RECIPE = ROOT / "configs/recipes/ling3_tiny_dspark.yaml" +DFLASH_RECIPE = ROOT / "configs/recipes/ling3_tiny_dflash.yaml" +DFLASH_CONFIG = ROOT / "aspec/config/dflash_ling3_tiny_draft_config.json" def test_ling_recipe_resolves_explicit_feature_contract(): @@ -55,6 +57,35 @@ def test_ling_draft_reuses_the_exportable_dense_dspark_config(): assert config.vocab_size == 157184 +def test_ling_tiny_dflash_recipe_resolves_explicit_feature_contract(): + config = load_config(str(DFLASH_RECIPE)) + plan = compile_execution_plan(config).to_dict() + assert plan["workload"]["models"]["target"]["family"] == "ling3" + assert plan["workload"]["models"]["draft"]["family"] == "dflash" + features = plan["workload"]["features"] + assert features["target_hidden_size"] == 1536 + assert features["target_num_hidden_layers"] == 24 + assert features["aux_hidden_state_layers"] == [1, 6, 11, 16, 21] + assert features["tensors"]["hidden_states"]["shape"] == ["sequence", 7680] + assert features["tensors"]["last_hidden_states"]["value_stage"] == "post_norm" + objective = plan["workload"]["objective"] + assert objective["family"] == "dflash" + assert objective["num_target_layers"] == 5 + assert objective["block_size"] == 7 + + +def test_ling_tiny_dflash_config_binds_tiny_target(): + config = AutoDraftModelConfig.from_file(str(DFLASH_CONFIG)) + assert config.architectures == ["DFlashDraftModel"] + assert config.model_type == "dflash" + assert config.hidden_size == 1536 + assert config.vocab_size == 157184 + assert config.target_hidden_size == 1536 + assert config.target_num_hidden_layers == 24 + assert config.target_layer_ids == [1, 6, 11, 16, 21] + assert config.mask_token_id == 156894 + + def test_ling_model_identity_uses_checkpoint_config(tmp_path): (tmp_path / "config.json").write_text( json.dumps( diff --git a/tools/recipe_catalog.json b/tools/recipe_catalog.json index e7c2b28..f81359d 100644 --- a/tools/recipe_catalog.json +++ b/tools/recipe_catalog.json @@ -99,6 +99,17 @@ "draft_gpus": 1, "native_only_export": false }, + "ling-tiny-dflash": { + "configs": [ + "configs/recipes/ling3_tiny_dflash.yaml" + ], + "model": "Ling-3.0-tiny", + "nodes": 1, + "gpus": 3, + "target_gpus": 1, + "draft_gpus": 2, + "native_only_export": false + }, "ling-flash": { "configs": [ "configs/recipes/ling3_flash_dspark.yaml" From f60838997b85f34a32acd56eabfdfc51165eec43 Mon Sep 17 00:00:00 2001 From: bohaotu Date: Fri, 27 Nov 2026 14:52:19 +0800 Subject: [PATCH 2/9] test(ling3): move DFlash recipe checks into CI and pin draft shape Move the Ling-3.0-tiny DFlash Plan/config checks from the repository-root tests/ directory into tests/cpu, which is the CI-discovered path. Pin the five-layer, 12/4-head, 128-dim dense geometry, the target layer invariants and the gMASK range, and cross-check the shared target binding against the DSpark tiny config so the two configs cannot drift independently. Also document the Ling DFlash export flags, keep the Ling note next to the DFlash paragraph and describe the recipe as a starting allocation. --- configs/recipes/ling3_tiny_dflash.yaml | 2 +- docs/user-guide/algorithms.md | 8 +-- docs/user-guide/ling.md | 9 +-- tests/cpu/test_ling3_dflash_recipe.py | 98 ++++++++++++++++++++++++++ tests/test_ling3_recipe.py | 31 -------- 5 files changed, 108 insertions(+), 40 deletions(-) create mode 100644 tests/cpu/test_ling3_dflash_recipe.py diff --git a/configs/recipes/ling3_tiny_dflash.yaml b/configs/recipes/ling3_tiny_dflash.yaml index 66542db..56f3172 100644 --- a/configs/recipes/ling3_tiny_dflash.yaml +++ b/configs/recipes/ling3_tiny_dflash.yaml @@ -2,7 +2,7 @@ # Hyperparameters are not a convergence/quality claim; see docs/user-guide/recipes.md. # Ling-3.0-tiny BF16 Target + five-layer dense DFlash Draft. # Data must use Ling's checkpoint chat template; see the recipe document. -# Initial three-GPU validation plan. Scale replicas from measured service rates. +# Starting three-GPU allocation. Scale replicas from measured service rates. model: target_model_path: ${oc.env:ASPEC_TARGET_MODEL,inclusionAI/Ling-3.0-tiny} native_context_length: 131072 diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index 36dec12..9a4e1c7 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -21,14 +21,14 @@ RAY_ADDRESS=local aspec --config configs/recipes/qwen3_8b_eagle3.yaml \ ``` DSpark retains CE/L1/Markov/confidence semantics; DFlash does not use those auxiliary targets. -EAGLE3 uses recurrent TTT and its selected distillation objective. Its pruned vocabulary preserves -the checkpoint's `d2t/t2d` mapping across recovery/export. Teacher argmax outside the selected -vocabulary is filtered; omitted probability mass is not reassigned to the reduced head. - Ling targets reuse the same DFlash trainer. `configs/recipes/ling3_tiny_dflash.yaml` binds Ling-3.0-tiny's capture layers `[1, 6, 11, 16, 21]`, frozen embedding/head/norm keys, the `ling3` template and gMASK 156894; it starts with one Target and two Draft GPUs. +EAGLE3 uses recurrent TTT and its selected distillation objective. Its pruned vocabulary preserves +the checkpoint's `d2t/t2d` mapping across recovery/export. Teacher argmax outside the selected +vocabulary is filtered; omitted probability mass is not reassigned to the reduced head. + The full-vocabulary recipe sets `training.eagle3_target_cache=logits`. This projects the frozen Target head once per microbatch and reuses the resulting BF16 logits across TTT depths and checkpoint recomputation; each depth still performs the same FP32 softmax and distillation loss. diff --git a/docs/user-guide/ling.md b/docs/user-guide/ling.md index 65752b5..c1153ea 100644 --- a/docs/user-guide/ling.md +++ b/docs/user-guide/ling.md @@ -79,10 +79,11 @@ properly prepared compatible data supplied by the user. Use [exact recovery](training.md) with the same model/data/routing and LR horizon, a complete checkpoint and a new output directory. Ling MoE router bias/control state is part of recovery. -Dense Ling DSpark uses faithful SGLang-format export with the correct embedding key. Qwen/Ling -MoE export declares the `dflash_moe_v1` loader requirement and the verified `moe_ep_size=1` boundary; -it is not an expert-parallel serving promise. MLA + MoE requires `--format aspec` and strict -native loading. Target hybrid KDA/MLA does not make every Draft structure or Target cache compatible. +Dense Ling DSpark and DFlash drafts share the faithful SGLang-format export boundary; supply the +Target path and the Ling embedding key explicitly. Qwen/Ling MoE export declares the +`dflash_moe_v1` loader requirement and the verified `moe_ep_size=1` boundary; it is not an +expert-parallel serving promise. MLA + MoE requires `--format aspec` and strict native loading. +Target hybrid KDA/MLA does not make every Draft structure or Target cache compatible. Short train/resume/export checks establish functionality. They do not establish convergence, acceptance or decode acceleration. See [support](../support.md) and [structure choices](structures.md). diff --git a/tests/cpu/test_ling3_dflash_recipe.py b/tests/cpu/test_ling3_dflash_recipe.py new file mode 100644 index 0000000..c4fe39b --- /dev/null +++ b/tests/cpu/test_ling3_dflash_recipe.py @@ -0,0 +1,98 @@ +# Copyright 2026 Ant Group Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from pathlib import Path + +from aspec.config.train_config import load_config +from aspec.models.draft import AutoDraftModelConfig +from aspec.models.draft.dflash import DFlashConfig +from aspec.planning import compile_execution_plan + +ROOT = Path(__file__).parents[2] +RECIPE = ROOT / "configs/recipes/ling3_tiny_dflash.yaml" +CONFIG = ROOT / "aspec/config/dflash_ling3_tiny_draft_config.json" +DSPARK_CONFIG = ROOT / "aspec/config/dspark_ling3_tiny_draft_config.json" + +SHARED_TARGET_BINDING = ( + "hidden_size", + "intermediate_size", + "head_dim", + "num_attention_heads", + "num_key_value_heads", + "vocab_size", + "rms_norm_eps", + "max_position_embeddings", + "rope_theta", + "num_target_layers", + "target_hidden_size", + "target_num_hidden_layers", + "target_layer_ids", + "mask_token_id", + "tie_word_embeddings", +) + + +def test_ling_tiny_dflash_recipe_resolves_explicit_feature_contract(): + plan = compile_execution_plan(load_config(str(RECIPE))).to_dict() + assert plan["workload"]["models"]["target"]["family"] == "ling3" + assert plan["workload"]["models"]["draft"]["family"] == "dflash" + features = plan["workload"]["features"] + assert features["target_hidden_size"] == 1536 + assert features["target_num_hidden_layers"] == 24 + assert features["aux_hidden_state_layers"] == [1, 6, 11, 16, 21] + assert features["tensors"]["hidden_states"]["shape"] == ["sequence", 7680] + assert features["tensors"]["last_hidden_states"]["value_stage"] == "post_norm" + objective = plan["workload"]["objective"] + assert objective["family"] == "dflash" + assert objective["num_target_layers"] == 5 + assert objective["num_anchors"] == 512 + assert objective["block_size"] == 7 + assert objective["loss_objective"] == "decay" + + +def test_ling_tiny_dflash_config_binds_tiny_target(): + config = AutoDraftModelConfig.from_file(str(CONFIG)) + assert config.architectures == ["DFlashDraftModel"] + assert config.model_type == "dflash" + assert config.hidden_size == 1536 + assert config.intermediate_size == 4608 + assert config.num_hidden_layers == 5 + assert config.num_attention_heads == 12 + assert config.num_key_value_heads == 4 + assert config.head_dim == 128 + assert config.vocab_size == 157184 + assert config.rms_norm_eps == 1e-6 + assert config.max_position_embeddings == 131072 + assert config.rope_theta == 6000000.0 + assert config.tie_word_embeddings is False + assert config.target_hidden_size == 1536 + assert config.target_num_hidden_layers == 24 + assert config.target_layer_ids == [1, 6, 11, 16, 21] + assert config.num_target_layers == len(config.target_layer_ids) == 5 + assert max(config.target_layer_ids) < config.target_num_hidden_layers + assert config.mask_token_id == 156894 + assert 0 <= config.mask_token_id < config.vocab_size + + trainer_config = DFlashConfig.from_pretrained(str(CONFIG)) + assert trainer_config.num_hidden_layers == config.num_hidden_layers + assert trainer_config.mask_token_id == config.mask_token_id + assert trainer_config.target_layer_ids == config.target_layer_ids + + +def test_ling_tiny_dflash_config_matches_dspark_target_binding(): + dflash = json.loads(CONFIG.read_text()) + dspark = json.loads(DSPARK_CONFIG.read_text()) + for key in SHARED_TARGET_BINDING: + assert dflash[key] == dspark[key], key diff --git a/tests/test_ling3_recipe.py b/tests/test_ling3_recipe.py index 4a16446..00103aa 100644 --- a/tests/test_ling3_recipe.py +++ b/tests/test_ling3_recipe.py @@ -25,8 +25,6 @@ ROOT = Path(__file__).parents[1] RECIPE = ROOT / "configs/recipes/ling3_tiny_dspark.yaml" -DFLASH_RECIPE = ROOT / "configs/recipes/ling3_tiny_dflash.yaml" -DFLASH_CONFIG = ROOT / "aspec/config/dflash_ling3_tiny_draft_config.json" def test_ling_recipe_resolves_explicit_feature_contract(): @@ -57,35 +55,6 @@ def test_ling_draft_reuses_the_exportable_dense_dspark_config(): assert config.vocab_size == 157184 -def test_ling_tiny_dflash_recipe_resolves_explicit_feature_contract(): - config = load_config(str(DFLASH_RECIPE)) - plan = compile_execution_plan(config).to_dict() - assert plan["workload"]["models"]["target"]["family"] == "ling3" - assert plan["workload"]["models"]["draft"]["family"] == "dflash" - features = plan["workload"]["features"] - assert features["target_hidden_size"] == 1536 - assert features["target_num_hidden_layers"] == 24 - assert features["aux_hidden_state_layers"] == [1, 6, 11, 16, 21] - assert features["tensors"]["hidden_states"]["shape"] == ["sequence", 7680] - assert features["tensors"]["last_hidden_states"]["value_stage"] == "post_norm" - objective = plan["workload"]["objective"] - assert objective["family"] == "dflash" - assert objective["num_target_layers"] == 5 - assert objective["block_size"] == 7 - - -def test_ling_tiny_dflash_config_binds_tiny_target(): - config = AutoDraftModelConfig.from_file(str(DFLASH_CONFIG)) - assert config.architectures == ["DFlashDraftModel"] - assert config.model_type == "dflash" - assert config.hidden_size == 1536 - assert config.vocab_size == 157184 - assert config.target_hidden_size == 1536 - assert config.target_num_hidden_layers == 24 - assert config.target_layer_ids == [1, 6, 11, 16, 21] - assert config.mask_token_id == 156894 - - def test_ling_model_identity_uses_checkpoint_config(tmp_path): (tmp_path / "config.json").write_text( json.dumps( From b18885d17f80b70286481d31c5c57e7cf8407566 Mon Sep 17 00:00:00 2001 From: bohaotu Date: Mon, 30 Nov 2026 16:44:26 +0800 Subject: [PATCH 3/9] fix(data): forward per-row tools to the chat template The tokenizer and format-only workers read a row's tools field but dropped it before calling preprocess_conversations/parser.format, so raw Ling JSONL lost the function signatures that apply_chat_template needs. Forward the field on both worker paths, keep rows without tools unchanged, and cover the raw JSONL path in tests/cpu. Also make the CE-only Ling DFlash recipe stop publishing the unused Target final hidden state, document the SGLang 0.5.21 DFLASH capture-hook limitation for Ling decode, and restrict the cross-recipe binding test to Target fields while pinning the recipe's Ling embedding/head/norm keys and chat template directly. --- aspec/data/dataset.py | 8 +- configs/recipes/ling3_tiny_dflash.yaml | 3 +- docs/user-guide/ling.md | 5 ++ tests/cpu/test_conversation_tools.py | 117 +++++++++++++++++++++++++ tests/cpu/test_ling3_dflash_recipe.py | 25 +++--- 5 files changed, 144 insertions(+), 14 deletions(-) create mode 100644 tests/cpu/test_conversation_tools.py diff --git a/aspec/data/dataset.py b/aspec/data/dataset.py index 544df12..d1a9261 100644 --- a/aspec/data/dataset.py +++ b/aspec/data/dataset.py @@ -323,6 +323,7 @@ def _tokenize_single(args): return_formatted_text=True, last_turn_loss_only=last_turn_only, min_loss_tokens=_worker_state.get("min_loss_tokens", 0), + **({"tools": [tools]} if tools is not None else {}), ) if not processed["input_ids"]: return None @@ -350,14 +351,17 @@ def _format_single(args): """ Worker function — format only, skip tokenization. """ - messages, _, _, _, train_with_decode = args + messages, tools, _, _, train_with_decode = args messages = _normalize_conversation(messages) result = _auto_decision_metadata(_resolve_last_turn_loss_only(messages)) parser = _worker_state["parser"] formatted = parser.format( - messages, add_generation_prompt=train_with_decode, expand_media_tokens=False + messages, + add_generation_prompt=train_with_decode, + expand_media_tokens=False, + **({"tools": tools} if tools is not None else {}), ) if not formatted: return None diff --git a/configs/recipes/ling3_tiny_dflash.yaml b/configs/recipes/ling3_tiny_dflash.yaml index 56f3172..0c59de1 100644 --- a/configs/recipes/ling3_tiny_dflash.yaml +++ b/configs/recipes/ling3_tiny_dflash.yaml @@ -62,7 +62,8 @@ training: inference: inference_engine_type: sgl - store_last_hidden_states: true + # CE-only DFlash training does not consume the Target final hidden state. + store_last_hidden_states: false # Native Ling runtime publishes GPU features through its forward-hook API. # Normal Target attention state is retained; optimized direct prefill is disabled. target_prefill_memory_optimized: false diff --git a/docs/user-guide/ling.md b/docs/user-guide/ling.md index c1153ea..f379e13 100644 --- a/docs/user-guide/ling.md +++ b/docs/user-guide/ling.md @@ -84,6 +84,11 @@ Target path and the Ling embedding key explicitly. Qwen/Ling MoE export declares `dflash_moe_v1` loader requirement and the verified `moe_ep_size=1` boundary; it is not an expert-parallel serving promise. MLA + MoE requires `--format aspec` and strict native loading. Target hybrid KDA/MLA does not make every Draft structure or Target cache compatible. +Speculative decode is a separate boundary: SGLang 0.5.21's `DFLASH` mode calls +`set_dflash_layers_to_capture`, while the Ling Target exposes only +`set_dspark_layers_to_capture`, so `aspec evaluate` stops during speculative engine +initialization. Training and strict native reload are unaffected; decoding a Ling DFlash Draft needs a +runtime that wires the Ling capture hook into the DFlash path. Short train/resume/export checks establish functionality. They do not establish convergence, acceptance or decode acceleration. See [support](../support.md) and [structure choices](structures.md). diff --git a/tests/cpu/test_conversation_tools.py b/tests/cpu/test_conversation_tools.py new file mode 100644 index 0000000..4312093 --- /dev/null +++ b/tests/cpu/test_conversation_tools.py @@ -0,0 +1,117 @@ +# Copyright 2026 Ant Group Co., Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from types import SimpleNamespace + +import torch + +from aspec.data import dataset as dataset_module +from aspec.data.template import TEMPLATE_REGISTRY + +TOOLS = [{"type": "function", "function": {"name": "lookup_city", "parameters": {}}}] +MESSAGES = [ + {"role": "user", "content": "weather"}, + {"role": "assistant", "content": "sunny"}, +] + + +class RecordingTokenizer: + """Character-level tokenizer that records the template arguments it receives.""" + + pad_token_id = 0 + unk_token_id = 0 + bos_token = "" + + def __init__(self): + self.chat_calls = [] + + def render(self, messages, tools=None): + template = TEMPLATE_REGISTRY.get("ling3") + parts = [] + if tools is not None: + parts.append("[TOOLS]" + json.dumps(tools, sort_keys=True)) + for message in messages: + header = ( + template.assistant_header + if message["role"] == "assistant" + else template.user_header + ) + parts.append(header + message["content"] + template.end_of_turn_token) + return "".join(parts) + + def apply_chat_template(self, messages, tokenize=False, **kwargs): + self.chat_calls.append({"messages": messages, **kwargs}) + return self.render(messages, kwargs.get("tools")) + + def __call__(self, text, **kwargs): + ids = [ord(char) for char in text][: kwargs.get("max_length", len(text))] + return SimpleNamespace(input_ids=torch.tensor([ids])) + + def encode(self, text, add_special_tokens=False): + return [ord(char) for char in text] + + +def _args(tmp_path, source, *, defer_tokenization): + return SimpleNamespace( + cache_dir=str(tmp_path / "cache"), + chat_template="ling3", + defer_tokenization=defer_tokenization, + last_turn_loss_only=False, + max_seq_length=256, + min_loss_tokens=1, + num_proc=1, + prompt_key="conversations", + renderer=None, + target_model_path="stub-model", + train_data_path=str(source), + train_with_decode=False, + dynamic_loss_mask=False, + ) + + +def _load(tmp_path, monkeypatch, row, *, defer_tokenization): + source = tmp_path / "rows.jsonl" + source.write_text(json.dumps(row) + "\n") + tokenizer = RecordingTokenizer() + monkeypatch.setattr(dataset_module, "load_tokenizer", lambda *_a, **_kw: tokenizer) + dataset_module._worker_state.clear() + prompts = dataset_module.load_conversation_dataset( + _args(tmp_path, source, defer_tokenization=defer_tokenization) + ) + return tokenizer, prompts + + +def test_tokenized_rows_forward_tools_to_the_chat_template(tmp_path, monkeypatch): + row = {"data_id": "row-1", "conversations": MESSAGES, "tools": TOOLS} + tokenizer, prompts = _load(tmp_path, monkeypatch, row, defer_tokenization=False) + + assert tokenizer.chat_calls[-1]["tools"] == TOOLS + expected = tokenizer.render(MESSAGES, TOOLS) + assert prompts[0]["input_ids"][0].tolist() == [ord(char) for char in expected] + + +def test_format_only_rows_forward_tools_to_the_chat_template(tmp_path, monkeypatch): + row = {"data_id": "row-1", "conversations": MESSAGES, "tools": TOOLS} + tokenizer, prompts = _load(tmp_path, monkeypatch, row, defer_tokenization=True) + + assert tokenizer.chat_calls[-1]["tools"] == TOOLS + assert prompts[0]["formatted_prompt"] == tokenizer.render(MESSAGES, TOOLS) + + +def test_rows_without_tools_do_not_send_a_tools_argument(tmp_path, monkeypatch): + row = {"data_id": "row-1", "conversations": MESSAGES} + tokenizer, _ = _load(tmp_path, monkeypatch, row, defer_tokenization=False) + + assert "tools" not in tokenizer.chat_calls[-1] diff --git a/tests/cpu/test_ling3_dflash_recipe.py b/tests/cpu/test_ling3_dflash_recipe.py index c4fe39b..5f62631 100644 --- a/tests/cpu/test_ling3_dflash_recipe.py +++ b/tests/cpu/test_ling3_dflash_recipe.py @@ -26,21 +26,11 @@ DSPARK_CONFIG = ROOT / "aspec/config/dspark_ling3_tiny_draft_config.json" SHARED_TARGET_BINDING = ( - "hidden_size", - "intermediate_size", - "head_dim", - "num_attention_heads", - "num_key_value_heads", "vocab_size", - "rms_norm_eps", - "max_position_embeddings", - "rope_theta", - "num_target_layers", "target_hidden_size", "target_num_hidden_layers", "target_layer_ids", "mask_token_id", - "tie_word_embeddings", ) @@ -53,7 +43,9 @@ def test_ling_tiny_dflash_recipe_resolves_explicit_feature_contract(): assert features["target_num_hidden_layers"] == 24 assert features["aux_hidden_state_layers"] == [1, 6, 11, 16, 21] assert features["tensors"]["hidden_states"]["shape"] == ["sequence", 7680] - assert features["tensors"]["last_hidden_states"]["value_stage"] == "post_norm" + assert "last_hidden_states" not in features["tensors"] + assert features["consumer"]["target_distribution"] == "token_labels" + assert {"tensor": "logits", "reason": "not_required_by_objective"} in features["omissions"] objective = plan["workload"]["objective"] assert objective["family"] == "dflash" assert objective["num_target_layers"] == 5 @@ -96,3 +88,14 @@ def test_ling_tiny_dflash_config_matches_dspark_target_binding(): dspark = json.loads(DSPARK_CONFIG.read_text()) for key in SHARED_TARGET_BINDING: assert dflash[key] == dspark[key], key + + +def test_ling_tiny_dflash_recipe_binds_ling_target_assets(): + config = load_config(str(RECIPE)) + assert config.model.embedding_key == "model.word_embeddings.weight" + assert config.model.lm_head_key == "lm_head.weight" + assert config.model.norm_key == "model.norm.weight" + assert config.model.draft_model_config.endswith("dflash_ling3_tiny_draft_config.json") + assert config.dataset.chat_template == "ling3" + assert config.training.dflash_num_target_layers == 5 + assert config.inference.store_last_hidden_states is False From a605809ff3302ec8ac3df6e3bb7326ea39ba4acd Mon Sep 17 00:00:00 2001 From: bohaotu Date: Mon, 30 Nov 2026 16:55:39 +0800 Subject: [PATCH 4/9] fix(data): fail closed when the fallback template would drop tools Forwarding per-row tools means a tool-bearing row can now reach the general parser's fallback branch when apply_chat_template rejects the request. That branch renders messages without the tool schema, so accepting the row would silently lose the definitions the change is meant to preserve. Reject tool-bearing rows on the fallback path with the original exception as the cause, and include that exception in the warning for rows without tools. Cover both tokenize and format-only paths. --- aspec/data/parse.py | 12 ++++++-- tests/cpu/test_conversation_tools.py | 42 ++++++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/aspec/data/parse.py b/aspec/data/parse.py index 5e28e26..9204c82 100644 --- a/aspec/data/parse.py +++ b/aspec/data/parse.py @@ -208,8 +208,16 @@ def format(self, conversation: "Conversation", **kwargs) -> str: try: return self._apply_chat_template(messages, **kwargs) - except (ValueError, TypeError): - warnings.warn("Tokenizer does not have a chat_template, using fallback rendering.") + except (ValueError, TypeError) as exc: + if kwargs.get("tools"): + raise ValueError( + "Cannot render a tool-bearing conversation through the fallback " + "chat-template path; the tool definitions would be dropped" + ) from exc + warnings.warn( + "Tokenizer does not have a chat_template " + f"({exc!r}), using fallback rendering." + ) add_generation_prompt = kwargs.get("add_generation_prompt", False) parts = [] bos_token = getattr(self.tokenizer, "bos_token", None) diff --git a/tests/cpu/test_conversation_tools.py b/tests/cpu/test_conversation_tools.py index 4312093..15a1d1e 100644 --- a/tests/cpu/test_conversation_tools.py +++ b/tests/cpu/test_conversation_tools.py @@ -15,6 +15,7 @@ import json from types import SimpleNamespace +import pytest import torch from aspec.data import dataset as dataset_module @@ -63,6 +64,13 @@ def encode(self, text, add_special_tokens=False): return [ord(char) for char in text] +class RejectingTokenizer(RecordingTokenizer): + """A tokenizer whose chat template rejects the request.""" + + def apply_chat_template(self, messages, tokenize=False, **kwargs): + raise TypeError("chat template does not support tools") + + def _args(tmp_path, source, *, defer_tokenization): return SimpleNamespace( cache_dir=str(tmp_path / "cache"), @@ -81,10 +89,10 @@ def _args(tmp_path, source, *, defer_tokenization): ) -def _load(tmp_path, monkeypatch, row, *, defer_tokenization): +def _load(tmp_path, monkeypatch, row, *, defer_tokenization, tokenizer=None): source = tmp_path / "rows.jsonl" source.write_text(json.dumps(row) + "\n") - tokenizer = RecordingTokenizer() + tokenizer = tokenizer or RecordingTokenizer() monkeypatch.setattr(dataset_module, "load_tokenizer", lambda *_a, **_kw: tokenizer) dataset_module._worker_state.clear() prompts = dataset_module.load_conversation_dataset( @@ -115,3 +123,33 @@ def test_rows_without_tools_do_not_send_a_tools_argument(tmp_path, monkeypatch): tokenizer, _ = _load(tmp_path, monkeypatch, row, defer_tokenization=False) assert "tools" not in tokenizer.chat_calls[-1] + + +@pytest.mark.parametrize("defer_tokenization", [False, True]) +def test_tool_rows_fail_closed_when_the_template_rejects_tools( + tmp_path, monkeypatch, defer_tokenization +): + row = {"data_id": "row-1", "conversations": MESSAGES, "tools": TOOLS} + + with pytest.raises(ValueError, match="tool-bearing"): + _load( + tmp_path, + monkeypatch, + row, + defer_tokenization=defer_tokenization, + tokenizer=RejectingTokenizer(), + ) + + +def test_rows_without_tools_keep_the_fallback_and_report_the_cause(tmp_path, monkeypatch): + row = {"data_id": "row-1", "conversations": MESSAGES} + + with pytest.warns(UserWarning, match="does not have a chat_template.*TypeError"): + _, prompts = _load( + tmp_path, + monkeypatch, + row, + defer_tokenization=False, + tokenizer=RejectingTokenizer(), + ) + assert prompts[0]["input_ids"].numel() > 0 From 6b8366cbc4e256c008eaa48d29da2ce61e5630df Mon Sep 17 00:00:00 2001 From: bohaotu Date: Fri, 4 Dec 2026 01:06:26 +0800 Subject: [PATCH 5/9] fix(data): reject rows whose content repeats the assistant header Both loss-mask implementations locate assistant spans by scanning the rendered text for the template's assistant header, so a header literal carried by a tool schema, a user turn or a tool response opens a phantom supervised span over text the model must not be trained to produce. Forwarding per-row tools makes this reachable on the shipped Ling recipe: the template renders a tool description through transformers' tojson, which does not escape angle brackets, so a description that mentions the role marker is supervised together with the whole tool instruction block. Reject such a row in GeneralParser.format, the only place that holds both the messages and the rendered text, so the offline tokenize path, the format-only path and the training-time token matcher are all covered. Only an excess of headers is rejected; a template that emits fewer stays as before. ThinkingParser accounts for the generation-prompt header that stands in for the final assistant turn. Also add ling3 to the opt-in real-tokenizer cross-validation, which previously skipped this template entirely. --- aspec/data/parse.py | 40 +++++++++++++++++++- docs/user-guide/data.md | 5 +++ tests/cpu/test_conversation_tools.py | 48 ++++++++++++++++++++++++ tests/test_loss_mask_cross_validation.py | 1 + 4 files changed, 92 insertions(+), 2 deletions(-) diff --git a/aspec/data/parse.py b/aspec/data/parse.py index 9204c82..92e1e3b 100644 --- a/aspec/data/parse.py +++ b/aspec/data/parse.py @@ -171,6 +171,32 @@ def _apply_chat_template(self, messages, **kwargs) -> str: conversation = self.tokenizer.apply_chat_template(messages, tokenize=False, **kwargs) return conversation + def _expected_assistant_headers(self, messages, add_generation_prompt: bool) -> int: + return sum(1 for msg in messages if msg.get("role") == "assistant") + int( + add_generation_prompt + ) + + def _reject_ambiguous_assistant_headers(self, text: str, messages, add_generation_prompt: bool): + """Refuse text whose assistant headers cannot be told apart from message content. + + The loss mask is derived by scanning the rendered text for the assistant + header, so a header literal carried by a tool schema, a user turn or a + tool response would open a phantom supervised span over text the model + must not be trained to produce. + """ + header = self.chat_template.assistant_header + if not header: + return + expected = self._expected_assistant_headers(messages, add_generation_prompt) + found = text.count(header) + if found > expected: + raise ValueError( + f"Rendered conversation contains {found} occurrences of the assistant " + f"header {header!r} but only {expected} assistant turn(s) can produce " + "one; message or tool content repeats the header and the loss mask " + "would supervise it. Remove the literal from the row." + ) + def format(self, conversation: "Conversation", **kwargs) -> str: messages = [] @@ -207,7 +233,7 @@ def format(self, conversation: "Conversation", **kwargs) -> str: messages.append(sentence) try: - return self._apply_chat_template(messages, **kwargs) + text = self._apply_chat_template(messages, **kwargs) except (ValueError, TypeError) as exc: if kwargs.get("tools"): raise ValueError( @@ -239,7 +265,12 @@ def format(self, conversation: "Conversation", **kwargs) -> str: if add_generation_prompt: parts.append(assistant_header) - return "".join(parts) + text = "".join(parts) + + self._reject_ambiguous_assistant_headers( + text, messages, kwargs.get("add_generation_prompt", False) + ) + return text def parse( self, @@ -359,6 +390,11 @@ class ThinkingParser(GeneralParser): def __init__(self, tokenizer: PreTrainedTokenizer, chat_template: ChatTemplate): super().__init__(tokenizer, chat_template) + def _expected_assistant_headers(self, messages, add_generation_prompt: bool) -> int: + # The history render always ends with a generation-prompt header, which + # stands in for the final assistant message's own header. + return sum(1 for msg in messages if msg.get("role") == "assistant") + def _apply_chat_template(self, messages, **kwargs) -> str: # ThinkingParser always generates prompt before appending last assistant content kwargs.pop("add_generation_prompt", None) diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index f93843c..e641563 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -15,6 +15,11 @@ Set `dataset.prompt_key=conversations` and the correct Target template. Do not s thinking mode between generation, training and decode. Loss masks supervise intended assistant tokens; short unusable rows are excluded and counted. DSpark block 7 needs at least 14 supervised tokens. +A row may carry a top-level `tools` list. Training and the decode evaluator both forward it to the +Target chat template, so a row's prompt is the same in both. Loss masks are derived by scanning the +rendered text for the template's assistant header, so a row whose tool schema, user turn or tool +response repeats that header is rejected rather than silently supervised on the wrong span. + Use disjoint train/eval data and preserve identity across resume. Evidence distinguishes raw, processed, admitted, skipped and DP-truncated counts. Epoch-scoped work count is not unique-document count. diff --git a/tests/cpu/test_conversation_tools.py b/tests/cpu/test_conversation_tools.py index 15a1d1e..7fc70ef 100644 --- a/tests/cpu/test_conversation_tools.py +++ b/tests/cpu/test_conversation_tools.py @@ -20,12 +20,14 @@ from aspec.data import dataset as dataset_module from aspec.data.template import TEMPLATE_REGISTRY +from aspec.data.utils import unpack_loss_mask TOOLS = [{"type": "function", "function": {"name": "lookup_city", "parameters": {}}}] MESSAGES = [ {"role": "user", "content": "weather"}, {"role": "assistant", "content": "sunny"}, ] +ASSISTANT_HEADER = TEMPLATE_REGISTRY.get("ling3").assistant_header class RecordingTokenizer: @@ -153,3 +155,49 @@ def test_rows_without_tools_keep_the_fallback_and_report_the_cause(tmp_path, mon tokenizer=RejectingTokenizer(), ) assert prompts[0]["input_ids"].numel() > 0 + + +def test_tool_schema_is_never_supervised(tmp_path, monkeypatch): + row = {"data_id": "row-1", "conversations": MESSAGES, "tools": TOOLS} + _, prompts = _load(tmp_path, monkeypatch, row, defer_tokenization=False) + + mask = unpack_loss_mask(prompts[0]["packed_loss_mask"]) + ids = prompts[0]["input_ids"][0] + supervised = "".join(chr(int(i)) for i, m in zip(ids, mask.tolist()) if m) + assert "[TOOLS]" not in supervised + assert "lookup_city" not in supervised + assert "sunny" in supervised + + +@pytest.mark.parametrize("defer_tokenization", [False, True]) +def test_rows_repeating_the_assistant_header_in_tools_fail_closed( + tmp_path, monkeypatch, defer_tokenization +): + tools = [ + { + "type": "function", + "function": { + "name": "lookup_city", + "description": f"answer with the {ASSISTANT_HEADER} marker", + "parameters": {}, + }, + } + ] + row = {"data_id": "row-1", "conversations": MESSAGES, "tools": tools} + + with pytest.raises(ValueError, match="assistant header"): + _load(tmp_path, monkeypatch, row, defer_tokenization=defer_tokenization) + + +@pytest.mark.parametrize("defer_tokenization", [False, True]) +def test_rows_repeating_the_assistant_header_in_a_user_turn_fail_closed( + tmp_path, monkeypatch, defer_tokenization +): + messages = [ + {"role": "user", "content": f"what does {ASSISTANT_HEADER} mean?"}, + {"role": "assistant", "content": "sunny"}, + ] + row = {"data_id": "row-1", "conversations": messages} + + with pytest.raises(ValueError, match="assistant header"): + _load(tmp_path, monkeypatch, row, defer_tokenization=defer_tokenization) diff --git a/tests/test_loss_mask_cross_validation.py b/tests/test_loss_mask_cross_validation.py index 94ba5af..ec28765 100644 --- a/tests/test_loss_mask_cross_validation.py +++ b/tests/test_loss_mask_cross_validation.py @@ -80,6 +80,7 @@ "kimi-k25-vlm": "moonshotai/Kimi-K2.5", "deepseek-v3": "deepseek-ai/DeepSeek-V3", "ling-flash-2.0": "inclusionAI/Ling-lite", + "ling3": "inclusionAI/Ling-3.0-tiny", "deepseek-v32": "deepseek-ai/DeepSeek-V3", "minimax-m2": "MiniMaxAI/MiniMax-M2.5", # GLM grammar is a continuous family (4.5 -> 5.2); GLM-4.5 loads cleanly via From 41fb28ab1467375f49aa4ad04b85bca675c951ed Mon Sep 17 00:00:00 2001 From: bohaotu Date: Fri, 4 Dec 2026 01:06:28 +0800 Subject: [PATCH 6/9] fix(eval): forward a row's tools when rendering a decode prefix Training now renders a row with its tool definitions, so a decode prefix rendered without them is a different prompt and leaves the function signature out of the evaluated context. --- aspec/commands/evaluate_draft.py | 5 +++++ tests/test_decode_evaluation.py | 14 ++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/aspec/commands/evaluate_draft.py b/aspec/commands/evaluate_draft.py index c8dac16..f2497df 100644 --- a/aspec/commands/evaluate_draft.py +++ b/aspec/commands/evaluate_draft.py @@ -68,6 +68,11 @@ def load_prompts(path, tokenizer, limit, *, enable_thinking=None): if not prefix or prefix[-1]["role"] != "user": raise ValueError("decode prefix must end with a user turn") options = {} if enable_thinking is None else {"enable_thinking": enable_thinking} + tools = row.get("tools") + if tools is not None: + # Training renders the same row with its tool definitions, so a + # prefix rendered without them is a different prompt. + options["tools"] = tools ids = tokenizer.apply_chat_template(prefix, tokenize=True, add_generation_prompt=True, return_dict=False, **options) if not ids or not isinstance(ids, list) or not all(type(i) is int and i >= 0 for i in ids): diff --git a/tests/test_decode_evaluation.py b/tests/test_decode_evaluation.py index c8545f1..8fec2a6 100644 --- a/tests/test_decode_evaluation.py +++ b/tests/test_decode_evaluation.py @@ -75,6 +75,20 @@ def test_decode_non_thinking_is_explicit_and_old_default_is_preserved(tmp_path): assert "enable_thinking" not in tokenizer.apply_chat_template.call_args.kwargs +def test_decode_prefix_forwards_the_row_tools(tmp_path): + data = tmp_path / "data.jsonl" + tools = [{"type": "function", "function": {"name": "lookup_city", "parameters": {}}}] + row = {"messages": [{"role": "user", "content": "question"}], "tools": tools} + data.write_text(json.dumps(row) + "\n") + tokenizer = Mock() + tokenizer.apply_chat_template.return_value = [1, 2] + load_prompts(data, tokenizer, 1) + assert tokenizer.apply_chat_template.call_args.kwargs["tools"] == tools + data.write_text(json.dumps({"messages": [{"role": "user", "content": "question"}]}) + "\n") + load_prompts(data, tokenizer, 1) + assert "tools" not in tokenizer.apply_chat_template.call_args.kwargs + + def test_generated_decode_selection_is_independent_of_completion_order(tmp_path): data = tmp_path / "data.jsonl" rows = [{"prompt_input_ids": [i], "input_ids": [i, 99], "loss_mask": [0, 1]} From 5a782c62265a6984d2c150f63ea5b66c9c569a0f Mon Sep 17 00:00:00 2001 From: bohaotu Date: Fri, 4 Dec 2026 01:20:36 +0800 Subject: [PATCH 7/9] fix(data): count assistant headers per rendering path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ThinkingParser drops the caller's add_generation_prompt and ends its history render with a generation-prompt header that stands in for the final assistant turn, but the fallback renderer emits that turn's own header plus the caller's prompt. The ambiguity guard assumed the native shape only, so a fallback row with add_generation_prompt=True — reachable through train_with_decode — was rejected even though its text was unambiguous. Derive the expected count from the path that produced the text. Both directions are pinned: counting the fallback as native fails test_thinking_fallback_header_count_follows_the_rendered_path, and counting the native path with the caller's flag fails test_thinking_native_rendering_still_rejects_a_repeated_header. --- aspec/data/parse.py | 26 ++++++++---- tests/cpu/test_conversation_tools.py | 59 ++++++++++++++++++++++++++-- 2 files changed, 73 insertions(+), 12 deletions(-) diff --git a/aspec/data/parse.py b/aspec/data/parse.py index 92e1e3b..6ef3ba5 100644 --- a/aspec/data/parse.py +++ b/aspec/data/parse.py @@ -171,12 +171,16 @@ def _apply_chat_template(self, messages, **kwargs) -> str: conversation = self.tokenizer.apply_chat_template(messages, tokenize=False, **kwargs) return conversation - def _expected_assistant_headers(self, messages, add_generation_prompt: bool) -> int: + def _expected_assistant_headers( + self, messages, add_generation_prompt: bool, fallback: bool + ) -> int: return sum(1 for msg in messages if msg.get("role") == "assistant") + int( add_generation_prompt ) - def _reject_ambiguous_assistant_headers(self, text: str, messages, add_generation_prompt: bool): + def _reject_ambiguous_assistant_headers( + self, text: str, messages, add_generation_prompt: bool, fallback: bool + ): """Refuse text whose assistant headers cannot be told apart from message content. The loss mask is derived by scanning the rendered text for the assistant @@ -187,7 +191,7 @@ def _reject_ambiguous_assistant_headers(self, text: str, messages, add_generatio header = self.chat_template.assistant_header if not header: return - expected = self._expected_assistant_headers(messages, add_generation_prompt) + expected = self._expected_assistant_headers(messages, add_generation_prompt, fallback) found = text.count(header) if found > expected: raise ValueError( @@ -232,6 +236,7 @@ def format(self, conversation: "Conversation", **kwargs) -> str: break messages.append(sentence) + fallback = False try: text = self._apply_chat_template(messages, **kwargs) except (ValueError, TypeError) as exc: @@ -266,9 +271,10 @@ def format(self, conversation: "Conversation", **kwargs) -> str: parts.append(assistant_header) text = "".join(parts) + fallback = True self._reject_ambiguous_assistant_headers( - text, messages, kwargs.get("add_generation_prompt", False) + text, messages, kwargs.get("add_generation_prompt", False), fallback ) return text @@ -390,10 +396,14 @@ class ThinkingParser(GeneralParser): def __init__(self, tokenizer: PreTrainedTokenizer, chat_template: ChatTemplate): super().__init__(tokenizer, chat_template) - def _expected_assistant_headers(self, messages, add_generation_prompt: bool) -> int: - # The history render always ends with a generation-prompt header, which - # stands in for the final assistant message's own header. - return sum(1 for msg in messages if msg.get("role") == "assistant") + def _expected_assistant_headers( + self, messages, add_generation_prompt: bool, fallback: bool + ) -> int: + # Native rendering drops the caller's flag and ends the history with a + # generation-prompt header that stands in for the final assistant turn. + # The fallback renders that turn's own header plus the caller's prompt. + count = sum(1 for msg in messages if msg.get("role") == "assistant") + return count + int(add_generation_prompt) if fallback else count def _apply_chat_template(self, messages, **kwargs) -> str: # ThinkingParser always generates prompt before appending last assistant content diff --git a/tests/cpu/test_conversation_tools.py b/tests/cpu/test_conversation_tools.py index 7fc70ef..d00d753 100644 --- a/tests/cpu/test_conversation_tools.py +++ b/tests/cpu/test_conversation_tools.py @@ -19,6 +19,7 @@ import torch from aspec.data import dataset as dataset_module +from aspec.data.parse import create_parser from aspec.data.template import TEMPLATE_REGISTRY from aspec.data.utils import unpack_loss_mask @@ -28,6 +29,7 @@ {"role": "assistant", "content": "sunny"}, ] ASSISTANT_HEADER = TEMPLATE_REGISTRY.get("ling3").assistant_header +THINKING_TEMPLATE = TEMPLATE_REGISTRY.get("deepseek-v32") class RecordingTokenizer: @@ -37,11 +39,12 @@ class RecordingTokenizer: unk_token_id = 0 bos_token = "" - def __init__(self): + def __init__(self, template_name="ling3"): self.chat_calls = [] + self.template = TEMPLATE_REGISTRY.get(template_name) - def render(self, messages, tools=None): - template = TEMPLATE_REGISTRY.get("ling3") + def render(self, messages, tools=None, add_generation_prompt=False): + template = self.template parts = [] if tools is not None: parts.append("[TOOLS]" + json.dumps(tools, sort_keys=True)) @@ -52,11 +55,15 @@ def render(self, messages, tools=None): else template.user_header ) parts.append(header + message["content"] + template.end_of_turn_token) + if add_generation_prompt: + parts.append(template.assistant_header) return "".join(parts) def apply_chat_template(self, messages, tokenize=False, **kwargs): self.chat_calls.append({"messages": messages, **kwargs}) - return self.render(messages, kwargs.get("tools")) + return self.render( + messages, kwargs.get("tools"), kwargs.get("add_generation_prompt", False) + ) def __call__(self, text, **kwargs): ids = [ord(char) for char in text][: kwargs.get("max_length", len(text))] @@ -201,3 +208,47 @@ def test_rows_repeating_the_assistant_header_in_a_user_turn_fail_closed( with pytest.raises(ValueError, match="assistant header"): _load(tmp_path, monkeypatch, row, defer_tokenization=defer_tokenization) + + +@pytest.mark.parametrize("add_generation_prompt", [False, True]) +def test_thinking_native_rendering_ignores_the_callers_generation_prompt(add_generation_prompt): + parser = create_parser(RecordingTokenizer("deepseek-v32"), THINKING_TEMPLATE) + + text = parser.format(MESSAGES, add_generation_prompt=add_generation_prompt) + + assert text.count(THINKING_TEMPLATE.assistant_header) == 1 + + +@pytest.mark.parametrize("add_generation_prompt", [False, True]) +def test_thinking_native_rendering_still_rejects_a_repeated_header(add_generation_prompt): + parser = create_parser(RecordingTokenizer("deepseek-v32"), THINKING_TEMPLATE) + messages = [ + {"role": "user", "content": "weather"}, + {"role": "assistant", "content": f"see {THINKING_TEMPLATE.assistant_header}"}, + ] + + with pytest.raises(ValueError, match="assistant header"): + parser.format(messages, add_generation_prompt=add_generation_prompt) + + +@pytest.mark.parametrize("add_generation_prompt", [False, True]) +def test_thinking_fallback_header_count_follows_the_rendered_path(add_generation_prompt): + parser = create_parser(RejectingTokenizer("deepseek-v32"), THINKING_TEMPLATE) + + with pytest.warns(UserWarning): + text = parser.format(MESSAGES, add_generation_prompt=add_generation_prompt) + + assert text.count(THINKING_TEMPLATE.assistant_header) == 1 + int(add_generation_prompt) + + +@pytest.mark.parametrize("add_generation_prompt", [False, True]) +def test_thinking_fallback_still_rejects_a_repeated_header(add_generation_prompt): + parser = create_parser(RejectingTokenizer("deepseek-v32"), THINKING_TEMPLATE) + messages = [ + {"role": "user", "content": "weather"}, + {"role": "assistant", "content": f"see {THINKING_TEMPLATE.assistant_header}"}, + ] + + with pytest.warns(UserWarning): + with pytest.raises(ValueError, match="assistant header"): + parser.format(messages, add_generation_prompt=add_generation_prompt) From 2dfb2f67d0eadd27be948add1ca9c12f0e583a71 Mon Sep 17 00:00:00 2001 From: bohaotu Date: Fri, 4 Dec 2026 01:20:36 +0800 Subject: [PATCH 8/9] docs(data): scope the repeated-header rejection Assistant content repeating the assistant header is rejected as well, and rows without tools are covered. Rows rendered through dataset.renderer derive a token-based mask from the renderer itself and never reach the parser, so they are not rejected for this reason. --- docs/user-guide/data.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index e641563..5169af8 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -16,9 +16,13 @@ thinking mode between generation, training and decode. Loss masks supervise inte short unusable rows are excluded and counted. DSpark block 7 needs at least 14 supervised tokens. A row may carry a top-level `tools` list. Training and the decode evaluator both forward it to the -Target chat template, so a row's prompt is the same in both. Loss masks are derived by scanning the -rendered text for the template's assistant header, so a row whose tool schema, user turn or tool -response repeats that header is rejected rather than silently supervised on the wrong span. +Target chat template, so a row's prompt is the same in both. + +Rows rendered through `dataset.chat_template` derive their loss mask by scanning the rendered text +for the template's assistant header. A row whose tool schema, user turn, tool response or assistant +content repeats that header is rejected rather than silently supervised on the wrong span, and this +applies to rows without tools as well. Rows rendered through `dataset.renderer` derive a token-based +mask from the renderer itself and are not rejected for this reason. Use disjoint train/eval data and preserve identity across resume. Evidence distinguishes raw, processed, admitted, skipped and DP-truncated counts. Epoch-scoped work count is not unique-document count. From c736066680a457b5e725da5625e426b21fe9f66b Mon Sep 17 00:00:00 2001 From: bohaotu Date: Fri, 4 Dec 2026 01:26:09 +0800 Subject: [PATCH 9/9] docs(data): describe the header check as count-based The guard rejects a row only when the rendered text holds more occurrences of the assistant header than its assistant turns can produce. A template whose registered header does not match what its tokenizer renders yields fewer occurrences than expected, so a repeated header can go undetected there; the guide now states that instead of implying an unconditional rejection. --- docs/user-guide/data.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 5169af8..9fcd52c 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -19,10 +19,13 @@ A row may carry a top-level `tools` list. Training and the decode evaluator both Target chat template, so a row's prompt is the same in both. Rows rendered through `dataset.chat_template` derive their loss mask by scanning the rendered text -for the template's assistant header. A row whose tool schema, user turn, tool response or assistant -content repeats that header is rejected rather than silently supervised on the wrong span, and this -applies to rows without tools as well. Rows rendered through `dataset.renderer` derive a token-based -mask from the renderer itself and are not rejected for this reason. +for the template's assistant header. The check is count-based: a row is rejected when the rendered +text holds more occurrences of that header than its assistant turns can produce, which is what a +tool schema, user turn, tool response or assistant content repeating the header causes, and it +applies to rows without tools as well. A template whose registered header does not match what its +tokenizer renders yields fewer occurrences than expected, so a repeated header can go undetected +there. Rows rendered through `dataset.renderer` derive a token-based mask from the renderer itself +and are not checked. Use disjoint train/eval data and preserve identity across resume. Evidence distinguishes raw, processed, admitted, skipped and DP-truncated counts. Epoch-scoped work count is not unique-document count.