已开启
refactor: reuse upstream DeepSeek-V4 chat processing #1256
refactor: reuse upstream DeepSeek-V4 chat processing #1256
已开启
hanboyou创建于 23 天前
共 14 个文件变更+267651-360
@@ -22,6 +22,7 @@ repos:
22 hooks:22 hooks:
23 - id: trailing-whitespace23 - id: trailing-whitespace
24 - id: end-of-file-fixer24 - id: end-of-file-fixer
25+ exclude: ^tests/assets/tokenizer/deepseek_v4/tokenizer(_config)?\.json$
25 - id: check-yaml26 - id: check-yaml
26 args: ["--allow-multiple-documents"]27 args: ["--allow-multiple-documents"]
27 - id: check-added-large-files28 - id: check-added-large-files
@@ -102,9 +102,11 @@ cu_seqlens = [0, 3, 5] # 一行里打包了 2 条序列
102`max_context_length` 和每批 token 数必须是对齐值的倍数,processor 在构建时校验。102`max_context_length` 和每批 token 数必须是对齐值的倍数,processor 在构建时校验。
103CPT 与 SFT 直接使用上游 `GrainDataLoader`,无需 loader override。103CPT 与 SFT 直接使用上游 `GrainDataLoader`,无需 loader override。
104`SingleDatasetConfig` 连接 Hugging Face 数据源、processor 与过滤:CPT 使用 `AlignedTextProcessor`,104`SingleDatasetConfig` 连接 Hugging Face 数据源、processor 与过滤:CPT 使用 `AlignedTextProcessor`,
105-SFT 使用 `DeepSeekV4ChatProcessor`,两个 processor 共用 `align_text_sequence` 补齐文档。105+SFT 使用 `AlignedChatProcessor`,通过上游 `ChatProcessor` 与 `renderers.DeepSeekV4Renderer` 完成
106-聊天处理器保留官方 chat encoder 的 tool、developer、reminder 和 assistant-only 标签语义,106+聊天渲染、assistant 监督 mask 和 next-token shift;本仓仅通过 `align_text_sequence` 补齐文档。
107-先做 next-token shift,再补无监督 pad。过长或无监督 token 的对话被过滤。107+样本的 `messages` 为消息字典列表,工具定义通过可选的顶层 `tools` 列表传入,recipe 直接交给上游处理。
108+数据集若将这些字段存为 JSON 字符串,需在数据准备阶段解析;本仓不自动改写角色、提取消息内工具定义或删除消息字段。
109+过长对话由上游 processor 过滤。
108CPT 使用 `ConcatThenSplitPackingConfig`,SFT 使用 `FirstFitPackingConfig`。110CPT 使用 `ConcatThenSplitPackingConfig`,SFT 使用 `FirstFitPackingConfig`。
109 111 
110SFT 入口选择 `deepseek_v4_flash_sft` recipe;JSON/JSONL 路径通过 `DSV4_SFT_DATASET` 传入。112SFT 入口选择 `deepseek_v4_flash_sft` recipe;JSON/JSONL 路径通过 `DSV4_SFT_DATASET` 传入。
@@ -115,11 +117,40 @@ DATASET_PATH=/path/to/train.jsonl \
115bash examples/deepseek_v4/deepseek_v4_flash_sft_4k_a3.sh117bash examples/deepseek_v4/deepseek_v4_flash_sft_4k_a3.sh
116```118```
117 119 
118-自定义 recipe 可按 registry 中的嵌套配置组合随机访问或流式 Hugging Face source、chat encoder 和120+自定义 recipe 可按 registry 中的嵌套配置组合随机访问或流式 Hugging Face source、renderer 和
119`num_packing_bins`(默认 `1`),并配置上游 loader 的 seed、shuffle/repeat、read options 和 prefetch。121`num_packing_bins`(默认 `1`),并配置上游 loader 的 seed、shuffle/repeat、read options 和 prefetch。
120数据采用 Grain 的排序、分片和打包状态,不能直接恢复旧122数据采用 Grain 的排序、分片和打包状态,不能直接恢复旧
121TorchData loader 的 checkpoint;迁移后需使用新的训练 checkpoint 目录,模型权重可单独初始化。123TorchData loader 的 checkpoint;迁移后需使用新的训练 checkpoint 目录,模型权重可单独初始化。
122 124 
125+### SFT renderer 配置与迁移
126+ 
127+`deepseek_v4_flash_sft()` 在 Python recipe 内配置上游聊天 processor 和 V4 renderer,默认启用 thinking 模式。
128+自定义 recipe 可直接修改 processor 的 renderer 配置:
129+ 
130+```python
131+from renderers import DeepSeekV4RendererConfig
132+from torchtitan.components.renderer import from_renderers
133+ 
134+from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_flash_sft
135+ 
136+config = deepseek_v4_flash_sft(dataset_path="/path/to/train.jsonl")
137+processor = config.dataloader.dataset.dataset.processor
138+processor.renderer = from_renderers(
139+ DeepSeekV4RendererConfig(enable_thinking=True, drop_thinking=True),
140+)
141+```
142+ 
143+`chat_encoder=`、`DSV4EncoderConfig` 和本仓独立的 chat encoder / processor 已移除。
144+tokenizer 目录只需 tokenizer 资源,不再动态加载 `encoding/encoding_dsv4.py`。
145+训练样本必须以 assistant 消息结束;末尾 `latest_reminder` 由上游拒绝,recipe 不转换 `last_reminder` 别名。
146+`wo_eos=True` 的最后一个 assistant 仍由上游补 EOS,并将 EOS 作为监督标签;空回复也可产生该标签。
147+工具定义的插入位置、effort 前缀与 task 转换 token 的监督范围均遵循上游 renderer,
148+不再保留本仓按完整 assistant 渲染片段构造 mask 的特殊行为。
149+同时存在 system 与 developer 消息时,工具定义插入首个 developer 消息,而不是首个 system 消息。
150+renderer 的 `reasoning_effort` 使用 Flash-0731 语义;对原始 Flash 编码器的 effort 设置迁移时,
151+旧 `None` / `low` / `high` 对应 renderer 的 `low`,旧 `max` 对应 renderer 的 `high`。
152+原先关闭 BOS 或使用已编码 context 的独立 encoder 调用没有对应的 recipe 参数。
153+ 
123补出的 pad 只影响它自己的位置:压缩槽位只在所属块的**最后一个** token 上可见,而被 pad 补完的尾块最后一个位置必然是 pad,154补出的 pad 只影响它自己的位置:压缩槽位只在所属块的**最后一个** token 上可见,而被 pad 补完的尾块最后一个位置必然是 pad,
124因此真实 token 因果上看不到任何含 pad 的压缩键(ratio-4 的选择器同样只会从因果可达的整块里挑),pad 的 label 又是155因此真实 token 因果上看不到任何含 pad 的压缩键(ratio-4 的选择器同样只会从因果可达的整块里挑),pad 的 label 又是
125`IGNORE_INDEX`,所以对齐不改变单篇文档真实 token 的前向与 loss。打包密度变化(pad 占掉 row 容量)才会改变同一 step156`IGNORE_INDEX`,所以对齐不改变单篇文档真实 token 的前向与 loss。打包密度变化(pad 占掉 row 容量)才会改变同一 step
@@ -172,7 +203,7 @@ CP 的 `cmp_k.residual = reach % ratio`;文档按 `cp × ratio` 对齐后 `rea
172 203 
173## Grain SFT 集成验证204## Grain SFT 集成验证
174 205 
175-`tests/integration_tests/deepseek_v4.py` 注册了 `dsv4_grain_sft`:单 NPU、debugmodel、参考算子、eager,检查两步训练完成。提供包含官方 `encoding_dsv4.py` 的 tokenizer 目录和至少一条编码后不超过 512 token、含 assistant 监督标签的 JSON/JSONL 样本:206+`tests/integration_tests/deepseek_v4.py` 注册了 `dsv4_grain_sft`:单 NPU、debugmodel、参考算子、eager,检查两步训练完成。提供与模型匹配的 tokenizer 目录和至少一条编码后不超过 512 token、以 assistant 结束的 JSON/JSONL 样本:
176 207 
177```bash208```bash
178DSV4_SFT_ASSETS=/path/to/DeepSeekV4_tokenizer \209DSV4_SFT_ASSETS=/path/to/DeepSeekV4_tokenizer \
@@ -181,7 +212,7 @@ python -m tests.integration_tests.run_tests /tmp/dsv4-grain-sft-results \
181 --test_suite deepseek_v4 --test_name dsv4_grain_sft --ngpu 1 --no-parallel212 --test_suite deepseek_v4 --test_name dsv4_grain_sft --ngpu 1 --no-parallel
182```213```
183 214 
184-输出目录必须为空。未提供两个环境变量时该 case 被禁用;不能把跳过视为验证通过。外部语料没有固定 golden loss,此 case 只检查完成性,不证明旧 loader 的数值等价或吞吐提升。CPU 单测使用固定编码结果验证 labels、padding、positions 和 Grain 状态恢复,不替代官方编码器与真实 NPU 训练验证。215+输出目录必须为空。未提供两个环境变量时该 case 被禁用;不能把跳过视为验证通过。外部语料没有固定 golden loss,此 case 只检查完成性,不证明旧 loader 的数值等价或吞吐提升。CPU 单测使用真实 tokenizer / renderer 验证 labels、padding、positions 和 Grain 状态恢复,不替代真实 NPU 训练验证。
185 216 
186## 当前边界217## 当前边界
187 218 
@@ -0,0 +1,21 @@
1+MIT License
2+ 
3+Copyright (c) 2023 DeepSeek
4+ 
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+ 
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+ 
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
@@ -0,0 +1,12 @@
1+# DeepSeek-V4 tokenizer 测试资源
2+ 
3+`tokenizer.json` 和 `tokenizer_config.json` 来自官方
4+[DeepSeek-V4-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/tree/60d8d70770c6776ff598c94bb586a859a38244f1),
5+固定 revision 为 `60d8d70770c6776ff598c94bb586a859a38244f1`,按该 revision 的 [MIT License](LICENSE) 分发。
6+ 
7+两个文件均保留原始内容。测试直接读取这些资源,不下载模型、不生成词表,也不修改特殊 token。
8+ 
9+| 文件 | SHA256 |
10+| --- | --- |
11+| `tokenizer.json` | `8f9f37ca37fdc4f5fd36d5cf4d3b0e8392edb4e894fd10cc0d70b4957c8633cf` |
12+| `tokenizer_config.json` | `6ac8c8dc065ed118161d02dd532749ae3f52c243deac27872134fae2f50d8547` |
此文件变更行数或变更字符数较多,你可以直接 查看源码
@@ -0,0 +1,34 @@
1+{
2+ "add_bos_token": false,
3+ "add_eos_token": false,
4+ "bos_token": {
5+ "__type": "AddedToken",
6+ "content": "<|begin▁of▁sentence|>",
7+ "lstrip": false,
8+ "normalized": true,
9+ "rstrip": false,
10+ "single_word": false
11+ },
12+ "clean_up_tokenization_spaces": false,
13+ "eos_token": {
14+ "__type": "AddedToken",
15+ "content": "<|end▁of▁sentence|>",
16+ "lstrip": false,
17+ "normalized": true,
18+ "rstrip": false,
19+ "single_word": false
20+ },
21+ "legacy": true,
22+ "model_max_length": 1048576,
23+ "pad_token": {
24+ "__type": "AddedToken",
25+ "content": "<|end▁of▁sentence|>",
26+ "lstrip": false,
27+ "normalized": true,
28+ "rstrip": false,
29+ "single_word": false
30+ },
31+ "sp_model_kwargs": {},
32+ "unk_token": null,
33+ "tokenizer_class": "PreTrainedTokenizerFast"
34+}
@@ -0,0 +1,17 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""Official DeepSeek-V4-Flash tokenizer shared by the chat tests."""
7+ 
8+from pathlib import Path
9+ 
10+import pytest
11+from torchtitan.components.tokenizer import HuggingFaceTokenizer
12+ 
13+ 
14+@pytest.fixture(scope="module")
15+def dsv4_tokenizer():
16+ path = Path(__file__).resolve().parents[3] / "assets" / "tokenizer" / "deepseek_v4"
17+ return HuggingFaceTokenizer(tokenizer_path=str(path))
@@ -3,7 +3,7 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6-"""Real recipe selection and Grain packing with a fixed chat-encoding oracle."""6+"""Real renderer output consumed by Grain packing and checkpoint replay."""
7 7 
8import json8import json
9from contextlib import ExitStack9from contextlib import ExitStack
@@ -13,24 +13,13 @@ import grain
13import pytest13import pytest
14import torch14import torch
15from torchtitan.components.data import FirstFitPackingConfig, GrainDataLoader, SingleDatasetConfig15from torchtitan.components.data import FirstFitPackingConfig, GrainDataLoader, SingleDatasetConfig
16-from torchtitan.components.tokenizer import HuggingFaceTokenizer
17 16 
18-from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig17+from torchtitan_npu.models.common.alignment import AlignedChatProcessor
19-from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor
20from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_flash_sft18from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_flash_sft
21 19 
22 20 
23-class _StubEncoder:
24- """Each integer prompt identifies one six-token conversation."""
25- 
26- def encode_messages_with_assistant_mask(self, messages, tokenizer, eos_id):
27- base = int(messages[0]["content"])
28- return "", list(range(base, base + 6)), [False, False, True, True, True, True]
29- 
30- 
31@pytest.fixture21@pytest.fixture
32-def sft_recipe(tmp_path, monkeypatch):22+def sft_recipe(tmp_path):
33- monkeypatch.setattr(DSV4EncoderConfig, "build", lambda self, path: _StubEncoder())
34 path = tmp_path / "chat.jsonl"23 path = tmp_path / "chat.jsonl"
35 path.write_text(24 path.write_text(
36 "".join(25 "".join(
@@ -43,19 +32,18 @@ def sft_recipe(tmp_path, monkeypatch):
43 assert isinstance(config.dataloader, GrainDataLoader.Config)32 assert isinstance(config.dataloader, GrainDataLoader.Config)
44 config.dataloader.shuffle = False33 config.dataloader.shuffle = False
45 config.dataloader.read_options = grain.ReadOptions(num_threads=2, prefetch_buffer_size=4)34 config.dataloader.read_options = grain.ReadOptions(num_threads=2, prefetch_buffer_size=4)
46- assert isinstance(config.dataloader, GrainDataLoader.Config)
47 assert isinstance(config.dataloader.dataset, FirstFitPackingConfig)35 assert isinstance(config.dataloader.dataset, FirstFitPackingConfig)
48 assert isinstance(config.dataloader.dataset.dataset, SingleDatasetConfig)36 assert isinstance(config.dataloader.dataset.dataset, SingleDatasetConfig)
49- assert isinstance(config.dataloader.dataset.dataset.processor, DeepSeekV4ChatProcessor.Config)37+ assert isinstance(config.dataloader.dataset.dataset.processor, AlignedChatProcessor.Config)
50 assert config.dataloader.dataset.dataset.processor.per_doc_alignment == 12838 assert config.dataloader.dataset.dataset.processor.per_doc_alignment == 128
51 return config.dataloader39 return config.dataloader
52 40 
53 41 
54-def test_sft_recipe_builds_aligned_supervised_batches(sft_recipe):42+def test_sft_recipe_builds_aligned_supervised_batches(sft_recipe, dsv4_tokenizer):
55 loader = sft_recipe.build(43 loader = sft_recipe.build(
56 dp_world_size=1,44 dp_world_size=1,
57 dp_rank=0,45 dp_rank=0,
58- tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"),46+ tokenizer=dsv4_tokenizer,
59 max_context_length=128,47 max_context_length=128,
60 num_tokens_per_microbatch=256,48 num_tokens_per_microbatch=256,
61 )49 )
@@ -63,20 +51,29 @@ def test_sft_recipe_builds_aligned_supervised_batches(sft_recipe):
63 microbatch = next(iter(loader))51 microbatch = next(iter(loader))
64 finally:52 finally:
65 loader.close()53 loader.close()
54+ # Literal template IDs from the official V4 vocabulary; 10 and 20 are each
55+ # one token (553 and 397), so each seven-token input needs 121 document pads.
56+ expected_inputs = (
57+ [0, 128803, 553, 128804, 128821, 128822, 633]
58+ + [0] * 121
59+ + [0, 128803, 397, 128804, 128821, 128822, 633]
60+ + [0] * 121
61+ )
62+ expected_labels = ([-100] * 4 + [128822, 633, 1] + [-100] * 121) * 2
66 63 
67- assert microbatch.input.tolist() == list(range(10, 15)) + [0] * 123 + list(range(20, 25)) + [0] * 12364+ assert microbatch.input.tolist() == expected_inputs
68- assert microbatch.labels.tolist() == [-100, 12, 13, 14, 15] + [-100] * 123 + [-100, 22, 23, 24, 25] + [-100] * 12365+ assert microbatch.labels.tolist() == expected_labels
69 assert microbatch.positions.tolist() == list(range(128)) * 266 assert microbatch.positions.tolist() == list(range(128)) * 2
70- assert microbatch.padding_mask.tolist() == ([False] * 5 + [True] * 123) * 267+ assert microbatch.padding_mask.tolist() == ([False] * 7 + [True] * 121) * 2
71- assert int(microbatch.loss_token_counts) == 868+ assert int(microbatch.loss_token_counts) == 6
72 69 
73 70 
74@pytest.mark.parametrize("rank", (0, 1), ids=("dp-rank-0", "dp-rank-1"))71@pytest.mark.parametrize("rank", (0, 1), ids=("dp-rank-0", "dp-rank-1"))
75-def test_sft_grain_restores_packing_and_prefetch_across_epoch(sft_recipe, rank):72+def test_sft_grain_restores_packing_and_prefetch_across_epoch(sft_recipe, dsv4_tokenizer, rank):
76 kwargs = dict(73 kwargs = dict(
77 dp_world_size=2,74 dp_world_size=2,
78 dp_rank=rank,75 dp_rank=rank,
79- tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"),76+ tokenizer=dsv4_tokenizer,
80 max_context_length=128,77 max_context_length=128,
81 num_tokens_per_microbatch=384,78 num_tokens_per_microbatch=384,
82 )79 )
@@ -86,7 +83,9 @@ def test_sft_grain_restores_packing_and_prefetch_across_epoch(sft_recipe, rank):
86 restored = sft_recipe.build(**kwargs)83 restored = sft_recipe.build(**kwargs)
87 cleanup.callback(restored.close)84 cleanup.callback(restored.close)
88 first = next(iter(original))85 first = next(iter(original))
89- assert first.input[::128].tolist() == ([10, 20, 30] if rank == 0 else [50, 60, 70])86+ # Original dataset rows 10/20/30 versus 50/60/70 after DP source sharding.
87+ expected_prompts = [553, 397, 1059] if rank == 0 else [1328, 1683, 2122]
88+ assert first.input[2::128].tolist() == expected_prompts
90 state = json.loads(json.dumps(deepcopy(original.state_dict())))89 state = json.loads(json.dumps(deepcopy(original.state_dict())))
91 restored.load_state_dict(state)90 restored.load_state_dict(state)
92 for _ in range(4):91 for _ in range(4):
@@ -3,107 +3,148 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6-"""Conversation semantics independent of the external DSV4 encoding asset."""6+"""V4 recipe rendering, assistant supervision and document alignment."""
7 7 
8-import json
9from copy import deepcopy8from copy import deepcopy
10 9 
11import grain10import grain
12import numpy as np11import numpy as np
13import pytest12import pytest
13+from renderers import DeepSeekV4RendererConfig
14from torchtitan.components.data import DatasetBuildContext14from torchtitan.components.data import DatasetBuildContext
15-from torchtitan.components.tokenizer import HuggingFaceTokenizer15+from torchtitan.components.renderer import from_renderers
16 16 
17-from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig17+from torchtitan_npu.models.common.alignment import AlignedChatProcessor
18-from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor18+from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash_sft as legacy_sft
19+from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_flash_sft
19 20 
20 21 
21-class _StubEncoder:22+def _processor(tokenizer, *, factory=deepseek_v4_flash_sft, alignment=8, max_context_length=128):
22- """Fixed token/mask oracle; records messages at the encoding boundary."""23+ config = factory()
23- 24+ processor_config = config.dataloader.dataset.dataset.processor
24- def __init__(self):25+ assert isinstance(processor_config, AlignedChatProcessor.Config)
25- self.tokens = [10, 11, 12, 13, 14, 15]26+ processor_config.per_doc_alignment = alignment
26- self.mask = [False, False, True, True, True, True]27+ return processor_config.build(
27- self.messages = None28+ context=DatasetBuildContext(
28- 29+ tokenizer=tokenizer,
29- def encode_messages_with_assistant_mask(self, messages, tokenizer, eos_id):30+ max_context_length=max_context_length,
30- self.messages = messages31+ num_tokens_per_microbatch=2 * max_context_length,
31- return "", self.tokens, self.mask32+ read_options=grain.ReadOptions(num_threads=0),
32- 33+ )
33- 
34-@pytest.fixture
35-def processor_and_encoder(monkeypatch):
36- encoder = _StubEncoder()
37- monkeypatch.setattr(DSV4EncoderConfig, "build", lambda self, path: encoder)
38- context = DatasetBuildContext(
39- tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"),
40- max_context_length=8,
41- num_tokens_per_microbatch=16,
42- read_options=grain.ReadOptions(num_threads=0),
43 )34 )
44- processor = DeepSeekV4ChatProcessor.Config(per_doc_alignment=8).build(context=context)
45- return processor, encoder
46 35 
47 36 
48-def test_chat_processor_shifts_supervision_then_aligns(processor_and_encoder):37+@pytest.mark.parametrize("factory", [deepseek_v4_flash_sft, legacy_sft], ids=["recipe", "legacy-factory"])
49- processor, _ = processor_and_encoder38+def test_sft_factories_render_assistant_targets_then_align(dsv4_tokenizer, factory):
39+ processor = _processor(dsv4_tokenizer, factory=factory)
50 sample = {"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "ok"}]}40 sample = {"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "ok"}]}
41+ # Official V4 vocabulary: BOS, User, hi, Assistant, think, /think, ok.
42+ expected_input = [0, 128803, 6366, 128804, 128821, 128822, 633]
43+ expected_labels = [-100, -100, -100, -100, 128822, 633, 1]
51 44 
52 sequence = processor(sample, np.random.default_rng(0))45 sequence = processor(sample, np.random.default_rng(0))
53 46 
54- assert sequence.input_ids.tolist() == [10, 11, 12, 13, 14, 0, 0, 0]47+ assert sequence.input_ids.tolist() == [*expected_input, 0]
55- assert sequence.labels.tolist() == [-100, 12, 13, 14, 15, -100, -100, -100]48+ assert sequence.labels.tolist() == [*expected_labels, -100]
49+ assert sequence.padding_mask.tolist() == [False] * 7 + [True]
56 assert sequence.positions is None50 assert sequence.positions is None
51+ assert sequence.input_ids.dtype == sequence.labels.dtype == np.int64
57 52 
58 53 
59-def test_chat_processor_preserves_tools_and_normalizes_reminders_without_mutation(processor_and_encoder):54+def test_sft_python_processor_config_controls_chat_mode_and_supervised_final_eos(dsv4_tokenizer):
60- processor, encoder = processor_and_encoder55+ def chat_recipe():
61- messages = [56+ config = deepseek_v4_flash_sft()
62- {"role": "developer", "content": "use tools"},57+ config.dataloader.dataset.dataset.processor.renderer = from_renderers(
63- {"role": "user", "content": "hi"},58+ DeepSeekV4RendererConfig(enable_thinking=False)
64- {"role": "assistant", "content": "call"},59+ )
65- {"role": "tool", "content": "result"},60+ return config
66- {"role": "assistant", "content": "ok"},61+ 
67- {"role": "last_reminder", "content": "remember"},62+ processor = _processor(dsv4_tokenizer, factory=chat_recipe, alignment=1)
63+ sample = {
64+ "messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "ok", "wo_eos": True}]
65+ }
66+ 
67+ sequence = processor(sample, np.random.default_rng(0))
68+ 
69+ assert dsv4_tokenizer.decode(sequence.input_ids.tolist(), skip_special_tokens=False) == (
70+ "<|begin▁of▁sentence|><|User|>hi<|Assistant|></think>ok"
71+ )
72+ assert dsv4_tokenizer.decode(sequence.labels[sequence.labels != -100].tolist(), skip_special_tokens=False) == (
73+ "ok<|end▁of▁sentence|>"
74+ )
75+ 
76+ 
77+@pytest.mark.parametrize("factory", [deepseek_v4_flash_sft, legacy_sft], ids=["recipe", "legacy-factory"])
78+def test_sft_factories_preserve_tools_and_reasoning_without_mutating_input(dsv4_tokenizer, factory):
79+ processor = _processor(dsv4_tokenizer, factory=factory, alignment=1, max_context_length=4096)
80+ tools = [
81+ {
82+ "type": "function",
83+ "function": {
84+ "name": "search",
85+ "parameters": {"type": "object", "properties": {"q": {"type": "string"}}, "required": ["q"]},
86+ },
87+ }
68 ]88 ]
69- sample = {"messages": json.dumps(messages), "tools": '[{"name":"search"}]'}89+ messages = [
90+ {"role": "developer", "content": "use tools", "response_format": {"type": "json_object"}},
91+ {"role": "user", "content": "hi"},
92+ {
93+ "role": "assistant",
94+ "content": "",
95+ "reasoning": "plan",
96+ "tool_calls": [
97+ {"id": "call-1", "type": "function", "function": {"name": "search", "arguments": '{"q":"hi"}'}}
98+ ],
99+ },
100+ {"role": "tool", "tool_call_id": "call-1", "content": "external result"},
101+ {"role": "latest_reminder", "content": "remember"},
102+ {"role": "assistant", "content": "ok", "reasoning": "answer"},
103+ ]
104+ sample = {"messages": messages, "tools": tools}
70 original = deepcopy(sample)105 original = deepcopy(sample)
71 106 
72 sequence = processor(sample, np.random.default_rng(0))107 sequence = processor(sample, np.random.default_rng(0))
73 108 
74- assert sequence is not None
75 assert sample == original109 assert sample == original
76- assert encoder.messages[0] == {"role": "developer", "content": "use tools", "tools": [{"name": "search"}]}110+ rendered = dsv4_tokenizer.decode(sequence.input_ids.tolist(), skip_special_tokens=False)
77- assert encoder.messages[-1] == {"role": "latest_reminder", "content": "remember"}111+ assert "## Tools" in rendered
78- assert encoder.messages[1:5] == messages[1:5]112+ assert "<tool_result>external result</tool_result>" in rendered
113+ assert "<|latest_reminder|>remember" in rendered
114+ assert (
115+ "## Response Format:\n\nYou MUST strictly adhere to the following schema to reply:\n"
116+ '{"type": "json_object"}'
117+ ) in rendered
118+ supervised = dsv4_tokenizer.decode(sequence.labels[sequence.labels != -100].tolist(), skip_special_tokens=False)
119+ assert supervised == (
120+ 'plan</think>\n\n<|DSML|tool_calls>\n<|DSML|invoke name="search">\n'
121+ '<|DSML|parameter name="q" string="true">hi</|DSML|parameter>\n'
122+ "</|DSML|invoke>\n</|DSML|tool_calls><|end▁of▁sentence|>answer</think>ok<|end▁of▁sentence|>"
123+ )
79 124 
80 125 
81-@pytest.mark.parametrize("case", ("oversized", "all-masked"), ids=("oversized", "all-masked"))126+@pytest.mark.parametrize("limit, dropped", [(7, False), (6, True)], ids=["exact-context", "over-context"])
82-def test_chat_processor_drops_unusable_conversations(processor_and_encoder, case):127+def test_sft_processor_preserves_whole_conversations_at_context_limit(dsv4_tokenizer, limit, dropped):
83- processor, encoder = processor_and_encoder128+ processor = _processor(dsv4_tokenizer, alignment=1, max_context_length=limit)
84- if case == "oversized":129+ sample = {"messages": [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "ok"}]}
85- encoder.tokens = list(range(10))
86- encoder.mask = [True] * 10
87- else:
88- encoder.mask = [False] * len(encoder.tokens)
89 130 
90- sequence = processor({"messages": [{"role": "assistant", "content": "ok"}]}, np.random.default_rng(0))131+ sequence = processor(sample, np.random.default_rng(0))
91 132 
92- assert sequence is None133+ assert (sequence is None) == dropped
134+ if not dropped:
135+ assert len(sequence.input_ids) == limit
136+ assert sequence.labels[-1] == dsv4_tokenizer.eos_id
93 137 
94 138 
95-def test_chat_processor_accepts_exact_context_boundary(processor_and_encoder):139+def test_sft_processor_rejects_a_terminal_reminder(dsv4_tokenizer):
96- processor, encoder = processor_and_encoder140+ processor = _processor(dsv4_tokenizer)
97- encoder.tokens = list(range(9))141+ sample = {
98- encoder.mask = [False, False] + [True] * 7142+ "messages": [
143+ {"role": "user", "content": "hi"},
144+ {"role": "assistant", "content": "ok"},
145+ {"role": "latest_reminder", "content": "remember"},
146+ ]
147+ }
99 148 
100- sequence = processor({"messages": [{"role": "assistant", "content": "ok"}]}, np.random.default_rng(0))149+ with pytest.raises(ValueError, match="must end with an assistant"):
101- 150+ processor(sample, np.random.default_rng(0))
102- assert sequence.input_ids.tolist() == list(range(8))
103- assert sequence.labels.tolist() == [-100, 2, 3, 4, 5, 6, 7, 8]
104- 
105- 
106-def test_chat_processor_rejects_unknown_role(processor_and_encoder):
107- processor, _ = processor_and_encoder
108- with pytest.raises(ValueError, match="Unsupported DeepSeek-V4 role"):
109- processor({"messages": [{"role": "unknown", "content": "hi"}]}, np.random.default_rng(0))
@@ -21,7 +21,7 @@ from typing import TYPE_CHECKING, Any
21 21 
22import numpy as np22import numpy as np
23from torchtitan.components.data import TextSequence23from torchtitan.components.data import TextSequence
24-from torchtitan.components.data.text_datasets import TextProcessor24+from torchtitan.components.data.text_datasets import ChatProcessor, TextProcessor
25from torchtitan.components.loss import IGNORE_INDEX25from torchtitan.components.loss import IGNORE_INDEX
26 26 
27if TYPE_CHECKING:27if TYPE_CHECKING:
@@ -173,3 +173,22 @@ class AlignedTextProcessor(TextProcessor):
173 if sequence is None:173 if sequence is None:
174 return None174 return None
175 return align_text_sequence(sequence, multiple=self._per_doc_alignment)175 return align_text_sequence(sequence, multiple=self._per_doc_alignment)
176+ 
177+ 
178+class AlignedChatProcessor(ChatProcessor):
179+ """Pad upstream chat sequences before packing forms compression groups."""
180+ 
181+ @dataclass(kw_only=True, slots=True)
182+ class Config(ChatProcessor.Config):
183+ per_doc_alignment: int = 1
184+ 
185+ def __init__(self, config: Config, *, context: "DatasetBuildContext") -> None:
186+ validate_alignment(config.per_doc_alignment, context=context)
187+ super().__init__(config, context=context)
188+ self._per_doc_alignment = config.per_doc_alignment
189+ 
190+ def __call__(self, sample: dict[str, Any], rng: np.random.Generator) -> TextSequence | None:
191+ sequence = super().__call__(sample, rng)
192+ if sequence is None:
193+ return None
194+ return align_text_sequence(sequence, multiple=self._per_doc_alignment)
@@ -1,134 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-# Copyright (c) Meta Platforms, Inc. and affiliates.
3-# SPDX-License-Identifier: BSD-3-Clause
4-#
5-# This source code is licensed under the BSD-style license found in the
6-# LICENSE file in the root directory of this source tree.
7- 
8-"""DeepSeek-V4's model-owned structured chat encoder."""
9- 
10-import importlib.util
11-from dataclasses import dataclass
12-from pathlib import Path
13-from typing import Any, Literal
14- 
15-from torchtitan.components.tokenizer import BaseTokenizer
16- 
17-ThinkingMode = Literal["chat", "thinking"]
18-ReasoningEffort = Literal["low", "high", "max"]
19- 
20- 
21-class DSV4ChatEncoder:
22- """Render messages with the model asset's official ``encoding_dsv4.py``."""
23- 
24- def __init__(
25- self,
26- encoding_module_path: str,
27- thinking_mode: ThinkingMode = "thinking",
28- context: list[dict[str, Any]] | None = None,
29- drop_thinking: bool = True,
30- add_default_bos_token: bool = True,
31- reasoning_effort: ReasoningEffort | None = None,
32- ) -> None:
33- if thinking_mode not in ("chat", "thinking"):
34- raise ValueError(f"Unsupported thinking_mode: {thinking_mode!r}")
35- if reasoning_effort not in (None, "low", "high", "max"):
36- raise ValueError(f"Unsupported reasoning_effort: {reasoning_effort!r}")
37- 
38- spec = importlib.util.spec_from_file_location("encoding_dsv4", encoding_module_path)
39- if spec is None or spec.loader is None:
40- raise FileNotFoundError(f"Cannot load encoding module: {encoding_module_path}")
41- self._encoding = importlib.util.module_from_spec(spec)
42- spec.loader.exec_module(self._encoding)
43- self.thinking_mode = thinking_mode
44- self.context = context
45- self.drop_thinking = drop_thinking
46- self.add_default_bos_token = add_default_bos_token
47- # The original V4 file accepts None, while later files also call it "low".
48- self.reasoning_effort = None if reasoning_effort == "low" else reasoning_effort
49- 
50- def encode_messages_with_assistant_mask(
51- self,
52- messages: list[dict[str, Any]],
53- tokenizer: BaseTokenizer,
54- eos_id: int,
55- ) -> tuple[str, list[int], list[bool]]:
56- # Official context is an already-encoded prefix: it affects rendering
57- # decisions but is not emitted or labeled by this sample.
58- context = [dict(message) for message in self.context or []]
59- messages = self._encoding.merge_tool_messages(messages)
60- messages = self._encoding.sort_tool_results_by_call_order(context + messages)[len(context) :]
61- if context:
62- context = self._encoding.sort_tool_results_by_call_order(self._encoding.merge_tool_messages(context))
63- messages = context + messages
64- context_len = len(context)
65- drop_thinking = self.drop_thinking and not any(message.get("tools") for message in messages)
66- if self.thinking_mode == "thinking" and drop_thinking:
67- # render_message drops earlier reasoning; encode_messages also removes earlier developer turns.
68- last_user = max(
69- (index for index, message in enumerate(messages) if message.get("role") in {"user", "developer"}),
70- default=-1,
71- )
72- last_context_user = max(
73- (index for index, message in enumerate(context) if message.get("role") in {"user", "developer"}),
74- default=-1,
75- )
76- context_len -= sum(
77- message.get("role") == "developer" and index < last_context_user
78- for index, message in enumerate(context)
79- )
80- messages = [
81- message
82- for index, message in enumerate(messages)
83- if message.get("role") != "developer" or index >= last_user
84- ]
85- 
86- rendered = [
87- self._encoding.render_message(
88- index,
89- messages,
90- thinking_mode=self.thinking_mode,
91- drop_thinking=drop_thinking,
92- reasoning_effort=self.reasoning_effort if index == 0 else None,
93- )
94- for index in range(context_len, len(messages))
95- ]
96- full_text = "".join(rendered)
97- add_bos = self.add_default_bos_token and not context
98- full_tokens = tokenizer.encode(full_text, add_bos=add_bos, add_eos=False)
99- if not full_tokens or full_tokens[-1] != eos_id:
100- full_tokens.append(eos_id)
101- 
102- assistant_mask = [False] * len(full_tokens)
103- prefix_text = ""
104- for index, (message, message_text) in enumerate(zip(messages[context_len:], rendered, strict=True)):
105- next_prefix_text = full_text if index == len(rendered) - 1 else prefix_text + message_text
106- if message.get("role") == "assistant":
107- prefix_tokens = tokenizer.encode(prefix_text, add_bos=add_bos, add_eos=False)
108- through_tokens = tokenizer.encode(next_prefix_text, add_bos=add_bos, add_eos=False)
109- if full_tokens[: len(prefix_tokens)] != prefix_tokens:
110- raise ValueError(f"Assistant prefix token alignment failed at message {index}")
111- if full_tokens[: len(through_tokens)] != through_tokens:
112- raise ValueError(f"Assistant boundary token alignment failed at message {index}")
113- start, end = len(prefix_tokens), len(through_tokens)
114- assistant_mask[start:end] = [True] * (end - start)
115- prefix_text = next_prefix_text
116- 
117- return full_text, full_tokens, assistant_mask
118- 
119- 
120-@dataclass(kw_only=True, slots=True)
121-class DSV4EncoderConfig:
122- thinking_mode: ThinkingMode = "thinking"
123- drop_thinking: bool = True
124- add_default_bos_token: bool = True
125- reasoning_effort: ReasoningEffort | None = None
126- 
127- def build(self, tokenizer_path: str) -> DSV4ChatEncoder:
128- return DSV4ChatEncoder(
129- encoding_module_path=str(Path(tokenizer_path) / "encoding" / "encoding_dsv4.py"),
130- thinking_mode=self.thinking_mode,
131- drop_thinking=self.drop_thinking,
132- add_default_bos_token=self.add_default_bos_token,
133- reasoning_effort=self.reasoning_effort,
134- )
@@ -1,111 +0,0 @@
1-# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2-# Copyright (c) Meta Platforms, Inc. and affiliates.
3-# SPDX-License-Identifier: BSD-3-Clause
4-#
5-# This source code is licensed under the BSD-style license found in the
6-# LICENSE file in the root directory of this source tree.
7- 
8-"""DeepSeek-V4 conversation processing for TorchTitan's Grain dataset graph."""
9- 
10-import json
11-import logging
12-from collections.abc import Callable
13-from dataclasses import dataclass, field
14-from typing import Annotated, Any
15- 
16-import numpy as np
17-import tyro
18-from torchtitan.components.data import DatasetBuildContext, SampleProcessor, TextSequence
19-from torchtitan.components.loss import IGNORE_INDEX
20-from torchtitan.components.tokenizer import HuggingFaceTokenizer
21- 
22-from torchtitan_npu.models.common.alignment import align_text_sequence, validate_alignment
23- 
24-from .chat_encoder import DSV4EncoderConfig
25- 
26-logger = logging.getLogger(__name__)
27- 
28- 
29-def _sft_messages(sample: dict[str, Any]) -> list[dict[str, Any]]:
30- raw_messages = sample["messages"]
31- return json.loads(raw_messages) if isinstance(raw_messages, str) else raw_messages
32- 
33- 
34-class DeepSeekV4ChatProcessor(SampleProcessor):
35- """Encode one conversation; Grain owns iteration and packing."""
36- 
37- @dataclass(kw_only=True, slots=True)
38- class Config(SampleProcessor.Config):
39- per_doc_alignment: int = 1
40- messages_fn: Annotated[Callable[[dict[str, Any]], list[dict[str, Any]]], tyro.conf.Suppress] = _sft_messages
41- chat_encoder: DSV4EncoderConfig = field(default_factory=DSV4EncoderConfig)
42- 
43- def __init__(self, config: Config, *, context: DatasetBuildContext) -> None:
44- validate_alignment(config.per_doc_alignment, context=context)
45- if not isinstance(context.tokenizer, HuggingFaceTokenizer):
46- raise TypeError("DeepSeek-V4 chat SFT requires HuggingFaceTokenizer")
47- if context.tokenizer.eos_id is None:
48- raise ValueError("DeepSeek-V4 chat SFT requires a tokenizer eos_id")
49- self._tokenizer = context.tokenizer
50- self._eos_id = context.tokenizer.eos_id
51- self._chat_encoder = config.chat_encoder.build(context.tokenizer.tokenizer_path)
52- self._max_context_length = context.max_context_length
53- self._per_doc_alignment = config.per_doc_alignment
54- self._messages_fn = config.messages_fn
55- 
56- @staticmethod
57- def _validate_v4_messages(messages: list[dict[str, Any]]) -> None:
58- roles = {"system", "developer", "user", "assistant", "tool", "latest_reminder"}
59- for index, message in enumerate(messages):
60- role = message.get("role")
61- if role not in roles:
62- raise ValueError(f"Unsupported DeepSeek-V4 role at messages[{index}]: {role!r}")
63- if role == "developer" and not (isinstance(message.get("content"), str) and message["content"]):
64- raise ValueError(f"messages[{index}] developer requires non-empty string content")
65- if role == "latest_reminder" and not isinstance(message.get("content"), str):
66- raise ValueError(f"messages[{index}] latest_reminder requires string content")
67- 
68- def __call__(self, sample: dict[str, Any], rng: np.random.Generator) -> TextSequence | None:
69- del rng
70- messages = [dict(message) for message in self._messages_fn(sample)]
71- for message in messages:
72- if message.get("role") == "last_reminder":
73- message["role"] = "latest_reminder" # Official encoding name.
74- raw_tools = sample.get("tools", [])
75- tools = json.loads(raw_tools) if isinstance(raw_tools, str) else raw_tools
76- if tools:
77- if messages and messages[0].get("role") in {"system", "developer"}:
78- messages[0]["tools"] = tools
79- else:
80- messages.insert(0, {"role": "system", "content": "", "tools": tools})
81- self._validate_v4_messages(messages)
82- # Official V4 permits a reminder after the last supervised assistant turn.
83- if not messages or messages[-1].get("role") not in {"assistant", "latest_reminder"}:
84- raise ValueError("SFT sample must end with an assistant or latest_reminder turn")
85- if not any(message.get("role") == "assistant" for message in messages):
86- raise ValueError("SFT sample requires an assistant turn for labels")
87- # V4 encoding merges tool results into user turns; assistant tool calls remain supervised.
88- _, full_tokens, assistant_mask = self._chat_encoder.encode_messages_with_assistant_mask(
89- messages, self._tokenizer, self._eos_id
90- )
91- 
92- if len(full_tokens) - 1 > self._max_context_length:
93- logger.debug("Dropping SFT sample exceeding max_context_length")
94- return None
95- 
96- if len(full_tokens) != len(assistant_mask):
97- raise ValueError("Chat encoder must return one assistant mask entry per token")
98- input_ids = full_tokens[:-1]
99- label_ids = [
100- token if keep else IGNORE_INDEX for token, keep in zip(full_tokens[1:], assistant_mask[1:], strict=True)
101- ]
102- if all(label == IGNORE_INDEX for label in label_ids):
103- logger.debug("Dropping SFT sample with no supervised labels")
104- return None
105- return align_text_sequence(
106- TextSequence(
107- input_ids=np.asarray(input_ids, dtype=np.int64),
108- labels=np.asarray(label_ids, dtype=np.int64),
109- ),
110- multiple=self._per_doc_alignment,
111- )
@@ -11,6 +11,7 @@ from importlib import import_module
11from typing import TYPE_CHECKING, Any, cast11from typing import TYPE_CHECKING, Any, cast
12 12 
13import torch13import torch
14+from renderers import DeepSeekV4RendererConfig
14from torchtitan.components.data import (15from torchtitan.components.data import (
15 ConcatThenSplitPackingConfig,16 ConcatThenSplitPackingConfig,
16 FirstFitPackingConfig,17 FirstFitPackingConfig,
@@ -20,6 +21,7 @@ from torchtitan.components.data import (
20)21)
21from torchtitan.components.loss import ChunkedLossWrapper, CrossEntropyLoss22from torchtitan.components.loss import ChunkedLossWrapper, CrossEntropyLoss
22from torchtitan.components.optim import AdamW, LRSchedulersContainer23from torchtitan.components.optim import AdamW, LRSchedulersContainer
24+from torchtitan.components.renderer import from_renderers
23from torchtitan.config.parallelism import ParallelismConfig25from torchtitan.config.parallelism import ParallelismConfig
24from torchtitan.distributed.flex_shard import (26from torchtitan.distributed.flex_shard import (
25 BlockShard,27 BlockShard,
@@ -42,7 +44,7 @@ from torchtitan_npu.config import (
42from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager44from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager
43from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler45from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler
44from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx46from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx
45-from torchtitan_npu.models.common.alignment import AlignedTextProcessor, compression_alignment47+from torchtitan_npu.models.common.alignment import AlignedChatProcessor, AlignedTextProcessor, compression_alignment
46from torchtitan_npu.models.common.muon import make_expert_layout, make_owned_layout, with_lora_compute_layouts48from torchtitan_npu.models.common.muon import make_expert_layout, make_owned_layout, with_lora_compute_layouts
47 49 
48from . import model_registry50from . import model_registry
@@ -53,8 +55,6 @@ if TYPE_CHECKING:
53 from torchtitan.experiments.graph_trainer.configs import GraphTrainerCompileConfig55 from torchtitan.experiments.graph_trainer.configs import GraphTrainerCompileConfig
54 from torchtitan.experiments.graph_trainer.trainer import GraphTrainer56 from torchtitan.experiments.graph_trainer.trainer import GraphTrainer
55 57 
56-from .chat_encoder import DSV4EncoderConfig
57-from .chat_processor import DeepSeekV4ChatProcessor
58from .model import DeepSeekV4Model, GraphTrainerDeepSeekV4Model58from .model import DeepSeekV4Model, GraphTrainerDeepSeekV4Model
59from .mtp import MTPChunkedLossWrapper59from .mtp import MTPChunkedLossWrapper
60 60 
@@ -388,7 +388,6 @@ def deepseek_v4_flash_sft(
388 flavor: str = "deepseek_v4_flash",388 flavor: str = "deepseek_v4_flash",
389 seq_len: int = 4096,389 seq_len: int = 4096,
390 num_packing_bins: int = 1,390 num_packing_bins: int = 1,
391- chat_encoder: DSV4EncoderConfig | None = None,
392 num_mtp_layers: int = 0,391 num_mtp_layers: int = 0,
393 converters: list[ModelConfigConverter.Config] | None = None,392 converters: list[ModelConfigConverter.Config] | None = None,
394) -> TrainerEx.Config:393) -> TrainerEx.Config:
@@ -410,9 +409,11 @@ def deepseek_v4_flash_sft(
410 source=HuggingFaceRandomAccessSource.Config(409 source=HuggingFaceRandomAccessSource.Config(
411 path="json", split="train", load_dataset_kwargs={"data_files": dataset_path}410 path="json", split="train", load_dataset_kwargs={"data_files": dataset_path}
412 ),411 ),
413- processor=DeepSeekV4ChatProcessor.Config(412+ processor=AlignedChatProcessor.Config(
414 per_doc_alignment=_per_doc_alignment(config.model),413 per_doc_alignment=_per_doc_alignment(config.model),
415- chat_encoder=DSV4EncoderConfig() if chat_encoder is None else chat_encoder,414+ messages_fn=lambda sample: sample["messages"],
415+ tools_fn=lambda sample: sample.get("tools"),
416+ renderer=from_renderers(DeepSeekV4RendererConfig(enable_thinking=True)),
416 ),417 ),
417 post_filters=(lambda sample: sample is not None,),418 post_filters=(lambda sample: sample is not None,),
418 ),419 ),
@@ -10,6 +10,7 @@ from dataclasses import fields
10from importlib import import_module10from importlib import import_module
11from typing import TYPE_CHECKING, Any11from typing import TYPE_CHECKING, Any
12 12 
13+from renderers import DeepSeekV4RendererConfig
13from torchtitan.components.data import (14from torchtitan.components.data import (
14 ConcatThenSplitPackingConfig,15 ConcatThenSplitPackingConfig,
15 FirstFitPackingConfig,16 FirstFitPackingConfig,
@@ -19,6 +20,7 @@ from torchtitan.components.data import (
19)20)
20from torchtitan.components.loss import ChunkedLossWrapper, CrossEntropyLoss21from torchtitan.components.loss import ChunkedLossWrapper, CrossEntropyLoss
21from torchtitan.components.optim import LRSchedulersContainer22from torchtitan.components.optim import LRSchedulersContainer
23+from torchtitan.components.renderer import from_renderers
22from torchtitan.config.parallelism import ParallelismConfig24from torchtitan.config.parallelism import ParallelismConfig
23from torchtitan.models.common.config_utils import decoder_vocab_size25from torchtitan.models.common.config_utils import decoder_vocab_size
24from torchtitan.observability.metrics import MetricsProcessor26from torchtitan.observability.metrics import MetricsProcessor
@@ -33,10 +35,8 @@ from torchtitan_npu.config import (
33from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager35from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager
34from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler36from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler
35from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx37from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx
36-from torchtitan_npu.models.common.alignment import AlignedTextProcessor, compression_alignment38+from torchtitan_npu.models.common.alignment import AlignedChatProcessor, AlignedTextProcessor, compression_alignment
37from torchtitan_npu.models.deepseek_v4 import model_registry39from torchtitan_npu.models.deepseek_v4 import model_registry
38-from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig
39-from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor
40from torchtitan_npu.models.deepseek_v4.model import DeepSeekV4Model40from torchtitan_npu.models.deepseek_v4.model import DeepSeekV4Model
41from torchtitan_npu.models.deepseek_v4.mtp import MTPChunkedLossWrapper41from torchtitan_npu.models.deepseek_v4.mtp import MTPChunkedLossWrapper
42from torchtitan_npu.models.deepseek_v4.muon import _dsv4_muon_profile, _dsv4_optimizer_config42from torchtitan_npu.models.deepseek_v4.muon import _dsv4_muon_profile, _dsv4_optimizer_config
@@ -199,7 +199,6 @@ def deepseek_v4_flash_sft(
199 flavor: str = "deepseek_v4_flash",199 flavor: str = "deepseek_v4_flash",
200 seq_len: int = 4096,200 seq_len: int = 4096,
201 num_packing_bins: int = 1,201 num_packing_bins: int = 1,
202- chat_encoder: DSV4EncoderConfig | None = None,
203 num_mtp_layers: int = 0,202 num_mtp_layers: int = 0,
204 converters: list[ModelConfigConverter.Config] | None = None,203 converters: list[ModelConfigConverter.Config] | None = None,
205) -> TrainerEx.Config:204) -> TrainerEx.Config:
@@ -221,9 +220,11 @@ def deepseek_v4_flash_sft(
221 source=HuggingFaceRandomAccessSource.Config(220 source=HuggingFaceRandomAccessSource.Config(
222 path="json", split="train", load_dataset_kwargs={"data_files": dataset_path}221 path="json", split="train", load_dataset_kwargs={"data_files": dataset_path}
223 ),222 ),
224- processor=DeepSeekV4ChatProcessor.Config(223+ processor=AlignedChatProcessor.Config(
225 per_doc_alignment=_per_doc_alignment(config.model),224 per_doc_alignment=_per_doc_alignment(config.model),
226- chat_encoder=DSV4EncoderConfig() if chat_encoder is None else chat_encoder,225+ messages_fn=lambda sample: sample["messages"],
226+ tools_fn=lambda sample: sample.get("tools"),
227+ renderer=from_renderers(DeepSeekV4RendererConfig(enable_thinking=True)),
Can Learn Bot
Can Learn BotCan Learn Bot20 天前
"""DeepSeek V4 Flash 0731 renderer.

The checkpoint does not ship a Jinja chat template.  Its source of truth is
``encoding/encoding_dsv4.py`` in the model repository.

上游源码明确的适配目标只有 DeepSeek-V4-Flash-0731 这一个日期版本。 源码

likedislike
Can Learn Bot
Can Learn Bot
20 天前 评论:
likedislike
227 ),228 ),
228 post_filters=(lambda sample: sample is not None,),229 post_filters=(lambda sample: sample is not None,),
229 ),230 ),