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/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/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/aspec/data/parse.py b/aspec/data/parse.py index 5e28e26..6ef3ba5 100644 --- a/aspec/data/parse.py +++ b/aspec/data/parse.py @@ -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 = [] @@ -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) @@ -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, @@ -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) diff --git a/configs/recipes/ling3_tiny_dflash.yaml b/configs/recipes/ling3_tiny_dflash.yaml new file mode 100644 index 0000000..0c59de1 --- /dev/null +++ b/configs/recipes/ling3_tiny_dflash.yaml @@ -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 + 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 diff --git a/docs/user-guide/algorithms.md b/docs/user-guide/algorithms.md index 7d433e4..9a4e1c7 100644 --- a/docs/user-guide/algorithms.md +++ b/docs/user-guide/algorithms.md @@ -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. diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index f93843c..9fcd52c 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -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. diff --git a/docs/user-guide/ling.md b/docs/user-guide/ling.md index 7ed7146..f379e13 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 | @@ -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 +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 +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/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_conversation_tools.py b/tests/cpu/test_conversation_tools.py new file mode 100644 index 0000000..d00d753 --- /dev/null +++ b/tests/cpu/test_conversation_tools.py @@ -0,0 +1,254 @@ +# 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 pytest +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 + +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 +THINKING_TEMPLATE = TEMPLATE_REGISTRY.get("deepseek-v32") + + +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, template_name="ling3"): + self.chat_calls = [] + self.template = TEMPLATE_REGISTRY.get(template_name) + + 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)) + 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) + 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"), kwargs.get("add_generation_prompt", False) + ) + + 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] + + +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"), + 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, tokenizer=None): + source = tmp_path / "rows.jsonl" + source.write_text(json.dumps(row) + "\n") + 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( + _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] + + +@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 + + +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) + + +@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) diff --git a/tests/cpu/test_ling3_dflash_recipe.py b/tests/cpu/test_ling3_dflash_recipe.py new file mode 100644 index 0000000..5f62631 --- /dev/null +++ b/tests/cpu/test_ling3_dflash_recipe.py @@ -0,0 +1,101 @@ +# 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 = ( + "vocab_size", + "target_hidden_size", + "target_num_hidden_layers", + "target_layer_ids", + "mask_token_id", +) + + +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 "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 + 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 + + +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 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_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]} 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 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"