Skip to content

Commit 29148e6

Browse files
sysuTobobohaotu
andauthored
feat(ling3): add Ling-3.0-tiny DFlash recipe (#67)
* 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. * 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. * 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. * 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. * 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. * 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. * fix(data): count assistant headers per rendering path 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. * 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(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. --------- Co-authored-by: bohaotu <bohaotu@pony.ai>
1 parent 6e7e3bc commit 29148e6

15 files changed

Lines changed: 603 additions & 11 deletions

‎aspec/commands/evaluate_draft.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,11 @@ def load_prompts(path, tokenizer, limit, *, enable_thinking=None):
6969
if not prefix or prefix[-1]["role"] != "user":
7070
raise ValueError("decode prefix must end with a user turn")
7171
options = {} if enable_thinking is None else {"enable_thinking": enable_thinking}
72+
tools = row.get("tools")
73+
if tools is not None:
74+
# Training renders the same row with its tool definitions, so a
75+
# prefix rendered without them is a different prompt.
76+
options["tools"] = tools
7277
ids = tokenizer.apply_chat_template(prefix, tokenize=True, add_generation_prompt=True,
7378
return_dict=False, **options)
7479
if not ids or not isinstance(ids, list) or not all(type(i) is int and i >= 0 for i in ids):
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"architectures": ["DFlashDraftModel"],
3+
"model_type": "dflash",
4+
"hidden_size": 1536,
5+
"intermediate_size": 4608,
6+
"num_hidden_layers": 5,
7+
"num_attention_heads": 12,
8+
"num_key_value_heads": 4,
9+
"head_dim": 128,
10+
"vocab_size": 157184,
11+
"rms_norm_eps": 1e-6,
12+
"max_position_embeddings": 131072,
13+
"rope_theta": 6000000.0,
14+
"num_target_layers": 5,
15+
"target_hidden_size": 1536,
16+
"target_num_hidden_layers": 24,
17+
"target_layer_ids": [1, 6, 11, 16, 21],
18+
"mask_token_id": 156894,
19+
"tie_word_embeddings": false
20+
}

‎aspec/data/dataset.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,7 @@ def _tokenize_single(args):
323323
return_formatted_text=True,
324324
last_turn_loss_only=last_turn_only,
325325
min_loss_tokens=_worker_state.get("min_loss_tokens", 0),
326+
**({"tools": [tools]} if tools is not None else {}),
326327
)
327328
if not processed["input_ids"]:
328329
return None
@@ -350,14 +351,17 @@ def _format_single(args):
350351
"""
351352
Worker function — format only, skip tokenization.
352353
"""
353-
messages, _, _, _, train_with_decode = args
354+
messages, tools, _, _, train_with_decode = args
354355
messages = _normalize_conversation(messages)
355356

356357
result = _auto_decision_metadata(_resolve_last_turn_loss_only(messages))
357358

358359
parser = _worker_state["parser"]
359360
formatted = parser.format(
360-
messages, add_generation_prompt=train_with_decode, expand_media_tokens=False
361+
messages,
362+
add_generation_prompt=train_with_decode,
363+
expand_media_tokens=False,
364+
**({"tools": tools} if tools is not None else {}),
361365
)
362366
if not formatted:
363367
return None

‎aspec/data/parse.py‎

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,36 @@ def _apply_chat_template(self, messages, **kwargs) -> str:
171171
conversation = self.tokenizer.apply_chat_template(messages, tokenize=False, **kwargs)
172172
return conversation
173173

174+
def _expected_assistant_headers(
175+
self, messages, add_generation_prompt: bool, fallback: bool
176+
) -> int:
177+
return sum(1 for msg in messages if msg.get("role") == "assistant") + int(
178+
add_generation_prompt
179+
)
180+
181+
def _reject_ambiguous_assistant_headers(
182+
self, text: str, messages, add_generation_prompt: bool, fallback: bool
183+
):
184+
"""Refuse text whose assistant headers cannot be told apart from message content.
185+
186+
The loss mask is derived by scanning the rendered text for the assistant
187+
header, so a header literal carried by a tool schema, a user turn or a
188+
tool response would open a phantom supervised span over text the model
189+
must not be trained to produce.
190+
"""
191+
header = self.chat_template.assistant_header
192+
if not header:
193+
return
194+
expected = self._expected_assistant_headers(messages, add_generation_prompt, fallback)
195+
found = text.count(header)
196+
if found > expected:
197+
raise ValueError(
198+
f"Rendered conversation contains {found} occurrences of the assistant "
199+
f"header {header!r} but only {expected} assistant turn(s) can produce "
200+
"one; message or tool content repeats the header and the loss mask "
201+
"would supervise it. Remove the literal from the row."
202+
)
203+
174204
def format(self, conversation: "Conversation", **kwargs) -> str:
175205
messages = []
176206

