| @@ -0,0 +1,65 @@ | |||
| 1 | +# DeepSeek V4 系列 SFT | ||
| 2 | + | ||
| 3 | +## 1. 准备 DeepSeek 官方发布模型资产 | ||
| 4 | + | ||
| 5 | +沿用所在集群的 CPT 环境。从官方权重启动 SFT 时,需要准备**完整的 DeepSeek 官方发布模型资产**,包括模型配置、权重分片及索引、tokenizer 和 `encoding/` 下的官方编码文件。**不同发布日期的 `encoding_dsv4.py` 或 `encoding.py` 即使同名也不可混用。** 编码文件须与权重和 tokenizer 来自同一发布版本。配方的 `hf_assets_path` 指向包含 tokenizer 和 `encoding/` 的目录,初始权重由原 CPT 配方加载。 | ||
| 6 | + | ||
| 7 | +- **DeepSeek V4** 的 Flash、Pro、Flash-0731 和 Pro-0813 都在 `encoding/encoding_dsv4.py` 提供文本对话编码。各版本沿用同一文件名,具体编码规则以随权重发布的文件为准。[V4 Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/tree/60d8d70770c6776ff598c94bb586a859a38244f1/encoding) · [V4 Pro](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/tree/b5968e9190ef611bbf34a7229255be88a0e937c1/encoding) · [Flash-0731](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731/tree/7872f01b1d1fe23eabc4c98b48bffcef5a386062/encoding) · [Pro-0813](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro-0813/tree/72e1d3230f6c080a530b0a1d46f8eeb4602340597/encoding) | ||
| 8 | +- **DeepSeek V4.1** 的 Flash 和 Flash-1017 在 `encoding/encoding.py` 提供文本与图文对话编码,可同时返回 prompt 和媒体记录。[V4.1 Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/tree/314113f8a7dadb388215396ba5fbee2c610a04d6/encoding) · [Flash-1017](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/tree/08c8657f02291e11b6f6b63e0e16014f8e748518/encoding) | ||
| 9 | + | ||
| 10 | +SFT 沿用 DeepSeek 官方示例的做法,直接调用对应版本 Python 编码器的 `encode_messages()`。官方编码器生成对话文本、特殊标记和 V4.1 的媒体信息,训练侧在编码结果上定位 assistant 片段并生成监督标签。[V4 官方推理示例](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/generate.py#L125) · [V4.1 官方编码示例](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/blob/08c8657f02291e11b6f6b63e0e16014f8e748518/encoding/README.md) | ||
| 11 | + | ||
| 12 | +从官方 FP8/FP4 权重开始时,先转换为 BF16 safetensors。将配方中 `checkpointer.initial_load_in_hf` 设为 `True`,`initial_load_path` 指向转换后的目录。V4.1 Flash 的 CPT 配方用 `HF_ASSETS_PATH` 指向 DeepSeek 官方发布模型资产目录,用 `CKPT_INIT_LOAD_PATH` 指定 BF16 权重。[V4 转换脚本](../../scripts/checkpoint_conversion/dequant_save_hf_dsv4.py) · [V4.1 转换脚本](https://gitcode.com/cann/cann-recipes-train/blob/78a47e5e3459601ee8e21fd64c1f8ac68e2bbd17/llm_pretrain/deepseek_v4_1/utils/convert_bf16.py) | ||
| 13 | + | ||
| 14 | +## 2. 准备数据 | ||
| 15 | + | ||
| 16 | +每行写一条 JSONL 对话。两种模型都接受纯文本多轮 `messages`。V4.1 的图文混排使用 JSONL 保留消息中的文字和图片块,图片相对路径以数据文件所在目录为基准。下列 `...` 表示省略的样本。 | ||
| 17 | + | ||
| 18 | +```jsonl | ||
| 19 | +{"messages":[{"role":"user","content":"Translate ‘晨雾’ into English."},{"role":"assistant","content":"Morning mist."},{"role":"user","content":"Use it in a sentence."},{"role":"assistant","content":"Morning mist covered the lake."}]} | ||
| 20 | +... | ||
| 21 | +{"messages":[{"role":"user","content":[{"type":"text","text":"Compare this view "},{"type":"image","path":"images/first.jpg"},{"type":"text","text":" with this one."},{"type":"image","path":"images/second.jpg"}]},{"role":"assistant","content":"The first view has clear skies, while the second is foggy."}]} | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +V4 使用第一种文本样式。工具对话沿用 DeepSeek 官方编码器的消息格式,函数定义放在 `tools`,assistant 的调用放在 `tool_calls`,工具返回以 `tool_call_id` 对应调用。 | ||
| 25 | + | ||
| 26 | +## 3. 复用 CPT 配方启动 | ||
| 27 | + | ||
| 28 | +**SFT 复用现有 CPT 配方和启动脚本。** `MODULE` 和 `CONFIG` 选择已能运行的 CPT 配方,沿用其模型、权重加载、优化器和并行配置。设置 `DATASET_PATH` 并追加相应的 SFT `--override`,即可切换 dataloader。 | ||
| 29 | + | ||
| 30 | +按原 CPT 命令填写两个 Bash 数组,没有对应设置时使用空数组 `()`。 | ||
| 31 | + | ||
| 32 | +- `ENV_ARGS` 放原命令中的环境变量赋值,例如 `NGPU=8`、`ASCEND_RT_VISIBLE_DEVICES=0,1,2,3,4,5,6,7`。通过 `env "${ENV_ARGS[@]}"` 在启动脚本前设置。 | ||
| 33 | +- `CPT_ARGS` 放原命令中写在 `bash scripts/run_train.sh` 后面的参数,例如 `--output-dir /path/to/sft-run`。通过 `"${CPT_ARGS[@]}"` 按原顺序传入,然后追加 SFT override。 | ||
| 34 | + | ||
| 35 | +下面以仓库现有的 V4 eager 配方和 V4.1 图文调试配方为例,说明如何复用 CPT 配方启动 SFT。将官方 tokenizer 和编码文件放在配方的 `hf_assets_path` 下,V4 示例使用 `/path/to/DeepSeekV4_tokenizer`,V4.1 示例使用 `tests/assets/tokenizer`。 | ||
| 36 | + | ||
| 37 | +```bash | ||
| 38 | +ENV_ARGS=("NGPU=${NGPU:-}") | ||
| 39 | +CPT_ARGS=(--output-dir /path/to/run) | ||
| 40 | + | ||
| 41 | +# V4 | ||
| 42 | +env "${ENV_ARGS[@]}" \ | ||
| 43 | + MODULE=torchtitan_npu_recipes.tests.models.deepseek_v4 \ | ||
| 44 | + CONFIG=deepseek_v4_flash_43layers_16experts_eager_bf16 \ | ||
| 45 | + DATASET_PATH=tests/assets/deepseek_v4/alpaca_samples.jsonl bash scripts/run_train.sh \ | ||
| 46 | + "${CPT_ARGS[@]}" \ | ||
| 47 | + --override torchtitan_npu.override.deepseek_v4.chat_dataloader.sft | ||
| 48 | + | ||
| 49 | +# V4.1 | ||
| 50 | +env "${ENV_ARGS[@]}" \ | ||
| 51 | + MODULE=torchtitan_npu_recipes.models.deepseek_v4_1 \ | ||
| 52 | + CONFIG=deepseek_v4_1_debugmodel_multimodal DATASET=cc12m-test \ | ||
| 53 | + DATASET_PATH=/path/to/docci_sft.jsonl bash scripts/run_train.sh \ | ||
| 54 | + "${CPT_ARGS[@]}" \ | ||
| 55 | + --override torchtitan_npu.override.deepseek_v4_1.vision_language_dataloader.sft | ||
| 56 | +``` | ||
| 57 | + | ||
| 58 | +训练步数和权重设置由 Python 配方提供。 | ||
| 59 | + | ||
| 60 | +V4.1 的每个微批次包含一个对话上下文,`num_tokens_per_microbatch_per_dp_rank` 须等于 `max_context_length`。 | ||
| 61 | + | ||
| 62 | +## 4. 短测 | ||
| 63 | + | ||
| 64 | +- **V4** 使用 512 条 Alpaca 文本对话样本。[样本文件](../../tests/assets/deepseek_v4/alpaca_samples.jsonl) · [数据来源与许可](../../tests/assets/deepseek_v4/ATTRIBUTION.md) | ||
| 65 | +- **V4.1** 下载并解压 [`docci_samples.zip`](https://raw.gitcode.com/cann/torchtitan-npu/attachment/uploads/3bb0f2e6-754f-4e63-ac67-c0b8ab689bf2/docci_samples.zip),将 `DATASET_PATH` 指向解包后的 `docci_sft.jsonl`,并保持 `images/` 与数据文件的相对位置。 | ||
| @@ -0,0 +1,5 @@ | |||
| 1 | +# Alpaca samples | ||
| 2 | + | ||
| 3 | +`alpaca_samples.jsonl` contains 512 samples adapted from Stanford Alpaca by Taori et al. | ||
| 4 | + | ||
| 5 | +The adapted data is licensed under [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/). [Source dataset](https://github.com/tatsu-lab/stanford_alpaca/blob/761dc5bfbdeeffa89b8bff5d038781a4055f796a/alpaca_data.json) · [Source data license](https://github.com/tatsu-lab/stanford_alpaca/blob/761dc5bfbdeeffa89b8bff5d038781a4055f796a/DATA_LICENSE) | ||
| @@ -17,7 +17,9 @@ from torchtitan.components.tokenizer import HuggingFaceTokenizer | |||
| 17 | 17 | ||
| 18 | from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig | 18 | from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig |
| 19 | from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor | 19 | from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor |
| 20 | +from torchtitan_npu.override.deepseek_v4.chat_dataloader import sft | ||
| 20 | from torchtitan_npu_recipes.tests.ci.deepseek_v4 import deepseek_v4_flash_sft | 21 | from torchtitan_npu_recipes.tests.ci.deepseek_v4 import deepseek_v4_flash_sft |
| 22 | +from torchtitan_npu_recipes.tests.models.deepseek_v4 import deepseek_v4_debugmodel | ||
| 21 | 23 | ||
| 22 | 24 | ||
| 23 | class _StubEncoder: | 25 | class _StubEncoder: |
| @@ -25,6 +27,8 @@ class _StubEncoder: | |||
| 25 | 27 | ||
| 26 | def encode_messages_with_assistant_mask(self, messages, tokenizer, eos_id): | 28 | def encode_messages_with_assistant_mask(self, messages, tokenizer, eos_id): |
| 27 | base = int(messages[0]["content"]) | 29 | base = int(messages[0]["content"]) |
| 30 | + if base < 0: | ||
| 31 | + return "", list(range(6)), [False] * 6 | ||
| 28 | return "", list(range(base, base + 6)), [False, False, True, True, True, True] | 32 | return "", list(range(base, base + 6)), [False, False, True, True, True, True] |
| 29 | 33 | ||
| 30 | 34 | ||
| @@ -99,3 +103,63 @@ def test_sft_grain_restores_packing_and_prefetch_across_epoch(sft_recipe, rank): | |||
| 99 | torch.testing.assert_close( | 103 | torch.testing.assert_close( |
| 100 | torch.as_tensor(inputs[key]), torch.as_tensor(expected_inputs[key]), rtol=0, atol=0 | 104 | torch.as_tensor(inputs[key]), torch.as_tensor(expected_inputs[key]), rtol=0, atol=0 |
| 101 | ) | 105 | ) |
| 106 | + | ||
| 107 | + | ||
| 108 | +def test_cpt_chat_override_rejects_shard_without_supervision(tmp_path, monkeypatch): | ||
| 109 | + monkeypatch.setattr(DSV4EncoderConfig, "build", lambda self, path: _StubEncoder()) | ||
| 110 | + data = tmp_path / "chat.jsonl" | ||
| 111 | + data.write_text( | ||
| 112 | + "".join( | ||
| 113 | + json.dumps({"messages": [{"role": "user", "content": prompt}, {"role": "assistant", "content": "ok"}]}) | ||
| 114 | + + "\n" | ||
| 115 | + for prompt in ("10", "-1") | ||
| 116 | + ) | ||
| 117 | + ) | ||
| 118 | + config = sft(deepseek_v4_debugmodel().dataloader, dataset_path=str(data)) | ||
| 119 | + config.shuffle = False | ||
| 120 | + loader = config.build( | ||
| 121 | + dp_world_size=2, | ||
| 122 | + dp_rank=1, | ||
| 123 | + tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"), | ||
| 124 | + max_context_length=128, | ||
| 125 | + num_tokens_per_microbatch=128, | ||
| 126 | + ) | ||
| 127 | + try: | ||
| 128 | + with pytest.raises(ValueError, match="SFT data shard 1/2 has no valid samples"): | ||
| 129 | + next(iter(loader)) | ||
| 130 | + finally: | ||
| 131 | + loader.close() | ||
| 132 | + | ||
| 133 | + | ||
| 134 | +@pytest.mark.parametrize("has_valid", (True, False), ids=("valid-in-later-epoch", "all-invalid")) | ||
| 135 | +def test_cpt_chat_override_checks_shuffled_shards(tmp_path, monkeypatch, has_valid): | ||
| 136 | + monkeypatch.setattr(DSV4EncoderConfig, "build", lambda self, path: _StubEncoder()) | ||
| 137 | + data = tmp_path / "chat_[v1].jsonl" | ||
| 138 | + data.write_text( | ||
| 139 | + "".join( | ||
| 140 | + json.dumps({"messages": [{"role": "user", "content": prompt}, {"role": "assistant", "content": "ok"}]}) | ||
| 141 | + + "\n" | ||
| 142 | + for prompt in ("10" if has_valid else "-1", "-1", "-1", "-1") | ||
| 143 | + ) | ||
| 144 | + ) | ||
| 145 | + link = tmp_path / "chat.jsonl" | ||
| 146 | + link.symlink_to(data) | ||
| 147 | + config = sft(deepseek_v4_debugmodel().dataloader, dataset_path=str(link)) | ||
| 148 | + config.shuffle = True | ||
| 149 | + config.seed = 42 | ||
| 150 | + loader = config.build( | ||
| 151 | + dp_world_size=2, | ||
| 152 | + dp_rank=1, | ||
| 153 | + tokenizer=HuggingFaceTokenizer(tokenizer_path="tests/assets/deepseek_v3"), | ||
| 154 | + max_context_length=128, | ||
| 155 | + num_tokens_per_microbatch=128, | ||
| 156 | + ) | ||
| 157 | + try: | ||
| 158 | + if has_valid: | ||
| 159 | + # Seed 42 assigns the first usable row to rank 1 only in epoch four. | ||
| 160 | + assert next(iter(loader)).input[0].item() == 10 | ||
| 161 | + else: | ||
| 162 | + with pytest.raises(ValueError, match="SFT data shard 1/2 has no valid samples"): | ||
| 163 | + next(iter(loader)) | ||
| 164 | + finally: | ||
| 165 | + loader.close() | ||
| @@ -11,10 +11,12 @@ from copy import deepcopy | |||
| 11 | import grain | 11 | import grain |
| 12 | import numpy as np | 12 | import numpy as np |
| 13 | import pytest | 13 | import pytest |
| 14 | +from tokenizers import Tokenizer | ||
| 15 | +from tokenizers.models import BPE | ||
| 14 | from torchtitan.components.data import DatasetBuildContext | 16 | from torchtitan.components.data import DatasetBuildContext |
| 15 | from torchtitan.components.tokenizer import HuggingFaceTokenizer | 17 | from torchtitan.components.tokenizer import HuggingFaceTokenizer |
| 16 | 18 | ||
| 17 | -from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig | 19 | +from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4ChatEncoder, DSV4EncoderConfig |
| 18 | from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor | 20 | from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor |
| 19 | 21 | ||
| 20 | 22 | ||
| @@ -56,6 +58,70 @@ def test_chat_processor_shifts_supervision_then_aligns(processor_and_encoder): | |||
| 56 | assert sequence.positions is None | 58 | assert sequence.positions is None |
| 57 | 59 | ||
| 58 | 60 | ||
| 61 | +@pytest.mark.parametrize("add_bos", (False, True)) | ||
| 62 | +@pytest.mark.parametrize("wo_eos", (False, True)) | ||
| 63 | +def test_chat_processor_supervises_tokens_across_assistant_fragments(tmp_path, add_bos, wo_eos): | ||
| 64 | + backend = Tokenizer(BPE(vocab={"?": 0, "a": 1, "b": 2, "ab": 3, "^": 4, "!": 5}, merges=[("a", "b")])) | ||
| 65 | + backend.add_special_tokens(["<s>", "</s>"]) | ||
| 66 | + backend.save(str(tmp_path / "tokenizer.json")) | ||
| 67 | + (tmp_path / "tokenizer_config.json").write_text(json.dumps({"bos_token": "<s>", "eos_token": "</s>"})) | ||
| 68 | + encoding = tmp_path / "encoding" | ||
| 69 | + encoding.mkdir() | ||
| 70 | + (encoding / "encoding_dsv4.py").write_text( | ||
| 71 | + "bos_token = '<s>'\n" | ||
| 72 | + "def merge_tool_messages(messages):\n" | ||
| 73 | + " return messages\n" | ||
| 74 | + "def sort_tool_results_by_call_order(messages):\n" | ||
| 75 | + " return messages\n" | ||
| 76 | + "def render_message(index, messages, *, reasoning_effort, **kwargs):\n" | ||
| 77 | + " message = messages[index]\n" | ||
| 78 | + " prefix = ''\n" | ||
| 79 | + " if message['role'] == 'user':\n" | ||
| 80 | + " prefix += '^' if index and messages[index - 1]['role'] == 'system' else ''\n" | ||
| 81 | + " prefix += '!' if reasoning_effort == 'high' else ''\n" | ||
| 82 | + " eos = '</s>' if message['role'] == 'assistant' and not message.get('wo_eos') else ''\n" | ||
| 83 | + " return prefix + message['content'] + eos\n" | ||
| 84 | + "def encode_messages(messages, *, context=None, add_default_bos_token, **kwargs):\n" | ||
| 85 | + " history = context or []\n" | ||
| 86 | + " conversation = history + messages\n" | ||
| 87 | + " prefix = bos_token if add_default_bos_token and not history else ''\n" | ||
| 88 | + " return prefix + ''.join(render_message(i, conversation, **kwargs)\n" | ||
| 89 | + " for i in range(len(history), len(conversation)))\n" | ||
| 90 | + ) | ||
| 91 | + tokenizer = HuggingFaceTokenizer(tokenizer_path=str(tmp_path)) | ||
| 92 | + context = DatasetBuildContext( | ||
| 93 | + tokenizer=tokenizer, | ||
| 94 | + max_context_length=8, | ||
| 95 | + num_tokens_per_microbatch=8, | ||
| 96 | + read_options=grain.ReadOptions(num_threads=0), | ||
| 97 | + ) | ||
| 98 | + config = DSV4EncoderConfig(thinking_mode="chat", add_default_bos_token=add_bos) | ||
| 99 | + processor = DeepSeekV4ChatProcessor.Config(chat_encoder=config).build(context=context) | ||
| 100 | + messages = [ | ||
| 101 | + {"role": "user", "content": "?"}, | ||
| 102 | + {"role": "assistant", "content": "a", "wo_eos": True}, | ||
| 103 | + {"role": "assistant", "content": "b", "wo_eos": wo_eos}, | ||
| 104 | + ] | ||
| 105 | + | ||
| 106 | + sequence = processor({"messages": messages}, np.random.default_rng(0)) | ||
| 107 | + | ||
| 108 | + assert sequence is not None | ||
| 109 | + expected_prompt = ("<s>" if add_bos else "") + "?ab" + ("" if wo_eos else "</s>") | ||
| 110 | + assert sequence.input_ids.tolist() == backend.encode(expected_prompt, add_special_tokens=False).ids[:-1] | ||
| 111 | + assert sequence.labels.tolist() == ([-100] if add_bos else []) + [3] + ([] if wo_eos else [tokenizer.eos_id]) | ||
| 112 | + | ||
| 113 | + encoder = DSV4ChatEncoder( | ||
| 114 | + str(encoding / "encoding_dsv4.py"), | ||
| 115 | + context=[{"role": "system", "content": "history"}], | ||
| 116 | + add_default_bos_token=add_bos, | ||
| 117 | + reasoning_effort="high", | ||
| 118 | + ) | ||
| 119 | + prompt, tokens, mask = encoder.encode_messages_with_assistant_mask(messages, tokenizer, tokenizer.eos_id) | ||
| 120 | + assert prompt == "^!?ab" + ("" if wo_eos else "</s>") | ||
| 121 | + assert tokens == backend.encode(prompt, add_special_tokens=False).ids | ||
| 122 | + assert mask == [False, False, False, True] + ([] if wo_eos else [True]) | ||
| 123 | + | ||
| 124 | + | ||
| 59 | def test_chat_processor_preserves_tools_and_normalizes_reminders_without_mutation(processor_and_encoder): | 125 | def test_chat_processor_preserves_tools_and_normalizes_reminders_without_mutation(processor_and_encoder): |
| 60 | processor, encoder = processor_and_encoder | 126 | processor, encoder = processor_and_encoder |
| 61 | messages = [ | 127 | messages = [ |
| @@ -9,17 +9,15 @@ import json | |||
| 9 | from copy import deepcopy | 9 | from copy import deepcopy |
| 10 | from itertools import islice | 10 | from itertools import islice |
| 11 | from pathlib import Path | 11 | from pathlib import Path |
| 12 | +from textwrap import dedent | ||
| 12 | 13 | ||
| 13 | import pytest | 14 | import pytest |
| 14 | import torch | 15 | import torch |
| 16 | +from datasets import Dataset | ||
| 15 | from PIL import Image | 17 | from PIL import Image |
| 16 | from torchtitan.components.data import GrainDataLoader | 18 | from torchtitan.components.data import GrainDataLoader |
缺少精度验证结果 本 PR 修改了可能影响数值结果的代码路径,但 PR 描述中没有看到精度验证结果及精度是否正常的说明。 请参考 精度对齐开发指南 完成精度验证, 并将验证结果(对齐目标、指标数值、是否满足阈值)写入 PR 描述。 问题编号:R1248-001 审查版本: ![]() ![]() | |||
| 17 | from torchtitan.components.tokenizer import HuggingFaceTokenizer | 19 | from torchtitan.components.tokenizer import HuggingFaceTokenizer |
| 18 | 20 | ||
| 19 | -from torchtitan_npu_recipes.models.deepseek_v4_1 import ( | ||
| 20 | - deepseek_v4_1_debugmodel_multimodal_sft, | ||
| 21 | - deepseek_v4_1_vision_sft, | ||
| 22 | -) | ||
| 23 | from torchtitan_npu.models.deepseek_v4_1.vision import language_dataset as dataset_module | 21 | from torchtitan_npu.models.deepseek_v4_1.vision import language_dataset as dataset_module |
| 24 | from torchtitan_npu.models.deepseek_v4_1.vision.data import ImagePatchProcessor | 22 | from torchtitan_npu.models.deepseek_v4_1.vision.data import ImagePatchProcessor |
| 25 | from torchtitan_npu.models.deepseek_v4_1.vision.language_dataset import ( | 23 | from torchtitan_npu.models.deepseek_v4_1.vision.language_dataset import ( |
| @@ -28,6 +26,13 @@ from torchtitan_npu.models.deepseek_v4_1.vision.language_dataset import ( | |||
| 28 | _SFTCollator, | 26 | _SFTCollator, |
| 29 | sft_dataloader_config, | 27 | sft_dataloader_config, |
| 30 | ) | 28 | ) |
| 29 | +from torchtitan_npu.models.deepseek_v4_1.vision.language_encoder import DeepSeekV41VisionLanguageEncoder | ||
| 30 | +from torchtitan_npu.override.deepseek_v4_1.vision_language_dataloader import sft as sft_override | ||
| 31 | +from torchtitan_npu_recipes.models.deepseek_v4_1 import ( | ||
| 32 | + deepseek_v4_1_debugmodel_multimodal, | ||
| 33 | + deepseek_v4_1_debugmodel_multimodal_sft, | ||
| 34 | + deepseek_v4_1_vision_sft, | ||
| 35 | +) | ||
| 31 | 36 | ||
| 32 | pytestmark = pytest.mark.cpu | 37 | pytestmark = pytest.mark.cpu |
| 33 | ASSETS = Path(__file__).resolve().parents[3] / "assets" | 38 | ASSETS = Path(__file__).resolve().parents[3] / "assets" |
| @@ -36,7 +41,7 @@ ASSETS = Path(__file__).resolve().parents[3] / "assets" | |||
| 36 | def _unpack(microbatch): | 41 | def _unpack(microbatch): |
| 37 | inputs = microbatch.as_input_dict() | 42 | inputs = microbatch.as_input_dict() |
| 38 | labels = inputs.pop("labels") | 43 | labels = inputs.pop("labels") |
| 39 | - inputs["num_valid_tokens"] = microbatch.num_valid_tokens | 44 | + inputs["loss_token_count"] = int(microbatch.loss_token_counts) |
| 40 | return inputs, labels | 45 | return inputs, labels |
| 41 | 46 | ||
| 42 | 47 | ||
| @@ -45,6 +50,105 @@ def tokenizer(): | |||
| 45 | return HuggingFaceTokenizer.Config().build(tokenizer_path=str(ASSETS / "deepseek_v3")) | 50 | return HuggingFaceTokenizer.Config().build(tokenizer_path=str(ASSETS / "deepseek_v3")) |
| 46 | 51 | ||
| 47 | 52 | ||
| 53 | +@pytest.mark.parametrize("with_tool_result", (True, False)) | ||
| 54 | +def test_tool_call_is_supervised_when_a_shorter_prefix_renders_differently(tmp_path, tokenizer, with_tool_result): | ||
| 55 | + asset = tmp_path / "encoding.py" | ||
| 56 | + asset.write_text( | ||
| 57 | + "IMAGE_PLACEHOLDER = '<image>'\n" | ||
| 58 | + "def encode_messages(messages, thinking_mode, context=None, drop_thinking=True,\n" | ||
| 59 | + " add_default_bos_token=True, reasoning_effort=None, return_multi_modal_data=False):\n" | ||
| 60 | + " if not messages and context:\n" | ||
| 61 | + " raise ValueError('This encoder cannot render an empty tool-call suffix')\n" | ||
| 62 | + " prompt = ''.join(message['content'] for message in messages)\n" | ||
| 63 | + f" if not context and len(messages) == {3 if with_tool_result else 2}:\n" | ||
| 64 | + " prompt += ' Earlier thinking.'\n" | ||
| 65 | + " return (prompt, {'images': []}) if return_multi_modal_data else prompt\n" | ||
| 66 | + ) | ||
| 67 | + messages = [ | ||
| 68 | + {"role": "user", "content": "Question!\n"}, | ||
| 69 | + {"role": "assistant", "content": "Look up the rec", "wo_eos": True}, | ||
| 70 | + {"role": "assistant", "content": "ord.", "tool_calls": [{"id": "lookup"}]}, | ||
| 71 | + ] | ||
| 72 | + if with_tool_result: | ||
| 73 | + messages.append({"role": "tool", "content": "\nTool result."}) | ||
| 74 | + encoder = DeepSeekV41VisionLanguageEncoder(str(asset), thinking_mode="thinking") | ||
| 75 | + prompt, tokens, keep, _, _ = encoder.encode_messages_with_assistant_mask(messages, tokenizer) | ||
| 76 | + assert prompt == "Question!\nLook up the record." + ("\nTool result." if with_tool_result else "") | ||
| 77 | + assert tokens == tokenizer.tokenizer.encode(prompt, add_special_tokens=False).ids | ||
| 78 | + assert [token for token, supervise in zip(tokens, keep, strict=True) if supervise] == ( | ||
| 79 | + tokenizer.tokenizer.encode("Look up the record.").ids | ||
| 80 | + ) | ||
| 81 | + | ||
| 82 | + | ||
| 83 | +@pytest.mark.parametrize("has_merge_helper", (True, False), ids=("ordered-images", "missing-helper")) | ||
| 84 | +def test_tool_result_images_follow_call_order(tmp_path, tokenizer, has_merge_helper): | ||
| 85 | + asset = tmp_path / "encoding.py" | ||
| 86 | + source = dedent( | ||
| 87 | + """\ | ||
| 88 | + IMAGE_PLACEHOLDER = "<image>" | ||
| 89 | + | ||
| 90 | + def merge_tool_messages(messages): | ||
| 91 | + return messages | ||
| 92 | + | ||
| 93 | + def sort_tool_results_by_call_order(messages): | ||
| 94 | + ordinary = [message for message in messages if "tool_call_id" not in message] | ||
| 95 | + order = [call["id"] for message in ordinary for call in message.get("tool_calls", [])] | ||
| 96 | + results = {message["tool_call_id"]: message for message in messages if "tool_call_id" in message} | ||
| 97 | + return ordinary + [results[key] for key in order if key in results] | ||
| 98 | + | ||
| 99 | + def process_image_messages(messages): | ||
| 100 | + return messages, [message["image"] for message in messages if "image" in message] | ||
| 101 | + | ||
| 102 | + def encode_messages(messages, thinking_mode, context=None, drop_thinking=True, | ||
| 103 | + add_default_bos_token=True, reasoning_effort=None, return_multi_modal_data=False): | ||
| 104 | + ordered = sort_tool_results_by_call_order(messages) | ||
| 105 | + prompt = "".join(message["content"] for message in ordered) | ||
| 106 | + _, images = process_image_messages(messages) | ||
| 107 | + return (prompt, {"images": images}) if return_multi_modal_data else prompt | ||
| 108 | + """ | ||
| 109 | + ) | ||
| 110 | + asset.write_text(source if has_merge_helper else source + "\ndel merge_tool_messages\n") | ||
| 111 | + messages = [ | ||
| 112 | + {"role": "user", "content": "Compare two images.\n"}, | ||
| 113 | + {"role": "assistant", "content": "Look them up.\n", "tool_calls": [{"id": "a"}, {"id": "b"}]}, | ||
| 114 | + {"role": "tool", "content": "B <image>\n", "tool_call_id": "b", "image": "b.png"}, | ||
| 115 | + {"role": "tool", "content": "A <image>\n", "tool_call_id": "a", "image": "a.png"}, | ||
| 116 | + ] | ||
| 117 | + encoder = DeepSeekV41VisionLanguageEncoder(str(asset)) | ||
| 118 | + if has_merge_helper: | ||
| 119 | + prompt, _, _, positions, images = encoder.encode_messages_with_assistant_mask(messages, tokenizer) | ||
| 120 | + assert prompt.endswith("A <image>\nB <image>\n") | ||
| 121 | + assert images == ["a.png", "b.png"] | ||
| 122 | + assert len(positions) == 2 | ||
| 123 | + else: | ||
| 124 | + with pytest.raises(RuntimeError, match="missing tool image helpers: merge_tool_messages"): | ||
| 125 | + encoder.encode_messages_with_assistant_mask(messages, tokenizer) | ||
| 126 | + | ||
| 127 | + | ||
| 128 | +def test_empty_historical_assistant_span(tmp_path, tokenizer): | ||
| 129 | + asset = tmp_path / "encoding.py" | ||
| 130 | + asset.write_text( | ||
| 131 | + "IMAGE_PLACEHOLDER = '<image>'\n" | ||
| 132 | + "def encode_messages(messages, thinking_mode, context=None, drop_thinking=True,\n" | ||
| 133 | + " add_default_bos_token=True, reasoning_effort=None, return_multi_modal_data=False):\n" | ||
| 134 | + " prompt = ''.join(message['content'] for message in messages)\n" | ||
| 135 | + " if len(messages) == 2:\n" | ||
| 136 | + " prompt += ' Earlier thinking.'\n" | ||
| 137 | + " return (prompt, {'images': []}) if return_multi_modal_data else prompt\n" | ||
| 138 | + ) | ||
| 139 | + messages = [ | ||
| 140 | + {"role": "user", "content": "Old question.\n"}, | ||
| 141 | + {"role": "assistant", "content": "", "wo_eos": True}, | ||
| 142 | + {"role": "user", "content": "New question.\n"}, | ||
| 143 | + {"role": "assistant", "content": "Answer."}, | ||
| 144 | + ] | ||
| 145 | + encoder = DeepSeekV41VisionLanguageEncoder(str(asset), thinking_mode="thinking") | ||
| 146 | + _, tokens, keep, _, _ = encoder.encode_messages_with_assistant_mask(messages, tokenizer) | ||
| 147 | + assert [token for token, supervise in zip(tokens, keep, strict=True) if supervise] == ( | ||
| 148 | + tokenizer.tokenizer.encode("Answer.").ids | ||
| 149 | + ) | ||
| 150 | + | ||
| 151 | + | ||
| 48 | class _StubVisionLanguageEncoder: | 152 | class _StubVisionLanguageEncoder: |
| 49 | """Encode plain text/image blocks only; exclude the official chat template.""" | 153 | """Encode plain text/image blocks only; exclude the official chat template.""" |
| 50 | 154 | ||
| @@ -160,9 +264,10 @@ def test_vqa_labels_only_assistant_text_and_eos(tmp_path, tokenizer): | |||
| 160 | # Labels are shifted targets, so the reply's EOS is supervised at the reply's | 264 | # Labels are shifted targets, so the reply's EOS is supervised at the reply's |
| 161 | # last token and the row tail (also filled with EOS) is unsupervised. | 265 | # last token and the row tail (also filled with EOS) is unsupervised. |
| 162 | last_supervised = int((labels != -100).nonzero().flatten().max()) | 266 | last_supervised = int((labels != -100).nonzero().flatten().max()) |
| 267 | + first_unsupervised = last_supervised + 1 | ||
| 163 | assert labels[last_supervised] == tokenizer.eos_id | 268 | assert labels[last_supervised] == tokenizer.eos_id |
| 164 | - assert inputs["input"][last_supervised + 1] == tokenizer.eos_id | 269 | + assert inputs["input"][first_unsupervised] == tokenizer.eos_id |
| 165 | - assert (labels[last_supervised + 1 :] == -100).all() | 270 | + assert (labels[first_unsupervised:] == -100).all() |
| 166 | assert (labels[:-1][inputs["token_types"][1:] >= 0] == -100).all() | 271 | assert (labels[:-1][inputs["token_types"][1:] >= 0] == -100).all() |
| 167 | supervised = labels[:-1] != -100 | 272 | supervised = labels[:-1] != -100 |
| 168 | assert torch.equal(labels[:-1][supervised], inputs["input"][1:][supervised]) | 273 | assert torch.equal(labels[:-1][supervised], inputs["input"][1:][supervised]) |
| @@ -202,7 +307,7 @@ def test_streaming_dp_shards_and_resume_round_trip(tmp_path, tokenizer): | |||
| 202 | actual = _unpack(next(iter(restored))) | 307 | actual = _unpack(next(iter(restored))) |
| 203 | assert torch.equal(actual[1], expected[1]) | 308 | assert torch.equal(actual[1], expected[1]) |
| 204 | for key in expected[0]: | 309 | for key in expected[0]: |
| 205 | - # ``num_valid_tokens`` rides the batch as the int the trainer pops. | 310 | + # The batch carries the count of supervised labels independently of padding. |
| 206 | if isinstance(expected[0][key], torch.Tensor): | 311 | if isinstance(expected[0][key], torch.Tensor): |
| 207 | assert torch.equal(actual[0][key], expected[0][key]), key | 312 | assert torch.equal(actual[0][key], expected[0][key]), key |
| 208 | else: | 313 | else: |
| @@ -212,6 +317,26 @@ def test_streaming_dp_shards_and_resume_round_trip(tmp_path, tokenizer): | |||
| 212 | restored.close() | 317 | restored.close() |
| 213 | 318 | ||
| 214 | 319 | ||
| 320 | +@pytest.mark.parametrize("has_valid", (True, False), ids=("valid-after-1000", "all-invalid")) | ||
| 321 | +def test_parquet_stream_checks_all_rows_before_declaring_a_shard_empty(tmp_path, tokenizer, has_valid): | ||
| 322 | + data = tmp_path / "questions_[train].parquet" | ||
| 323 | + rows = [{"instruction": "word " * 700, "output": "Too long"}] * 1_000 | ||
| 324 | + if has_valid: | ||
| 325 | + rows.append({"instruction": "Question", "output": "Answer"}) | ||
| 326 | + Dataset.from_list(rows).to_parquet(str(data)) | ||
| 327 | + | ||
| 328 | + if not has_valid: | ||
| 329 | + with pytest.raises(ValueError, match="SFT data shard 0/1 has no valid samples"): | ||
| 330 | + _loader(data, tokenizer, infinite=True) | ||
| 331 | + return | ||
| 332 | + | ||
| 333 | + loader = _loader(data, tokenizer, infinite=True) | ||
| 334 | + try: | ||
| 335 | + assert next(iter(loader)).loss_token_counts.item() > 0 | ||
| 336 | + finally: | ||
| 337 | + loader.close() | ||
| 338 | + | ||
| 339 | + | ||
| 215 | def test_single_context_budget_and_shifted_batch_contract(tmp_path, tokenizer): | 340 | def test_single_context_budget_and_shifted_batch_contract(tmp_path, tokenizer): |
| 216 | dataset_path = tmp_path / "text_vqa.jsonl" | 341 | dataset_path = tmp_path / "text_vqa.jsonl" |
| 217 | dataset_path.write_text( | 342 | dataset_path.write_text( |
| @@ -245,8 +370,8 @@ def test_single_context_budget_and_shifted_batch_contract(tmp_path, tokenizer): | |||
| 245 | raw = json.loads(dataset_path.read_text()) | 370 | raw = json.loads(dataset_path.read_text()) |
| 246 | expected_inputs, expected_labels = _processor(dataset_path, tokenizer)._sample(raw) | 371 | expected_inputs, expected_labels = _processor(dataset_path, tokenizer)._sample(raw) |
| 247 | assert inputs["input"].shape == labels.shape == (512,) | 372 | assert inputs["input"].shape == labels.shape == (512,) |
| 248 | - assert type(inputs["num_valid_tokens"]) is int | 373 | + assert type(inputs["loss_token_count"]) is int |
| 249 | - assert inputs["num_valid_tokens"] == (expected_labels != -100).sum() | 374 | + assert inputs["loss_token_count"] == (expected_labels != -100).sum() |
| 250 | torch.testing.assert_close(labels, expected_labels, rtol=0, atol=0) | 375 | torch.testing.assert_close(labels, expected_labels, rtol=0, atol=0) |
| 251 | for key, value in expected_inputs.items(): | 376 | for key, value in expected_inputs.items(): |
| 252 | torch.testing.assert_close(inputs[key], value, rtol=0, atol=0) | 377 | torch.testing.assert_close(inputs[key], value, rtol=0, atol=0) |
| @@ -289,9 +414,8 @@ def test_sft_recipe_requires_a_dataset(monkeypatch): | |||
| 289 | deepseek_v4_1_vision_sft() | 414 | deepseek_v4_1_vision_sft() |
| 290 | 415 | ||
| 291 | 416 | ||
| 292 | -def test_config_name_installs_the_sft_loader_with_cli_policy(tmp_path, monkeypatch): | 417 | +def test_python_recipe_controls_sft_loader_policy(tmp_path, monkeypatch): |
| 293 | - """The recipe, not an override, installs the loader; tyro still owns the policy.""" | 418 | + from torchtitan.config import ConfigLoader |
| 294 | - from torchtitan.config import ConfigManager | ||
| 295 | 419 | ||
| 296 | dataset_path = tmp_path / "cli.jsonl" | 420 | dataset_path = tmp_path / "cli.jsonl" |
| 297 | dataset_path.write_text( | 421 | dataset_path.write_text( |
| @@ -307,27 +431,28 @@ def test_config_name_installs_the_sft_loader_with_cli_policy(tmp_path, monkeypat | |||
| 307 | encoding="utf-8", | 431 | encoding="utf-8", |
| 308 | ) | 432 | ) |
| 309 | monkeypatch.setenv("DSV41_SFT_DATASET", str(dataset_path)) | 433 | monkeypatch.setenv("DSV41_SFT_DATASET", str(dataset_path)) |
| 310 | - config = ConfigManager().parse_args( | 434 | + (tmp_path / "local_vision_sft_recipe.py").write_text( |
| 311 | - [ | 435 | + """from torchtitan_npu_recipes.models.deepseek_v4_1 import deepseek_v4_1_debugmodel_multimodal_sft |
| 312 | - "--module", | 436 | + |
| 313 | - "torchtitan_npu_recipes.models.deepseek_v4_1", | 437 | +def recipe(): |
| 314 | - "--config", | 438 | + config = deepseek_v4_1_debugmodel_multimodal_sft() |
| 315 | - "deepseek_v4_1_debugmodel_multimodal_sft", | 439 | + config.dataloader.seed = 137 |
| 316 | - "--dataloader.seed", | 440 | + return config |
| 317 | - "137", | 441 | +""", |
| 318 | - ] | 442 | + encoding="utf-8", |
| 319 | ) | 443 | ) |
| 444 | + monkeypatch.syspath_prepend(str(tmp_path)) | ||
| 445 | + config = ConfigLoader().load(["--module", "local_vision_sft_recipe", "--config", "recipe"]) | ||
| 320 | assert isinstance(config.dataloader, GrainDataLoader.Config) | 446 | assert isinstance(config.dataloader, GrainDataLoader.Config) |
| 321 | assert isinstance(config.dataloader.collator, _SFTCollator.Config) | 447 | assert isinstance(config.dataloader.collator, _SFTCollator.Config) |
| 322 | assert isinstance(config.dataloader.dataset.processor, _GrainSFTProcessor.Config) | 448 | assert isinstance(config.dataloader.dataset.processor, _GrainSFTProcessor.Config) |
| 323 | - # The old override had to carry the policy fields over; the recipe is parsed by | ||
| 324 | - # tyro like any other config, so a CLI value lands on the freshly built loader. | ||
| 325 | assert config.dataloader.seed == 137 | 449 | assert config.dataloader.seed == 137 |
| 326 | assert config.dataloader.dataset.processor.dataset_path == str(dataset_path.resolve()) | 450 | assert config.dataloader.dataset.processor.dataset_path == str(dataset_path.resolve()) |
| 327 | 451 | ||
| 328 | 452 | ||
| 329 | @pytest.mark.parametrize("num_images", (0, 2), ids=("text-dummy", "interleaved-images")) | 453 | @pytest.mark.parametrize("num_images", (0, 2), ids=("text-dummy", "interleaved-images")) |
| 330 | -def test_grain_sft_preserves_processed_multimodal_fixture(tmp_path, tokenizer, num_images): | 454 | +@pytest.mark.parametrize("suffix", (".jsonl", ".json")) |
| 455 | +def test_grain_sft_preserves_processed_multimodal_fixture(tmp_path, tokenizer, num_images, suffix): | ||
| 331 | for index, size in enumerate(((101, 100), (140, 70))): | 456 | for index, size in enumerate(((101, 100), (140, 70))): |
| 332 | Image.new("RGB", size, color=(index * 127, 37, 255)).save(tmp_path / f"image{index}.png") | 457 | Image.new("RGB", size, color=(index * 127, 37, 255)).save(tmp_path / f"image{index}.png") |
| 333 | blocks = [] | 458 | blocks = [] |
| @@ -339,13 +464,25 @@ def test_grain_sft_preserves_processed_multimodal_fixture(tmp_path, tokenizer, n | |||
| 339 | ] | 464 | ] |
| 340 | ) | 465 | ) |
| 341 | blocks.append({"type": "text", "text": "Describe the colors."}) | 466 | blocks.append({"type": "text", "text": "Describe the colors."}) |
| 342 | - row = {"messages": [{"role": "user", "content": blocks}, {"role": "assistant", "content": "Blue and red."}]} | 467 | + row = { |
| 343 | - dataset_path = tmp_path / "multimodal.jsonl" | 468 | + "messages": [ |
| 469 | + {"role": "user", "content": blocks}, | ||
| 470 | + {"role": "assistant", "content_blocks": [{"type": "text", "text": "Blue and red."}]}, | ||
| 471 | + ] | ||
| 472 | + } | ||
| 473 | + dataset_path = tmp_path / f"multimodal{suffix}" | ||
| 344 | # Overlong rows are filtered before collation; they must not affect labels. | 474 | # Overlong rows are filtered before collation; they must not affect labels. |
| 345 | overlong = {"messages": [{"role": "user", "content": "word " * 700}, {"role": "assistant", "content": "Skipped."}]} | 475 | overlong = {"messages": [{"role": "user", "content": "word " * 700}, {"role": "assistant", "content": "Skipped."}]} |
| 346 | - dataset_path.write_text(json.dumps(overlong) + "\n" + json.dumps(row) + "\n") | 476 | + rows = [overlong, row] |
| 477 | + dataset_path.write_text( | ||
| 478 | + json.dumps(rows) if suffix == ".json" else "".join(json.dumps(sample) + "\n" for sample in rows) | ||
| 479 | + ) | ||
| 347 | expected_inputs, expected_labels = _processor(dataset_path, tokenizer)._sample(row) | 480 | expected_inputs, expected_labels = _processor(dataset_path, tokenizer)._sample(row) |
| 348 | - loader = _loader(dataset_path, tokenizer) | 481 | + loader_config = sft_override(deepseek_v4_1_debugmodel_multimodal().dataloader, dataset_path=str(dataset_path)) |
| 482 | + loader_config.repeat = False | ||
| 483 | + loader = loader_config.build( | ||
| 484 | + tokenizer=tokenizer, dp_rank=0, dp_world_size=1, max_context_length=512, num_tokens_per_microbatch=512 | ||
| 485 | + ) | ||
| 349 | try: | 486 | try: |
| 350 | inputs, labels = _unpack(next(iter(loader))) | 487 | inputs, labels = _unpack(next(iter(loader))) |
| 351 | finally: | 488 | finally: |
| @@ -355,8 +492,27 @@ def test_grain_sft_preserves_processed_multimodal_fixture(tmp_path, tokenizer, n | |||
| 355 | torch.testing.assert_close(inputs[key], value, rtol=0, atol=0) | 492 | torch.testing.assert_close(inputs[key], value, rtol=0, atol=0) |
| 356 | expected_reply = [*tokenizer.tokenizer.encode("Blue and red.").ids, tokenizer.eos_id] | 493 | expected_reply = [*tokenizer.tokenizer.encode("Blue and red.").ids, tokenizer.eos_id] |
| 357 | assert labels[labels != -100].tolist() == expected_reply | 494 | assert labels[labels != -100].tolist() == expected_reply |
| 358 | - assert inputs["num_valid_tokens"] == len(expected_reply) | 495 | + assert inputs["loss_token_count"] == len(expected_reply) |
| 359 | assert inputs["pixel_values"].shape[0] == max(num_images, 1) | 496 | assert inputs["pixel_values"].shape[0] == max(num_images, 1) |
| 360 | if not num_images: | 497 | if not num_images: |
| 361 | assert (inputs["image_feature_indices"] == -1).all() | 498 | assert (inputs["image_feature_indices"] == -1).all() |
| 362 | assert torch.count_nonzero(inputs["pixel_values"]) == 0 | 499 | assert torch.count_nonzero(inputs["pixel_values"]) == 0 |
| 500 | + | ||
| 501 | + | ||
| 502 | +def test_repeating_sft_rejects_a_dp_shard_with_no_valid_samples(tmp_path, tokenizer): | ||
| 503 | + dataset_path = tmp_path / "shards.jsonl" | ||
| 504 | + rows = [ | ||
| 505 | + {"instruction": "Question", "output": "Answer"}, | ||
| 506 | + {"instruction": "word " * 700, "output": "Too long"}, | ||
| 507 | + ] | ||
| 508 | + dataset_path.write_text("".join(json.dumps(row) + "\n" for row in rows)) | ||
| 509 | + config = sft_override(deepseek_v4_1_debugmodel_multimodal().dataloader, dataset_path=str(dataset_path)) | ||
| 510 | + config.shuffle = False | ||
| 511 | + loader = config.build( | ||
| 512 | + tokenizer=tokenizer, dp_rank=1, dp_world_size=2, max_context_length=512, num_tokens_per_microbatch=512 | ||
| 513 | + ) | ||
| 514 | + try: | ||
| 515 | + with pytest.raises(ValueError, match="SFT data shard 1/2 has no valid samples"): | ||
| 516 | + next(iter(loader)) | ||
| 517 | + finally: | ||
| 518 | + loader.close() | ||
| @@ -0,0 +1,90 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# SPDX-License-Identifier: BSD-3-Clause | ||
| 3 | + | ||
| 4 | +import json | ||
| 5 | +from dataclasses import fields | ||
| 6 | +from glob import escape | ||
| 7 | +from importlib import import_module | ||
| 8 | + | ||
| 9 | +import pytest | ||
| 10 | +from torchtitan.components.data import ( | ||
| 11 | + FirstFitPackingConfig, | ||
| 12 | + GrainDataLoader, | ||
| 13 | + HuggingFaceRandomAccessSource, | ||
| 14 | + HuggingFaceStreamingSource, | ||
| 15 | + IndexedJsonlSource, | ||
| 16 | + SingleDatasetConfig, | ||
| 17 | +) | ||
| 18 | +from torchtitan.config import OverrideConfig | ||
| 19 | +from torchtitan.config.override import apply_overrides, parse_cli_imports | ||
| 20 | +from torchtitan.trainer import Trainer | ||
| 21 | + | ||
| 22 | +from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor | ||
| 23 | +from torchtitan_npu.models.deepseek_v4_1.vision.language_dataset import _GrainSFTProcessor | ||
| 24 | + | ||
| 25 | +pytestmark = pytest.mark.cpu | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +@pytest.mark.parametrize("hardware", ["a3", "a5"]) | ||
| 29 | +@pytest.mark.parametrize("vision", [False, True], ids=["v4", "v4_1"]) | ||
| 30 | +@pytest.mark.parametrize("indexed", [True, False], ids=["jsonl", "json-or-parquet"]) | ||
| 31 | +def test_sft_overrides_only_cpt_dataloader(tmp_path, monkeypatch, hardware, vision, indexed): | ||
| 32 | + suffix = ".jsonl" if indexed else (".parquet" if vision else ".json") | ||
| 33 | + data = tmp_path / f"chat [train]{suffix}" | ||
| 34 | + monkeypatch.setenv("DATASET_PATH", str(data)) | ||
| 35 | + monkeypatch.setenv("WORLD_SIZE", "128") | ||
| 36 | + monkeypatch.setenv("CP", "1") | ||
| 37 | + if vision: | ||
| 38 | + monkeypatch.setenv("DATASET", "cc12m-test") | ||
| 39 | + monkeypatch.setenv("PACKING_BUFFER_SIZE", "2") | ||
| 40 | + monkeypatch.setenv("DP_SHARD", "128") | ||
| 41 | + monkeypatch.setenv("EP", "128") | ||
| 42 | + model = "deepseek_v4_1" if vision else "deepseek_v4" | ||
| 43 | + name = f"{model}_flash_cpt_4k_{hardware}" | ||
| 44 | + module = import_module(f"torchtitan_npu_recipes.models.{model}") | ||
| 45 | + loader_name = "vision_language_dataloader" if vision else "chat_dataloader" | ||
| 46 | + target = f"torchtitan_npu.override.{model}.{loader_name}.sft" | ||
| 47 | + | ||
| 48 | + config = getattr(module, name)() | ||
| 49 | + assert isinstance(config, Trainer.Config) | ||
| 50 | + before = config.to_dict() | ||
| 51 | + cpt_loader = config.dataloader | ||
| 52 | + options = {"thinking_mode": "thinking" if vision else "chat", "reasoning_effort": "high"} | ||
| 53 | + imports = parse_cli_imports([f"{target}={json.dumps(options)}"]) | ||
| 54 | + replacements = apply_overrides(OverrideConfig(imports=imports), config) | ||
| 55 | + assert len(replacements) == 1 | ||
| 56 | + after = config.to_dict() | ||
| 57 | + before.pop("dataloader") | ||
| 58 | + after.pop("dataloader") | ||
| 59 | + assert after == before | ||
| 60 | + loader = config.dataloader | ||
| 61 | + assert isinstance(loader, GrainDataLoader.Config) | ||
| 62 | + assert all( | ||
| 63 | + getattr(loader, field.name) == getattr(cpt_loader, field.name) | ||
| 64 | + for field in fields(loader) | ||
| 65 | + if field.name not in {"dataset", "collator"} | ||
| 66 | + ) | ||
| 67 | + dataset = loader.dataset | ||
| 68 | + if not vision: | ||
| 69 | + assert isinstance(dataset, FirstFitPackingConfig) | ||
| 70 | + dataset = dataset.dataset | ||
| 71 | + assert isinstance(dataset, SingleDatasetConfig) | ||
| 72 | + processor = dataset.processor | ||
| 73 | + if vision: | ||
| 74 | + assert isinstance(processor, _GrainSFTProcessor.Config) | ||
| 75 | + encoder = processor | ||
| 76 | + else: | ||
| 77 | + assert isinstance(processor, DeepSeekV4ChatProcessor.Config) | ||
| 78 | + encoder = processor.chat_encoder | ||
| 79 | + assert encoder.thinking_mode == options["thinking_mode"] | ||
| 80 | + assert encoder.reasoning_effort == options["reasoning_effort"] | ||
| 81 | + pattern = escape(str(data.resolve())) | ||
| 82 | + if indexed: | ||
| 83 | + assert isinstance(dataset.source, IndexedJsonlSource.Config) | ||
| 84 | + assert dataset.source.patterns == (pattern,) | ||
| 85 | + elif vision: | ||
| 86 | + assert isinstance(dataset.source, HuggingFaceStreamingSource.Config) | ||
| 87 | + assert dataset.source.load_dataset_kwargs["data_files"] == {"train": pattern} | ||
| 88 | + else: | ||
| 89 | + assert isinstance(dataset.source, HuggingFaceRandomAccessSource.Config) | ||
| 90 | + assert dataset.source.load_dataset_kwargs["data_files"] == pattern | ||
| @@ -0,0 +1,80 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# SPDX-License-Identifier: BSD-3-Clause | ||
| 3 | + | ||
| 4 | +from collections.abc import Callable | ||
| 5 | +from contextlib import closing | ||
| 6 | +from dataclasses import replace | ||
| 7 | +from functools import partial | ||
| 8 | +from typing import cast | ||
| 9 | + | ||
| 10 | +import grain.python as grain | ||
| 11 | +from torchtitan.components.data.dataset import GrainDataset, SingleDatasetConfig | ||
| 12 | +from torchtitan.components.data.types import DatasetBuildContext, DatasetIterationPolicy | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +class _CheckedMapShardIterator(grain.DatasetIterator): | ||
| 16 | + def __init__(self, parent: grain.DatasetIterator, check_after: int, error: str, probe: Callable[[], bool] | None): | ||
| 17 | + super().__init__(parent) | ||
| 18 | + self._source = parent | ||
| 19 | + self._check_after = check_after | ||
| 20 | + self._error = error | ||
| 21 | + self._probe = probe | ||
| 22 | + | ||
| 23 | + def __next__(self): | ||
| 24 | + for rows_read, sample in enumerate(self._source, start=1): | ||
| 25 | + if sample is not None: | ||
| 26 | + return sample | ||
| 27 | + if rows_read == self._check_after: | ||
| 28 | + if self._probe is None or not self._probe(): | ||
| 29 | + raise ValueError(self._error) | ||
| 30 | + # Only the finite probe is disposable. Keep the shuffled cursor. | ||
| 31 | + self._check_after = 0 | ||
| 32 | + self._probe = None | ||
| 33 | + raise StopIteration | ||
| 34 | + | ||
| 35 | + def get_state(self): | ||
| 36 | + return self._source.get_state() | ||
| 37 | + | ||
| 38 | + def set_state(self, state): | ||
| 39 | + self._source.set_state(state) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +class _CheckedMapShard(grain.IterDataset): | ||
| 43 | + def __init__(self, parent: grain.IterDataset, check_after: int, error: str, probe: Callable[[], bool] | None): | ||
| 44 | + super().__init__(parent) | ||
| 45 | + self._source = parent | ||
| 46 | + self._check_after = check_after | ||
| 47 | + self._error = error | ||
| 48 | + self._probe = probe | ||
| 49 | + | ||
| 50 | + def __iter__(self) -> grain.DatasetIterator: | ||
| 51 | + return _CheckedMapShardIterator(iter(self._source), self._check_after, self._error, self._probe) | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +class SFTMapDatasetConfig(SingleDatasetConfig): | ||
| 55 | + """Repeat a map shard while detecting rows entirely removed by SFT filters.""" | ||
| 56 | + | ||
| 57 | + def build(self, *, context: DatasetBuildContext, dataset_iteration_policy: DatasetIterationPolicy) -> GrainDataset: | ||
| 58 | + policy = dataset_iteration_policy | ||
| 59 | + shard = super().build(context=context, dataset_iteration_policy=replace(policy, repeat=False)) | ||
| 60 | + if not policy.repeat: | ||
| 61 | + return shard | ||
| 62 | + | ||
| 63 | + shard = cast("grain.MapDataset", shard) | ||
| 64 | + size = len(shard) | ||
| 65 | + check_after = 2 * size - 1 if policy.shuffle else size | ||
| 66 | + probe = None | ||
| 67 | + if policy.shuffle and policy.dp_world_size > 1: | ||
| 68 | + # Each epoch reshuffles before sharding, so consecutive misses do | ||
| 69 | + # not imply that the next epoch will leave this rank empty. | ||
| 70 | + probe = partial(self._has_valid_sample, context=context, policy=policy) | ||
| 71 | + repeated = shard.repeat().to_iter_dataset(read_options=context.read_options, allow_nones=True) | ||
| 72 | + error = f"SFT data shard {policy.dp_rank}/{policy.dp_world_size} has no valid samples" | ||
| 73 | + return _CheckedMapShard(repeated, check_after, error, probe) | ||
| 74 | + | ||
| 75 | + def _has_valid_sample(self, *, context: DatasetBuildContext, policy: DatasetIterationPolicy) -> bool: | ||
| 76 | + finite = replace(policy, shuffle=False, repeat=False, dp_rank=0, dp_world_size=1) | ||
| 77 | + dataset = cast("grain.MapDataset", super().build(context=context, dataset_iteration_policy=finite)) | ||
| 78 | + rows = dataset.to_iter_dataset(read_options=context.read_options, allow_nones=True) | ||
| 79 | + with closing(iter(rows)) as iterator: | ||
| 80 | + return any(sample is not None for sample in iterator) | ||
| @@ -8,11 +8,12 @@ | |||
| 8 | """DeepSeek-V4's model-owned structured chat encoder.""" | 8 | """DeepSeek-V4's model-owned structured chat encoder.""" |
| 9 | 9 | ||
| 10 | import importlib.util | 10 | import importlib.util |
| 11 | +from copy import deepcopy | ||
| 11 | from dataclasses import dataclass | 12 | from dataclasses import dataclass |
| 12 | from pathlib import Path | 13 | from pathlib import Path |
| 13 | from typing import Any, Literal | 14 | from typing import Any, Literal |
| 14 | 15 | ||
| 15 | -from torchtitan.components.tokenizer import BaseTokenizer | 16 | +from torchtitan.components.tokenizer import HuggingFaceTokenizer |
| 16 | 17 | ||
| 17 | ThinkingMode = Literal["chat", "thinking"] | 18 | ThinkingMode = Literal["chat", "thinking"] |
| 18 | ReasoningEffort = Literal["low", "high", "max"] | 19 | ReasoningEffort = Literal["low", "high", "max"] |
| @@ -50,14 +51,24 @@ class DSV4ChatEncoder: | |||
| 50 | def encode_messages_with_assistant_mask( | 51 | def encode_messages_with_assistant_mask( |
| 51 | self, | 52 | self, |
| 52 | messages: list[dict[str, Any]], | 53 | messages: list[dict[str, Any]], |
| 53 | - tokenizer: BaseTokenizer, | 54 | + tokenizer: HuggingFaceTokenizer, |
| 54 | eos_id: int, | 55 | eos_id: int, |
| 55 | ) -> tuple[str, list[int], list[bool]]: | 56 | ) -> tuple[str, list[int], list[bool]]: |
| 56 | - # Official context is an already-encoded prefix: it affects rendering | 57 | + del eos_id # The official template controls EOS, including wo_eos. |
一般(S2): 删掉 问题编号:R1248-002 审查版本: ![]() ![]() Can Learn Bot 16 days ago Comments: 16 days ago Comments: ![]() ![]() | |||
| 57 | - # decisions but is not emitted or labeled by this sample. | 58 | + full_text = self._encoding.encode_messages( |
| 58 | - context = [dict(message) for message in self.context or []] | 59 | + messages, |
| 60 | + thinking_mode=self.thinking_mode, | ||
| 61 | + context=deepcopy(self.context), | ||
| 62 | + drop_thinking=self.drop_thinking, | ||
| 63 | + add_default_bos_token=self.add_default_bos_token, | ||
| 64 | + reasoning_effort=self.reasoning_effort, | ||
| 65 | + ) | ||
| 66 | + # Per-message rendering only identifies the assistant boundaries. | ||
| 67 | + context = deepcopy(self.context) or [] | ||
| 68 | + bos = self._encoding.bos_token if self.add_default_bos_token and not context else "" | ||
| 59 | messages = self._encoding.merge_tool_messages(messages) | 69 | messages = self._encoding.merge_tool_messages(messages) |
| 60 | - messages = self._encoding.sort_tool_results_by_call_order(context + messages)[len(context) :] | 70 | + context_len = len(context) |
| 71 | + messages = self._encoding.sort_tool_results_by_call_order(context + messages)[context_len:] | ||
| 61 | if context: | 72 | if context: |
| 62 | context = self._encoding.sort_tool_results_by_call_order(self._encoding.merge_tool_messages(context)) | 73 | context = self._encoding.sort_tool_results_by_call_order(self._encoding.merge_tool_messages(context)) |
| 63 | messages = context + messages | 74 | messages = context + messages |
| @@ -89,32 +100,25 @@ class DSV4ChatEncoder: | |||
| 89 | messages, | 100 | messages, |
| 90 | thinking_mode=self.thinking_mode, | 101 | thinking_mode=self.thinking_mode, |
| 91 | drop_thinking=drop_thinking, | 102 | drop_thinking=drop_thinking, |
| 92 | - reasoning_effort=self.reasoning_effort if index == 0 else None, | 103 | + reasoning_effort=self.reasoning_effort, |
| 93 | ) | 104 | ) |
| 94 | for index in range(context_len, len(messages)) | 105 | for index in range(context_len, len(messages)) |
| 95 | ] | 106 | ] |
| 96 | - full_text = "".join(rendered) | 107 | + if bos + "".join(rendered) != full_text: |
| 97 | - add_bos = self.add_default_bos_token and not context | 108 | + raise ValueError("Per-message rendering diverges from the official DeepSeek V4 prompt") |
| 98 | - full_tokens = tokenizer.encode(full_text, add_bos=add_bos, add_eos=False) | 109 | + encoded = tokenizer.tokenizer.encode(full_text, add_special_tokens=False) |
| 99 | - if not full_tokens or full_tokens[-1] != eos_id: | 110 | + assistant_spans = [] |
| 100 | - full_tokens.append(eos_id) | 111 | + cursor = len(bos) |
| 101 | - | 112 | + for message, message_text in zip(messages[context_len:], rendered, strict=True): |
| 102 | - assistant_mask = [False] * len(full_tokens) | 113 | + end = cursor + len(message_text) |
| 103 | - prefix_text = "" | 114 | + if message.get("role") == "assistant" and cursor < end: |
| 104 | - for index, (message, message_text) in enumerate(zip(messages[context_len:], rendered, strict=True)): | 115 | + assistant_spans.append((cursor, end)) |
| 105 | - next_prefix_text = full_text if index == len(rendered) - 1 else prefix_text + message_text | 116 | + cursor = end |
| 106 | - if message.get("role") == "assistant": | 117 | + assistant_mask = [ |
| 107 | - prefix_tokens = tokenizer.encode(prefix_text, add_bos=add_bos, add_eos=False) | 118 | + any(begin < span_end and finish > span_start for span_start, span_end in assistant_spans) |
| 108 | - through_tokens = tokenizer.encode(next_prefix_text, add_bos=add_bos, add_eos=False) | 119 | + for begin, finish in encoded.offsets |
| 109 | - if full_tokens[: len(prefix_tokens)] != prefix_tokens: | 120 | + ] |
| 110 | - raise ValueError(f"Assistant prefix token alignment failed at message {index}") | 121 | + return full_text, encoded.ids, assistant_mask |
| 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 | 122 | ||
| 119 | 123 | ||
| 120 | @dataclass(kw_only=True, slots=True) | 124 | @dataclass(kw_only=True, slots=True) |
| @@ -1,4 +1,5 @@ | |||
| 1 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | 1 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. |
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 2 | # | 3 | # |
| 3 | # This source code is licensed under the BSD-style license found in the | 4 | # 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 | # LICENSE file in the root directory of this source tree. |
| @@ -7,19 +8,21 @@ | |||
| 7 | 8 | ||
| 8 | import base64 | 9 | import base64 |
| 9 | import json | 10 | import json |
| 10 | -from dataclasses import dataclass | 11 | +from contextlib import closing |
| 12 | +from dataclasses import dataclass, replace | ||
| 13 | +from glob import escape | ||
| 11 | from io import BytesIO | 14 | from io import BytesIO |
| 12 | from pathlib import Path | 15 | from pathlib import Path |
| 13 | -from typing import Any, cast | 16 | +from typing import TYPE_CHECKING, Any, cast |
| 14 | 17 | ||
| 15 | import torch | 18 | import torch |
| 16 | from PIL import Image | 19 | from PIL import Image |
| 17 | from torch.nn.utils.rnn import pad_sequence | 20 | from torch.nn.utils.rnn import pad_sequence |
| 18 | from torchtitan.components.data import GrainDataLoader | 21 | from torchtitan.components.data import GrainDataLoader |
| 19 | from torchtitan.components.data.collators import Collator | 22 | from torchtitan.components.data.collators import Collator |
| 20 | -from torchtitan.components.data.dataset import SampleProcessor, SingleDatasetConfig | 23 | +from torchtitan.components.data.dataset import GrainDataset, SampleProcessor, SingleDatasetConfig |
| 21 | from torchtitan.components.data.sources import HuggingFaceStreamingSource | 24 | from torchtitan.components.data.sources import HuggingFaceStreamingSource |
| 22 | -from torchtitan.components.data.types import TokenizedTrainingMicrobatch | 25 | +from torchtitan.components.data.types import DatasetBuildContext, DatasetIterationPolicy, TokenizedTrainingMicrobatch |
| 23 | from torchtitan.components.tokenizer import HuggingFaceTokenizer | 26 | from torchtitan.components.tokenizer import HuggingFaceTokenizer |
| 24 | 27 | ||
| 25 | from torchtitan_npu.models.common.alignment import validate_alignment | 28 | from torchtitan_npu.models.common.alignment import validate_alignment |
| @@ -31,6 +34,9 @@ from .language_encoder import ( | |||
| 31 | ThinkingMode, | 34 | ThinkingMode, |
| 32 | ) | 35 | ) |
| 33 | 36 | ||
| 37 | +if TYPE_CHECKING: | ||
| 38 | + import grain.python as grain | ||
| 39 | + | ||
| 34 | _STACKED_INPUT_KEYS = ( | 40 | _STACKED_INPUT_KEYS = ( |
| 35 | "input", | 41 | "input", |
| 36 | "positions", | 42 | "positions", |
| @@ -153,7 +159,9 @@ class DeepSeekV41VisionLanguageProcessor: | |||
| 153 | raise ValueError("LLaVA message value must be text") | 159 | raise ValueError("LLaVA message value must be text") |
| 154 | parts = split_text(value) | 160 | parts = split_text(value) |
| 155 | else: | 161 | else: |
| 156 | - content = message.get("content_blocks", message.get("content")) | 162 | + content = message.get("content_blocks") |
| 163 | + if content is None: | ||
| 164 | + content = message.get("content") | ||
| 157 | parts = [] | 165 | parts = [] |
| 158 | if isinstance(content, str): | 166 | if isinstance(content, str): |
| 159 | parts = split_text(content) | 167 | parts = split_text(content) |
| @@ -225,7 +233,11 @@ class DeepSeekV41VisionLanguageProcessor: | |||
| 225 | if any(not isinstance(message, dict) for message in context): | 233 | if any(not isinstance(message, dict) for message in context): |
| 226 | raise ValueError("context messages must be objects") | 234 | raise ValueError("context messages must be objects") |
| 227 | context = [ | 235 | context = [ |
| 228 | - {**message, "role": aliases.get(message.get("role"), message.get("role"))} for message in context | 236 | + { |
| 237 | + **message, | ||
| 238 | + "role": aliases.get(message.get("role"), message.get("role")), | ||
| 239 | + } | ||
| 240 | + for message in context | ||
| 229 | ] | 241 | ] |
| 230 | _, text_ids, text_mask, image_positions, image_sources = ( | 242 | _, text_ids, text_mask, image_positions, image_sources = ( |
| 231 | self.vision_language_encoder.encode_messages_with_assistant_mask( | 243 | self.vision_language_encoder.encode_messages_with_assistant_mask( |
| @@ -308,7 +320,7 @@ class DeepSeekV41VisionLanguageProcessor: | |||
| 308 | types.extend([TEXT] * (len(text_ids) - cursor)) | 320 | types.extend([TEXT] * (len(text_ids) - cursor)) |
| 309 | indices.extend([-1] * (len(text_ids) - cursor)) | 321 | indices.extend([-1] * (len(text_ids) - cursor)) |
| 310 | target_mask.extend(text_mask[cursor:]) | 322 | target_mask.extend(text_mask[cursor:]) |
| 311 | - if not any(target_mask): | 323 | + if not any(target_mask[1:]): |
| 312 | raise ValueError("V4.1 chat SFT requires an assistant response") | 324 | raise ValueError("V4.1 chat SFT requires an assistant response") |
| 313 | if len(ids) > self.seq_len: | 325 | if len(ids) > self.seq_len: |
| 314 | return None | 326 | return None |
| @@ -421,6 +433,21 @@ class _SFTCollator(Collator): | |||
| 421 | ) | 433 | ) |
| 422 | 434 | ||
| 423 | 435 | ||
| 436 | +class _VisionLanguageStreamConfig(SingleDatasetConfig): | ||
| 437 | + def build(self, *, context: DatasetBuildContext, dataset_iteration_policy: DatasetIterationPolicy) -> GrainDataset: | ||
| 438 | + policy = dataset_iteration_policy | ||
| 439 | + if not policy.repeat or not isinstance(self.source, HuggingFaceStreamingSource.Config): | ||
| 440 | + return super().build(context=context, dataset_iteration_policy=policy) | ||
| 441 | + | ||
| 442 | + # A stream has no row count. Check a finite pass before enabling its native repeat. | ||
| 443 | + finite_policy = replace(policy, repeat=False, shuffle=False) | ||
| 444 | + shard = cast("grain.IterDataset", super().build(context=context, dataset_iteration_policy=finite_policy)) | ||
| 445 | + with closing(iter(shard)) as iterator: | ||
| 446 | + if next(iterator, None) is None: | ||
| 447 | + raise ValueError(f"SFT data shard {policy.dp_rank}/{policy.dp_world_size} has no valid samples") | ||
| 448 | + return super().build(context=context, dataset_iteration_policy=policy) | ||
| 449 | + | ||
| 450 | + | ||
| 424 | def sft_dataloader_config( | 451 | def sft_dataloader_config( |
| 425 | *, | 452 | *, |
| 426 | dataset_path: str, | 453 | dataset_path: str, |
| @@ -442,11 +469,11 @@ def sft_dataloader_config( | |||
| 442 | if suffix not in (".json", ".jsonl", ".parquet"): | 469 | if suffix not in (".json", ".jsonl", ".parquet"): |
| 443 | raise ValueError("vision SFT dataset must be JSON, JSONL, or Parquet") | 470 | raise ValueError("vision SFT dataset must be JSON, JSONL, or Parquet") |
| 444 | return GrainDataLoader.Config( | 471 | return GrainDataLoader.Config( |
| 445 | - dataset=SingleDatasetConfig( | 472 | + dataset=_VisionLanguageStreamConfig( |
| 446 | source=HuggingFaceStreamingSource.Config( | 473 | source=HuggingFaceStreamingSource.Config( |
| 447 | path="parquet" if suffix == ".parquet" else "json", | 474 | path="parquet" if suffix == ".parquet" else "json", |
| 448 | split="train", | 475 | split="train", |
| 449 | - load_dataset_kwargs={"data_files": {"train": dataset_path}}, | 476 | + load_dataset_kwargs={"data_files": {"train": escape(dataset_path)}}, |
| 450 | ), | 477 | ), |
| 451 | processor=_GrainSFTProcessor.Config( | 478 | processor=_GrainSFTProcessor.Config( |
| 452 | dataset_path=dataset_path, | 479 | dataset_path=dataset_path, |
| @@ -8,6 +8,7 @@ | |||
| 8 | import copy | 8 | import copy |
| 9 | import importlib.util | 9 | import importlib.util |
| 10 | import inspect | 10 | import inspect |
| 11 | +from pathlib import Path | ||
| 11 | from typing import Any, Literal | 12 | from typing import Any, Literal |
| 12 | 13 | ||
| 13 | from torchtitan.components.tokenizer import HuggingFaceTokenizer | 14 | from torchtitan.components.tokenizer import HuggingFaceTokenizer |
| @@ -29,6 +30,11 @@ class DeepSeekV41VisionLanguageEncoder: | |||
| 29 | ) -> None: | 30 | ) -> None: |
| 30 | if thinking_mode not in ("chat", "thinking"): | 31 | if thinking_mode not in ("chat", "thinking"): |
| 31 | raise ValueError(f"Unsupported thinking_mode: {thinking_mode!r}") | 32 | raise ValueError(f"Unsupported thinking_mode: {thinking_mode!r}") |
| 33 | + if not Path(encoding_module_path).is_file(): | ||
| 34 | + raise FileNotFoundError( | ||
| 35 | + f"DeepSeek V4.1 SFT could not find {encoding_module_path}. " | ||
| 36 | + "Set --hf-assets-path to the model directory containing encoding/encoding.py." | ||
| 37 | + ) | ||
| 32 | spec = importlib.util.spec_from_file_location("encoding_dsv41", encoding_module_path) | 38 | spec = importlib.util.spec_from_file_location("encoding_dsv41", encoding_module_path) |
| 33 | if spec is None or spec.loader is None: | 39 | if spec is None or spec.loader is None: |
| 34 | raise FileNotFoundError(f"Cannot load encoding module: {encoding_module_path}") | 40 | raise FileNotFoundError(f"Cannot load encoding module: {encoding_module_path}") |
| @@ -49,6 +55,7 @@ class DeepSeekV41VisionLanguageEncoder: | |||
| 49 | missing = required - inspect.signature(encode_messages).parameters.keys() | 55 | missing = required - inspect.signature(encode_messages).parameters.keys() |
| 50 | if missing: | 56 | if missing: |
| 51 | raise RuntimeError(f"The V4.1 encoding API is missing parameters: {sorted(missing)}") | 57 | raise RuntimeError(f"The V4.1 encoding API is missing parameters: {sorted(missing)}") |
| 58 | + self._encoding = encoding | ||
| 52 | self._encode_messages: Any = encode_messages | 59 | self._encode_messages: Any = encode_messages |
| 53 | self._image_placeholder = image_placeholder | 60 | self._image_placeholder = image_placeholder |
| 54 | self.thinking_mode = thinking_mode | 61 | self.thinking_mode = thinking_mode |
| @@ -76,9 +83,23 @@ class DeepSeekV41VisionLanguageEncoder: | |||
| 76 | prompt: str, | 83 | prompt: str, |
| 77 | encoding_options: dict[str, Any], | 84 | encoding_options: dict[str, Any], |
| 78 | ) -> tuple[int, int]: | 85 | ) -> tuple[int, int]: |
| 79 | - """Derive one span by changing only public message fields.""" | 86 | + """Derive one span with the full conversation available to the encoder.""" |
| 80 | if messages[index].get("tool_calls"): | 87 | if messages[index].get("tool_calls"): |
| 81 | - raise RuntimeError("tool-call supervision requires a prefix-stable V4.1 encoding") | 88 | + # Keep the later user turns visible to drop_thinking and include the |
| 89 | + # serialized tool calls that follow the assistant's text. | ||
| 90 | + context = encoding_options["context"] or [] | ||
| 91 | + options = encoding_options | {"add_default_bos_token": False} | ||
| 92 | + with_call = self._encode_messages(messages[index:], **(options | {"context": context + messages[:index]})) | ||
| 93 | + next_index = index + 1 | ||
| 94 | + after_call = "" | ||
| 95 | + if next_index < len(messages): | ||
| 96 | + after_call = self._encode_messages( | ||
| 97 | + messages[next_index:], **(options | {"context": context + messages[:next_index]}) | ||
| 98 | + ) | ||
| 99 | + start, end = len(prompt) - len(with_call), len(prompt) - len(after_call) | ||
| 100 | + if start >= end or not prompt.endswith(with_call) or not with_call.endswith(after_call): | ||
| 101 | + raise RuntimeError("the official V4.1 encoding did not preserve the tool-call SFT span") | ||
| 102 | + return start, end | ||
| 82 | marker = f"\ue000torchtitan_sft_{index}\ue001" | 103 | marker = f"\ue000torchtitan_sft_{index}\ue001" |
| 83 | if marker in prompt: | 104 | if marker in prompt: |
| 84 | raise RuntimeError("SFT span probe marker occurs in the encoded prompt") | 105 | raise RuntimeError("SFT span probe marker occurs in the encoded prompt") |
| @@ -105,10 +126,20 @@ class DeepSeekV41VisionLanguageEncoder: | |||
| 105 | if marker_end < len(marker) or not prompt.endswith(suffix): | 126 | if marker_end < len(marker) or not prompt.endswith(suffix): |
| 106 | raise RuntimeError("the official V4.1 encoding did not preserve the SFT end probe") | 127 | raise RuntimeError("the official V4.1 encoding did not preserve the SFT end probe") |
| 107 | end = len(prompt) - len(suffix) | 128 | end = len(prompt) - len(suffix) |
| 108 | - if start >= end: | 129 | + if start > end: |
| 109 | - raise RuntimeError("the official V4.1 encoding produced an empty assistant span") | 130 | + raise RuntimeError("the official V4.1 encoding produced an inverted assistant span") |
| 110 | return start, end | 131 | return start, end |
| 111 | 132 | ||
| 133 | + def _merge_tool_messages(self, messages): | ||
| 134 | + normalized = [] | ||
| 135 | + for message in messages: | ||
| 136 | + content = message.get("content") | ||
| 137 | + if message.get("role") == "user" and message.get("content_blocks") is None and isinstance(content, list): | ||
| 138 | + # The first release expects user blocks to be set before merging tools. | ||
| 139 | + message = message | {"content_blocks": content} | ||
| 140 | + normalized.append(message) | ||
| 141 | + return self._encoding.merge_tool_messages(normalized) | ||
| 142 | + | ||
| 112 | def encode_messages_with_assistant_mask( | 143 | def encode_messages_with_assistant_mask( |
| 113 | self, | 144 | self, |
| 114 | messages: list[dict[str, Any]], | 145 | messages: list[dict[str, Any]], |
| @@ -143,10 +174,19 @@ class DeepSeekV41VisionLanguageEncoder: | |||
| 143 | images = media.get("images") | 174 | images = media.get("images") |
| 144 | if not isinstance(images, list): | 175 | if not isinstance(images, list): |
| 145 | raise RuntimeError("The V4.1 encoding did not return an images list") | 176 | raise RuntimeError("The V4.1 encoding did not return an images list") |
| 177 | + if images and any(message.get("tool_calls") for message in (context or []) + messages): | ||
建议:为首版
![]() ![]() | |||
| 178 | + # The first V4.1 release collected images before sorting tool results. | ||
| 179 | + helpers = ("merge_tool_messages", "sort_tool_results_by_call_order", "process_image_messages") | ||
| 180 | + missing = [name for name in helpers if not callable(getattr(self._encoding, name, None))] | ||
| 181 | + if missing: | ||
| 182 | + raise RuntimeError(f"The V4.1 encoding is missing tool image helpers: {', '.join(missing)}") | ||
| 183 | + history = self._merge_tool_messages(context or []) | ||
| 184 | + history_length = len(history) | ||
| 185 | + ordered = self._encoding.sort_tool_results_by_call_order(history + self._merge_tool_messages(messages)) | ||
| 186 | + _, images = self._encoding.process_image_messages(ordered[history_length:]) | ||
| 146 | 187 | ||
| 147 | - # Ask the official encoder for every assistant boundary instead of | 188 | + # Use official prefixes when stable and recover the span against the |
| 148 | - # reproducing its image, tool and thinking preprocessing. Prefix | 189 | + # full conversation when later messages change the prefix rendering. |
| 149 | - # stability is the only contract required for multi-turn supervision. | ||
| 150 | assistant_spans = [] | 190 | assistant_spans = [] |
| 151 | for index, message in enumerate(messages): | 191 | for index, message in enumerate(messages): |
| 152 | if message.get("role") != "assistant": | 192 | if message.get("role") != "assistant": |
| @@ -154,9 +194,11 @@ class DeepSeekV41VisionLanguageEncoder: | |||
| 154 | before = self._encode_messages(messages[:index], **encoding_options) | 194 | before = self._encode_messages(messages[:index], **encoding_options) |
| 155 | through = self._encode_messages(messages[: index + 1], **encoding_options) | 195 | through = self._encode_messages(messages[: index + 1], **encoding_options) |
| 156 | if through.startswith(before) and prompt.startswith(through): | 196 | if through.startswith(before) and prompt.startswith(through): |
| 157 | - assistant_spans.append((len(before), len(through))) | 197 | + start, end = len(before), len(through) |
| 158 | else: | 198 | else: |
| 159 | - assistant_spans.append(self._assistant_span_by_probe(messages, index, prompt, encoding_options)) | 199 | + start, end = self._assistant_span_by_probe(messages, index, prompt, encoding_options) |
| 200 | + if start < end: | ||
| 201 | + assistant_spans.append((start, end)) | ||
| 160 | 202 | ||
| 161 | placeholder = self._image_placeholder | 203 | placeholder = self._image_placeholder |
| 162 | image_spans = [] | 204 | image_spans = [] |
| @@ -167,15 +209,12 @@ class DeepSeekV41VisionLanguageEncoder: | |||
| 167 | if len(image_spans) != len(images): | 209 | if len(image_spans) != len(images): |
| 168 | raise ValueError("Encoded image count does not match the prompt") | 210 | raise ValueError("Encoded image count does not match the prompt") |
| 169 | 211 | ||
| 170 | - cuts = sorted(image_spans + [(end, end) for _, end in assistant_spans]) | ||
| 171 | token_ids: list[int] = [] | 212 | token_ids: list[int] = [] |
| 172 | assistant_mask: list[bool] = [] | 213 | assistant_mask: list[bool] = [] |
| 173 | image_positions: list[int] = [] | 214 | image_positions: list[int] = [] |
| 174 | cursor = 0 | 215 | cursor = 0 |
| 175 | - for start, end in [*cuts, (len(prompt), len(prompt))]: | 216 | + for start, end in [*image_spans, (len(prompt), len(prompt))]: |
| 176 | - if start < cursor: | 217 | + encoded = tokenizer.tokenizer.encode(prompt[cursor:start], add_special_tokens=False) |
| 177 | - continue | ||
| 178 | - encoded = tokenizer.tokenizer.encode(prompt[cursor:start]) | ||
| 179 | token_ids.extend(encoded.ids) | 218 | token_ids.extend(encoded.ids) |
| 180 | assistant_mask.extend( | 219 | assistant_mask.extend( |
| 181 | any( | 220 | any( |
| @@ -184,13 +223,6 @@ class DeepSeekV41VisionLanguageEncoder: | |||
| 184 | ) | 223 | ) |
| 185 | for begin, finish in encoded.offsets | 224 | for begin, finish in encoded.offsets |
| 186 | ) | 225 | ) |
| 187 | - if ( | ||
| 188 | - start == end | ||
| 189 | - and any(span_end == end for _, span_end in assistant_spans) | ||
| 190 | - and token_ids | ||
| 191 | - and token_ids[-1] == tokenizer.eos_id | ||
| 192 | - ): | ||
| 193 | - assistant_mask[-1] = True | ||
| 194 | if end > start: | 226 | if end > start: |
| 195 | image_positions.append(len(token_ids)) | 227 | image_positions.append(len(token_ids)) |
| 196 | cursor = end | 228 | cursor = end |
| @@ -0,0 +1,67 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# SPDX-License-Identifier: BSD-3-Clause | ||
| 3 | + | ||
| 4 | +import os | ||
| 5 | +from dataclasses import replace | ||
| 6 | +from glob import escape | ||
| 7 | +from pathlib import Path | ||
| 8 | + | ||
| 9 | +from torchtitan.components.data import ( | ||
| 10 | + ConcatThenSplitPackingConfig, | ||
| 11 | + FirstFitPackingConfig, | ||
| 12 | + GrainDataLoader, | ||
| 13 | + HuggingFaceRandomAccessSource, | ||
| 14 | + IndexedJsonlSource, | ||
| 15 | + SingleDatasetConfig, | ||
| 16 | +) | ||
| 17 | +from torchtitan.config import override | ||
| 18 | + | ||
| 19 | +from torchtitan_npu.models.common.alignment import AlignedTextProcessor | ||
| 20 | +from torchtitan_npu.models.common.sft_shard import SFTMapDatasetConfig | ||
| 21 | +from torchtitan_npu.models.deepseek_v4.chat_encoder import DSV4EncoderConfig, ReasoningEffort, ThinkingMode | ||
| 22 | +from torchtitan_npu.models.deepseek_v4.chat_processor import DeepSeekV4ChatProcessor | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +@override(target=GrainDataLoader.Config, fqns=["dataloader"], exact=True, description="DeepSeek V4 chat SFT") | ||
| 26 | +def sft( | ||
| 27 | + cfg: GrainDataLoader.Config, | ||
| 28 | + *, | ||
| 29 | + dataset_path: str | None = None, | ||
| 30 | + thinking_mode: ThinkingMode = "thinking", | ||
| 31 | + drop_thinking: bool = True, | ||
| 32 | + add_default_bos_token: bool = True, | ||
| 33 | + reasoning_effort: ReasoningEffort | None = None, | ||
| 34 | +) -> GrainDataLoader.Config: | ||
| 35 | + packed = cfg.dataset | ||
| 36 | + if not isinstance(packed, ConcatThenSplitPackingConfig) or not isinstance(packed.dataset, SingleDatasetConfig): | ||
| 37 | + raise ValueError("DeepSeek V4 chat SFT requires the CPT text data recipe") | ||
| 38 | + samples = packed.dataset | ||
| 39 | + if not isinstance(samples.processor, AlignedTextProcessor.Config): | ||
| 40 | + raise ValueError("DeepSeek V4 chat SFT requires the CPT text processor") | ||
| 41 | + | ||
| 42 | + dataset_path = dataset_path or os.environ.get("DATASET_PATH") | ||
| 43 | + path = Path(dataset_path).resolve() if dataset_path else None | ||
| 44 | + suffix = path.suffix.lower() if path else "" | ||
| 45 | + if path is None or suffix not in (".jsonl", ".json"): | ||
| 46 | + raise ValueError("Set DATASET_PATH to a DeepSeek V4 chat JSONL or JSON file") | ||
| 47 | + pattern = escape(str(path)) | ||
| 48 | + source = ( | ||
| 49 | + IndexedJsonlSource.Config(patterns=(pattern,)) | ||
| 50 | + if suffix == ".jsonl" | ||
| 51 | + else HuggingFaceRandomAccessSource.Config( | ||
| 52 | + path="json", split="train", load_dataset_kwargs={"data_files": pattern} | ||
| 53 | + ) | ||
| 54 | + ) | ||
| 55 | + processor = DeepSeekV4ChatProcessor.Config( | ||
| 56 | + per_doc_alignment=samples.processor.per_doc_alignment, | ||
| 57 | + chat_encoder=DSV4EncoderConfig( | ||
| 58 | + thinking_mode=thinking_mode, | ||
| 59 | + drop_thinking=drop_thinking, | ||
| 60 | + add_default_bos_token=add_default_bos_token, | ||
| 61 | + reasoning_effort=reasoning_effort, | ||
| 62 | + ), | ||
| 63 | + ) | ||
| 64 | + dataset = SFTMapDatasetConfig( | ||
| 65 | + source=source, pre_filters=samples.pre_filters, processor=processor, post_filters=samples.post_filters | ||
| 66 | + ) | ||
| 67 | + return replace(cfg, dataset=FirstFitPackingConfig(dataset=dataset)) | ||
| @@ -0,0 +1,70 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# SPDX-License-Identifier: BSD-3-Clause | ||
| 3 | + | ||
| 4 | +import os | ||
| 5 | +from dataclasses import replace | ||
| 6 | +from glob import escape | ||
| 7 | +from pathlib import Path | ||
| 8 | +from typing import cast | ||
| 9 | + | ||
| 10 | +from torchtitan.components.data import ( | ||
| 11 | + GrainDataLoader, | ||
| 12 | + HuggingFaceRandomAccessSource, | ||
| 13 | + IndexedJsonlSource, | ||
| 14 | + SingleDatasetConfig, | ||
| 15 | +) | ||
| 16 | +from torchtitan.components.data.multimodal.mm_datasets import MMSamplePackingConfig | ||
| 17 | +from torchtitan.config import override | ||
| 18 | + | ||
| 19 | +from torchtitan_npu.models.common.sft_shard import SFTMapDatasetConfig | ||
| 20 | +from torchtitan_npu.models.deepseek_v4_1.vision.dataloader import CaptionProcessor | ||
| 21 | +from torchtitan_npu.models.deepseek_v4_1.vision.language_dataset import sft_dataloader_config | ||
| 22 | +from torchtitan_npu.models.deepseek_v4_1.vision.language_encoder import ReasoningEffort, ThinkingMode | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +@override( | ||
| 26 | + target=GrainDataLoader.Config, fqns=["dataloader"], exact=True, description="DeepSeek V4.1 vision-language SFT" | ||
| 27 | +) | ||
| 28 | +def sft( | ||
| 29 | + cfg: GrainDataLoader.Config, | ||
| 30 | + *, | ||
| 31 | + dataset_path: str | None = None, | ||
| 32 | + image_root: str = "", | ||
| 33 | + thinking_mode: ThinkingMode = "chat", | ||
| 34 | + drop_thinking: bool = True, | ||
| 35 | + add_default_bos_token: bool = True, | ||
| 36 | + reasoning_effort: ReasoningEffort | None = None, | ||
| 37 | +) -> GrainDataLoader.Config: | ||
| 38 | + samples = cfg.dataset.dataset if isinstance(cfg.dataset, MMSamplePackingConfig) else cfg.dataset | ||
| 39 | + if not isinstance(samples, SingleDatasetConfig) or not isinstance(samples.processor, CaptionProcessor.Config): | ||
| 40 | + raise ValueError("DeepSeek V4.1 vision-language SFT requires the CPT multimodal data recipe") | ||
| 41 | + | ||
| 42 | + dataset_path = dataset_path or os.environ.get("DATASET_PATH") | ||
| 43 | + if not dataset_path: | ||
| 44 | + raise ValueError("Set DATASET_PATH to a DeepSeek V4.1 SFT JSONL, JSON, or Parquet file") | ||
| 45 | + spec = sft_dataloader_config( | ||
| 46 | + dataset_path=dataset_path, | ||
| 47 | + image_root=image_root, | ||
| 48 | + thinking_mode=thinking_mode, | ||
| 49 | + drop_thinking=drop_thinking, | ||
| 50 | + add_default_bos_token=add_default_bos_token, | ||
| 51 | + reasoning_effort=reasoning_effort, | ||
| 52 | + per_doc_alignment=samples.processor.per_doc_alignment, | ||
| 53 | + ) | ||
| 54 | + path = Path(dataset_path).resolve() | ||
| 55 | + suffix = path.suffix.lower() | ||
| 56 | + if suffix == ".parquet": | ||
| 57 | + return replace(cfg, dataset=spec.dataset, collator=spec.collator) | ||
| 58 | + pattern = escape(str(path)) | ||
| 59 | + source = ( | ||
| 60 | + IndexedJsonlSource.Config(patterns=(pattern,)) | ||
| 61 | + if suffix == ".jsonl" | ||
| 62 | + else HuggingFaceRandomAccessSource.Config( | ||
| 63 | + path="json", split="train", load_dataset_kwargs={"data_files": pattern} | ||
| 64 | + ) | ||
| 65 | + ) | ||
| 66 | + stream = cast("SingleDatasetConfig", spec.dataset) | ||
| 67 | + dataset = SFTMapDatasetConfig( | ||
| 68 | + source=source, pre_filters=stream.pre_filters, processor=stream.processor, post_filters=stream.post_filters | ||
| 69 | + ) | ||
| 70 | + return replace(cfg, dataset=dataset, collator=spec.collator) | ||


当前PR改动代码超过1k行,建议拆分PR后合入。
问题编号:R1248-011
审查版本:
f229f6175368fe590efdfce474e5f55d2aa2e798