Merged
040 的 Qwen 和 SFT #1205
Merged
Can Learn BotAdd on 28 days ago
Total: 23 files changed+2903-380
Rexamples/qwen3_6/run_qwen3_6_4k.sh→examples/qwen3_5/run_qwen3_5_4k.sh+2-2
@@ -8,7 +8,7 @@ set -euo pipefail
8 8 
9SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
10 10 
11-MODULE="${MODULE:-torchtitan_npu_recipes.examples.qwen3_6}" \11+MODULE="${MODULE:-torchtitan_npu_recipes.examples.qwen3_5}" \
12-CONFIG="${CONFIG:-run_qwen3_6_4k}" \12+CONFIG="${CONFIG:-run_qwen3_5_4k}" \
13NGPU="${NGPU:-16}" \13NGPU="${NGPU:-16}" \
14exec bash "${SCRIPT_DIR}/../../scripts/run_train.sh" "$@"14exec bash "${SCRIPT_DIR}/../../scripts/run_train.sh" "$@"
@@ -0,0 +1,98 @@
1+#!/usr/bin/env bash
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
3+# SPDX-License-Identifier: BSD-3-Clause
4+ 
5+set -eo pipefail
6+ 
7+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
8+MODULE="${MODULE:-torchtitan_npu_recipes.examples.qwen3_5}"
9+NGPU="${NGPU:-16}"
10+TRAIN_FILE=torchtitan_npu_recipes.qwen_sft
11+ 
12+usage() {
13+ cat <<'HELP'
14+Usage: bash examples/qwen3_5/run_qwen_sft.sh --hf-assets-path DIR --dataset-path FILE --output-dir DIR
15+Presets: --config run_qwen_sft (default), run_qwen3_5_32k_cp8, run_qwen3_5_64k_cp8, run_qwen3_5_128k_cp8
16+Optional FLA 32K preset: --config run_qwen3_5_32k_cp8_fla
17+Custom recipe: --module FILE.py --config FUNCTION
18+Data: JSONL with messages. Optional: --chat-template FILE, --loss-mask POLICY
19+Training: --smoke-test, --max-steps N, --resume-step N, --init-checkpoint DIR
20+HELP
21+}
22+ 
23+data_override() {
24+ python3 - "$@" <<'PY'
25+import json
26+from pathlib import Path
27+import sys
28+ 
29+dataset, template, mask = sys.argv[1:]
30+if not dataset or not Path(dataset).is_file():
31+ sys.exit("--dataset-path must name an existing JSONL file")
32+options = {"dataset_path": str(Path(dataset).resolve())}
33+if template:
34+ if not Path(template).is_file():
35+ sys.exit("--chat-template must name an existing Jinja file")
36+ options["chat_template"] = str(Path(template).resolve())
37+if mask:
38+ options["loss_mask"] = mask
39+print(json.dumps(options))
40+PY
41+}
42+ 
43+main() {
44+ local dataset= assets= template= mask= option value kwargs
45+ local -a args=() data_args=()
46+ while (( $# )); do
47+ case "${1%%=*}" in
48+ --help|-h) usage; return ;;
49+ --print-config) export COMM_BACKEND=fake; args+=("$1") ;;
50+ --module|--dataset-path|--hf-assets-path|--chat-template|--loss-mask|--init-checkpoint)
51+ option="${1%%=*}"
52+ if [[ "$1" == *=* ]]; then
53+ value="${1#*=}"
54+ else
55+ value="${2:-}"
56+ if (( $# > 1 )); then shift; fi
57+ fi
58+ if [[ -z "$value" || "$value" == --* ]]; then
59+ echo "$option requires a value" >&2
60+ return 2
61+ fi
62+ case "$option" in
63+ --dataset-path) dataset="$value" ;;
64+ --hf-assets-path) assets="$value" ;;
65+ --chat-template) template="$value" ;;
66+ --loss-mask) mask="$value" ;;
67+ --module|--init-checkpoint)
68+ if [[ "$value" != /* && ( "$option" == --init-checkpoint || "$value" == *.py ) ]]; then
69+ value="$PWD/$value"
70+ fi
71+ args+=("$option" "$value")
72+ ;;
73+ esac
74+ ;;
75+ *) args+=("$1") ;;
76+ esac
77+ shift
78+ done
79+ 
80+ if [[ -n "$dataset$assets$template$mask" ]]; then
81+ dataset="${dataset:-${DATA_FILES:-}}"
82+ assets="${assets:-${HF_ASSETS_PATH:-}}"
83+ if [[ ! -d "$assets" ]]; then
84+ echo '--hf-assets-path must name an existing model directory' >&2
85+ return 2
86+ fi
87+ export HF_ASSETS_PATH="$(cd -- "$assets" && pwd)"
88+ unset DATA_FILES
89+ kwargs=$(data_override "$dataset" "$template" "$mask")
90+ data_args=(--override "torchtitan_npu.models.qwen3_5.dataloader.chat_sft=$kwargs")
91+ fi
92+ 
93+ CONFIG="${CONFIG:-run_qwen_sft}"
94+ export MODULE CONFIG NGPU TRAIN_FILE
95+ exec bash "$SCRIPT_DIR/../../scripts/run_train.sh" "${data_args[@]}" "${args[@]}"
96+}
97+ 
98+main "$@"
@@ -0,0 +1,16 @@
1+{"messages": [{"role": "user", "content": "Give three tips for staying healthy."}, {"role": "assistant", "content": "1.Eat a balanced diet and make sure to include plenty of fruits and vegetables. \n2. Exercise regularly to keep your body active and strong. \n3. Get enough sleep and maintain a consistent sleep schedule."}]}
2+{"messages": [{"role": "user", "content": "What are the three primary colors?"}, {"role": "assistant", "content": "The three primary colors are red, blue, and yellow."}]}
3+{"messages": [{"role": "user", "content": "Describe the structure of an atom."}, {"role": "assistant", "content": "An atom is made up of a nucleus, which contains protons and neutrons, surrounded by electrons that travel in orbits around the nucleus. The protons and neutrons have a positive charge, while the electrons have a negative charge, resulting in an overall neutral atom. The number of each particle determines the atomic number and the type of atom."}]}
4+{"messages": [{"role": "user", "content": "How can we reduce air pollution?"}, {"role": "assistant", "content": "There are a number of ways to reduce air pollution, such as shifting to renewable energy sources, encouraging the use of public transportation, prohibiting the burning of fossil fuels, implementing policies to reduce emissions from industrial sources, and implementing vehicle emissions standards. Additionally, individuals can do their part to reduce air pollution by reducing car use, avoiding burning materials such as wood, and changing to energy efficient appliances."}]}
5+{"messages": [{"role": "user", "content": "Describe a time when you had to make a difficult decision."}, {"role": "assistant", "content": "I had to make a difficult decision when I was working as a project manager at a construction company. I was in charge of a project that needed to be completed by a certain date in order to meet the client’s expectations. However, due to unexpected delays, we were not able to meet the deadline and so I had to make a difficult decision. I decided to extend the deadline, but I had to stretch the team’s resources even further and increase the budget. Although it was a risky decision, I ultimately decided to go ahead with it to ensure that the project was completed on time and that the client’s expectations were met. The project was eventually successfully completed and this was seen as a testament to my leadership and decision-making abilities."}]}
6+{"messages": [{"role": "user", "content": "Identify the odd one out.\n\nTwitter, Instagram, Telegram"}, {"role": "assistant", "content": "Telegram"}]}
7+{"messages": [{"role": "user", "content": "Explain why the following fraction is equivalent to 1/4\n\n4/16"}, {"role": "assistant", "content": "The fraction 4/16 is equivalent to 1/4 because both numerators and denominators are divisible by 4. Dividing both the top and bottom numbers by 4 yields the fraction 1/4."}]}
8+{"messages": [{"role": "user", "content": "Write a short story in third person narration about a protagonist who has to make an important career decision."}, {"role": "assistant", "content": "John was at a crossroads in his life. He had just graduated college and was now facing the big decision of what career to pursue. After much deliberation, he decided that he wanted to be an accountant and help the financially disadvantaged. He had always been good with numbers and enjoyed seeing the tangible results of his work. \n\nJohn enrolled in accounting courses and initially found it quite challenging. He had to learn multiple systems and regulations quickly, but he worked hard and eventually excelled in his studies. After a few years, John started working at an accounting firm in his city. He was eager to put his knowledge of taxes and accounting to use in a real-world setting.\n\nJohn loved his job, as it let him express his creativity in finding strategies to save his clients money. After a few years at the firm, he became a senior accountant and was asked to manage bigger and more challenging cases. He was now a respected figure in the financial industry, but he still remembers when he was just a recent college graduate, unsure of the direction in which his life would take him."}]}
9+{"messages": [{"role": "user", "content": "Render a 3D model of a house"}, {"role": "assistant", "content": "<nooutput> This type of instruction cannot be fulfilled by a GPT model."}]}
10+{"messages": [{"role": "user", "content": "Evaluate this sentence for spelling and grammar mistakes\n\nHe finnished his meal and left the resturant"}, {"role": "assistant", "content": "He finished his meal and left the restaurant."}]}
11+{"messages": [{"role": "user", "content": "How did Julius Caesar die?"}, {"role": "assistant", "content": "Julius Caesar was assassinated by a group of up to 60 conspirators, led by Gaius Cassius Longinus and Marcus Junius Brutus, in the Senate House on the Ides of March (15 March) of 44 BC."}]}
12+{"messages": [{"role": "user", "content": "What is the capital of France?"}, {"role": "assistant", "content": "The capital of France is Paris."}]}
13+{"messages": [{"role": "user", "content": "Generate a list of ten items a person might need for a camping trip"}, {"role": "assistant", "content": "1. Tent\n2. Sleeping bags\n3. Flashlight\n4. Matches/lighter\n5. Insect repellent\n6. Extra clothes\n7. First aid kit\n8. Camp stove\n9. Cooking utensils\n10. Biodegradable soaps/shampoos"}]}
14+{"messages": [{"role": "user", "content": "Discuss the causes of the Great Depression"}, {"role": "assistant", "content": "The Great Depression was a severe global economic downturn that lasted from 1929 to 1939. It was caused by several factors, including the stock market crash of 1929, structural weaknesses in the economy, low consumer spending, high unemployment, and a lack of confidence in the banking system. Other contributing factors included overproduction of commodities, reliance on borrowing to finance investments, agricultural overproduction, and a decrease in international trade."}]}
15+{"messages": [{"role": "user", "content": "Classify the following into animals, plants, and minerals\n\nOak tree, copper ore, elephant"}, {"role": "assistant", "content": "Oak tree: Plant\n Copper ore: Mineral\n Elephant: Animal"}]}
16+{"messages": [{"role": "user", "content": "Explain the use of word embeddings in Natural Language Processing"}, {"role": "assistant", "content": "Word embeddings are one of the most powerful tools available for Natural Language Processing (NLP). They are mathematical representations of words or phrases in a vector space, allowing similarities between words and the context in which they are used to be measured. Word embeddings are useful for tasks such as sentiment analysis, text classification, predicting the next word in a sequence, and understanding synonyms and analogies. They allow for words to be processed as numerical values, giving machines an easier way to perform NLP tasks."}]}
@@ -3,6 +3,11 @@
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+import atexit
7+import json
8+from pathlib import Path
9+from tempfile import TemporaryDirectory
10+ 
6from tests.integration_tests import OverrideDefinitions11from tests.integration_tests import OverrideDefinitions
7 12 
8# The Qwen3.5 launcher supplies the tokenizer and cc12m-test defaults. Keep13# The Qwen3.5 launcher supplies the tokenizer and cc12m-test defaults. Keep
@@ -61,4 +66,57 @@ def build_qwen3_5_test_list() -> list[OverrideDefinitions]:
61 ngpu=1,66 ngpu=1,
62 extra_args=common,67 extra_args=common,
63 ),68 ),
69+ OverrideDefinitions(
70+ override_args=[()],
71+ test_descr="Qwen packed text SFT on CP2 and FSDP2",
72+ test_name="qwen3_5_packed_sft_cp2",
73+ ngpu=4,
74+ env_vars={"MODULE": "tests.integration_tests.qwen3_5", "CONFIG": "packed_sft_debug"},
75+ use_golden=False,
76+ check_loss=False,
77+ python_config=True,
78+ expected_steps=((1,),),
79+ ),
64 ]80 ]
81+ 
82+ 
83+def packed_sft_debug():
84+ from tokenizers import Tokenizer, models, pre_tokenizers
85+ from torchtitan.components.data import FirstFitPackingConfig
86+ from transformers import PreTrainedTokenizerFast
87+ 
88+ from torchtitan_npu.models.qwen3_5.dataloader import SFTGrainDataLoader, raw_sft_dataset
89+ from torchtitan_npu_recipes.models.qwen3_5 import _text_sft_config
90+ 
91+ assets = TemporaryDirectory(prefix="qwen-sft-smoke-")
92+ atexit.register(assets.cleanup)
93+ root = Path(assets.name)
94+ vocab = {
95+ token: index
96+ for index, token in enumerate(("[UNK]", "<|im_end|>", "<|im_start|>", "user", "assistant", "answer"))
97+ }
98+ backend = Tokenizer(models.WordLevel(vocab=vocab, unk_token="[UNK]"))
99+ backend.pre_tokenizer = pre_tokenizers.WhitespaceSplit()
100+ tokenizer = PreTrainedTokenizerFast(tokenizer_object=backend, unk_token="[UNK]", eos_token="<|im_end|>")
101+ tokenizer.add_special_tokens({"additional_special_tokens": ["<|im_start|>"]})
102+ tokenizer.chat_template = (
103+ "{%- for message in messages %}"
104+ "{{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>\\n' }}"
105+ "{%- endfor %}"
106+ )
107+ tokenizer.save_pretrained(root)
108+ data = root / "train.jsonl"
109+ row = {"messages": [{"role": "user", "content": "answer"}, {"role": "assistant", "content": "answer"}]}
110+ data.write_text((json.dumps(row) + "\n") * 8)
111+ dataset, contract = raw_sft_dataset(dataset_path=str(data))
112+ loader = SFTGrainDataLoader.Config(
113+ dataset=FirstFitPackingConfig(dataset=dataset, num_packing_bins=1), input_contract=contract, max_num_documents=8
114+ )
115+ config = _text_sft_config(
116+ flavor="debugmodel", length=128, cp=2, dp_shard=2, steps=1, load_checkpoint=False, dataloader=loader
117+ )
118+ config.hf_assets_path = str(root)
119+ config.checkpointer = None
120+ config.metrics.enable_tensorboard = True
121+ config.metrics.save_tb_folder = "tb_phase_0"
122+ return config
@@ -49,7 +49,6 @@ collect_ignore = [
49 "models/test_mtp_cp_chunk_loss.py",49 "models/test_mtp_cp_chunk_loss.py",
50 # CP metadata rebuild tests wait for the v0.4 context-parallel transform.50 # CP metadata rebuild tests wait for the v0.4 context-parallel transform.
51 "override/deepseek_v4_1/test_asc_metadata_reuse.py",51 "override/deepseek_v4_1/test_asc_metadata_reuse.py",
52- "override/qwen3_5/test_cp_config.py",
53 # The stage-denominator AuxLoss patch was replaced by v0.4.0's inject(denominator=...).52 # The stage-denominator AuxLoss patch was replaced by v0.4.0's inject(denominator=...).
54 "patches/torchtitan/models/common/test_aux_loss.py",53 "patches/torchtitan/models/common/test_aux_loss.py",
55 # Multimodal / Qwen runtime migration is deferred by the upgrade plan.54 # Multimodal / Qwen runtime migration is deferred by the upgrade plan.
@@ -53,7 +53,6 @@ def test_qwen_launchers_select_recipes_and_delegate_to_run_train():
53 for model, recipe, devices in (53 for model, recipe, devices in (
54 ("qwen3_5", "qwen3_5_debugmodel_1p_cpt_512", 1),54 ("qwen3_5", "qwen3_5_debugmodel_1p_cpt_512", 1),
55 ("qwen3_5", "qwen3_5_debugmodel_moe_8p_cpt_512", 8),55 ("qwen3_5", "qwen3_5_debugmodel_moe_8p_cpt_512", 8),
56- ("qwen3_6", "run_qwen3_6_4k", 16),
57 ):56 ):
58 script = (root / "examples" / model / f"{recipe}.sh").read_text(encoding="utf-8")57 script = (root / "examples" / model / f"{recipe}.sh").read_text(encoding="utf-8")
59 assert f"MODULE:-torchtitan_npu_recipes.examples.{model}" in script58 assert f"MODULE:-torchtitan_npu_recipes.examples.{model}" in script
@@ -1,34 +1,434 @@
1# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.1# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2# SPDX-License-Identifier: BSD-3-Clause2# SPDX-License-Identifier: BSD-3-Clause
3 3 
4+import json
5+import os
6+import re
7+import subprocess
8+import sys
9+from copy import deepcopy
10+from dataclasses import replace
11+from types import SimpleNamespace
12+ 
13+import grain.python as grain
14+import numpy as np
15+import pytest
4import torch16import torch
5-from torchtitan.config import ConfigManager17+import torch.distributed.checkpoint as dcp
6-from torchtitan.config.override import apply_overrides18+from torchtitan.components.data import FirstFitPackingConfig
7-from torchtitan.models.base.module import Module19+from torchtitan.config import apply_overrides
8-from torchtitan.models.common.attention import VarlenAttentionMetadata20+from torchtitan.config.loader import ConfigLoader
9-from torchtitan.models.common.cp_attention import CPInnerAttention21+from torchtitan.models.common.attention.gdn import GDN
22+from transformers import AutoTokenizer
10 23 
11-from torchtitan_npu.override.qwen3_5.gated_delta import ContextParallelGatedDeltaNet24+from torchtitan_npu.models.qwen3_5.chat_processor import QwenSFTChatProcessor
12-from torchtitan_npu.override.qwen3_5.varlen_attention import AscVarlenInnerAttention25+from torchtitan_npu.models.qwen3_5.dataloader import (
26+ SFTGrainDataLoader,
27+ _TrainableShard,
28+ raw_sft_dataset,
29+ tokenizer_identity,
30+)
31+from torchtitan_npu.override.qwen3_5.gated_delta import AscContextParallelInnerGDN, AscInnerGDN
32+from torchtitan_npu.override.qwen3_5.varlen_attention import AscCPVarlenInnerAttention, AscVarlenInnerAttention
33+from torchtitan_npu_recipes.models.qwen3_5 import _text_sft_config
13 34 
14 35 
15-def test_long_text_cli_keeps_cp_and_selects_typed_cp_attention_and_gdn():36+@pytest.mark.parametrize("cp", (1, 2, 8))
16- config = ConfigManager().parse_args(37+def test_native_recipe_selects_only_the_inner_npu_implementations(cp, monkeypatch, tmp_path):
17- [38+ monkeypatch.setenv("DATA_FILES", str(tmp_path / "train.jsonl"))
18- "--module",39+ monkeypatch.setenv("HF_ASSETS_PATH", str(tmp_path))
19- "torchtitan_npu_recipes.models.qwen3_5",40+ config = _text_sft_config(
20- "--config",41+ flavor="27B" if cp == 8 else "debugmodel", length=512, cp=cp, dp_shard=2, steps=2, load_checkpoint=False
21- "qwen35_27b_long_text_sft",
22- "--hf-assets-path",
23- "/tmp",
24- ]
25 )42 )
43+ outer_types = [type(layer.attention) for layer in config.model.layers]
26 apply_overrides(config.override, config)44 apply_overrides(config.override, config)
27- assert config.parallelism.context_parallel_degree == 445+ assert [type(layer.attention) for layer in config.model.layers] == outer_types
28- configs = [cfg for _, cfg, _, _ in config.model.traverse(Module.Config, recurse=True)]46+ gdn_owner = AscContextParallelInnerGDN if cp > 1 else AscInnerGDN
29- cores = [cfg for cfg in configs if isinstance(cfg, CPInnerAttention.Config)]47+ attention_owner = AscCPVarlenInnerAttention if cp > 1 else AscVarlenInnerAttention
30- assert cores and all(cfg._owner is AscVarlenInnerAttention for cfg in cores)48+ for layer in config.model.layers:
31- assert any(cfg._owner is ContextParallelGatedDeltaNet for cfg in configs)49+ inner = layer.attention.inner_attention
32- cu = torch.tensor([0, 2, 8], dtype=torch.int32)50+ assert inner._owner is (gdn_owner if isinstance(layer.attention, GDN.Config) else attention_owner)
33- metadata = VarlenAttentionMetadata(cu, cu.clone(), max_q=6, max_k=6)51+ assert inner.sharding_config is not None
34- assert AscVarlenInnerAttention.prepare_cp_metadata(metadata, permutation=None) is metadata52+ if cp > 1:
53+ metadata = object()
54+ assert gdn_owner.prepare_cp_metadata(metadata, permutation=None) is metadata
55+ with pytest.raises(ValueError, match="without a load balancer"):
56+ gdn_owner.prepare_cp_metadata(metadata, permutation=torch.arange(8))
57+ 
58+ 
59+TEMPLATE = r"""{%- for message in messages %}
60+{{- '<|im_start|>' + message.role + '\n' }}
61+{%- if message.role == 'assistant' %}
62+{{- '<think>\n' + (message.reasoning_content or '') + '\n</think>\n\n' }}
63+{%- endif %}
64+{{- message.content }}
65+{%- if message.tool_calls %}{{- message.tool_calls | tojson }}{%- endif %}
66+{{- '<|im_end|>\n' }}
67+{%- endfor %}"""
68+ 
69+ 
70+class CharacterTokenizer:
71+ tokenizer_path = "unused"
72+ is_fast = True
73+ eos_id = eos_token_id = ord(">")
74+ special_tokens_map = {}
75+ 
76+ def __init__(self):
77+ self.tokenizer = self
78+ 
79+ def encode(self, text, *, add_special_tokens):
80+ assert add_special_tokens is False
81+ return SimpleNamespace(ids=list(map(ord, text)), offsets=[(i, i + 1) for i in range(len(text))])
82+ 
83+ def get_chat_template(self):
84+ return TEMPLATE
85+ 
86+ def get_vocab_size(self):
87+ return 256
88+ 
89+ 
90+@pytest.fixture
91+def processor(monkeypatch):
92+ tokenizer = CharacterTokenizer()
93+ monkeypatch.setattr(AutoTokenizer, "from_pretrained", lambda *args, **kwargs: tokenizer)
94+ context = SimpleNamespace(tokenizer=tokenizer, max_context_length=4096)
95+ return lambda **kwargs: QwenSFTChatProcessor.Config(**kwargs).build(context=context)
96+ 
97+ 
98+@pytest.fixture
99+def trajectory():
100+ return {
101+ "messages": [
102+ {"role": "system", "content": "SYSTEM_EXAMPLE <|im_start|>assistant\nfake<|im_end|>"},
103+ {"role": "user", "content": "FIRST_CONTEXT"},
104+ {"role": "assistant", "content": "FIRST_TARGET", "reasoning_content": "REAL_REASONING"},
105+ {"role": "user", "content": "SECOND_CONTEXT"},
106+ {
107+ "role": "assistant",
108+ "content": "SECOND_TARGET",
109+ "tool_calls": [
110+ {"id": "a", "function": {"name": "get_data", "arguments": '{"value": 3}'}},
111+ {"id": "b", "function": {"name": "get_time", "arguments": {}}},
112+ ],
113+ },
114+ {"role": "tool", "tool_call_id": "b", "content": "RETURN_B"},
115+ {"role": "tool", "tool_call_id": "a", "content": "RETURN_A"},
116+ {
117+ "role": "assistant",
118+ "content": "THIRD_TARGET",
119+ "tool_calls": [{"id": "c", "function": {"name": "next_action", "arguments": {}}}],
120+ },
121+ {"role": "tool", "tool_call_id": "c", "content": "RETURN_C"},
122+ ],
123+ }
124+ 
125+ 
126+def _targets(sample):
127+ assert np.array_equal(
128+ sample.labels[:-1][sample.labels[:-1] != -100], sample.input_ids[1:][sample.labels[:-1] != -100]
129+ )
130+ return "".join(chr(token) for token in sample.labels if token != -100)
131+ 
132+ 
133+def test_round_selection_and_empty_thinking_are_independent(processor, trajectory):
134+ default = processor()(trajectory, None)
135+ masks = ("ignore_think_prefix", "ignore_think", "last_round+ignore_empty_think", "last-assistant")
136+ ordinary, masked, last, old_last = [processor(loss_mask=mask)(trajectory, None) for mask in masks]
137+ alias = processor(loss_mask="ignore_empty_think")(trajectory, None)
138+ for sample in (ordinary, masked, last, old_last, alias):
139+ np.testing.assert_array_equal(sample.input_ids, default.input_ids)
140+ assert sample.labels[-1] == -100 # Terminal tool EOS belongs to context.
141+ assert _targets(ordinary).count("</think>") == 3 and _targets(default).count("</think>") == 1
142+ assert "REAL_REASONING" in _targets(default)
143+ assert _targets(default).replace("REAL_REASONING\n</think>\n\n", "") == _targets(masked)
144+ for targets in (_targets(default), _targets(masked), _targets(last)):
145+ assert not any(part in targets for part in ("fake", "SYSTEM_EXAMPLE", "CONTEXT", "RETURN_"))
146+ assert all(part in targets for part in ("SECOND_TARGET", '"value": 3', "THIRD_TARGET"))
147+ assert "FIRST_TARGET" in _targets(masked) and "FIRST_TARGET" not in _targets(last)
148+ assert "THIRD_TARGET" in _targets(old_last) and "SECOND_TARGET" not in _targets(old_last)
149+ np.testing.assert_array_equal(alias.labels, default.labels)
150+ for turn in trajectory["messages"]:
151+ if turn["role"] == "assistant":
152+ turn["loss"] = False
153+ assert processor()(trajectory, None) is None
154+ 
155+ 
156+def test_parallel_tool_results_follow_call_order(processor, trajectory):
157+ sample = processor()(trajectory, None)
158+ text = "".join(chr(token) for token in sample.input_ids)
159+ assert text.index("RETURN_A") < text.index("RETURN_B") < text.index("RETURN_C")
160+ bad = deepcopy(trajectory)
161+ bad["messages"][-1]["tool_call_id"] = "unrelated"
162+ with pytest.raises(ValueError, match="matching preceding call"):
163+ processor()(bad, None)
164+ incomplete = deepcopy(trajectory)
165+ del incomplete["messages"][6]
166+ with pytest.raises(ValueError, match="identify a prefix"):
167+ processor()(incomplete, None)
168+ 
169+ 
170+def test_custom_template_accepts_whitespace_after_supervised_eos(processor, tmp_path, monkeypatch):
171+ template = tmp_path / "custom.jinja"
172+ template.write_text(TEMPLATE)
173+ with pytest.raises(ValueError, match="generation blocks in a custom template"):
174+ processor(chat_template=str(template), loss_mask="template")
175+ template.write_text("{% generation %}answer{% endgeneration %}")
176+ with monkeypatch.context() as patch:
177+ patch.setattr(CharacterTokenizer, "decode", lambda _, ids: "".join(map(chr, ids)), raising=False)
178+ patch.setattr(
179+ CharacterTokenizer,
180+ "apply_chat_template",
181+ lambda *a, **k: {"input_ids": [ord("Q"), ord("A"), ord(">"), 10], "assistant_masks": [0, 1, 1, 1]},
182+ raising=False,
183+ )
184+ row = {"messages": [{"role": "user", "content": "Q"}, {"role": "assistant", "content": "A"}]}
185+ sample = processor(chat_template=str(template), loss_mask="template")(row, None)
186+ assert sample.labels.tolist() == [ord("A"), ord(">")]
187+ 
188+ 
189+def test_trainable_shard_crosses_empty_shuffled_epoch():
190+ pool = grain.MapDataset.source([0, 1, 2, 3]).filter(lambda value: value < 2)
191+ for seed in range(100):
192+ shard = pool.shuffle(seed=seed)[:2]
193+ available = [any(shard[start + index] is not None for index in (0, 1)) for start in (0, 2, 4)]
194+ if available == [True, False, True]:
195+ break
196+ else:
197+ pytest.fail("No deterministic empty intermediate shard found")
198+ guarded = _TrainableShard(shard, dp_rank=0, dp_world_size=2, context_length=128, shuffle=True).repeat()
199+ assert [guarded[i] for i in range(2, 6)] == [shard[i] for i in range(2, 6)]
200+ 
201+ 
202+class ToyTokenizer:
203+ eos_id, pad_id, bos_id = 1, 0, 2
204+ eos_token_id = eos_id
205+ tokenizer_path = "unused"
206+ is_fast = True
207+ special_tokens_map = {}
208+ 
209+ def __init__(self):
210+ self.tokenizer = self
211+ 
212+ def apply_chat_template(self, messages, **kwargs):
213+ return "".join(f"<|im_start|>{message['role']}\n{message['content']}<|im_end|>\n" for message in messages)
214+ 
215+ def get_chat_template(self):
216+ return (
217+ "{%- for message in messages %}{{- '<|im_start|>' + message.role + '\\n' + "
218+ "message.content + '<|im_end|>\\n' }}{%- endfor %}"
219+ )
220+ 
221+ def encode(self, text, *, add_bos=True, add_eos=False, add_special_tokens=None):
222+ parts = list(re.finditer(r"<\|im_end\|>|[\s\S]", text))
223+ ids = [self.eos_id if len(part[0]) > 1 else ord(part[0]) + 3 for part in parts]
224+ if add_special_tokens is not None:
225+ return SimpleNamespace(ids=ids, offsets=[part.span() for part in parts])
226+ return ([2] if add_bos else []) + ids + ([1] if add_eos else [])
227+ 
228+ 
229+@pytest.fixture
230+def toy_tokenizer(monkeypatch):
231+ tokenizer = ToyTokenizer()
232+ monkeypatch.setattr(AutoTokenizer, "from_pretrained", lambda *args, **kwargs: tokenizer)
233+ return tokenizer
234+ 
235+ 
236+@pytest.fixture
237+def raw_data(tmp_path, toy_tokenizer):
238+ assets = tmp_path / "assets"
239+ assets.mkdir()
240+ (assets / "tokenizer.json").write_text('{"toy":"tokens"}')
241+ (assets / "chat_template.jinja").write_text("toy-template-v1")
242+ toy_tokenizer.tokenizer_path = str(assets)
243+ sources = []
244+ for source_index in range(2):
245+ source = tmp_path / f"raw-{source_index}.jsonl"
246+ source.write_text(
247+ "".join(
248+ json.dumps(
249+ {
250+ "messages": [
251+ {"role": "user", "content": f"source-{source_index}-row-{row}"},
252+ {
253+ "role": "assistant",
254+ "content": "answer" * (1 + row % 3),
255+ "reasoning_content": "reason" if row % 2 else "",
256+ },
257+ ]
258+ }
259+ )
260+ + "\n"
261+ for row in range(24)
262+ )
263+ )
264+ sources.append(str(source))
265+ return toy_tokenizer, tuple(sources)
266+ 
267+ 
268+def test_dp2_prefetched_packing_and_real_dcp_cursor_recovery(raw_data, tmp_path):
269+ tokenizer, sources = raw_data
270+ without_template = deepcopy(tokenizer)
271+ without_template.apply_chat_template = lambda *_: pytest.fail("An external template must bypass the built-in probe")
272+ identity = tokenizer_identity(without_template, tokenizer.tokenizer_path, chat_template="external.jinja")
273+ assert identity["eos_id"] == tokenizer.eos_id
274+ dataset, input_contract = raw_sft_dataset(patterns=sources)
275+ config = SFTGrainDataLoader.Config(
276+ dataset=FirstFitPackingConfig(dataset=dataset, num_packing_bins=2),
277+ input_contract=input_contract,
278+ read_options=grain.ReadOptions(num_threads=1, prefetch_buffer_size=2),
279+ )
280+ 
281+ def build_rank_pair():
282+ return [
283+ config.build(
284+ tokenizer=tokenizer,
285+ dp_rank=rank,
286+ dp_world_size=2,
287+ max_context_length=512,
288+ num_tokens_per_microbatch=512,
289+ )
290+ for rank in range(2)
291+ ]
292+ 
293+ originals, restored = build_rank_pair(), build_rank_pair()
294+ try:
295+ iterators = [iter(loader) for loader in originals]
296+ for iterator in iterators:
297+ next(iterator)
298+ next(iterator)
299+ saved = originals[0].state_dict() | originals[1].state_dict()
300+ expected = [[next(iterator) for _ in range(3)] for iterator in iterators]
301+ assert all((batch.labels != -100).any() for batches in expected for batch in batches)
302+ checkpoint = tmp_path / "dcp"
303+ dcp.save({"data": saved}, checkpoint_id=checkpoint)
304+ receiving = {"data": restored[0].state_dict() | restored[1].state_dict()}
305+ dcp.load(receiving, checkpoint_id=checkpoint)
306+ incompatible = replace(config, dataset=replace(config.dataset, num_packing_bins=1)).build(
307+ tokenizer=tokenizer, dp_rank=0, dp_world_size=2, max_context_length=512, num_tokens_per_microbatch=512
308+ )
309+ try:
310+ with pytest.raises(ValueError, match="packing"):
311+ incompatible.load_state_dict(receiving["data"])
312+ finally:
313+ incompatible.close()
314+ for rank, loader in enumerate(restored):
315+ loader.load_state_dict(receiving["data"])
316+ iterator = iter(loader)
317+ for reference in expected[rank]:
318+ torch.testing.assert_close(next(iterator).as_input_dict(), reference.as_input_dict(), rtol=0, atol=0)
319+ finally:
320+ for loader in originals + restored:
321+ loader.close()
322+ 
323+ 
324+def test_optional_attention_backends_and_cold_sft_import(tmp_path):
325+ program = """
326+import sys
327+from importlib.abc import MetaPathFinder
328+from types import ModuleType
329+ 
330+class MissingCutlass(MetaPathFinder):
331+ def find_spec(self, fullname, path=None, target=None):
332+ if fullname == "cutlass" or fullname.startswith("cutlass."):
333+ raise ModuleNotFoundError(fullname, name=fullname)
334+ 
335+sys.meta_path.insert(0, MissingCutlass())
336+import torchtitan_npu_recipes.qwen_sft
337+import pytest
338+from torchtitan.config import ConfigLoader, apply_overrides
339+from torchtitan.models.common.attention import gdn
340+from torchtitan_npu.override.qwen3_5.gated_delta import AscContextParallelInnerGDN, TritonGatedDeltaKernel
341+from torchtitan_npu.override.qwen3_5.varlen_attention import AscCPVarlenInnerAttention
342+ 
343+def unavailable(*args):
344+ raise AssertionError("Attention Gym is unavailable")
345+ 
346+gdn.require_attn_gym = unavailable
347+for name, function in (
348+ ("fla.modules.causal_conv1d", "causal_conv1d"),
349+ ("fla.ops.gated_delta_rule", "chunk_gated_delta_rule"),
350+):
351+ module = ModuleType(name)
352+ setattr(module, function, unavailable)
353+ sys.modules[name] = module
354+from torchtitan_npu.override.qwen3_5.fla import FLAContextParallelInnerGDN, FLAGatedDeltaKernel, FLAInnerGDN
355+ 
356+def load(recipe, override="context_parallel"):
357+ return ConfigLoader().load([
358+ "--module", "torchtitan_npu_recipes.qwen_sft", "--config", recipe,
359+ "--override", "torchtitan_npu.override.qwen3_5.fla." + override,
360+ ])
361+ 
362+for recipe in ("run_qwen3_5_32k_cp8", "run_qwen3_5_64k_cp8"):
363+ config = load(recipe)
364+ native = {path: node for path, node, _, _ in config.model.traverse(AscContextParallelInnerGDN.Config)}
365+ varlen = {path: node for path, node, _, _ in config.model.traverse(AscCPVarlenInnerAttention.Config)}
366+ assert native and all(type(node.kernel) is TritonGatedDeltaKernel.Config for node in native.values())
367+ apply_overrides(config.override, config)
368+ selected = {path: node for path, node, _, _ in config.model.traverse(FLAContextParallelInnerGDN.Config)}
369+ assert selected.keys() == native.keys()
370+ assert all(type(node.kernel) is FLAGatedDeltaKernel.Config for node in selected.values())
371+ assert isinstance(next(iter(selected.values())).kernel.build(), FLAGatedDeltaKernel)
372+ assert next(iter(selected.values())).build().use_fla_convolution
373+ assert all(varlen[path] is node for path, node, _, _ in config.model.traverse(AscCPVarlenInnerAttention.Config))
374+ 
375+config = load("run_qwen3_5_4k")
376+with pytest.raises(ValueError, match="requires a context-parallel GDN recipe"):
377+ apply_overrides(config.override, config)
378+ 
379+config = load("run_qwen3_5_4k", 'operators={"causal_conv1d":false,"force_fp32":true}')
380+apply_overrides(config.override, config)
381+node = next(config.model.traverse(FLAInnerGDN.Config))[1]
382+assert not node.build().use_fla_convolution
383+assert node.kernel.force_fp32
384+"""
385+ env = os.environ | {
386+ "HF_ASSETS_PATH": str(tmp_path),
387+ "DATA_FILES": str(tmp_path / "train.jsonl"),
388+ "NGPU": "16",
389+ "TORCH_DEVICE_BACKEND_AUTOLOAD": "0",
390+ }
391+ subprocess.run([sys.executable, "-c", program], env=env, check=True, timeout=90)
392+ 
393+ 
394+def test_short_resume_uses_an_absolute_target_and_smoke_requires_fresh_output(monkeypatch, tmp_path):
395+ from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager
396+ from torchtitan_npu_recipes.qwen_sft import sft_launch_args
397+ 
398+ monkeypatch.setenv("HF_ASSETS_PATH", str(tmp_path))
399+ monkeypatch.setenv("DATA_FILES", str(tmp_path / "unused.jsonl"))
400+ monkeypatch.setenv("QWEN_STEPS", "16")
401+ monkeypatch.setenv("NGPU", "16")
402+ args = ["--module", "torchtitan_npu_recipes.qwen_sft", "--config", "run_qwen3_5_4k"]
403+ 
404+ def config_with(*options):
405+ with sft_launch_args([*args, *options]) as native:
406+ return ConfigLoader().load(native)
407+ 
408+ with pytest.raises(SystemExit, match="2"):
409+ config_with("--smoke-test", "--resume-step=2")
410+ logger = tmp_path / "structured_logger"
411+ logger.mkdir()
412+ (logger / "rank0.jsonl").touch()
413+ (tmp_path / "checkpoint" / "step-2").mkdir(parents=True)
414+ config = config_with("--smoke-test", "--output-dir", str(tmp_path))
415+ assert config.training.steps == 1 and config.checkpointer.load_only
416+ (tmp_path / "checkpoint" / "step-2" / ".metadata").touch()
417+ with pytest.raises(ValueError, match="found an existing checkpoint"):
418+ config_with("--smoke-test", "--output-dir", str(tmp_path))
419+ with pytest.raises(ValueError, match="must exceed resume step"):
420+ config_with("--resume-step", "2", "--max-steps", "2")
421+ config = config_with("--resume-step", "2", "--max-steps", "3")
422+ assert config.checkpointer.load_step == 2 and config.training.steps == 3
423+ assert config.optim.lr_scheduler.total_steps == 16
424+ args[-1] = "qwen3_5_27b_sft_64k_cp8"
425+ truncated = config_with("--max-steps", "2")
426+ assert truncated.checkpointer.target_steps == 2
427+ assert not truncated.checkpointer.last_save_in_hf and not truncated.checkpointer.last_save_model_only
428+ owner = truncated.checkpointer._owner
429+ checkpointer = owner.__new__(owner)
430+ checkpointer.target_steps = 2
431+ checkpointer.states = {"train_state": SimpleNamespace(num_completed_steps=2)}
432+ monkeypatch.setattr(CheckpointManager, "load", lambda *_: True)
433+ with pytest.raises(ValueError, match="must exceed restored step 2"):
434+ checkpointer.load()
@@ -5,12 +5,25 @@
5 5 
6"""Qwen example configuration selection through the native recipe loader."""6"""Qwen example configuration selection through the native recipe loader."""
7 7 
8+import json
9+import os
10+import subprocess
11+import sys
12+from pathlib import Path
13+from types import SimpleNamespace
14+ 
8import pytest15import pytest
16+import torch
17+import torch.distributed.checkpoint as dcp
18+from safetensors.torch import load_file, save_file
9from torchtitan.components.data import HuggingFaceStreamingSource19from torchtitan.components.data import HuggingFaceStreamingSource
20+from torchtitan.config import apply_overrides
10from torchtitan.config.loader import ConfigLoader21from torchtitan.config.loader import ConfigLoader
11 22 
12import torchtitan_npu # noqa: F40123import torchtitan_npu # noqa: F401
13from torchtitan_npu.models.qwen3_5 import NPUQwen35Model24from torchtitan_npu.models.qwen3_5 import NPUQwen35Model
25+from torchtitan_npu_recipes.models import qwen3_5
26+from torchtitan_npu_recipes.models.qwen3_5 import _text_sft_config
14 27 
15 28 
16@pytest.fixture29@pytest.fixture
@@ -136,14 +149,308 @@ def test_legacy_qwen_override_environment_requires_explicit_configuration(monkey
136 )149 )
137 150 
138 151 
139-@pytest.mark.cpu152+def test_qwen_moe_checkpoint_preserves_single_router_update_and_gradients(monkeypatch):
140-def test_qwen36_selector_keeps_27b_migration_requirement():153+ from copy import deepcopy
141- with pytest.raises(NotImplementedError, match=r"Qwen3\.5 27B recipe requires migration"):154+ 
142- ConfigLoader().load(155+ from torch import nn
143- [156+ from torch.utils.checkpoint import DefaultDeviceType
144- "--module",157+ from torchtitan.models.common.moe import MoE
145- "torchtitan_npu_recipes.examples.qwen3_6",158+ 
146- "--config",159+ monkeypatch.setattr(DefaultDeviceType, "_default_device_type", "cpu")
147- "run_qwen3_6_4k",160+ 
148- ]161+ class CountingMoE(MoE):
162+ def __init__(self):
163+ nn.Module.__init__(self)
164+ self.routed_experts = nn.Module()
165+ self.routed_experts.w13 = nn.Linear(4, 8)
166+ self.routed_experts.w2 = nn.Linear(8, 4)
167+ self.shared_experts = nn.Linear(4, 4)
168+ self.register_buffer("routing_calls", torch.zeros((), dtype=torch.long))
169+ 
170+ def forward(self, inputs):
171+ self.routing_calls.add_(1)
172+ hidden = torch.nn.functional.silu(self.routed_experts.w13(inputs))
173+ return self.routed_experts.w2(hidden) + self.shared_experts(inputs)
174+ 
175+ class Block(nn.Module):
176+ def __init__(self):
177+ super().__init__()
178+ self.attention = nn.Linear(4, 4)
179+ self.feed_forward = CountingMoE()
180+ 
181+ def forward(self, inputs):
182+ hidden = inputs + self.attention(inputs)
183+ return hidden + self.feed_forward(hidden)
184+ 
185+ reference = Block()
186+ candidate = deepcopy(reference)
187+ container = nn.Module()
188+ container.layers = nn.ModuleList([candidate])
189+ qwen3_5.QwenFullActivationRematConfig().apply(container)
190+ inputs = torch.randn(3, 4, requires_grad=True)
191+ reference_inputs = inputs.detach().clone().requires_grad_()
192+ expected = reference(reference_inputs)
193+ actual = candidate(inputs)
194+ expected.square().sum().backward()
195+ actual.square().sum().backward()
196+ torch.testing.assert_close(actual, expected)
197+ torch.testing.assert_close(inputs.grad, reference_inputs.grad)
198+ assert reference.feed_forward.routing_calls.item() == candidate.feed_forward.routing_calls.item() == 1
199+ assert candidate.state_dict().keys() == reference.state_dict().keys()
200+ for expected_parameter, actual_parameter in zip(reference.parameters(), candidate.parameters(), strict=True):
201+ torch.testing.assert_close(actual_parameter.grad, expected_parameter.grad)
202+ 
203+ 
204+@pytest.mark.parametrize(
205+ "preset,length,cp",
206+ [
207+ ("run_qwen3_5_4k", 64, 1),
208+ ("run_qwen3_5_32k_cp8", 32768, 8),
209+ ("run_qwen3_5_64k_cp8", 65536, 8),
210+ ("run_qwen3_5_128k_cp8", 131072, 8),
211+ ("qwen3_5_27b_sft_64k_cp8", 65536, 8),
212+ ],
213+)
214+@pytest.mark.parametrize("launcher", ["examples/qwen3_5/run_qwen_sft.sh", "examples/qwen3_5/run_qwen3_5_4k.sh"])
215+def test_sft_launcher_emits_only_native_cli(preset, length, cp, launcher, monkeypatch, tmp_path):
216+ root = Path(__file__).resolve().parents[3]
217+ bin_dir = tmp_path / "bin"
218+ bin_dir.mkdir()
219+ capture = tmp_path / "capture.json"
220+ fake = bin_dir / "torchrun"
221+ fake.write_text(
222+ f"#!{sys.executable}\n"
223+ + """import json, os, pathlib, sys
224+args = sys.argv[1:]
225+pathlib.Path(os.environ['CAPTURE']).write_text(json.dumps({
226+ 'args': args[args.index('-m') + 2:],
227+ 'env': {k: v for k, v in os.environ.items() if k.startswith('QWEN_') or k == 'SEQ_LEN'},
228+}))
229+"""
230+ )
231+ fake.chmod(0o755)
232+ set_env = tmp_path / "set_env.sh"
233+ set_env.write_text("# CPU argv rendering only\n")
234+ dataset = tmp_path / "train.jsonl"
235+ dataset.write_text('{"messages":[{"role":"user","content":"question"},{"role":"assistant","content":"answer"}]}\n')
236+ monkeypatch.setenv("HF_ASSETS_PATH", str(tmp_path))
237+ monkeypatch.setenv("DATA_FILES", str(dataset))
238+ env = os.environ | {
239+ "PATH": str(bin_dir) + os.pathsep + os.environ["PATH"],
240+ "CAPTURE": str(capture),
241+ "ASCEND_SET_ENV_PATH": str(set_env),
242+ "SEQ_LEN": "64",
243+ "NGPU": "16",
244+ "DUMP_FOLDER": str(tmp_path / "output"),
245+ }
246+ selector = ["--config", preset] if cp > 1 else []
247+ subprocess.run(
248+ ["bash", str(root / launcher), *selector, "--output-dir", str(tmp_path / "output")],
249+ cwd=root,
250+ env=env,
251+ check=True,
252+ )
253+ rendered = json.loads(capture.read_text())
254+ for name, value in rendered["env"].items():
255+ monkeypatch.setenv(name, value)
256+ config = ConfigLoader().load(rendered["args"])
257+ apply_overrides(config.override, config)
258+ from torchtitan_npu.models.qwen3_5.chat_processor import QwenSFTChatProcessor
259+ from torchtitan_npu.models.qwen3_5.dataloader import SFTGrainDataLoader
260+ 
261+ assert isinstance(config.dataloader, SFTGrainDataLoader.Config)
262+ assert isinstance(config.dataloader.dataset.dataset.processor, QwenSFTChatProcessor.Config)
263+ assert config.training.max_context_length == length
264+ assert config.parallelism.context_parallel_degree == cp
265+ assert config.parallelism.data_parallel_shard_degree == (2 if cp > 1 else -1)
266+ assert config.model.text_only and config.checkpointer.initial_load_in_hf
267+ assert config.dump_folder == str(tmp_path / "output")
268+ assert config.dataloader.max_num_documents == (512 if length >= 32768 else None)
269+ from torchtitan_npu.override.qwen3_5.gated_delta import AscInnerGDN, TritonGatedDeltaKernel
270+ 
271+ gdn_configs = [inner for _, inner, _, _ in config.model.traverse(AscInnerGDN.Config)]
272+ assert gdn_configs and all(isinstance(inner.kernel, TritonGatedDeltaKernel.Config) for inner in gdn_configs)
273+ from torchtitan_npu.override.qwen3_5.gated_delta import QwenSFTGatedRMSNorm
274+ 
275+ assert len(list(config.model.traverse(QwenSFTGatedRMSNorm.Config))) == len(gdn_configs)
276+ 
277+ 
278+@pytest.mark.parametrize("trial", [False, True])
279+def test_external_python_recipe_uses_native_config_loader(tmp_path, monkeypatch, trial):
280+ from torchtitan_npu_recipes.qwen_sft import config_file_args, sft_launch_args
281+ 
282+ folder = tmp_path / "my configs"
283+ folder.mkdir()
284+ (folder / "qwen_team_settings.py").write_text("STEPS = 9\n")
285+ path = folder / "qwen.recipe.py"
286+ path.write_text(
287+ "from qwen_team_settings import STEPS\n"
288+ "from torchtitan_npu_recipes.qwen_sft import run_qwen3_5_4k\n"
289+ "def train():\n"
290+ " config = run_qwen3_5_4k()\n"
291+ " config.training.steps = STEPS\n"
292+ " return config\n"
293+ )
294+ monkeypatch.setenv("HF_ASSETS_PATH", str(tmp_path))
295+ monkeypatch.setenv("NGPU", "1")
296+ args = [
297+ "--module",
298+ "torchtitan_npu_recipes.qwen_sft",
299+ "--config",
300+ "run_qwen3_5_4k",
301+ f"--module={path}",
302+ "--config",
303+ "train",
304+ "--output-dir",
305+ str(tmp_path / "train"),
306+ ]
307+ if trial:
308+ args += ["--smoke-test"]
309+ with config_file_args(args) as selected, sft_launch_args(selected) as native:
310+ config = ConfigLoader().load(native)
311+ assert config.training.steps == (1 if trial else 9)
312+ assert config.dump_folder == str(tmp_path / "train")
313+ assert config.checkpointer.load_only is trial
314+ 
315+ 
316+@pytest.fixture(params=("model", "model.language_model"), ids=("text-checkpoint", "conditional-checkpoint"))
317+def recipe_and_prefix(request, monkeypatch, tmp_path):
318+ prefix = request.param
319+ keys = (
320+ f"{prefix}.embed_tokens.weight",
321+ f"{prefix}.layers.0.linear_attn.in_proj_qkv.weight",
322+ f"{prefix}.layers.0.linear_attn.conv1d.weight",
323+ "lm_head.weight",
324+ "model.visual.patch_embed.proj.weight",
325+ "mtp.layers.0.weight",
326+ )
327+ (tmp_path / "model.safetensors.index.json").write_text(
328+ json.dumps(
329+ {
330+ "weight_map": dict.fromkeys(keys, "model-00001-of-00001.safetensors"),
331+ }
149 )332 )
333+ )
334+ save_file(
335+ {
336+ "model.visual.patch_embed.proj.weight": torch.full((2, 3), 0.25),
337+ "mtp.layers.0.weight": torch.full((2, 3), 0.5),
338+ },
339+ tmp_path / "model-00001-of-00001.safetensors",
340+ )
341+ dataset = tmp_path / "train.jsonl"
342+ dataset.write_text('{"prompt":"sum?","response":"two"}\n')
343+ monkeypatch.setenv("HF_ASSETS_PATH", str(tmp_path))
344+ monkeypatch.setenv("DATA_FILES", str(dataset))
345+ recipe = _text_sft_config(flavor="debugmodel", length=512, cp=2, dp_shard=2, steps=2, load_checkpoint=True)
346+ adapter = recipe.model._owner.state_dict_adapter_cls(recipe.model, str(tmp_path / "tokenizer-only"))
347+ adapter.prepare_hf_load(str(tmp_path))
348+ return recipe, adapter, prefix
349+ 
350+ 
351+def test_text_recipe_imports_source_prefix_and_gdn_slices(recipe_and_prefix, tmp_path):
352+ recipe, adapter, prefix = recipe_and_prefix
353+ gdn = recipe.model.layers[0].attention
354+ q_channels, v_channels = gdn.in_proj_q.out_features, gdn.in_proj_v.out_features
355+ rows = 2 * q_channels + v_channels
356+ qkv = torch.arange(rows * recipe.model.dim, dtype=torch.float32).reshape(rows, recipe.model.dim)
357+ embedding = torch.arange(6, dtype=torch.float32).reshape(2, 3)
358+ 
359+ actual = adapter.from_hf(
360+ {
361+ f"{prefix}.embed_tokens.weight": embedding,
362+ f"{prefix}.layers.0.linear_attn.in_proj_qkv.weight": qkv,
363+ "lm_head.weight": torch.ones(2, 3),
364+ }
365+ )
366+ 
367+ torch.testing.assert_close(actual["tok_embeddings.weight"], embedding, rtol=0, atol=0)
368+ key_end = 2 * q_channels
369+ for name, expected in (
370+ ("q", qkv[:q_channels]),
371+ ("k", qkv[q_channels:key_end]),
372+ ("v", qkv[key_end:]),
373+ ):
374+ torch.testing.assert_close(actual[f"layers.0.attention.in_proj_{name}.weight"], expected, rtol=0, atol=0)
375+ vision, mtp = "model.visual.patch_embed.proj.weight", "mtp.layers.0.weight"
376+ restored = type(adapter)(recipe.model, str(tmp_path / "different-tokenizer"))
377+ dcp.save({"source": adapter}, checkpoint_id=tmp_path / "dcp")
378+ dcp.load({"source": restored}, checkpoint_id=tmp_path / "dcp")
379+ assert restored.state_dict() == adapter.state_dict()
380+ load_targets = adapter.to_hf(actual)
381+ assert vision not in load_targets and mtp not in load_targets
382+ with restored.export_hf():
383+ exported = restored.to_hf(actual)
384+ torch.testing.assert_close(exported[vision], torch.full((2, 3), 0.25))
385+ torch.testing.assert_close(exported[mtp], torch.full((2, 3), 0.5))
386+ 
387+ 
388+@pytest.mark.parametrize("layout", ["vision", "stacked", "separate"])
389+def test_qwen_offline_export_uses_dcp_layout(layout, monkeypatch, tmp_path):
390+ from torchtitan_npu.models import qwen3_5 as model_module
391+ from torchtitan_npu.tools.checkpoint_conversion.convert_to_hf import convert_to_hf
392+ 
393+ build_config = model_module.checkpoint_model_config
394+ 
395+ def compact(flavor, **kwargs):
396+ config = build_config(flavor, **kwargs)
397+ config.vocab_size = config.tok_embeddings.num_embeddings = config.lm_head.out_features = 32
398+ config.layers = config.layers[:1]
399+ return config
400+ 
401+ monkeypatch.setattr(model_module, "checkpoint_model_config", compact)
402+ config = compact("debugmodel", has_vision=layout == "vision", separate_gate_up=layout == "separate")
403+ with torch.device("cpu"):
404+ model = config.build()
405+ state = {key: torch.zeros_like(value) for key, value in model.state_dict().items()}
406+ state["tok_embeddings.weight"].fill_(0.125)
407+ vision_key = "model.visual.patch_embed.proj.weight"
408+ source = tmp_path / "original_hf"
409+ source.mkdir()
410+ hf_assets = tmp_path / "different_assets"
411+ if layout == "vision":
412+ state["vision_encoder.patch_embed.weight"].fill_(0.25)
413+ adapter = type(model).state_dict_adapter_cls(config, None)
414+ expected_index = {
415+ key: "model-00002-of-00002.safetensors" if key == vision_key else "model-00001-of-00002.safetensors"
416+ for key in adapter.to_hf(state)
417+ }
418+ hf_assets.mkdir()
419+ reference_index = {**expected_index, "mtp.fc.weight": expected_index[vision_key]}
420+ (hf_assets / "model.safetensors.index.json").write_text(json.dumps({"weight_map": reference_index}))
421+ else:
422+ save_file(
423+ {
424+ "model.language_model.embed_tokens.weight": state["tok_embeddings.weight"],
425+ vision_key: torch.full((2, 3), 0.5),
426+ },
427+ source / "model.safetensors",
428+ )
429+ adapter = type(model).state_dict_adapter_cls(config, None)
430+ adapter.prepare_hf_load(str(source))
431+ state["qwen_hf_source"] = adapter
432+ dcp.save(state, checkpoint_id=tmp_path / "input")
433+ 
434+ convert_to_hf(
435+ SimpleNamespace(
436+ input_dir=tmp_path / "input",
437+ output_dir=tmp_path / "output",
438+ model_name="qwen3_5",
439+ model_flavor="debugmodel",
440+ hf_assets_path=hf_assets,
441+ export_dtype="float32",
442+ ema_output=None,
443+ read_threads=1,
444+ )
445+ )
446+ exported = {}
447+ for shard in (tmp_path / "output").glob("*.safetensors"):
448+ exported.update(load_file(shard))
449+ torch.testing.assert_close(exported["model.language_model.embed_tokens.weight"], state["tok_embeddings.weight"])
450+ if layout == "vision":
451+ index = json.loads((tmp_path / "output" / "model.safetensors.index.json").read_text())
452+ assert set(exported) == set(expected_index)
453+ assert index["weight_map"] == expected_index
454+ torch.testing.assert_close(exported[vision_key].flatten(1), state["vision_encoder.patch_embed.weight"])
455+ else:
456+ torch.testing.assert_close(exported[vision_key], torch.full((2, 3), 0.5))
@@ -0,0 +1,70 @@
1+# Qwen3.5 系列模型
2+ 
3+Qwen3.5 系列包括 Qwen3.5、Qwen3.6 和 Qwen3.8。同架构的官方权重使用同一套 SFT 入口。训练从各自的 HF 目录读取权重、tokenizer 和 chat template。以下用 27B 配方演示。
4+ 
5+## 1. 安装训练环境
6+ 
7+完成[基础安装](../../../docs/user-guides/installation.md)并加载 CANN 环境。在仓库根目录执行:
8+ 
9+```bash
10+python -m pip install 'jinja2>=3.1' 'transformers>=5.13,<6'
11+export CC="$ASCEND_HOME_PATH/tools/ccec_compiler/bin/bisheng" CCC_OVERRIDE_OPTIONS="# +-std=c++20"
12+```
13+ 
14+默认训练使用原生 Triton-Ascend GDN 和 CANN varlen attention。需要 FLA 时,按 [master 的安装指南](https://gitcode.com/cann/torchtitan-npu/blob/3734a27ed73012a0b190d394f23067147fc3dc07/torchtitan_npu/models/qwen3_5/README.md)在独立环境安装配套版本:
15+ 
16+```bash
17+python -m pip install --only-binary=:all: \
18+ 'flash-linear-attention==0.6.0' 'fla-core==0.6.0' \
19+ 'triton==3.6.0' 'triton-ascend==3.6.0.post2' 'transformers==5.22.1' 'tokenizers==0.23.2' \
20+ --extra-index-url=https://triton-ascend.osinfra.cn/pypi/simple
21+```
22+ 
23+## 2. 快速上手
24+ 
25+样本取自 Stanford Alpaca 2023 发布版的前 16 条。转换时将 `instruction` 和非空的 `input` 合并为 user 消息,将 `output` 写为 assistant 消息。该样本按 CC BY-NC 4.0 提供。[JSONL 样本](../../../tests/assets/qwen3_5/alpaca.jsonl) · [Stanford Alpaca 原始数据](https://github.com/tatsu-lab/stanford_alpaca/blob/f13496211289def0ff88ae673389ae14a818b4b3/alpaca_data.json) · [数据许可](https://creativecommons.org/licenses/by-nc/4.0/)
26+ 
27+在仓库根目录执行下面的命令,将模型路径换成官方 HF 权重所在目录,并用 `--output-dir` 指定本次短测的新输出目录。`--smoke-test` 执行一个优化步。
28+ 
29+```bash
30+bash examples/qwen3_5/run_qwen_sft.sh \
31+ --hf-assets-path /models/Qwen3.5-27B \
32+ --dataset-path tests/assets/qwen3_5/alpaca.jsonl \
33+ --output-dir ./outputs/qwen-alpaca-smoke \
34+ --smoke-test
35+```
36+ 
37+## 3. 启动训练并选择 loss mask
38+ 
39+```bash
40+bash examples/qwen3_5/run_qwen_sft.sh \
41+ --hf-assets-path /models/Qwen3.5-27B \
42+ --dataset-path /data/train.jsonl \
43+ --output-dir /outputs/qwen-sft \
44+ --loss-mask ignore_empty_think
45+```
46+ 
47+`ignore_empty_think` 可以直接配置,是 `default+ignore_empty_think` 的简写,也是省略 `--loss-mask` 时的行为。空 thinking 指模板生成的 `<think>\n\n</think>\n\n` 一类只有空白的块。处理器将屏蔽位置的标签设为 `-100`,对应内容作为输入上下文。
48+ 
49+- `--loss-mask ignore_empty_think` 选择所有有监督的 assistant 轮次,屏蔽空 thinking,监督真实推理、工具调用、答复及对应的 EOS。
50+- `--loss-mask last_round+ignore_empty_think` 把范围收至最后一条 user 后的 assistant 轮次。消息上的 `"loss": true` 或 `false` 可以覆盖轮次选择。
51+- `--loss-mask ignore_think_prefix` 只屏蔽 thinking 开始标签及其紧随的换行,推理正文与结束标签参与 loss。
52+- `--loss-mask ignore_think` 将整个 thinking 块作为上下文,监督工具调用、答复和 EOS。也可使用 `last_round+ignore_think`。
53+ 
54+下例包含多轮对话、推理和工具调用。用 `"loss": false` 将第一轮 assistant 消息保留为上下文。工具回执通过 `tool_call_id` 对应 `tool_calls` 中的调用。选择 `ignore_think` 时,`reasoning_content` 作为上下文,两次工具调用和最终答复参与 loss。
55+ 
56+```jsonl
57+{"tools":[{"type":"function","function":{"name":"get_temperature","description":"查询城市示例气温","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}],"messages":[{"role":"user","content":"报气温用什么单位?"},{"role":"assistant","content":"用摄氏度。","loss":false},{"role":"user","content":"查询上海和深圳的示例气温。"},{"role":"assistant","content":"","reasoning_content":"两个城市可以并行查询。","tool_calls":[{"id":"sh","type":"function","function":{"name":"get_temperature","arguments":{"city":"上海"}}},{"id":"sz","type":"function","function":{"name":"get_temperature","arguments":{"city":"深圳"}}}]},{"role":"tool","content":"上海测站返回 21 ℃","tool_call_id":"sh"},{"role":"tool","content":"深圳测站返回 29 ℃","tool_call_id":"sz"},{"role":"assistant","content":"上海 21 ℃,深圳 29 ℃。"}]}
58+```
59+ 
60+启用已安装的 FLA 时,追加 `--override torchtitan_npu.override.qwen3_5.fla.operators`。使用长上下文配方时,运行 `bash examples/qwen3_5/run_qwen_sft.sh --help` 查看配置列表。
61+ 
62+## 4. 定制模板、短测和导出
63+ 
64+自定义模板用 `--chat-template /data/team.jinja --loss-mask template`,在要监督的内容周围加 `{% generation %}…{% endgeneration %}`。只训练推理时标记非空推理正文,混训时给无推理的样本保留答复监督。使用模型自带 generation 标记时,移动边界即可。团队自定义工具格式应配套推理模板和解析器。
65+ 
66+已验证的 Qwen3.5 模板渲染最后一条 user 后的推理。需要较早轮次的推理时,复制该模板,将 assistant 分支条件改为 `loop.index0 > ns.last_query_index or reasoning_content`。已验证的 Qwen3.6 和 Qwen3.8 模板支持 `preserve_thinking`,训练用它保留历史推理。
67+ 
68+- 续训沿用原输出目录、训练配置、数据、模板和运行环境,使用 `--resume-step N` 指定步数。`--max-steps M` 截短时保存完整 DCP,目标步数必须大于已恢复步数。旧版本游标请使用原提交续训。
69+- 自定义 Python 配方用 `--module /jobs/config_registry.py --config train`。可导入的模型配方也能通过 `scripts/run_train.sh --module torchtitan_npu_recipes.models.qwen3_5 --config run_qwen3_5_4k` 启动。
70+- 正常训练结束时,配方可用 `checkpointer.last_save_in_hf = True`、`checkpointer.last_save_model_only = True` 和 `checkpointer.export_dtype = "bfloat16"` 导出。保留初始化所用的 HF 权重目录,续训后的导出也从该目录补齐未训练的辅助权重。推理目录使用同一步的 safetensors 及其索引,配上同源模型配置、tokenizer 和处理器文件。
@@ -6,13 +6,25 @@
6 6 
7# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.7# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
8 8 
9-from dataclasses import dataclass9+import hashlib
10+import json
11+from contextlib import contextmanager
12+from dataclasses import dataclass, replace
13+from pathlib import Path
14+from typing import Any, cast
10 15 
16+import torch
17+import torch.nn.functional as F
18+from safetensors import safe_open
11from torchtitan.config import derive19from torchtitan.config import derive
12from torchtitan.config.parallelism import ParallelismConfig20from torchtitan.config.parallelism import ParallelismConfig
13from torchtitan.config.transform import ModelConfigConverter21from torchtitan.config.transform import ModelConfigConverter
22+from torchtitan.models.common.decoder_sharding import colwise_sharding_config, residual_activation_placement
23+from torchtitan.models.common.feed_forward import DenseFeedForward, FeedForward
24+from torchtitan.models.common.linear import ColumnParallelLinear, Linear
14from torchtitan.models.qwen3_5 import build_model_config as _upstream_build_model_config25from torchtitan.models.qwen3_5 import build_model_config as _upstream_build_model_config
15from torchtitan.models.qwen3_5.model import Qwen35Model26from torchtitan.models.qwen3_5.model import Qwen35Model
27+from torchtitan.models.qwen3_5.state_dict_adapter import Qwen35StateDictAdapter
16 28 
17from torchtitan_npu.patches.torchtitan.models.qwen3_5 import (29from torchtitan_npu.patches.torchtitan.models.qwen3_5 import (
18 vision_encoder as _vision_patch,30 vision_encoder as _vision_patch,
@@ -21,6 +33,81 @@ from torchtitan_npu.patches.torchtitan.models.qwen3_5 import (
21_vision_patch.apply()33_vision_patch.apply()
22 34 
23 35 
36+class Qwen35TextStateDictAdapter(Qwen35StateDictAdapter):
37+ """Map Qwen text weights using the actual HF initialization checkpoint."""
38+ 
39+ def __init__(self, model_config: Qwen35Model.Config, hf_assets_path: str | None):
40+ if model_config.vision_encoder is not None:
41+ raise ValueError("The text checkpoint adapter requires vision_encoder=None.")
42+ # The tokenizer assets can live outside the HF weight directory.
43+ super().__init__(model_config, None)
44+ self._source: dict[str, str] = {"path": "", "layout": ""}
45+ self._export_auxiliary = False
46+ self._auxiliary: dict[str, str] = {}
47+ 
48+ def prepare_hf_load(self, path: str) -> None:
49+ root = Path(path)
50+ index = root / "model.safetensors.index.json"
51+ if index.is_file():
52+ weight_map = json.loads(index.read_text())["weight_map"]
53+ if not isinstance(weight_map, dict):
54+ raise ValueError(f"Invalid Qwen HF weight index: {index}")
55+ else:
56+ single = root / "model.safetensors"
57+ with safe_open(single, framework="pt", device="cpu") as shard:
58+ weight_map = dict.fromkeys(shard.keys(), single.name)
59+ 
60+ has_text = "model.embed_tokens.weight" in weight_map
61+ has_conditional = "model.language_model.embed_tokens.weight" in weight_map
62+ if has_text == has_conditional:
63+ raise ValueError(f"Expected exactly one Qwen language-model prefix in {root}")
64+ layout = hashlib.sha256(json.dumps(weight_map, sort_keys=True).encode()).hexdigest()
65+ if self._source["path"] == str(root) and self._source["layout"] != layout:
66+ raise ValueError(f"Qwen HF weight layout changed at {root}")
67+ 
68+ # Reuse upstream's index and native-to-HF key mapping for this source.
69+ model_config = cast("Qwen35Model.Config", self.model_config)
70+ super().__init__(model_config, str(root) if index.is_file() else None)
71+ if has_conditional:
72+ self.hf_language_model_prefix = "model.language_model"
73+ self.from_hf_map = {
74+ key.replace("model.", "model.language_model.", 1) if key.startswith("model.") else key: value
75+ for key, value in self.from_hf_map.items()
76+ }
77+ self._source = {"path": str(root), "layout": layout}
78+ auxiliary_prefixes = ("model.visual.", "mtp.")
79+ self._auxiliary = {key: filename for key, filename in weight_map.items() if key.startswith(auxiliary_prefixes)}
80+ 
81+ def state_dict(self) -> dict[str, str]:
82+ return self._source.copy()
83+ 
84+ def load_state_dict(self, state_dict: dict[str, str]) -> None:
85+ self._source = state_dict.copy()
86+ 
87+ @contextmanager
88+ def export_hf(self, *, fallback_path: str | None = None):
89+ path = self._source["path"] or fallback_path
90+ if not path:
91+ raise ValueError("Qwen HF export requires the original HF weight source in the checkpoint.")
92+ self.prepare_hf_load(path)
93+ self._export_auxiliary = True
94+ try:
95+ yield
96+ finally:
97+ self._export_auxiliary = False
98+ 
99+ def to_hf(self, state_dict: dict[str, Any], *, to_quantized_layout: bool = False) -> dict[str, Any]:
100+ converted = super().to_hf(state_dict, to_quantized_layout=to_quantized_layout)
101+ if self._export_auxiliary:
102+ root = Path(self._source["path"])
103+ for filename in sorted(set(self._auxiliary.values())):
104+ with safe_open(root / filename, framework="pt", device="cpu") as shard:
105+ for key, source in self._auxiliary.items():
106+ if source == filename and key not in converted:
107+ converted[key] = shard.get_tensor(key)
108+ return converted
109+ 
110+ 
24class NPUQwen35Model(Qwen35Model):111class NPUQwen35Model(Qwen35Model):
25 @dataclass(kw_only=True, slots=True)112 @dataclass(kw_only=True, slots=True)
26 class Config(Qwen35Model.Config):113 class Config(Qwen35Model.Config):
@@ -35,18 +122,6 @@ class NPUQwen35Model(Qwen35Model):
35 kwargs.setdefault("special_tokens", {"image_id": -1, "video_id": -1})122 kwargs.setdefault("special_tokens", {"image_id": -1, "video_id": -1})
36 return super().forward(*args, **kwargs)123 return super().forward(*args, **kwargs)
37 124 
38- def parallelize(self, **kwargs):
39- from torchtitan_npu.models.common.compile_policy import parallelize_with_model_compile
40- 
41- return parallelize_with_model_compile(self, **kwargs)
42- 
43- def apply_model_compile(self, model_compile):
44- from torchtitan_npu.models.common.compile_policy import compile_transformer_blocks
45- from torchtitan_npu.override.qwen3_5.parallelize import _qwen_aot_eager_compile_options
46- 
47- with _qwen_aot_eager_compile_options(model_compile.backend):
48- compile_transformer_blocks(self, model_compile)
49- 
50 def _apply_fsdp(self, **kwargs):125 def _apply_fsdp(self, **kwargs):
51 from torchtitan_npu.override.qwen3_5.parallelize import apply_qwen3_5_npu_fsdp126 from torchtitan_npu.override.qwen3_5.parallelize import apply_qwen3_5_npu_fsdp
52 127 
@@ -70,3 +145,81 @@ def model_registry(
70 converters=converters,145 converters=converters,
71 )146 )
72 return derive(config, NPUQwen35Model.Config)147 return derive(config, NPUQwen35Model.Config)
148+ 
149+ 
150+def checkpoint_model_config(flavor: str, *, has_vision: bool, separate_gate_up: bool) -> NPUQwen35Model.Config:
151+ """Build the weight layout present in a Qwen DCP for offline export."""
152+ from torchtitan.models.common.attention.gdn import GDN, InnerGDN
153+ 
154+ from torchtitan_npu.override.qwen3_5.gated_delta import npu
155+ 
156+ model = model_registry(flavor, parallelism=ParallelismConfig())
157+ if not has_vision:
158+ model = derive(model, Qwen35TextModel.Config, text_only=True, vision_encoder=None)
159+ if separate_gate_up:
160+ split_gate_up(model, enable_sequence_parallel=True)
161+ for _, attention, _, _ in model.traverse(GDN.Config):
162+ if isinstance(attention.inner_attention, InnerGDN.Config):
163+ attention.inner_attention = npu(attention.inner_attention)
164+ return model
165+ 
166+ 
167+class _SeparateGateUp(FeedForward):
168+ @dataclass(kw_only=True, slots=True)
169+ class Config(FeedForward.Config):
170+ w1: Linear.Config
171+ w2: Linear.Config
172+ w3: Linear.Config
173+ 
174+ def __init__(self, config: Config):
175+ super().__init__()
176+ self.w1 = config.w1.build()
177+ self.w2 = config.w2.build()
178+ self.w3 = config.w3.build()
179+ 
180+ def forward(self, x: torch.Tensor) -> torch.Tensor:
181+ return self.w2(F.silu(self.w1(x)) * self.w3(x))
182+ 
183+ 
184+def split_gate_up(model: NPUQwen35Model.Config, *, enable_sequence_parallel: bool) -> None:
185+ """Use separate gate and up parameters with the master FFN layout."""
186+ for layer in model.layers:
187+ ffn = layer.feed_forward
188+ if not isinstance(ffn, DenseFeedForward.Config) or ffn.w13.num_linears != 2:
189+ raise ValueError("The Qwen master FFN layout requires two dense gate/up projections.")
190+ projection = ColumnParallelLinear.Config(
191+ in_features=ffn.w13.in_features,
192+ out_features=ffn.w13.out_features,
193+ param_init=ffn.w2.param_init,
194+ sharding_config=colwise_sharding_config(
195+ input_layout=residual_activation_placement(enable_sp=enable_sequence_parallel)
196+ ),
197+ inplace_wgrad_accum=False,
198+ )
199+ layer.feed_forward = _SeparateGateUp.Config(
200+ w1=projection, w2=ffn.w2, w3=replace(projection), sharding_config=ffn.sharding_config
201+ )
202+ 
203+ 
204+class Qwen35TextModel(NPUQwen35Model):
205+ """Keep the native model and select its text-checkpoint adapter explicitly."""
206+ 
207+ state_dict_adapter_cls = Qwen35TextStateDictAdapter
208+ 
209+ @dataclass(kw_only=True, slots=True)
210+ class Config(NPUQwen35Model.Config):
211+ pass
212+ 
213+ def __init__(self, config: Config):
214+ if config.vision_encoder is not None:
215+ raise ValueError("The text model requires vision_encoder=None.")
216+ super().__init__(config)
217+ 
218+ def parallelize(self, **kwargs):
219+ context, parallelism = kwargs["parallelism_context"], kwargs["parallelism"]
220+ if context.cp_enabled:
221+ if context.tp_enabled or context.ep_enabled:
222+ raise NotImplementedError("Qwen NPU head exchange requires TP1 and EP1.")
223+ if parallelism.context_parallel_load_balancer is not None:
224+ raise ValueError("Qwen NPU head exchange requires contiguous CP sharding without a load balancer.")
225+ return super().parallelize(**kwargs)
@@ -0,0 +1,366 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+# SPDX-License-Identifier: BSD-3-Clause
3+ 
4+"""Raw Qwen text and tool conversations with supervision on the rendered tokens."""
5+ 
6+import json
7+import re
8+from dataclasses import dataclass
9+from itertools import groupby
10+from pathlib import Path
11+from threading import Lock
12+from typing import TYPE_CHECKING, Any, cast
13+ 
14+import numpy as np
15+from jinja2 import nodes
16+from torchtitan.components.data import SampleProcessor, TextSequence
17+from torchtitan.components.loss import IGNORE_INDEX
18+from torchtitan.components.tokenizer import HuggingFaceTokenizer
19+ 
20+if TYPE_CHECKING:
21+ from transformers import PreTrainedTokenizerBase
22+ 
23+DEFAULT_LOSS_MASK = "default+ignore_empty_think"
24+_MASK_SCOPES = ("default", "last_round", "template", "last-assistant")
25+_THINK_MASKS = ("ignore_empty_think", "ignore_think_prefix", "ignore_think")
26+_HEADER, _STOP = "<|im_start|>assistant\n", "<|im_end|>"
27+_THINK, _THINK_END = "<think>", "</think>"
28+_TEMPLATE_LOCK = Lock() # Transformers caches one stateful assistant tracker per template.
29+_BEGIN = "\x00qwen-assistant-begin\x00"
30+_END = "\x00qwen-assistant-end\x00"
31+ 
32+ 
33+GENERATION_BLOCK = re.compile(r"\{%[-+]?\s*generation\s*[-+]?%\}")
34+ 
35+ 
36+class QwenSFTTokenizer(HuggingFaceTokenizer):
37+ @dataclass(kw_only=True, slots=True)
38+ class Config(HuggingFaceTokenizer.Config):
39+ pass
40+ 
41+ def set_chat_template(self, template: str) -> None:
42+ if GENERATION_BLOCK.search(template):
43+ from transformers.utils.chat_template_utils import _compile_jinja_template
44+ 
45+ self._chat_template = _compile_jinja_template(template)
46+ else:
47+ super().set_chat_template(template)
48+ 
49+ 
50+def assistant_turn_supervision(messages: list[dict[str, Any]], *, last_round: bool) -> list[bool]:
51+ last_user = (
52+ max((index for index, turn in enumerate(messages) if turn.get("role") == "user"), default=-1)
53+ if last_round
54+ else -1
55+ )
56+ keep = []
57+ for index, turn in enumerate(messages):
58+ if turn.get("role") == "assistant":
59+ loss = turn.get("loss")
60+ keep.append(index >= last_user if loss is None else loss)
61+ return keep
62+ 
63+ 
64+def _order_tool_results(messages):
65+ ordered = []
66+ for is_result, group in groupby(messages, key=lambda message: message["role"] == "tool"):
67+ if not is_result:
68+ ordered.extend(group)
69+ continue
70+ results = {message["tool_call_id"]: message for message in group}
71+ preceding = ordered[-1] if ordered else {}
72+ calls = (preceding.get("tool_calls") or []) if preceding.get("role") == "assistant" else []
73+ count = len(results)
74+ call_ids = [call["id"] for call in calls[:count]]
75+ if results.keys() != set(call_ids):
76+ raise ValueError("Tool results must follow their assistant call batch and identify a prefix of that batch")
77+ ordered.extend(results[call_id] for call_id in call_ids)
78+ return ordered
79+ 
80+ 
81+def _messages(row):
82+ raw = row.get("messages") if isinstance(row, dict) else None
83+ if not isinstance(raw, list) or not raw:
84+ raise ValueError("Qwen SFT requires a JSONL row with a nonempty messages list")
85+ messages = []
86+ call_ids = set()
87+ pending_ids = set()
88+ for turn in raw:
89+ if not isinstance(turn, dict) or turn.get("role") not in ("system", "user", "assistant", "tool"):
90+ raise ValueError("Qwen SFT expects system, user, assistant or tool messages")
91+ message = dict(turn)
92+ content = message.get("content")
93+ if isinstance(content, list):
94+ if not all(isinstance(part, dict) and isinstance(part.get("text"), str) for part in content):
95+ raise ValueError("The Qwen text SFT recipe requires text content")
96+ message["content"] = "".join(part["text"] for part in content)
97+ if message["role"] != "assistant" and not isinstance(message.get("content"), str):
98+ raise ValueError("System, user and tool messages require text content")
99+ if message.get("role") == "assistant":
100+ if "loss" in message and message["loss"] is not None and type(message["loss"]) is not bool:
101+ raise ValueError("Assistant loss must be true, false or null")
102+ for field in ("content", "reasoning_content"):
103+ value = message.get(field)
104+ if value is not None and not isinstance(value, str):
105+ raise ValueError(f"Expected text in assistant {field}")
106+ if value and (_THINK in value or _THINK_END in value):
107+ raise ValueError("Provide reasoning_content without thinking tags")
108+ if message.get("tool_calls") is not None:
109+ if not isinstance(message["tool_calls"], list):
110+ raise ValueError("Assistant tool_calls must be a list")
111+ calls = []
112+ for call in message["tool_calls"]:
113+ if not isinstance(call, dict) or call.get("type", "function") != "function":
114+ raise ValueError("Each tool call must describe a function")
115+ function = call.get("function")
116+ if not isinstance(function, dict):
117+ raise ValueError("Each tool call must describe a function")
118+ name = function.get("name")
119+ if not isinstance(name, str) or not name:
120+ raise ValueError("Each tool call must name a function")
121+ function = dict(function)
122+ args = function.get("arguments", {})
123+ if isinstance(args, str):
124+ args = json.loads(args) if args.strip() else {}
125+ if not isinstance(args, dict):
126+ raise ValueError("Tool arguments must decode to a JSON object")
127+ function["arguments"] = args
128+ call_id = call.get("id")
129+ if not isinstance(call_id, str) or not call_id or call_id in call_ids:
130+ raise ValueError("Tool call IDs must be unique nonempty strings")
131+ call_ids.add(call_id)
132+ pending_ids.add(call_id)
133+ calls.append({**call, "function": function})
134+ message["tool_calls"] = calls
135+ elif message["role"] == "tool":
136+ result_id = message.get("tool_call_id")
137+ if not isinstance(result_id, str) or result_id not in pending_ids:
138+ raise ValueError("Tool result must identify a matching preceding call")
139+ pending_ids.remove(result_id)
140+ messages.append(message)
141+ if messages[-1]["role"] not in ("assistant", "tool"):
142+ raise ValueError("Qwen SFT conversations must end with an assistant or tool message")
143+ return _order_tool_results(messages) if call_ids != pending_ids else messages
144+ 
145+ 
146+@dataclass(frozen=True, slots=True)
147+class _AssistantSpan:
148+ body_start: int
149+ target_start: int
150+ end: int
151+ masked_think_end: int | None
152+ 
153+ 
154+def _assistant_range(turn, offset, think_mask):
155+ if not turn.startswith(_HEADER) or not turn.rstrip().endswith(_STOP):
156+ raise ValueError("Expected Qwen assistant framing; use --loss-mask template for other framing")
157+ body = start = len(_HEADER)
158+ end = len(turn.rstrip())
159+ masked_think_end = None
160+ if turn.startswith(_THINK, body):
161+ start += len(_THINK)
162+ closing = turn.find(_THINK_END, start, end)
163+ if closing < 0:
164+ raise ValueError("Assistant thinking has no closing tag")
165+ reasoning = turn[start:closing]
166+ start += len(reasoning) - len(reasoning.lstrip("\n"))
167+ if think_mask == "ignore_think_prefix":
168+ masked_think_end = offset + start
169+ elif think_mask == "ignore_think" or (think_mask == "ignore_empty_think" and not reasoning.strip()):
170+ after_think = closing + len(_THINK_END)
171+ masked_think_end = offset + end - len(turn[after_think:end].lstrip("\n"))
172+ return _AssistantSpan(offset + body, offset + start, offset + end, masked_think_end)
173+ 
174+ 
175+def _instrument(template):
176+ # The Blueown loader locates assistant turns at the official Jinja message
177+ # loop so that literal ChatML examples in code or tool results stay context.
178+ from transformers.utils.chat_template_utils import _compile_jinja_template
179+ 
180+ env = _compile_jinja_template(template).environment
181+ tree = env.parse(template)
182+ loops = [
183+ node
184+ for node in tree.find_all(nodes.For)
185+ if isinstance(node.iter, nodes.Name)
186+ and node.iter.name == "messages"
187+ and isinstance(node.target, nodes.Name)
188+ and node.target.name == "message"
189+ ]
190+ if len(loops) != 1:
191+ raise ValueError("Expected the Qwen message loop; use --loss-mask template for custom framing")
192+ 
193+ def mark(value):
194+ assistant = nodes.Compare(
195+ nodes.Getattr(nodes.Name("message", "load"), "role", "load"),
196+ [nodes.Operand("eq", nodes.Const("assistant"))],
197+ )
198+ return nodes.If(assistant, [nodes.Output([nodes.Const(value)])], [], [])
199+ 
200+ loop = loops[0]
201+ loop.body = [mark(_BEGIN), *loop.body, mark(_END)]
202+ return env.template_class.from_code(env, env.compile(tree), env.globals, None)
203+ 
204+ 
205+def _strip_markers(marked, count, think_mask):
206+ parts = marked.split(_BEGIN)
207+ if len(parts) != count + 1 or _END in parts[0]:
208+ raise ValueError("Assistant boundaries differ from the input conversation")
209+ clean = [parts[0]]
210+ ranges = []
211+ offset = len(parts[0])
212+ for part in parts[1:]:
213+ if part.count(_END) != 1:
214+ raise ValueError("Invalid assistant template boundary")
215+ turn, rest = part.split(_END)
216+ ranges.append(_assistant_range(turn, offset, think_mask))
217+ clean.extend((turn, rest))
218+ offset += len(turn) + len(rest)
219+ return "".join(clean).rstrip("\n"), ranges
220+ 
221+ 
222+def _tokens_in_spans(offsets, spans, *, overlap=False):
223+ keep = np.zeros(len(offsets), dtype=np.bool_)
224+ span = 0
225+ for index, (start, end) in enumerate(offsets):
226+ while span < len(spans) and start >= spans[span][1]:
227+ span += 1
228+ if span < len(spans) and end > start:
229+ low, high = spans[span]
230+ keep[index] = end > low if overlap else start >= low and end <= high
231+ return keep
232+ 
233+ 
234+class QwenSFTChatProcessor(SampleProcessor):
235+ @dataclass(kw_only=True, slots=True)
236+ class Config(SampleProcessor.Config):
237+ chat_template: str | None = None
238+ loss_mask: str = DEFAULT_LOSS_MASK
239+ 
240+ def __post_init__(self):
241+ if self.loss_mask == "thinking-safe":
242+ self.loss_mask = DEFAULT_LOSS_MASK
243+ elif self.loss_mask == "last-assistant":
244+ self.loss_mask = "last-assistant+ignore_empty_think"
245+ elif self.loss_mask in _THINK_MASKS:
246+ self.loss_mask = f"default+{self.loss_mask}"
247+ scope, separator, modifier = self.loss_mask.partition("+")
248+ if scope not in _MASK_SCOPES or (separator and modifier not in _THINK_MASKS):
249+ raise ValueError(
250+ "Use --loss-mask default, last_round, template or a thinking modifier "
251+ "(ignore_empty_think, ignore_think_prefix, ignore_think). Join scope and modifier with '+'."
252+ )
253+ 
254+ def __init__(self, config, *, context):
255+ from transformers import AutoTokenizer
256+ 
257+ self.tokenizer = cast(
258+ "PreTrainedTokenizerBase",
259+ AutoTokenizer.from_pretrained(context.tokenizer.tokenizer_path, local_files_only=True),
260+ )
261+ self.backend = context.tokenizer.tokenizer
262+ self.eos_id = context.tokenizer.eos_id
263+ if not self.tokenizer.is_fast or self.eos_id != self.tokenizer.eos_token_id:
264+ raise ValueError("Qwen SFT requires the matching fast HF tokenizer")
265+ self.max_length = context.max_context_length
266+ self.loss_mask = config.loss_mask
267+ self.policy, _, self.think_mask = config.loss_mask.partition("+")
268+ self.template = (
269+ self.tokenizer.get_chat_template()
270+ if config.chat_template is None
271+ else Path(config.chat_template).read_text(encoding="utf-8")
272+ )
273+ self.use_generation_mask = self.policy == "template" and bool(GENERATION_BLOCK.search(self.template))
274+ if self.policy == "template" and config.chat_template is not None and not self.use_generation_mask:
275+ raise ValueError("--loss-mask template requires Hugging Face generation blocks in a custom template")
276+ self.instrumented = _instrument(self.template) if not self.use_generation_mask or self.think_mask else None
277+ 
278+ def __call__(self, row, rng):
279+ del rng
280+ messages = _messages(row)
281+ tools = row.get("tools")
282+ if tools is not None and (
283+ not isinstance(tools, list)
284+ or any(
285+ not isinstance(tool, dict)
286+ or tool.get("type") != "function"
287+ or not isinstance(tool.get("function"), dict)
288+ for tool in tools
289+ )
290+ ):
291+ raise ValueError("Qwen tools must be a list of function definitions")
292+ options = dict(tools=tools, add_generation_prompt=False, preserve_thinking=True, enable_thinking=True)
293+ if self.use_generation_mask:
294+ ids, keep = self._template_mask(messages, options)
295+ else:
296+ ids, keep = self._span_mask(messages, options)
297+ ids = np.asarray(ids, dtype=np.int64)
298+ keep = np.asarray(keep, dtype=np.bool_)
299+ if len(ids) - 1 > self.max_length or not keep[1:].any():
300+ return None
301+ # As in MindSpeed, context and targets share the input axis. TorchTitan
302+ # expects prediction alignment at the processor boundary, before packing.
303+ return TextSequence(input_ids=ids[:-1], labels=np.where(keep[1:], ids[1:], IGNORE_INDEX))
304+ 
305+ def _assistant_encoding(self, messages, options, count):
306+ if self.instrumented is None:
307+ raise RuntimeError("Assistant boundaries require an instrumented template")
308+ with _TEMPLATE_LOCK:
309+ marked = self.instrumented.render(
310+ messages=messages,
311+ documents=None,
312+ **self.tokenizer.special_tokens_map,
313+ **options,
314+ )
315+ rendered, ranges = _strip_markers(marked, count, self.think_mask)
316+ return self.backend.encode(rendered, add_special_tokens=False), ranges
317+ 
318+ def _span_mask(self, messages, options):
319+ if self.policy == "template":
320+ # Older official templates emit the same assistant framing without
321+ # HF generation blocks. Supervise the rendered body and EOS.
322+ keep = [True for turn in messages if turn["role"] == "assistant"]
323+ else:
324+ keep = assistant_turn_supervision(messages, last_round=self.policy == "last_round")
325+ encoded, ranges = self._assistant_encoding(messages, options, len(keep))
326+ spans = []
327+ for index, (selected, span) in enumerate(zip(keep, ranges, strict=True)):
328+ if not selected or (self.policy == "last-assistant" and index != len(keep) - 1):
329+ continue
330+ start = span.body_start if self.policy == "template" else span.target_start
331+ spans.append((span.masked_think_end if span.masked_think_end is not None else start, span.end))
332+ return encoded.ids, _tokens_in_spans(encoded.offsets, spans)
333+ 
334+ def _template_mask(self, messages, options):
335+ with _TEMPLATE_LOCK:
336+ encoded = self.tokenizer.apply_chat_template(
337+ messages,
338+ **options,
339+ chat_template=self.template,
340+ tokenize=True,
341+ return_dict=True,
342+ return_assistant_tokens_mask=True,
343+ )
344+ # return_dict=True selects the mapping form of the Hugging Face API.
345+ batch = cast("dict[str, list[int]]", encoded)
346+ ids, keep = batch["input_ids"], batch["assistant_masks"]
347+ if len(ids) != len(keep):
348+ raise ValueError("The chat template must return one mask entry per token")
349+ while ids and ids[-1] != self.eos_id and not cast("str", self.tokenizer.decode([ids[-1]])).strip():
350+ ids.pop()
351+ keep.pop()
352+ if not ids or ids[-1] != self.eos_id:
353+ raise ValueError("The custom chat template must end with Qwen EOS")
354+ if self.think_mask:
355+ count = sum(turn["role"] == "assistant" for turn in messages)
356+ qwen, ranges = self._assistant_encoding(messages, options, count)
357+ if qwen.ids != ids:
358+ raise ValueError("Thinking masks require matching Qwen and HF template tokenization")
359+ thinking = []
360+ for span in ranges:
361+ if span.masked_think_end is not None:
362+ thinking.append((span.body_start, span.masked_think_end))
363+ keep = np.asarray(keep, dtype=np.bool_) & ~_tokens_in_spans(
364+ qwen.offsets, thinking, overlap=self.think_mask != "ignore_empty_think"
365+ )
366+ return ids, keep
@@ -1,31 +1,362 @@
1# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.1# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2-#2+# Copyright (c) Meta Platforms, Inc. and affiliates.
3-# This source code is licensed under the BSD-style license found in the3+# SPDX-License-Identifier: BSD-3-Clause
4-# LICENSE file in the root directory of this source tree.
5 4 
5+"""Composable native Grain nodes and a narrow resume compatibility guard."""
6 6 
7-from typing import TYPE_CHECKING, Any, cast7+import hashlib
8+import importlib
9+import importlib.metadata
10+import json
11+import socket
12+import sys
13+from dataclasses import dataclass, fields, replace
14+from glob import escape
15+from pathlib import Path
16+from typing import TYPE_CHECKING, Any, cast, overload
17+ 
18+import grain.python as grain
19+import torch.distributed as dist
20+from torchtitan.components.data import (
21+ FirstFitPackingConfig,
22+ GrainDataLoader,
23+ IndexedJsonlSource,
24+ SingleDatasetConfig,
25+)
26+from torchtitan.components.data.sources import _file_patterns_to_paths
27+from torchtitan.components.loss import IGNORE_INDEX
28+from torchtitan.components.tokenizer import HuggingFaceTokenizer
29+from torchtitan.config import derive, override
30+ 
31+from . import chat_processor
8 32 
9if TYPE_CHECKING:33if TYPE_CHECKING:
10 from renderers import Message34 from renderers import Message
11 35 
12 36 
37+def digest(value):
38+ return hashlib.sha256(
39+ json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
40+ ).hexdigest()
41+ 
42+ 
43+def file_digest(path):
44+ result = hashlib.sha256()
45+ with Path(path).open("rb") as stream:
46+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
47+ result.update(chunk)
48+ return result.hexdigest()
49+ 
50+ 
51+def chat_processor_digest():
52+ return digest([file_digest(chat_processor.__file__)])
53+ 
54+ 
55+def tokenizer_identity(tokenizer, assets_path, *, chat_template=None):
56+ """Bind files and effective template/tokenizer behavior without dataset re-tokenization."""
57+ root = Path(assets_path)
58+ names = (
59+ "tokenizer.json",
60+ "tokenizer_config.json",
61+ "special_tokens_map.json",
62+ "added_tokens.json",
63+ "chat_template.jinja",
64+ "tokenizer.model",
65+ "vocab.json",
66+ "merges.txt",
67+ )
68+ files = {name: file_digest(root / name) for name in names if (root / name).is_file()}
69+ if not files:
70+ raise ValueError("Tokenizer assets must contain tokenizer/template files")
71+ probes = [
72+ [{"role": "user", "content": "Question?中文"}, {"role": "assistant", "content": "Answer."}],
73+ [
74+ {"role": "system", "content": "System"},
75+ {"role": "user", "content": "First"},
76+ {"role": "assistant", "content": "A", "reasoning_content": "Reason"},
77+ {"role": "user", "content": "Next"},
78+ {"role": "assistant", "content": "B"},
79+ ],
80+ ]
81+ if chat_template is None:
82+ rendered = [tokenizer.apply_chat_template(messages) for messages in probes]
83+ else:
84+ # The processor renders external templates with the actual conversation and tools.
85+ # Its template bytes are recorded separately. Probe only the tokenizer here.
86+ rendered = []
87+ for messages in probes:
88+ for message in messages:
89+ rendered.append(message["content"])
90+ encoded = [tokenizer.encode(text, add_bos=True, add_eos=False) for text in rendered]
91+ backend = getattr(tokenizer, "tokenizer", None)
92+ backend_identity = digest(json.loads(backend.to_str())) if hasattr(backend, "to_str") else None
93+ versions = {}
94+ for name in ("tokenizers", "jinja2"):
95+ try:
96+ versions[name] = importlib.metadata.version(name)
97+ except importlib.metadata.PackageNotFoundError:
98+ versions[name] = None
99+ encode_code = getattr(tokenizer.encode, "__code__", None)
100+ provider = Path(encode_code.co_filename) if encode_code is not None else None
101+ return {
102+ "files": files,
103+ "eos_id": tokenizer.eos_id,
104+ "behavior": digest(encoded),
105+ "backend": backend_identity,
106+ "versions": versions,
107+ "provider_sha256": file_digest(provider) if provider and provider.is_file() else None,
108+ }
109+ 
110+ 
111+def _tokenizer_contract(identity):
112+ return {key: identity[key] for key in ("files", "eos_id", "behavior")}
113+ 
114+ 
115+class _TrainableShard(grain.MapDataset):
116+ """Bound filtered reads while retaining Grain's map indices and cursor."""
117+ 
118+ def __init__(self, parent, *, dp_rank, dp_world_size, context_length, shuffle):
119+ super().__init__(parent)
120+ self._shard = parent
121+ self._size = len(parent)
122+ self._search_size = self._size * (4 if shuffle else 1)
123+ self._description = f"Qwen SFT DP rank {dp_rank}/{dp_world_size} at context length {context_length}"
124+ self._first_index, self._first_sample = self._first_trainable(0)
125+ 
126+ def _first_trainable(self, start):
127+ for index in range(start, start + self._search_size):
128+ sample = self._shard[index]
129+ if sample is not None:
130+ return index, sample
131+ raise ValueError(f"{self._description}: no trainable samples in {self._search_size} consecutive rows")
132+ 
133+ def __len__(self):
134+ return self._size
135+ 
136+ @overload
137+ def __getitem__(self, index: slice) -> grain.MapDataset:
138+ """Return a view of a range of rows."""
139+ 
140+ @overload
141+ def __getitem__(self, index: int) -> Any:
142+ """Return the sampled row at an absolute index."""
143+ 
144+ def __getitem__(self, index: int | slice):
145+ if isinstance(index, slice):
146+ return self.slice(index)
147+ if index < 0:
148+ index %= self._size
149+ if index < self._first_index:
150+ return None
151+ if index == self._first_index:
152+ return self._first_sample
153+ sample = self._shard[index]
154+ # A shuffled repeat can have an empty shard in a later epoch too.
155+ if sample is None and index % self._size == 0:
156+ self._first_trainable(index)
157+ return sample
158+ 
159+ 
160+@dataclass(frozen=True, kw_only=True, slots=True)
161+class _QwenRawDataset(SingleDatasetConfig):
162+ def build(self, *, context, dataset_iteration_policy):
163+ if not dataset_iteration_policy.repeat:
164+ return SingleDatasetConfig.build(self, context=context, dataset_iteration_policy=dataset_iteration_policy)
165+ shard = SingleDatasetConfig.build(
166+ self, context=context, dataset_iteration_policy=replace(dataset_iteration_policy, repeat=False)
167+ )
168+ return _TrainableShard(
169+ shard,
170+ dp_rank=dataset_iteration_policy.dp_rank,
171+ dp_world_size=dataset_iteration_policy.dp_world_size,
172+ context_length=context.max_context_length,
173+ shuffle=dataset_iteration_policy.shuffle,
174+ ).repeat()
175+ 
176+ 
177+def _check_rank_inputs(fingerprints: dict[str, str] | None, error: Exception | None = None):
178+ if not dist.is_initialized() or dist.get_world_size() == 1 or dist.get_backend() == "fake":
179+ return
180+ ranks: list[tuple[str, dict[str, str], str | None]] = [("", {}, None)] * dist.get_world_size()
181+ failure = None if error is None else f"{type(error).__name__}: {error}"
182+ dist.all_gather_object(ranks, (socket.gethostname(), fingerprints or {}, failure))
183+ errors = [f"rank {rank} ({host}): {reason}" for rank, (host, _, reason) in enumerate(ranks) if reason is not None]
184+ if errors:
185+ raise ValueError("Qwen SFT dataloader startup failed: " + "; ".join(errors))
186+ 
187+ reference = ranks[0][1]
188+ mismatches = []
189+ for rank, (host, inputs, _) in enumerate(ranks[1:], start=1):
190+ fields = sorted(key for key in inputs.keys() | reference.keys() if inputs.get(key) != reference.get(key))
191+ if fields:
192+ mismatches.append(f"rank {rank} ({host}): {', '.join(fields)}")
193+ if mismatches:
194+ raise ValueError("Qwen SFT inputs differ from rank 0: " + "; ".join(mismatches))
195+ 
196+ 
197+class SFTGrainDataLoader(GrainDataLoader):
198+ """Delegate all iteration/state to Grain; guard the state input contract."""
199+ 
200+ @dataclass(kw_only=True, slots=True)
201+ class Config(GrainDataLoader.Config):
202+ input_contract: dict
203+ 
204+ def __init__(
205+ self, config, *, dp_rank, dp_world_size, tokenizer, max_context_length, num_tokens_per_microbatch, **kwargs
206+ ):
207+ try:
208+ contract = self._build_contract(
209+ config, dp_rank, dp_world_size, tokenizer, max_context_length, num_tokens_per_microbatch
210+ )
211+ super().__init__(
212+ config,
213+ dp_rank=dp_rank,
214+ dp_world_size=dp_world_size,
215+ tokenizer=tokenizer,
216+ max_context_length=max_context_length,
217+ num_tokens_per_microbatch=num_tokens_per_microbatch,
218+ **kwargs,
219+ )
220+ except Exception as error:
221+ _check_rank_inputs(None, error)
222+ raise
223+ 
224+ # Match data and tokenizer behavior across ranks. Keep runtime provenance in the saved cursor.
225+ shared = {key: digest(value) for key, value in contract.items() if key not in ("dp_rank", "input")}
226+ shared["versions"] = digest({key: contract["versions"][key] for key in ("grain", "torch", "torch-npu")})
227+ shared.update({key: digest(value) for key, value in contract["input"].items() if key != "transformers"})
228+ shared["tokenizer"] = digest(_tokenizer_contract(contract["input"]["tokenizer"]))
229+ try:
230+ _check_rank_inputs(shared)
231+ except Exception:
232+ self.close()
233+ raise
234+ self._contract_fingerprint = digest(contract)
235+ # Per-DP keys remain distinct when distributed DCP merges rank states.
236+ self._contract_key = f"qwen_sft_contract_dp_rank_{dp_rank}"
237+ 
238+ @staticmethod
239+ def _build_contract(config, dp_rank, dp_world_size, tokenizer, max_context_length, num_tokens_per_microbatch):
240+ expected = config.input_contract
241+ raw = expected.get("raw_source")
242+ patterns = expected.get("raw_patterns")
243+ template = expected["chat_template"]
244+ if raw is None and not patterns:
245+ raise ValueError("Provide Qwen SFT data with --dataset-path or DATA_FILES")
246+ files = [raw] if raw is not None else _file_patterns_to_paths(patterns)
247+ hashes = [file_digest(path) for path in files]
248+ expected = {
249+ "raw_sha256": hashes[0] if len(hashes) == 1 else digest(hashes),
250+ "template_sha256": file_digest(template) if template is not None else None,
251+ "loss_mask": expected["loss_mask"],
252+ "tokenizer": tokenizer_identity(tokenizer, tokenizer.tokenizer_path, chat_template=template),
253+ "processor_sha256": chat_processor_digest(),
254+ "transformers": importlib.metadata.version("transformers"),
255+ }
256+ versions = {}
257+ for name in ("grain", "torch", "torch-npu", "tokenizers", "jinja2"):
258+ try:
259+ versions[name] = importlib.metadata.version(name)
260+ except importlib.metadata.PackageNotFoundError:
261+ versions[name] = None
262+ upstream = {
263+ name: file_digest(importlib.import_module("torchtitan.components.data." + name).__file__)
264+ for name in ("loader", "dataset", "packing", "collators", "sources", "types")
265+ }
266+ return {
267+ "input": expected,
268+ "seed": config.seed,
269+ "shuffle": config.shuffle,
270+ "repeat": config.repeat,
271+ "context": max_context_length,
272+ "microbatch_tokens": num_tokens_per_microbatch,
273+ "dp_rank": dp_rank,
274+ "dp_world_size": dp_world_size,
275+ "max_num_documents": config.max_num_documents,
276+ "packing_bins": getattr(config.dataset, "num_packing_bins", None),
277+ "prefetch": config.num_prefetch_microbatches,
278+ "read_options": repr(config.read_options),
279+ "collator": {field.name: repr(getattr(config.collator, field.name)) for field in fields(config.collator)},
280+ "collator_type": type(config.collator).__module__ + "." + type(config.collator).__qualname__,
281+ "python": list(sys.version_info[:2]),
282+ "versions": versions,
283+ "upstream": upstream,
284+ "schema": "qwen.sft.loader.v2",
285+ }
286+ 
287+ def state_dict(self):
288+ return super().state_dict() | {self._contract_key: self._contract_fingerprint}
289+ 
290+ def load_state_dict(self, state_dict):
291+ if state_dict.get(self._contract_key) != self._contract_fingerprint:
292+ raise ValueError(
293+ "Incompatible Qwen Grain state: input, packing, topology, policy, runtime, or loader version"
294+ )
295+ super().load_state_dict(state_dict)
296+ 
297+ 
298+def _has_supervision(sample) -> bool:
299+ return sample is not None and bool((sample.labels != IGNORE_INDEX).any())
300+ 
301+ 
302+def raw_sft_dataset(
303+ *,
304+ dataset_path: str | None = None,
305+ patterns: tuple[str, ...] = (),
306+ chat_template: str | None = None,
307+ loss_mask: str = chat_processor.DEFAULT_LOSS_MASK,
308+) -> tuple[SingleDatasetConfig, dict[str, Any]]:
309+ """Build the same raw dataset for native recipes and command-line overrides."""
310+ processor = chat_processor.QwenSFTChatProcessor.Config(chat_template=chat_template, loss_mask=loss_mask)
311+ contract: dict[str, Any] = {"chat_template": chat_template, "loss_mask": processor.loss_mask}
312+ if dataset_path is None:
313+ contract["raw_patterns"] = patterns
314+ else:
315+ path = Path(dataset_path).resolve()
316+ contract["raw_source"] = str(path)
317+ patterns = (escape(str(path)),)
318+ dataset = _QwenRawDataset(
319+ source=IndexedJsonlSource.Config(patterns=patterns),
320+ processor=processor,
321+ post_filters=(_has_supervision,),
322+ )
323+ return dataset, contract
324+ 
325+ 
13def _messages(sample: dict[str, Any]) -> list["Message"]:326def _messages(sample: dict[str, Any]) -> list["Message"]:
14 return cast("list[Message]", sample["messages"])327 return cast("list[Message]", sample["messages"])
15 328 
16 329 
17-def _long_text_messages(sample: dict[str, Any]) -> list["Message"]:330+@override(target=HuggingFaceTokenizer.Config, fqns=["tokenizer"])
18- if "messages" in sample:331+def qwen_sft_tokenizer(_config: HuggingFaceTokenizer.Config) -> chat_processor.QwenSFTTokenizer.Config:
19- return cast("list[Message]", sample["messages"])332+ return chat_processor.QwenSFTTokenizer.Config()
20- if "prompt" in sample:333+ 
21- return cast(334+ 
22- "list[Message]",335+@override(target=GrainDataLoader.Config, fqns=["dataloader"])
23- [{"role": "user", "content": sample["prompt"]}, {"role": "assistant", "content": sample["response"]}],336+def chat_sft(
24- )337+ config: GrainDataLoader.Config,
25- user = sample["instruction"]338+ *,
26- if sample.get("input"):339+ dataset_path: str,
27- user = f"{user}\n\n{sample['input']}"340+ chat_template: str | None = None,
28- return cast(341+ loss_mask: str | None = None,
29- "list[Message]",342+) -> GrainDataLoader.Config:
30- [{"role": "user", "content": user}, {"role": "assistant", "content": sample["output"]}],343+ packing = config.dataset
344+ if (
345+ not isinstance(packing, FirstFitPackingConfig)
346+ or not isinstance(packing.dataset, SingleDatasetConfig)
347+ or not isinstance(packing.dataset.processor, chat_processor.QwenSFTChatProcessor.Config)
348+ ):
349+ raise ValueError("Select a Qwen raw SFT recipe for chat template and loss mask options")
350+ processor = packing.dataset.processor
351+ selected, input_contract = raw_sft_dataset(
352+ dataset_path=dataset_path,
353+ chat_template=chat_template if chat_template is not None else processor.chat_template,
354+ loss_mask=loss_mask if loss_mask is not None else processor.loss_mask,
355+ )
356+ dataset = replace(packing.dataset, source=selected.source, processor=selected.processor)
357+ return derive(
358+ config,
359+ SFTGrainDataLoader.Config,
360+ dataset=replace(packing, dataset=dataset),
361+ input_contract=input_contract,
31 )362 )
@@ -0,0 +1,211 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+# SPDX-License-Identifier: BSD-3-Clause
3+ 
4+"""Optional official FLA operators for Qwen's inner GDN."""
5+ 
6+from dataclasses import dataclass
7+from functools import lru_cache
8+from typing import TYPE_CHECKING, Any, cast
9+ 
10+import torch
11+import torch_remat as remat
12+from torchtitan.config import derive, override
13+from torchtitan.models.base.module import Module
14+from torchtitan.models.common.attention.attention import local_head_split
15+from torchtitan.models.common.attention.gdn import GDN, GDNKernel, InnerGDN
16+from torchtitan.models.common.linear import Linear, maybe_gather_tp_input
17+ 
18+try:
19+ from fla.modules.causal_conv1d import causal_conv1d # pyrefly: ignore [missing-import]
20+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule # pyrefly: ignore [missing-import]
21+except ImportError as error:
22+ raise ImportError(
23+ "Install the supported flash-linear-attention and fla-core packages to use the Qwen FLA override."
24+ ) from error
25+ 
26+from .gated_delta import AscContextParallelInnerGDN, AscInnerGDN
27+ 
28+if TYPE_CHECKING:
29+ from torchtitan.models.common.attention.linear_attention import LinearAttentionMetadata
30+ from torchtitan.trainer import Trainer
31+ 
32+ 
33+@lru_cache(maxsize=8)
34+def _packed_offsets(cu_seqlens: torch.Tensor | None):
35+ # The upstream model creates immutable offsets for each microbatch.
36+ if cu_seqlens is None:
37+ return None, None
38+ offsets_cpu = cu_seqlens.to(device="cpu", dtype=torch.int64).unique_consecutive()
39+ return offsets_cpu.to(cu_seqlens.device), offsets_cpu
40+ 
41+ 
42+class FLAGatedDeltaKernel(GDNKernel):
43+ @dataclass(kw_only=True, slots=True)
44+ class Config(GDNKernel.Config):
45+ force_fp32: bool = False
46+ 
47+ def __init__(self, config: Config):
48+ # Forward uses FLA directly, so it needs no Attention Gym kernels.
49+ Module.__init__(self)
50+ self.force_fp32 = config.force_fp32
51+ 
52+ # TorchTitan passes layout-specific tensors positionally.
53+ def forward( # pyrefly: ignore [bad-param-name-override]
54+ self, xq_thk, xk_thk, xv_thv, g_th, beta_th, *, cu_seqlens=None
55+ ):
56+ offsets, _ = _packed_offsets(cu_seqlens)
57+ inputs = (xq_thk, xk_thk, xv_thv, g_th, beta_th)
58+ if self.force_fp32:
59+ inputs = tuple(tensor.float() for tensor in inputs)
60+ gated_delta = cast("Any", chunk_gated_delta_rule)
61+ output, _ = gated_delta(
62+ *(tensor.unsqueeze(0) for tensor in inputs),
63+ use_qk_l2norm_in_kernel=True,
64+ cu_seqlens=offsets,
65+ chunk_size=64,
66+ )
67+ return output.squeeze(0).to(xv_thv.dtype)
68+ 
69+ 
70+def _convolution(x, weight, cu_seqlens, *, force_fp32: bool, preserve_stride: bool):
71+ dtype = x.dtype
72+ if force_fp32:
73+ x, weight = x.float(), weight.float()
74+ offsets, offsets_cpu = _packed_offsets(cu_seqlens)
75+ output, _ = cast("Any", causal_conv1d)(
76+ x=(x if preserve_stride else x.contiguous()).unsqueeze(0),
77+ weight=weight.squeeze(1),
78+ bias=None,
79+ activation="silu",
80+ backend="triton",
81+ cu_seqlens=offsets,
82+ cu_seqlens_cpu=offsets_cpu,
83+ )
84+ return output.squeeze(0).to(dtype)
85+ 
86+ 
87+class FLAInnerGDN(AscInnerGDN):
88+ @dataclass(kw_only=True, slots=True)
89+ class Config(AscInnerGDN.Config):
90+ causal_conv1d: bool = True
91+ force_fp32: bool = False
92+ preserve_conv_stride: bool = False
93+ 
94+ def __init__(self, config: Config):
95+ super().__init__(config)
96+ self.use_fla_convolution = config.causal_conv1d
97+ self.force_fp32 = config.force_fp32
98+ self.preserve_conv_stride = config.preserve_conv_stride
99+ 
100+ # InnerGDN passes the activation and weight positionally.
101+ def short_convolution( # pyrefly: ignore [bad-param-name-override]
102+ self, x_tc, weight_c1w, initial_state=None, *, cu_seqlens, routing
103+ ):
104+ if initial_state is not None or routing is not None or not self.use_fla_convolution:
105+ return super().short_convolution(x_tc, weight_c1w, initial_state, cu_seqlens=cu_seqlens, routing=routing)
106+ return _convolution(
107+ x_tc,
108+ weight_c1w,
109+ cu_seqlens,
110+ force_fp32=self.force_fp32,
111+ preserve_stride=self.preserve_conv_stride,
112+ )
113+ 
114+ 
115+class FLAContextParallelInnerGDN(AscContextParallelInnerGDN, FLAInnerGDN):
116+ """Reuse Qwen's packed CP8 exchange for single-node 64K and two-node 256K."""
117+ 
118+ @dataclass(kw_only=True, slots=True)
119+ class Config(AscContextParallelInnerGDN.Config, FLAInnerGDN.Config):
120+ pass
121+ 
122+ 
123+@override(
124+ target=InnerGDN.Config,
125+ fqns=["model.layers.*.attention.inner_attention"],
126+ description="Use official optional FLA operators for Qwen",
127+)
128+def operators(
129+ cfg: InnerGDN.Config, *, context_parallel: bool | None = None, causal_conv1d: bool = True, force_fp32: bool = False
130+) -> FLAInnerGDN.Config | FLAContextParallelInnerGDN.Config:
131+ uses_cp = isinstance(cfg, AscContextParallelInnerGDN.Config)
132+ if context_parallel is not None and context_parallel != uses_cp:
133+ raise ValueError("FLA context_parallel must match the Qwen recipe's GDN layout.")
134+ kernel = derive(cfg.kernel, FLAGatedDeltaKernel.Config, force_fp32=force_fp32)
135+ if uses_cp:
136+ return derive(
137+ cfg, FLAContextParallelInnerGDN.Config, kernel=kernel, causal_conv1d=causal_conv1d, force_fp32=force_fp32
138+ )
139+ return derive(cfg, FLAInnerGDN.Config, kernel=kernel, causal_conv1d=causal_conv1d, force_fp32=force_fp32)
140+ 
141+ 
142+@override(
143+ target=InnerGDN.Config,
144+ fqns=["model.layers.*.attention.inner_attention"],
145+ description="Use official FLA GDN and convolution with Qwen CP head exchange",
146+)
147+def context_parallel(cfg: InnerGDN.Config) -> FLAContextParallelInnerGDN.Config:
148+ if not isinstance(cfg, AscContextParallelInnerGDN.Config):
149+ raise ValueError("The Qwen FLA override requires a context-parallel GDN recipe.")
150+ result = operators(cfg, context_parallel=True)
151+ assert isinstance(result, FLAContextParallelInnerGDN.Config)
152+ return result
153+ 
154+ 
155+class _MasterOrderGDN(GDN):
156+ @dataclass(kw_only=True, slots=True)
157+ class Config(GDN.Config):
158+ pass
159+ 
160+ # Form the projection nodes in master's order for BF16 gradient accumulation.
161+ def forward( # pyrefly: ignore [bad-param-name-override]
162+ self, hidden_states: torch.Tensor, attention_metadata: "LinearAttentionMetadata | None" = None
163+ ) -> torch.Tensor:
164+ hidden_states = maybe_gather_tp_input(self, hidden_states)
165+ projections = (self.in_proj_q, self.in_proj_k, self.in_proj_v, self.in_proj_a, self.in_proj_b, self.in_proj_z)
166+ query, key, value, decay, beta, gate = (projection(hidden_states) for projection in projections)
167+ output = remat.region(
168+ self.inner_attention,
169+ self.remat_region_name("inner_attention"),
170+ recompute=self.remat_should_recompute("inner_attention"),
171+ )(
172+ query,
173+ key,
174+ value,
175+ decay,
176+ beta,
177+ self.conv_q.weight,
178+ self.conv_k.weight,
179+ self.conv_v.weight,
180+ self.A_log,
181+ self.dt_bias,
182+ key_head_dim=self.key_head_dim,
183+ value_head_dim=self.value_head_dim,
184+ attention_metadata=attention_metadata,
185+ )
186+ gate = local_head_split(gate, self.value_head_dim, cp_shard_dim=0)
187+ remat.recompute_needs_tensor(output, gate)
188+ output = self.norm(output, gate)
189+ return self.out_proj(output.reshape(hidden_states.shape[0], -1))
190+ 
191+ 
192+def use_master_fla(config: "Trainer.Config") -> None:
193+ """Select master's projection, parameter and FLA input layouts for packed Qwen SFT."""
194+ from torchtitan_npu.models.qwen3_5 import Qwen35TextModel, split_gate_up
195+ 
196+ if not isinstance(config.model, Qwen35TextModel.Config) or config.parallelism.context_parallel_degree != 8:
197+ raise ValueError("The Qwen master FLA layout requires a dense text recipe with CP8.")
198+ split_gate_up(config.model, enable_sequence_parallel=config.parallelism.enable_sequence_parallel)
199+ for layer in config.model.layers:
200+ attention = layer.attention
201+ if isinstance(attention, GDN.Config):
202+ if not isinstance(attention.inner_attention, AscContextParallelInnerGDN.Config):
203+ raise TypeError("The Qwen master FLA layout requires the native CP GDN configuration.")
204+ inner = derive(
205+ context_parallel(attention.inner_attention),
206+ FLAContextParallelInnerGDN.Config,
207+ preserve_conv_stride=True,
208+ )
209+ layer.attention = derive(attention, _MasterOrderGDN.Config, inner_attention=inner)
210+ for _, linear, _, _ in config.model.traverse(Linear.Config):
211+ linear.inplace_wgrad_accum = False
@@ -13,16 +13,18 @@ from itertools import pairwise
13 13 
14import torch14import torch
15import torch.nn.functional as F15import torch.nn.functional as F
16-from torch.distributed.device_mesh import DeviceMesh
17from torchtitan.config import derive, override16from torchtitan.config import derive, override
17+from torchtitan.distributed.parallelism_context import MeshAxisName
18+from torchtitan.distributed.spmd_types import spmd_mesh_group
19+from torchtitan.models.base.module import Module
18from torchtitan.models.common.attention import LinearAttentionMetadata20from torchtitan.models.common.attention import LinearAttentionMetadata
19-from torchtitan.models.common.attention import gdn as upstream_gdn21+from torchtitan.models.common.attention.cp_attention import CPInnerAttention
20-from torchtitan.models.common.attention.gdn import GDN, GDNKernel22+from torchtitan.models.common.attention.gdn import GDNKernel, InnerGDN
23+from torchtitan.models.common.norm import GatedRMSNorm
21 24 
22from torchtitan_npu.ops.triton.gdn import gated_delta_rule as run_gdn25from torchtitan_npu.ops.triton.gdn import gated_delta_rule as run_gdn
23-from torchtitan_npu.override.qwen3_5.parallelize import (26+ 
24- QWEN_CONTEXT_PARALLEL_UNSUPPORTED,27+from .parallelize import exchange_sequence_heads, head_to_sequence_shard, shard_local_heads
25-)
26 28 
27 29 
28class TritonGatedDeltaKernel(GDNKernel):30class TritonGatedDeltaKernel(GDNKernel):
@@ -30,6 +32,10 @@ class TritonGatedDeltaKernel(GDNKernel):
30 class Config(GDNKernel.Config):32 class Config(GDNKernel.Config):
31 pass33 pass
32 34 
35+ def __init__(self, config: Config):
36+ # The native CUDA constructor checks for Attention Gym kernels.
37+ Module.__init__(self)
38+ 
33 def forward(39 def forward(
34 self,40 self,
35 xq_THK: torch.Tensor,41 xq_THK: torch.Tensor,
@@ -46,9 +52,11 @@ class TritonGatedDeltaKernel(GDNKernel):
46 # result's batch axis comes back off.52 # result's batch axis comes back off.
47 reset = None53 reset = None
48 if cu_seqlens is not None:54 if cu_seqlens is not None:
49- reset = torch.zeros(xq_THK.shape[0], dtype=torch.bool, device=xq_THK.device)55+ # Fixed-capacity upstream metadata repeats the terminal offset.
56+ # Keep a sentinel slot so these empty segments never index past T.
57+ reset = torch.zeros(xq_THK.shape[0] + 1, dtype=torch.bool, device=xq_THK.device)
50 reset[cu_seqlens[:-1].to(device=reset.device, dtype=torch.long)] = True58 reset[cu_seqlens[:-1].to(device=reset.device, dtype=torch.long)] = True
51- reset = reset.unsqueeze(0)59+ reset = reset[:-1].unsqueeze(0)
52 return run_gdn(60 return run_gdn(
53 xq_THK.unsqueeze(0),61 xq_THK.unsqueeze(0),
54 xk_THK.unsqueeze(0),62 xk_THK.unsqueeze(0),
@@ -59,7 +67,11 @@ class TritonGatedDeltaKernel(GDNKernel):
59 ).squeeze(0)67 ).squeeze(0)
60 68 
61 69 
62-@override(target=GDNKernel.Config, exact=True, description="Use the Triton-Ascend GDN kernel")70+@override(
71+ target=GDNKernel.Config,
72+ exact=True,
73+ description="Use the Triton-Ascend GDN kernel",
74+)
63def triton(cfg: GDNKernel.Config) -> TritonGatedDeltaKernel.Config:75def triton(cfg: GDNKernel.Config) -> TritonGatedDeltaKernel.Config:
64 return derive(cfg, TritonGatedDeltaKernel.Config)76 return derive(cfg, TritonGatedDeltaKernel.Config)
65 77 
@@ -115,13 +127,13 @@ def _causal_conv1d_varlen_tensor(
115 raise ValueError("Qwen3.5 compiled varlen convolution requires kernel=4, stride=1, padding=0, dilation=1")127 raise ValueError("Qwen3.5 compiled varlen convolution requires kernel=4, stride=1, padding=0, dilation=1")
116 128 
117 boundary_indices = cu_seqlens[1:-1].to(device=x_BTD.device, dtype=torch.long)129 boundary_indices = cu_seqlens[1:-1].to(device=x_BTD.device, dtype=torch.long)
118- boundary_mask = torch.zeros(x_BTD.shape[1], dtype=torch.bool, device=x_BTD.device)130+ boundary_mask = torch.zeros(x_BTD.shape[1] + 1, dtype=torch.bool, device=x_BTD.device)
119 boundary_mask = boundary_mask.scatter(131 boundary_mask = boundary_mask.scatter(
120 0,132 0,
121 boundary_indices,133 boundary_indices,
122 torch.ones_like(boundary_indices, dtype=torch.bool),134 torch.ones_like(boundary_indices, dtype=torch.bool),
123 )135 )
124- segment_ids = boundary_mask.cumsum(dim=0)136+ segment_ids = boundary_mask[:-1].cumsum(dim=0)
125 137 
126 output = x_BTD * weight[:, -1].view(1, 1, -1)138 output = x_BTD * weight[:, -1].view(1, 1, -1)
127 for delay in range(1, _QWEN3_5_CONV_KERNEL_SIZE):139 for delay in range(1, _QWEN3_5_CONV_KERNEL_SIZE):
@@ -183,46 +195,136 @@ def _causal_conv1d_varlen_folded(
183 weight_C1W: torch.Tensor,195 weight_C1W: torch.Tensor,
184 cu_seqlens: torch.Tensor,196 cu_seqlens: torch.Tensor,
185) -> torch.Tensor:197) -> torch.Tensor:
186- """The folded ``[T, C]`` signature the 0.4.0 ``InnerGDN`` implementation calls.198+ """Apply the packed tensor convolution at the native InnerGDN hook."""
187- 
188- Device-side offsets keep the convolution traceable inside checkpoint HOP; the
189- eager strict-validation branch of :func:`_causal_conv1d_varlen` cannot run
190- because the folded metadata no longer carries CPU-side offsets.
191- """
192 return _causal_conv1d_varlen_tensor(x_TD.unsqueeze(0), weight_C1W, cu_seqlens).squeeze(0)199 return _causal_conv1d_varlen_tensor(x_TD.unsqueeze(0), weight_C1W, cu_seqlens).squeeze(0)
193 200 
194 201 
195-@override(target=GDNKernel.Config, exact=True, description="Use the NPU GDN kernel without FLA")202+class AscInnerGDN(InnerGDN):
196-def npu(cfg: GDNKernel.Config) -> TritonGatedDeltaKernel.Config:203+ """NPU convolution and the existing repository GDN custom op.
197- # The upstream 0.4.0 ``InnerGDN`` implementation resolves its packed
198- # convolution through the ``gdn`` module global at call time, so swapping
199- # that global is the seam the folded upstream actually calls. FLA's
200- # ``causal_conv1d`` is CUDA-only, which is why the reference cannot run
201- # as-is on NPU. FLA availability is not used as a backend selector
202- # because its convolution is not an NPU implementation.
203- upstream_gdn._causal_conv1d_varlen = _causal_conv1d_varlen_folded # pyrefly: ignore [bad-assignment]
204- return derive(cfg, TritonGatedDeltaKernel.Config)
205 204 
206- 205+ This adapter owns the packed-convolution policy. The Triton forward,
207-class ContextParallelGatedDeltaNet(GDN):206+ backward and autograd registration are consumed unchanged from ops/.
208- """Refuse the not-yet-migrated context-parallel GDN forward.
209- 
210- The class preserves the configured CP implementation while its forward
211- refuses execution: the pre-fold implementation exchanged rank-local
212- heads, convolved ``[B, L, D]`` rows, and called the kernel through
213- ``self.kernel``, none of which exists on the folded ``[T, ...]`` module.
214 """207 """
215 208 
216- context_parallel_mesh: DeviceMesh
217- 
218 @dataclass(kw_only=True, slots=True)209 @dataclass(kw_only=True, slots=True)
219- class Config(GDN.Config):210+ class Config(InnerGDN.Config):
220 pass211 pass
221 212 
222- def forward(self, x_TD: torch.Tensor, attention_metadata: LinearAttentionMetadata | None = None) -> torch.Tensor:213+ def __init__(self, config: Config):
223- raise NotImplementedError(QWEN_CONTEXT_PARALLEL_UNSUPPORTED)214+ Module.__init__(self)
215+ self.kernel = config.kernel.build()
216+ 
217+ def short_convolution(self, x_TC, weight_C1W, initial_state=None, *, cu_seqlens, routing):
218+ if initial_state is not None or routing is not None:
219+ raise ValueError("NPU head exchange consumes complete sequences without recurrent routing.")
220+ if cu_seqlens is None or cu_seqlens.numel() == 2:
221+ return _causal_conv1d(x_TC.unsqueeze(0), weight_C1W).squeeze(0)
222+ return _causal_conv1d_varlen_folded(x_TC, weight_C1W, cu_seqlens)
224 223 
225 224 
226-@override(target=GDN.Config, exact=True, description="Use Triton GDN with Context Parallel")225+class AscContextParallelInnerGDN(CPInnerAttention[LinearAttentionMetadata, LinearAttentionMetadata], AscInnerGDN):
227-def context_parallel(cfg: GDN.Config) -> ContextParallelGatedDeltaNet.Config:226+ """CP8 exchanges packed GDN inputs before causal convolution so document resets stay global."""
228- return derive(cfg, ContextParallelGatedDeltaNet.Config)227+ 
228+ @dataclass(kw_only=True, slots=True)
229+ class Config(CPInnerAttention.Config, AscInnerGDN.Config):
230+ pass
231+ 
232+ @staticmethod
233+ def prepare_cp_metadata(attention_metadata, *, permutation):
234+ if permutation is not None:
235+ raise ValueError("NPU GDN head exchange requires contiguous CP sharding without a load balancer.")
236+ return attention_metadata
237+ 
238+ def forward(
239+ self,
240+ query_TC,
241+ key_TC,
242+ value_TC,
243+ a_TH,
244+ b_TH,
245+ conv_q_weight_C1W,
246+ conv_k_weight_C1W,
247+ conv_v_weight_C1W,
248+ A_log_H,
249+ dt_bias_H,
250+ *,
251+ key_head_dim,
252+ value_head_dim,
253+ attention_metadata: LinearAttentionMetadata | None,
254+ ):
255+ group = spmd_mesh_group(MeshAxisName.CP)
256+ if group is None:
257+ raise RuntimeError("NPU context-parallel GDN requires an active CP group.")
258+ if any(
259+ tensor.shape[1] % (group.size() * dimension)
260+ for tensor, dimension in ((query_TC, key_head_dim), (key_TC, key_head_dim), (value_TC, value_head_dim))
261+ ):
262+ raise ValueError("GDN query, key and value head counts must be divisible by CP.")
263+ query_TC, key_TC, value_TC, a_TH, b_TH = exchange_sequence_heads(
264+ (query_TC, key_TC, value_TC, a_TH, b_TH), group
265+ )
266+ parameters = tuple(
267+ shard_local_heads(tensor, group)
268+ for tensor in (conv_q_weight_C1W, conv_k_weight_C1W, conv_v_weight_C1W, A_log_H, dt_bias_H)
269+ )
270+ conv_q, conv_k, conv_v, A_log, dt_bias = parameters
271+ output = super().forward(
272+ query_TC,
273+ key_TC,
274+ value_TC,
275+ a_TH,
276+ b_TH,
277+ conv_q,
278+ conv_k,
279+ conv_v,
280+ A_log,
281+ dt_bias,
282+ key_head_dim=key_head_dim,
283+ value_head_dim=value_head_dim,
284+ attention_metadata=attention_metadata,
285+ )
286+ return head_to_sequence_shard(output, group)
287+ 
288+ 
289+@override(
290+ target=InnerGDN.Config,
291+ fqns=["model.layers.*.attention.inner_attention"],
292+ exact=True,
293+ description="Use NPU convolution and the built-in Triton GDN",
294+)
295+def npu(cfg: InnerGDN.Config) -> AscInnerGDN.Config:
296+ return derive(cfg, AscInnerGDN.Config, kernel=derive(cfg.kernel, TritonGatedDeltaKernel.Config))
297+ 
298+ 
299+@override(
300+ target=AscContextParallelInnerGDN.Config,
301+ fqns=["model.layers.*.attention.inner_attention"],
302+ exact=True,
303+ description="Use NPU GDN with full-sequence head exchange",
304+)
305+def context_parallel(cfg: AscContextParallelInnerGDN.Config) -> AscContextParallelInnerGDN.Config:
306+ return derive(cfg, AscContextParallelInnerGDN.Config, kernel=derive(cfg.kernel, TritonGatedDeltaKernel.Config))
307+ 
308+ 
309+class QwenSFTGatedRMSNorm(GatedRMSNorm):
310+ """Preserve the Qwen SFT rounding point before multiplying by the gate."""
311+ 
312+ @dataclass(kw_only=True, slots=True)
313+ class Config(GatedRMSNorm.Config):
314+ pass
315+ 
316+ def forward(self, hidden_states: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
317+ values = hidden_states.float()
318+ values = values * torch.rsqrt(values.pow(2).mean(-1, keepdim=True) + self.eps)
319+ normalized = (self.weight.float() * values).to(hidden_states.dtype)
320+ return (normalized * self.activation_fn(gate.float())).to(hidden_states.dtype)
321+ 
322+ 
323+@override(
324+ target=GatedRMSNorm.Config,
325+ fqns=["model.layers.*.attention.norm"],
326+ exact=True,
327+ description="Preserve the Qwen SFT normalization and gating precision",
328+)
329+def qwen_sft(cfg: GatedRMSNorm.Config) -> QwenSFTGatedRMSNorm.Config:
330+ return derive(cfg, QwenSFTGatedRMSNorm.Config)
@@ -1,16 +1,15 @@
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 the4# 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.
5 6 
6-__all__ = ["QwenCPMetadata", "apply_qwen3_5_npu_fsdp", "parallelize_qwen3_5_cp"]7+from collections.abc import Sequence
7- 
8-import inspect
9-from contextlib import contextmanager
10from dataclasses import dataclass8from dataclasses import dataclass
11 9 
10+import spmd_types as spmd
12import torch11import torch
13-from torch.distributed.tensor import DTensor, Shard12+import torch.distributed as dist
14from torchtitan.config import TORCH_DTYPE_MAP13from torchtitan.config import TORCH_DTYPE_MAP
15from torchtitan.distributed.fsdp import (14from torchtitan.distributed.fsdp import (
16 apply_fsdp_to_decoder,15 apply_fsdp_to_decoder,
@@ -20,60 +19,6 @@ from torchtitan.distributed.fsdp import (
20)19)
21 20 
22 21 
23-@contextmanager
24-def _qwen_aot_eager_compile_options(backend: str):
25- """Isolate Qwen3.5 recompilation caches for dynamic multimodal inputs.
26- 
27- The upstream compiler applies fullgraph=True to every transformer block.
28- Qwen3.5 multimodal batches legitimately vary in vision-token and
29- packed-document metadata shapes, so one shared checkpoint-wrapper code
30- object can exceed Dynamo's recompilation cache. Keep this policy local to
31- the Qwen3.5 adapter and only for aot_eager; other models and backends
32- retain the upstream compile contract.
33- """
34- if backend != "aot_eager":
35- yield
36- return
37- 
38- original_compile = torch.nn.Module.compile
39- try:
40- compile_parameters = inspect.signature(torch.compile).parameters
41- except (TypeError, ValueError):
42- compile_parameters = {}
43- 
44- def _compile_qwen_block(self, *args, **kwargs):
45- # Isolate per-call cache entries when supported; heterogeneous Qwen
46- # blocks otherwise share checkpoint-wrapper recompilation counters.
47- # Keep upstream fullgraph=True so each block remains an aot_eager
48- # graph; isolation prevents unrelated block variants exhausting the
49- # shared Dynamo cache.
50- if "isolate_recompiles" in compile_parameters:
51- kwargs.setdefault("isolate_recompiles", True)
52- return original_compile(self, *args, **kwargs)
53- 
54- torch.nn.Module.compile = _compile_qwen_block
55- try:
56- yield
57- finally:
58- torch.nn.Module.compile = original_compile
59- 
60- 
61-@dataclass(frozen=True, slots=True)
62-class QwenCPMetadata:
63- cu_seqlens: torch.Tensor
64- cu_seqlens_cpu: torch.Tensor
65- actual_seq_qlen: torch.Tensor
66- 
67- 
68-QWEN_CONTEXT_PARALLEL_UNSUPPORTED = (
69- "Qwen3.5/3.6 NPU Context Parallel is not migrated to the folded token layout yet: "
70- "the CP GatedDeltaNet and varlen-attention forwards still target the pre-fold "
71- "[B, L, ...] interface, and upstream 0.4.0 moved the GatedDeltaNet seam under "
72- "inner_gated_delta_net. Keep context_parallel_degree at 1 until the CP NPU "
73- "validation pass lands."
74-)
75- 
76- 
77def apply_qwen3_5_npu_fsdp(model, *, parallelism_context, training, parallelism):22def apply_qwen3_5_npu_fsdp(model, *, parallelism_context, training, parallelism):
78 """Wrap vision independently of the decoder's pipeline stages."""23 """Wrap vision independently of the decoder's pipeline stages."""
79 dp_mesh, dp_mesh_dims = resolve_fsdp_mesh(parallelism_context)24 dp_mesh, dp_mesh_dims = resolve_fsdp_mesh(parallelism_context)
@@ -107,26 +52,30 @@ def apply_qwen3_5_npu_fsdp(model, *, parallelism_context, training, parallelism)
107 )52 )
108 53 
109 54 
110-def shard_local_heads(tensor, mesh):55+def exchange_sequence_heads(tensors: Sequence[torch.Tensor], group: dist.ProcessGroup) -> tuple[torch.Tensor, ...]:
111- return tensor.chunk(mesh.size(), 0)[mesh.get_local_rank()].contiguous()56+ """Combine CP exchanges while preserving each projection's head order."""
57+ degree = group.size()
58+ if any(tensor.shape[1] % degree for tensor in tensors):
59+ raise ValueError("Each projection's channel count must be divisible by CP.")
60+ shards = [tensor.chunk(degree, 1) for tensor in tensors]
61+ packed = torch.cat([parts[rank] for rank in range(degree) for parts in shards], 1)
62+ packed = spmd.redistribute(packed, group, src=spmd.S(0), dst=spmd.S(1))
63+ return packed.split([parts[0].shape[1] for parts in shards], 1)
112 64 
113 65 
114-def sequence_to_head_shard(tensor, mesh, head_dim):66+def head_to_sequence_shard(tensor: torch.Tensor, group: dist.ProcessGroup) -> torch.Tensor:
115- tensor = DTensor.from_local(tensor, mesh, (Shard(1),), run_check=False)67+ return spmd.redistribute(tensor, group, src=spmd.S(1), dst=spmd.S(0))
116- return tensor.redistribute(placements=(Shard(head_dim),)).to_local()
117 68 
118 69 
119-def head_to_sequence_shard(tensor, mesh, head_dim):70+def shard_local_heads(tensor: torch.Tensor, group: dist.ProcessGroup) -> torch.Tensor:
120- tensor = DTensor.from_local(tensor, mesh, (Shard(head_dim),), run_check=False)71+ return spmd.redistribute(tensor, group, src=spmd.R, dst=spmd.S(0))
121- return tensor.redistribute(placements=(Shard(1),)).to_local()
122 72 
123 73 
124-def exchange_sequence_heads(tensors, mesh, head_dim):74+@dataclass(frozen=True, slots=True)
125- degree = mesh.size()75+class QwenCPMetadata:
126- shards = [tensor.chunk(degree, head_dim) for tensor in tensors]76+ cu_seqlens: torch.Tensor
127- packed = torch.cat([part[rank] for rank in range(degree) for part in shards], head_dim)77+ cu_seqlens_cpu: torch.Tensor
128- packed = sequence_to_head_shard(packed, mesh, head_dim)78+ actual_seq_qlen: torch.Tensor
129- return packed.split([part[0].size(head_dim) for part in shards], head_dim)
130 79 
131 80 
132def build_sequence_metadata(varlen):81def build_sequence_metadata(varlen):
@@ -153,29 +102,3 @@ def prepare_sequence_metadata(module, args, kwargs):
153 elif not isinstance(masks, QwenCPMetadata):102 elif not isinstance(masks, QwenCPMetadata):
154 kwargs["attention_masks"] = build_sequence_metadata(masks)103 kwargs["attention_masks"] = build_sequence_metadata(masks)
155 return args, kwargs104 return args, kwargs
156- 
157- 
158-def parallelize_qwen3_5_cp(model, *, parallelism_context, **kwargs):
159- """Refuse the not-yet-migrated Qwen3.5 NPU context-parallel path.
160- 
161- The CP graph (rank-local ``QwenCPMetadata`` pre-hook, head exchange in the
162- GatedDeltaNet/varlen-attention forwards, and the FSDP2 wrap over the CP
163- storage mesh) still targets the pre-fold ``[B, L, ...]`` modules, while the
164- pinned trainer hands folded ``[T, ...]`` rows to folded attention seams.
165- Wiring the old modules into that contract would train on mis-sharded
166- activations, so the path is disabled until its NPU validation pass lands.
167- The CPU-safe metadata helpers above are kept for that migration and for
168- their unit tests.
169- """
170- # Keep the mode-specific refusals first: recipes may call the CP helper
171- # directly, and those combinations are rejected for their own reasons even
172- # after the folded migration.
173- if parallelism_context.ep_enabled:
174- raise NotImplementedError("Qwen3.5 NPU Context Parallel does not support Expert Parallel yet.")
175- if parallelism_context.tp_enabled:
176- raise NotImplementedError("Qwen3.5 NPU Context Parallel does not support Tensor Parallel yet.")
177- if getattr(model, "vision_encoder", None) is not None:
178- raise NotImplementedError(
179- "Qwen3.5-VL NPU Context Parallel is not supported for multimodal attention masks yet."
180- )
181- raise NotImplementedError(QWEN_CONTEXT_PARALLEL_UNSUPPORTED)
@@ -5,49 +5,127 @@
5 5 
6# pylint: disable=huawei-invalid-name6# pylint: disable=huawei-invalid-name
7 7 
8+from collections.abc import Callable
8from dataclasses import dataclass9from dataclasses import dataclass
9 10 
11+import spmd_types as spmd
10import torch12import torch
11from torchtitan.config import derive, override13from torchtitan.config import derive, override
12-from torchtitan.models.common.attention.cp_attention import UlyssesVarlenInnerAttention14+from torchtitan.distributed.parallelism_context import MeshAxisName
13- 15+from torchtitan.distributed.spmd_types import spmd_mesh_group
14-from torchtitan_npu.override.qwen3_5.parallelize import (16+from torchtitan.models.base.module import Module
15- QWEN_CONTEXT_PARALLEL_UNSUPPORTED,17+from torchtitan.models.common.attention import VarlenInnerAttention
16-)18+from torchtitan.models.common.attention.attention import VarlenAttentionMetadata
19+from torchtitan.models.common.attention.cp_attention import CPInnerAttention, UlyssesVarlenInnerAttention
17 20 
18 21 
19-class AscVarlenInnerAttention(UlyssesVarlenInnerAttention):22+class AscVarlenInnerAttention(VarlenInnerAttention):
20- """Refuse the not-yet-migrated context-parallel varlen attention.23+ """Use the CANN TND operator at the native varlen attention boundary."""
21- 
22- Upstream 0.4.0 folds the batch dimension into the token row: the base
23- ``VarlenInnerAttention.forward`` now takes ``[T, N, H]`` and a
24- ``VarlenAttentionMetadata``. The removed implementation exchanged rank-local heads
25- on pre-fold ``[B, L, N, H]`` tensors and fed CANN TND attention with
26- ``actual_seq_qlen`` from the old CP metadata, so running it against the
27- folded caller would mis-shard the sequence. Configuration retains the real
28- Ulysses CP owner and its global-metadata preparation protocol; this forward
29- keeps the explicit runtime refusal until the CP NPU validation pass.
30- """
31 24 
32 @dataclass(kw_only=True, slots=True)25 @dataclass(kw_only=True, slots=True)
33- class Config(UlyssesVarlenInnerAttention.Config):26+ class Config(VarlenInnerAttention.Config):
34 pass27 pass
35 28 
29+ def __init__(self, config: Config):
30+ Module.__init__(self)
31+ if config.window_size != (-1, 0):
32+ raise ValueError("The Qwen CANN adapter requires full causal attention.")
33+ self._causal_mask = None
34+ 
36 def forward(35 def forward(
37 self,36 self,
38 q_THK: torch.Tensor,37 q_THK: torch.Tensor,
39 k_THK: torch.Tensor,38 k_THK: torch.Tensor,
40 v_THV: torch.Tensor,39 v_THV: torch.Tensor,
40+ *,
41+ attention_metadata,
42+ scale: float | None = None,
43+ out_transform: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] | None = None,
44+ enable_gqa: bool = False,
41 **kwargs,45 **kwargs,
42 ) -> torch.Tensor:46 ) -> torch.Tensor:
43- raise NotImplementedError(QWEN_CONTEXT_PARALLEL_UNSUPPORTED)47+ if kwargs:
48+ raise NotImplementedError(f"Unsupported Qwen CANN attention options: {sorted(kwargs)}")
49+ if out_transform is not None:
50+ raise NotImplementedError("NPU CP attention does not provide the LSE required by out_transform.")
51+ if enable_gqa and q_THK.shape[1] != k_THK.shape[1]:
52+ repeats = q_THK.shape[1] // k_THK.shape[1]
53+ k_THK = k_THK.repeat_interleave(repeats, 1)
54+ v_THV = v_THV.repeat_interleave(repeats, 1)
55+ cu_q = attention_metadata.cu_seq_q.to(device="cpu", dtype=torch.int64)
56+ cu_k = attention_metadata.cu_seq_k.to(device="cpu", dtype=torch.int64)
57+ actual_seq_q = cu_q[1:][cu_q[1:] > cu_q[:-1]].tolist()
58+ actual_seq_kv = cu_k[1:][cu_k[1:] > cu_k[:-1]].tolist()
59+ if self._causal_mask is None or self._causal_mask.device != q_THK.device:
60+ self._causal_mask = torch.triu(torch.ones(2048, 2048, dtype=torch.bool, device=q_THK.device), diagonal=1)
61+ output_THV = torch.ops.npu.npu_fusion_attention(
62+ query=q_THK,
63+ key=k_THK,
64+ value=v_THV,
65+ head_num=q_THK.shape[1],
66+ input_layout="TND",
67+ atten_mask=self._causal_mask,
68+ scale=q_THK.shape[-1] ** -0.5 if scale is None else scale,
69+ keep_prob=1.0,
70+ pre_tockens=q_THK.shape[0],
71+ next_tockens=0,
72+ actual_seq_qlen=actual_seq_q,
73+ actual_seq_kvlen=actual_seq_kv,
74+ sparse_mode=7,
75+ )[0]
76+ return output_THV
77+ 
78+ 
79+class AscCPVarlenInnerAttention(
80+ CPInnerAttention[VarlenAttentionMetadata, VarlenAttentionMetadata], AscVarlenInnerAttention
81+):
82+ """Replicate Qwen's four KV heads before Ulysses sharding across eight CP ranks."""
83+ 
84+ @dataclass(kw_only=True, slots=True)
85+ class Config(CPInnerAttention.Config, AscVarlenInnerAttention.Config):
86+ pass
87+ 
88+ @staticmethod
89+ def prepare_cp_metadata(attention_metadata, *, permutation):
90+ if permutation is not None:
91+ raise ValueError("NPU head exchange requires contiguous CP sharding without a load balancer.")
92+ return attention_metadata
93+ 
94+ def forward(self, q_THK, k_THK, v_THV, *, out_transform=None, enable_gqa=False, **kwargs):
95+ if out_transform is not None:
96+ raise NotImplementedError("NPU CP attention does not provide the LSE required by out_transform.")
97+ group = spmd_mesh_group(MeshAxisName.CP)
98+ if group is None:
99+ raise RuntimeError("NPU context-parallel attention requires an active CP group.")
100+ if q_THK.shape[1] % group.size():
101+ raise ValueError("Qwen query heads must be divisible by CP.")
102+ if enable_gqa and k_THK.shape[1] % group.size():
103+ repeats = q_THK.shape[1] // k_THK.shape[1]
104+ k_THK = k_THK.repeat_interleave(repeats, 1)
105+ v_THV = v_THV.repeat_interleave(repeats, 1)
106+ if k_THK.shape[1] % group.size() or v_THV.shape[1] % group.size():
107+ raise ValueError("Qwen K/V heads must divide CP, or enable_gqa must allow head replication.")
108+ seq, heads = spmd.S(0), spmd.S(1)
109+ q_THK, k_THK, v_THV = (spmd.redistribute(x, group, src=seq, dst=heads) for x in (q_THK, k_THK, v_THV))
110+ output = super().forward(q_THK, k_THK, v_THV, enable_gqa=enable_gqa, **kwargs)
111+ return spmd.redistribute(output, group, src=heads, dst=seq)
44 112 
45 113 
46@override(114@override(
47 target=UlyssesVarlenInnerAttention.Config,115 target=UlyssesVarlenInnerAttention.Config,
48 fqns=["model.layers.*.attention.inner_attention"],116 fqns=["model.layers.*.attention.inner_attention"],
49 exact=True,117 exact=True,
50- description="Use CANN TND attention with Qwen3.5/3.6 Context Parallel",118+ description="Use CANN TND attention with Qwen CP head exchange",
51)119)
52-def asc_cp(cfg: UlyssesVarlenInnerAttention.Config) -> AscVarlenInnerAttention.Config:120+def asc_cp(cfg: UlyssesVarlenInnerAttention.Config) -> AscCPVarlenInnerAttention.Config:
121+ return derive(cfg, AscCPVarlenInnerAttention.Config)
122+ 
123+ 
124+@override(
125+ target=VarlenInnerAttention.Config,
126+ fqns=["model.layers.*.attention.inner_attention"],
127+ exact=True,
128+ description="Use CANN TND attention for Qwen",
129+)
130+def asc(cfg: VarlenInnerAttention.Config) -> AscVarlenInnerAttention.Config:
53 return derive(cfg, AscVarlenInnerAttention.Config)131 return derive(cfg, AscVarlenInnerAttention.Config)
@@ -42,4 +42,32 @@ import torchtitan_npu.patches.torchtitan.distributed.checkpoint.filesystem # no
42from . import observability # noqa: F40142from . import observability # noqa: F401
43 43 
44from .models.common import moe, rope, token_dispatcher # noqa: F40144from .models.common import moe, rope, token_dispatcher # noqa: F401
45+ 
46+ 
47+def _patch_optional_qwen_short_conv() -> None:
48+ # Apply before a Qwen import resolves the optional CuTeDSL backend.
49+ from torchtitan.models.common import attn_gym
50+ 
51+ resolve = attn_gym.__getattr__
52+ backend = "attn_gym.linear.short_conv"
53+ 
54+ def resolve_optional_short_conv(name: str):
55+ try:
56+ return resolve(name)
57+ except ImportError as error:
58+ cause = error.__cause__
59+ if name != "causal_conv1d" or not isinstance(cause, ModuleNotFoundError) or cause.name != "cutlass":
60+ raise
61+ # Attention Gym 0.0.17 wraps this missing backend on attribute
62+ # access. Give TorchTitan the same deferred error it uses when
63+ # a backend fails during module import.
64+ vars(attn_gym)["_BACKEND_ERRORS"].setdefault(backend, cause)
65+ kernel = vars(attn_gym)["_missing_backend_kernel"](backend)
66+ vars(attn_gym)[name] = kernel
67+ return kernel
68+ 
69+ attn_gym.__getattr__ = resolve_optional_short_conv
70+ 
71+ 
72+_patch_optional_qwen_short_conv()
45from .models import deepseek_v4 # noqa: F40173from .models import deepseek_v4 # noqa: F401
@@ -17,7 +17,9 @@ import io
17import logging17import logging
18import os18import os
19from concurrent.futures import ThreadPoolExecutor19from concurrent.futures import ThreadPoolExecutor
20+from contextlib import AbstractContextManager, nullcontext
20from pathlib import Path21from pathlib import Path
22+from typing import TYPE_CHECKING, cast
21 23 
22import torch24import torch
23import torch.distributed.checkpoint as dcp25import torch.distributed.checkpoint as dcp
@@ -30,6 +32,9 @@ from torchtitan.components.checkpointer import ModelWrapper
30from torchtitan.components.checkpointer.utils import canonical_fqn32from torchtitan.components.checkpointer.utils import canonical_fqn
31from torchtitan.config import TORCH_DTYPE_MAP33from torchtitan.config import TORCH_DTYPE_MAP
32 34 
35+if TYPE_CHECKING:
36+ from torchtitan_npu.models.qwen3_5 import Qwen35TextStateDictAdapter
37+ 
33_EMA_STATE_PREFIX = "ema_optimizer.state."38_EMA_STATE_PREFIX = "ema_optimizer.state."
34_EMA_STATE_SUFFIX = ".ema_params"39_EMA_STATE_SUFFIX = ".ema_params"
35logger = logging.getLogger(__name__)40logger = logging.getLogger(__name__)
@@ -134,17 +139,25 @@ def _load_ema_state_dict(model_state_dict, trainable_fqns, input_dir, read_threa
134 return ema_state_dict139 return ema_state_dict
135 140 
136 141 
137-def _save_as_hf(state_dict, sd_adapter, target_dtype, output_dir):142+def _save_as_hf(state_dict, sd_adapter, target_dtype, output_dir, *, filter_weight_index=False):
138 hf_state_dict = sd_adapter.to_hf(state_dict)143 hf_state_dict = sd_adapter.to_hf(state_dict)
139 if target_dtype != torch.float32:144 if target_dtype != torch.float32:
140 # The adapter stores hash routing indices as float32 in HF format.145 # The adapter stores hash routing indices as float32 in HF format.
141 # Rounding those indices changes the selected expert after reload.146 # Rounding those indices changes the selected expert after reload.
142 hf_state_dict = {k: v if k.endswith(".tid2eid") else v.to(target_dtype) for k, v in hf_state_dict.items()}147 hf_state_dict = {k: v if k.endswith(".tid2eid") else v.to(target_dtype) for k, v in hf_state_dict.items()}
143 148 
149+ weight_index = sd_adapter.fqn_to_index_mapping
150+ if filter_weight_index and weight_index is not None:
151+ # A Qwen vision DCP can omit auxiliary weights listed in the source HF index.
152+ if hf_state_dict.keys() <= weight_index.keys():
153+ weight_index = {name: weight_index[name] for name in hf_state_dict}
154+ else:
155+ weight_index = None
156+ 
144 storage_writer = HuggingFaceStorageWriter(157 storage_writer = HuggingFaceStorageWriter(
145 path=output_dir,158 path=output_dir,
146 save_distributed=True,159 save_distributed=True,
147- fqn_to_index_mapping=sd_adapter.fqn_to_index_mapping,160+ fqn_to_index_mapping=weight_index,
148 enable_consolidation=True,161 enable_consolidation=True,
149 thread_count_consolidation=5,162 thread_count_consolidation=5,
150 )163 )
@@ -165,8 +178,21 @@ def convert_to_hf(args: argparse.Namespace):
165 # Allow a fully-qualified module path (e.g. torchtitan_npu.models.deepseek_v4)178 # Allow a fully-qualified module path (e.g. torchtitan_npu.models.deepseek_v4)
166 # while preserving the short ``llama3`` form used upstream.179 # while preserving the short ``llama3`` form used upstream.
167 module_name = model_name if "." in model_name else f"torchtitan.models.{model_name}"180 module_name = model_name if "." in model_name else f"torchtitan.models.{model_name}"
168- model_module = importlib.import_module(module_name)181+ reader = ParallelFileSystemReader(input_dir, thread_count=read_threads)
169- model_config = model_module.model_registry(model_flavor)182+ metadata = None
183+ has_vision = False
184+ if module_name in {"torchtitan.models.qwen3_5", "torchtitan_npu.models.qwen3_5"}:
185+ import torchtitan_npu # noqa: F401 -- load the NPU patches before importing Qwen
186+ from torchtitan_npu.models.qwen3_5 import checkpoint_model_config
187+ 
188+ metadata = reader.read_metadata().state_dict_metadata
189+ has_vision = any(key.startswith("vision_encoder.") for key in metadata)
190+ model_config = checkpoint_model_config(
191+ model_flavor, has_vision=has_vision, separate_gate_up="layers.0.feed_forward.w1.weight" in metadata
192+ )
193+ else:
194+ model_module = importlib.import_module(module_name)
195+ model_config = model_module.model_registry(model_flavor)
170 196 
171 with torch.device("cpu"):197 with torch.device("cpu"):
172 raw_model = model_config.build()198 raw_model = model_config.build()
@@ -182,23 +208,30 @@ def convert_to_hf(args: argparse.Namespace):
182 208 
183 # allocate state dict memory with empty weights to load checkpoint209 # allocate state dict memory with empty weights to load checkpoint
184 state_dict = model.state_dict()210 state_dict = model.state_dict()
185- reader = ParallelFileSystemReader(input_dir, thread_count=read_threads)211+ load_state = state_dict
186- dcp.load(state_dict, storage_reader=reader)212+ export_context: AbstractContextManager[None] = nullcontext()
213+ if metadata is not None and not has_vision:
214+ text_adapter = cast("Qwen35TextStateDictAdapter", sd_adapter)
215+ if "qwen_hf_source.path" in metadata:
216+ load_state = state_dict | {"qwen_hf_source": text_adapter}
217+ export_context = text_adapter.export_hf(fallback_path=str(hf_assets_path))
218+ dcp.load(load_state, storage_reader=reader)
187 219 
188 target_dtype = TORCH_DTYPE_MAP[export_dtype]220 target_dtype = TORCH_DTYPE_MAP[export_dtype]
189- _save_as_hf(state_dict, sd_adapter, target_dtype, output_dir)221+ with export_context:
222+ _save_as_hf(state_dict, sd_adapter, target_dtype, output_dir, filter_weight_index=has_vision)
190 223 
191- if ema_output is not None:224+ if ema_output is not None:
192- ema_state_dict = _load_ema_state_dict(state_dict, trainable_fqns, input_dir, read_threads)225+ ema_state_dict = _load_ema_state_dict(state_dict, trainable_fqns, input_dir, read_threads)
193- if ema_state_dict is None:226+ if ema_state_dict is None:
194- logger.warning(227+ logger.warning(
195- "--ema_output was given but the checkpoint at %s has no EMA weights "228+ "--ema_output was given but the checkpoint at %s has no EMA weights "
196- "(EMA was disabled during that training run, or this checkpoint predates "229+ "(EMA was disabled during that training run, or this checkpoint predates "
197- "EMA support). Skipping EMA export.",230+ "EMA support). Skipping EMA export.",
198- input_dir,231+ input_dir,
199- )232+ )
200- else:233+ else:
201- _save_as_hf(ema_state_dict, sd_adapter, target_dtype, ema_output)234+ _save_as_hf(ema_state_dict, sd_adapter, target_dtype, ema_output, filter_weight_index=has_vision)
202 235 
203 236 
204def main():237def main():
@@ -6,12 +6,11 @@
6| --- | --- |6| --- | --- |
7| `torchtitan_npu_recipes.models.deepseek_v4` | V4 eager、SFT、LoRA 和 TorchFT 配置工厂 |7| `torchtitan_npu_recipes.models.deepseek_v4` | V4 eager、SFT、LoRA 和 TorchFT 配置工厂 |
8| `torchtitan_npu_recipes.models.deepseek_v4_1` | V4.1 文本、多模态和 LoRA 配置工厂 |8| `torchtitan_npu_recipes.models.deepseek_v4_1` | V4.1 文本、多模态和 LoRA 配置工厂 |
9-| `torchtitan_npu_recipes.models.qwen3_5` | Qwen 配置工厂 |9+| `torchtitan_npu_recipes.models.qwen3_5` | Qwen3.5 系列配置工厂 |
10| `torchtitan_npu_recipes.graph_trainer.deepseek_v4` | V4 GraphTrainer 配置工厂 |10| `torchtitan_npu_recipes.graph_trainer.deepseek_v4` | V4 GraphTrainer 配置工厂 |
11| `torchtitan_npu_recipes.examples.deepseek_v4` | 19 个 V4 launcher 的完整配置 |11| `torchtitan_npu_recipes.examples.deepseek_v4` | 19 个 V4 launcher 的完整配置 |
12| `torchtitan_npu_recipes.examples.deepseek_v4_1` | 12 个 V4.1 launcher 的完整配置 |12| `torchtitan_npu_recipes.examples.deepseek_v4_1` | 12 个 V4.1 launcher 的完整配置 |
13| `torchtitan_npu_recipes.examples.qwen3_5` | 2 个 Qwen3.5 launcher 的完整配置 |13| `torchtitan_npu_recipes.examples.qwen3_5` | 2 个 Qwen3.5 launcher 的完整配置 |
14-| `torchtitan_npu_recipes.examples.qwen3_6` | Qwen3.6 launcher 的配置入口(基础工厂仍延期) |
15 14 
16这些是配置的归属,不是功能支持声明。TorchTitan 0.4.0 的当前 NPU 适配优先覆盖 DeepSeek 文本 eager;TP、CP、PP、多模态、SFT、LoRA、图训练与其他延期路径仍受各实现的限制。移动配置不会启用这些功能。15这些是配置的归属,不是功能支持声明。TorchTitan 0.4.0 的当前 NPU 适配优先覆盖 DeepSeek 文本 eager;TP、CP、PP、多模态、SFT、LoRA、图训练与其他延期路径仍受各实现的限制。移动配置不会启用这些功能。
17 16 
@@ -11,6 +11,28 @@ import os
11from pathlib import Path11from pathlib import Path
12from typing import TYPE_CHECKING12from typing import TYPE_CHECKING
13 13 
14+from torchtitan_npu_recipes.models.qwen3_5 import (
15+ qwen3_5_27b_sft_64k_cp8 as qwen3_5_27b_sft_64k_cp8,
16+)
17+from torchtitan_npu_recipes.models.qwen3_5 import (
18+ run_qwen3_5_4k as run_qwen3_5_4k,
19+)
20+from torchtitan_npu_recipes.models.qwen3_5 import (
21+ run_qwen3_5_32k_cp8 as run_qwen3_5_32k_cp8,
22+)
23+from torchtitan_npu_recipes.models.qwen3_5 import (
24+ run_qwen3_5_32k_cp8_fla as run_qwen3_5_32k_cp8_fla,
25+)
26+from torchtitan_npu_recipes.models.qwen3_5 import (
27+ run_qwen3_5_64k_cp8 as run_qwen3_5_64k_cp8,
28+)
29+from torchtitan_npu_recipes.models.qwen3_5 import (
30+ run_qwen3_5_128k_cp8 as run_qwen3_5_128k_cp8,
31+)
32+from torchtitan_npu_recipes.models.qwen3_5 import (
33+ run_qwen_sft as run_qwen_sft,
34+)
35+ 
14if TYPE_CHECKING:36if TYPE_CHECKING:
15 from torchtitan.trainer import Trainer37 from torchtitan.trainer import Trainer
16 38 
@@ -1,48 +0,0 @@
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-"""Qwen3.6 SFT launch configuration, pending the Qwen 27B model migration."""
7- 
8-from __future__ import annotations
9- 
10-import os
11-from typing import TYPE_CHECKING
12- 
13-if TYPE_CHECKING:
14- from torchtitan.trainer import Trainer
15- 
16- 
17-def run_qwen3_6_4k(*, seq_len: int | None = None) -> Trainer.Config:
18- from torchtitan.config import derive
19- from torchtitan.models.common.rope import RoPE
20- 
21- from torchtitan_npu.models.qwen3_5 import NPUQwen35Model
22- from torchtitan_npu_recipes.models.qwen3_5 import qwen35_27b_4k_sft
23- 
24- # The base factory deliberately raises until the 27B model is migrated.
25- config = qwen35_27b_4k_sft()
26- if seq_len is None:
27- seq_len = int(os.environ.get("SEQ_LEN", "4096"))
28- if not 64 <= seq_len <= 4096 or seq_len % 64:
29- raise ValueError("seq_len must be a multiple of 64 in [64, 4096]")
30- hf_assets_path = os.environ.get("HF_ASSETS_PATH")
31- if not hf_assets_path:
32- raise ValueError("Set HF_ASSETS_PATH to the Qwen3.5/Qwen3.6 Hugging Face model directory")
33- if not os.environ.get("DATA_FILES"):
34- raise ValueError("Set DATA_FILES to the CANNBOT 4K SFT JSONL file")
35- config.hf_assets_path = hf_assets_path
36- config.dump_folder = os.environ.get("DUMP_FOLDER", "./outputs/qwen3_6_4k_sft")
37- config.override.imports = ["torchtitan_npu.override.qwen3_5.gated_delta.triton"]
38- config.training.max_context_length = seq_len
39- config.training.num_tokens_per_microbatch_per_dp_rank = seq_len
40- assert isinstance(config.model, NPUQwen35Model.Config)
41- config.model = derive(config.model, NPUQwen35Model.Config, max_context_length=seq_len)
42- for _, rope, _, _ in config.model.traverse(RoPE.Config):
43- rope.max_context_length = seq_len
44- assert config.checkpointer is not None
45- config.checkpointer.initial_load_path = os.environ.get("CHECKPOINT_INITIAL_LOAD_PATH", hf_assets_path)
46- config.checkpointer.initial_load_in_hf = True
47- config.checkpointer.initial_load_model_only = True
48- return config