@@ -206,10 +236,19 @@ def format(self, conversation: "Conversation", **kwargs) -> str:
206236
break
207237
messages.append(sentence)
208238

239+
fallback = False
209240
try:
210-
return self._apply_chat_template(messages, **kwargs)
211-
except (ValueError, TypeError):
212-
warnings.warn("Tokenizer does not have a chat_template, using fallback rendering.")
241+
text = self._apply_chat_template(messages, **kwargs)
242+
except (ValueError, TypeError) as exc:
243+
if kwargs.get("tools"):
244+
raise ValueError(
245+
"Cannot render a tool-bearing conversation through the fallback "
246+
"chat-template path; the tool definitions would be dropped"
247+
) from exc
248+
warnings.warn(
249+
"Tokenizer does not have a chat_template "
250+
f"({exc!r}), using fallback rendering."
251+
)
213252
add_generation_prompt = kwargs.get("add_generation_prompt", False)
214253
parts = []
215254
bos_token = getattr(self.tokenizer, "bos_token", None)
@@ -231,7 +270,13 @@ def format(self, conversation: "Conversation", **kwargs) -> str:
231270
if add_generation_prompt:
232271
parts.append(assistant_header)
233272

234-
return "".join(parts)
273+
text = "".join(parts)
274+
fallback = True
275+
276+
self._reject_ambiguous_assistant_headers(
277+
text, messages, kwargs.get("add_generation_prompt", False), fallback
278+
)
279+
return text
235280

