Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions aspec/commands/evaluate_draft.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
20 changes: 20 additions & 0 deletions aspec/config/dflash_ling3_tiny_draft_config.json
Original file line number Diff line number Diff line change
@@ -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
}
8 changes: 6 additions & 2 deletions aspec/data/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)
if not processed["input_ids"]:
return None
Expand Down Expand Up @@ -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
Expand Down
62 changes: 58 additions & 4 deletions aspec/data/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,36 @@ 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, 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, 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
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, fallback)
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 = []

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

fallback = False
try:
return self._apply_chat_template(messages, **kwargs)
except (ValueError, TypeError):
warnings.warn("Tokenizer does not have a chat_template, using fallback rendering.")
text = self._apply_chat_template(messages, **kwargs)
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)
Expand All @@ -231,7 +270,13 @@ def format(self, conversation: "Conversation", **kwargs) -> str:
if add_generation_prompt:
parts.append(assistant_header)

return "".join(parts)
text = "".join(parts)
fallback = True

self._reject_ambiguous_assistant_headers(
text, messages, kwargs.get("add_generation_prompt", False), fallback
)
return text

def parse(
self,
Expand Down Expand Up @@ -351,6 +396,15 @@ 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, 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
kwargs.pop("add_generation_prompt", None)
Expand Down
104 changes: 104 additions & 0 deletions configs/recipes/ling3_tiny_dflash.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# 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.
# 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
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
Comment thread
sysuTobo marked this conversation as resolved.
Resolved
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
# 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
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
4 changes: 4 additions & 0 deletions docs/user-guide/algorithms.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ 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.
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.
Expand Down
12 changes: 12 additions & 0 deletions docs/user-guide/data.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@ 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.

Rows rendered through `dataset.chat_template` derive their loss mask by scanning the rendered text
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.

Expand Down
15 changes: 11 additions & 4 deletions docs/user-guide/ling.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down Expand Up @@ -78,10 +79,16 @@ 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
Comment thread
sysuTobo marked this conversation as resolved.
Resolved
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.
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for documenting where decode stops on the pinned runtime. One non-blocking follow-up for the shared evaluator: training now passes a raw row’s tools to the template, but aspec evaluate still omits them when it renders a prefix from messages or conversations. With the same question and a lookup_city tool, that leaves the function signature out of the evaluation prompt.

Could the evaluator forward row["tools"] when present and cover that case with a prompt-rendering test? Saved prompt_input_ids already preserve the intended prefix. I’m happy for the evaluator change to land separately given the Ling DFlash runtime limitation documented here. Raw evaluation prompt rendering

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 41fb28a — aspec evaluate now forwards row["tools"] when it renders a prefix from messages/conversations, so the evaluated prompt is the one training renders. tests/test_decode_evaluation.py::test_decode_prefix_forwards_the_row_tools covers a tool-bearing row and asserts a row without tools still sends no tools argument.

I also checked the decode limitation you flagged against the pinned runtime rather than taking it on trust. In SGLang e00930c, bailing_moe_v3.py defines only set_dspark_layers_to_capture, and SpeculativeAlgorithm.is_dspark() is true only for DSPARK, so DFLASH takes the set_dflash_layers_to_capture branch and raises. That stays documented in docs/user-guide/ling.md; this PR still does not claim decode support.

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).
1 change: 1 addition & 0 deletions docs/user-guide/recipes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Loading