236281
def parse(
237282
self,
@@ -351,6 +396,15 @@ class ThinkingParser(GeneralParser):
351396
def __init__(self, tokenizer: PreTrainedTokenizer, chat_template: ChatTemplate):
352397
super().__init__(tokenizer, chat_template)
353398

399+
def _expected_assistant_headers(
400+
self, messages, add_generation_prompt: bool, fallback: bool
401+
) -> int:
402+
# Native rendering drops the caller's flag and ends the history with a
403+
# generation-prompt header that stands in for the final assistant turn.
404+
# The fallback renders that turn's own header plus the caller's prompt.
405+
count = sum(1 for msg in messages if msg.get("role") == "assistant")
406+
return count + int(add_generation_prompt) if fallback else count
407+
354408
def _apply_chat_template(self, messages, **kwargs) -> str:
355409
# ThinkingParser always generates prompt before appending last assistant content
356410
kwargs.pop("add_generation_prompt", None)
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# Release training starting point: three passes, held-out eval and checkpoints.
2+
# Hyperparameters are not a convergence/quality claim; see docs/user-guide/recipes.md.
3+
# Ling-3.0-tiny BF16 Target + five-layer dense DFlash Draft.
4+
# Data must use Ling's checkpoint chat template; see the recipe document.
5+
# Starting three-GPU allocation. Scale replicas from measured service rates.
6+
model:
7+
target_model_path: ${oc.env:ASPEC_TARGET_MODEL,inclusionAI/Ling-3.0-tiny}
8+
native_context_length: 131072
9+
trust_remote_code: true
10+
draft_model_config: aspec/config/dflash_ling3_tiny_draft_config.json
11+
embedding_key: model.word_embeddings.weight
12+
lm_head_key: lm_head.weight
13+
norm_key: model.norm.weight
14+
15+
dataset:
16+
eval_interval: 100
17+
eval_micro_batch_size: 1
18+
train_data_path: ${oc.env:ASPEC_TRAIN_DATA}
19+
eval_data_path: ${oc.env:ASPEC_EVAL_DATA}
20+
chat_template: ling3
21+
prompt_key: conversations
22+
min_loss_tokens: 32
23+
shuffle_dataset: true
24+
dataset_seed: 42
25+
26+
training:
27+
attention_backend: flex_attention
28+
draft_context_parallel_size: 1
29+
micro_batch_size: 1
30+
draft_accumulation_steps: 2
31+
learning_rate: 6e-4
32+
min_lr: 6e-5
33+
weight_decay: 0.0
34+
max_grad_norm: 1.0
35+
max_seq_length: 4096
36+
num_epochs: 3
37+
warmup_ratio: 0.04
38+
seed: 42
39+
continual_training: false
40+
deterministic_anchor_sampling: false
41+
training_num_gpus_per_node: 2
42+
training_num_nodes: 1
43+
placement_strategy: inference_first
44+
fsdp_strategy: REPLICATE
45+
fsdp_reduce_dtype: bfloat16
46+
compile_model: false
47+
max_concurrent_batches: 1
48+
streaming_dispatch_with_training: true
49+
pipeline_dispatch_with_training: true
50+
prefetch_depth: 1
51+
save_interval: 100
52+
save_per_epoch: false
53+
save_final_checkpoint: true
54+
max_checkpoints: 2
55+
dflash_block_size: 7
56+
dflash_packing: false
57+
dflash_num_target_layers: 5
58+
dflash_num_anchors: 512
59+
dflash_loss_objective: decay
60+
dflash_ce_loss_alpha: 1.0
61+
dflash_l1_loss_alpha: 0.0
62+
63+
inference:
64+
inference_engine_type: sgl
65+
# CE-only DFlash training does not consume the Target final hidden state.
66+
store_last_hidden_states: false
67+
# Native Ling runtime publishes GPU features through its forward-hook API.
68+
# Normal Target attention state is retained; optimized direct prefill is disabled.
69+
target_prefill_memory_optimized: false
70+
inference_num_gpus: 1
71+
inference_num_gpus_per_engine: 1
72+
inference_num_gpus_per_node: 3
73+
inference_fetch_batch: 4
74+
inference_buffer_threshold: 4
75+
max_sample_pool_size: 8
76+
inference_batch_size: 2
77+
sglang:
78+
tp_size: 1
79+
mem_fraction_static: 0.6
80+
81+
mooncake:
82+
data_plane: transfer_engine
83+
protocol: nvlink_intra
84+
require_nvlink: true
85+
enable_gpu_direct: true
86+
allow_host_fallback: false
87+
enable_hard_pin: true
88+
max_seq_len: 4096
89+
hidden_dim: 1536
90+
global_segment_size: 16GB
91+
local_buffer_size: 4GB
92+
host_buffer_size: 1GB
93+
gpu_ring_slots: 32
94+
source_gpu_ring_slots: 32
95+
destination_gpu_ring_slots: 1
96+
kv_lease_ttl_s: 600
97+
get_retry_max_wait_seconds: 600
98+
99+
logging:
100+
report_to: none
101+
debug:
102+
enable_perf_metrics: true
103+
output_dir: outputs/ling3-tiny-dflash
104+
cache_dir: cache/ling3-tiny-dflash

‎docs/user-guide/algorithms.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ RAY_ADDRESS=local aspec --config configs/recipes/qwen3_8b_eagle3.yaml \
2121
```
2222

2323
DSpark retains CE/L1/Markov/confidence semantics; DFlash does not use those auxiliary targets.
24+
Ling targets reuse the same DFlash trainer. `configs/recipes/ling3_tiny_dflash.yaml` binds
25+
Ling-3.0-tiny's capture layers `[1, 6, 11, 16, 21]`, frozen embedding/head/norm keys, the `ling3`
26+
template and gMASK 156894; it starts with one Target and two Draft GPUs.
27+
2428
EAGLE3 uses recurrent TTT and its selected distillation objective. Its pruned vocabulary preserves
2529
the checkpoint's `d2t/t2d` mapping across recovery/export. Teacher argmax outside the selected
2630
vocabulary is filtered; omitted probability mass is not reassigned to the reduced head.

‎docs/user-guide/data.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,18 @@ Set `dataset.prompt_key=conversations` and the correct Target template. Do not s
1515
thinking mode between generation, training and decode. Loss masks supervise intended assistant tokens;
1616
short unusable rows are excluded and counted. DSpark block 7 needs at least 14 supervised tokens.
1717

18+
A row may carry a top-level `tools` list. Training and the decode evaluator both forward it to the
19+
Target chat template, so a row's prompt is the same in both.
20+
21+
Rows rendered through `dataset.chat_template` derive their loss mask by scanning the rendered text
22+
for the template's assistant header. The check is count-based: a row is rejected when the rendered
23+
text holds more occurrences of that header than its assistant turns can produce, which is what a
24+
tool schema, user turn, tool response or assistant content repeating the header causes, and it
25+
applies to rows without tools as well. A template whose registered header does not match what its
26+
tokenizer renders yields fewer occurrences than expected, so a repeated header can go undetected
27+
there. Rows rendered through `dataset.renderer` derive a token-based mask from the renderer itself
28+
and are not checked.
29+
1830
Use disjoint train/eval data and preserve identity across resume. Evidence distinguishes raw, processed,
1931
admitted, skipped and DP-truncated counts. Epoch-scoped work count is not unique-document count.
2032

‎docs/user-guide/ling.md‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ tokens or feature-layer offsets. Model/dataset licenses are independent of ASpec
77
| Target | YAML | Starting allocation | Draft |
88
| --- | --- | --- | --- |
99
| Ling-3.0-tiny | `configs/recipes/ling3_tiny_dspark.yaml` | 1 Target + 1 Draft GPU | Two-layer Dense DSpark |
10+
| Ling-3.0-tiny DFlash | `configs/recipes/ling3_tiny_dflash.yaml` | 1 Target + 2 Draft GPUs | Five-layer Dense DFlash |
1011
| Ling-3.0-flash BF16 | `configs/recipes/ling3_flash_dspark.yaml` | TP2 Target + 1 Draft GPU | Five-layer Dense DSpark |
1112
| 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 |
1213

@@ -78,10 +79,16 @@ properly prepared compatible data supplied by the user.
7879
Use [exact recovery](training.md) with the same model/data/routing and LR horizon, a complete
7980
checkpoint and a new output directory. Ling MoE router bias/control state is part of recovery.
8081

81-
Dense Ling DSpark uses faithful SGLang-format export with the correct embedding key. Qwen/Ling
82-
MoE export declares the `dflash_moe_v1` loader requirement and the verified `moe_ep_size=1` boundary;
83-
it is not an expert-parallel serving promise. MLA + MoE requires `--format aspec` and strict
84-
native loading. Target hybrid KDA/MLA does not make every Draft structure or Target cache compatible.
82+
Dense Ling DSpark and DFlash drafts share the faithful SGLang-format export boundary; supply the
83+
Target path and the Ling embedding key explicitly. Qwen/Ling MoE export declares the
84+
`dflash_moe_v1` loader requirement and the verified `moe_ep_size=1` boundary; it is not an
85+
expert-parallel serving promise. MLA + MoE requires `--format aspec` and strict native loading.
86+
Target hybrid KDA/MLA does not make every Draft structure or Target cache compatible.
87+
Speculative decode is a separate boundary: SGLang 0.5.21's `DFLASH` mode calls
88+
`set_dflash_layers_to_capture`, while the Ling Target exposes only
89+
`set_dspark_layers_to_capture`, so `aspec evaluate` stops during speculative engine
90+
initialization. Training and strict native reload are unaffected; decoding a Ling DFlash Draft needs a
91+
runtime that wires the Ling capture hook into the DFlash path.
8592

8693
Short train/resume/export checks establish functionality. They do not establish convergence,
8794
acceptance or decode acceleration. See [support](../support.md) and [structure choices](structures.md).

‎docs/user-guide/recipes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ connections on your hardware before training.
2626
| `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 |
2727
| `native-mtp` | Qwen3.5-9B / native predictor | 1 node, 3 GPUs: 1T + 2D; 4K | Fine-tune the Target's native predictor |
2828
| `ling-tiny` | Ling-3.0-tiny / Dense DSpark | 1 node, 2 GPUs: 1T + 1D; 4K | Train a small Ling Draft |
29+
| `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 |
2930
| `ling-flash` | Ling-3.0-flash / Dense DSpark | 1 node, 3 GPUs: 2T (TP2) + 1D; 4K | Train against a larger Ling Target |
3031
| `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 |
3132
| `shared-target` | Qwen3-8B / two independent DSpark Drafts | 1 node, 8 GPUs: 4T + 2D × 2; 4K | Compare independent Drafts sharing Target features |

0 commit comments

Comments
 (0)