| @@ -0,0 +1,171 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# | ||
当前PR改动代码超过1k行,建议拆分PR后合入。 问题编号:R1212-001 审查版本: ![]() ![]() 当前PR改动代码超过1k行,建议拆分PR后合入。 问题编号:R1212-001 审查版本: ![]() ![]() | |||
| 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 | +"""V4.1 training with BF16 NPU router GEMMs and retained FP32 gradients.""" | ||
| 7 | + | ||
| 8 | +from dataclasses import replace | ||
| 9 | +from functools import wraps | ||
| 10 | +from pathlib import Path | ||
| 11 | + | ||
| 12 | +from tests.integration_tests import OverrideDefinitions | ||
| 13 | + | ||
| 14 | +_MODULE = "tests.integration_tests.hi_mid_lo_linear" | ||
| 15 | +_OVERRIDE = "torchtitan_npu.override.common.hi_mid_lo_linear.asc" | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def build_hi_mid_lo_linear_test_list() -> list[OverrideDefinitions]: | ||
| 19 | + # The target dev branch still has the older runner until the release API migration lands. | ||
| 20 | + if not hasattr(OverrideDefinitions, "native_config"): | ||
实际位置是 一般(S2): 这里用 这也违反 问题编号:R1212-003 审查版本: ![]() ![]() | |||
| 21 | + return [] | ||
| 22 | + return [ | ||
| 23 | + OverrideDefinitions( | ||
| 24 | + test_name="dsv41_hi_mid_lo_linear_ep2_fsdp2", | ||
| 25 | + test_descr="V4.1 NPU HiMidLoLinear routers, eager EP2/FSDP2, ten AdamW steps", | ||
| 26 | + ngpu=2, | ||
| 27 | + timeout=1800, | ||
| 28 | + env_vars={"MODULE": _MODULE, "CONFIG": "deepseek_v4_1_hi_mid_lo_linear", "TRAIN_FILE": _MODULE}, | ||
| 29 | + override_args=((),), | ||
| 30 | + native_config=True, | ||
| 31 | + # This approximate GEMM path has no exact-loss golden. The runner | ||
| 32 | + # checks finite losses and steps; the entry checks the selected path. | ||
| 33 | + check_loss=False, | ||
| 34 | + expected_steps=(tuple(range(1, 11)),), | ||
| 35 | + ) | ||
| 36 | + ] | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def deepseek_v4_1_hi_mid_lo_linear(): | ||
| 40 | + # Keep recipe imports after backend initialization in the training entry; | ||
| 41 | + # importing this module for runner case discovery must stay device-free. | ||
| 42 | + from torchtitan_npu.models.common.alignment import compression_alignment | ||
| 43 | + from torchtitan_npu.models.deepseek_v4_1.config_registry import deepseek_v4_1_debugmodel_multimodal | ||
| 44 | + from torchtitan_npu.models.deepseek_v4_1.vision.dataloader import caption_dataloader_config | ||
| 45 | + | ||
| 46 | + assets = Path(__file__).resolve().parents[1] / "assets" | ||
| 47 | + config = deepseek_v4_1_debugmodel_multimodal() | ||
| 48 | + config.hf_assets_path = str(assets / "deepseek_v3") | ||
| 49 | + config.dataloader = caption_dataloader_config( | ||
| 50 | + dataset="cc12m-test", | ||
| 51 | + dataset_path=str(assets / "cc12m_test"), | ||
| 52 | + per_doc_alignment=compression_alignment(config.model.compress_ratios), | ||
| 53 | + seed=42, | ||
| 54 | + shuffle=False, | ||
| 55 | + repeat=True, | ||
| 56 | + ) | ||
| 57 | + config.dataloader.read_options = replace(config.dataloader.read_options, num_threads=1, prefetch_buffer_size=8) | ||
| 58 | + config.dataloader.num_prefetch_microbatches = 1 | ||
| 59 | + config.training.dtype = "float32" | ||
| 60 | + config.training.mixed_precision_param = "bfloat16" | ||
| 61 | + config.training.mixed_precision_reduce = "float32" | ||
| 62 | + config.training.max_context_length = 512 | ||
| 63 | + config.training.num_tokens_per_microbatch_per_dp_rank = 512 | ||
| 64 | + config.training.num_tokens_per_train_step = 1024 | ||
| 65 | + config.training.steps = 10 | ||
| 66 | + config.training.disable_cuda_graphs = True | ||
| 67 | + config.training.enable_cpu_offload = False | ||
| 68 | + # Keep FP32 reference arithmetic free of HF32 input rounding during alignment. | ||
| 69 | + config.training.extension.allow_hf32 = False | ||
| 70 | + config.parallelism.data_parallel_shard_degree = 2 | ||
| 71 | + config.parallelism.data_parallel_replicate_degree = 1 | ||
| 72 | + config.parallelism.expert_parallel_degree = 2 | ||
| 73 | + config.parallelism.tensor_parallel_degree = 1 | ||
| 74 | + config.parallelism.pipeline_parallel_degree = 1 | ||
| 75 | + config.parallelism.context_parallel_degree = 1 | ||
| 76 | + config.parallelism.fsdp_reshard_after_forward = "always" | ||
| 77 | + config.optim.optimizer.name = "AdamW" | ||
| 78 | + config.optim.lr_scheduler.warmup_steps = 2 | ||
| 79 | + config.optim.lr_scheduler.total_steps = 100 | ||
| 80 | + config.debug.seed = 42 | ||
| 81 | + config.debug.deterministic = True | ||
| 82 | + config.debug.deterministic_warn_only = False | ||
| 83 | + config.model.local_compile_regions = [] | ||
| 84 | + config.override.imports = ["torchtitan_npu.override.common.rope.workaround", _OVERRIDE] | ||
| 85 | + config.metrics.enable_tensorboard = True | ||
| 86 | + config.metrics.log_freq = 1 | ||
| 87 | + config.metrics.save_tb_folder = "tb_phase_0" | ||
| 88 | + config.checkpointer = None | ||
| 89 | + config.profiler.enable_profiling = False | ||
| 90 | + config.__post_init__() | ||
| 91 | + return config | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def main(): | ||
| 95 | + import torchtitan_npu # noqa: F401, I001 | ||
| 96 | + | ||
| 97 | + # Initialize the NPU backend before importing upstream training modules. | ||
| 98 | + import torch | ||
| 99 | + from torchtitan.distributed.batch_invariant import is_in_batch_invariant_mode | ||
| 100 | + from torchtitan.train import main as train_main | ||
| 101 | + from torchtitan.training_engine import TrainingEngine | ||
| 102 | + | ||
| 103 | + from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx | ||
| 104 | + from torchtitan_npu.override.common.hi_mid_lo_linear import AscHiMidLoLinear | ||
| 105 | + | ||
| 106 | + original_init, original_train = TrainerEx.__init__, TrainerEx.train | ||
| 107 | + original_optim_step = TrainingEngine.optim_step | ||
| 108 | + states, handles = {}, [] | ||
| 109 | + | ||
| 110 | + @wraps(original_init) | ||
| 111 | + def initialize(self, config): | ||
| 112 | + original_init(self, config) | ||
| 113 | + assert not is_in_batch_invariant_mode(), "Batch-invariant mode would select the FP32 fallback" | ||
| 114 | + gates = { | ||
| 115 | + name: module | ||
| 116 | + for part in self.engine.model_parts | ||
| 117 | + for name, module in part.named_modules() | ||
| 118 | + if name.endswith(".moe.router.gate") | ||
| 119 | + } | ||
| 120 | + assert len(gates) == len(config.model.layers), "Expected every V4.1 router gate" | ||
| 121 | + assert all(isinstance(gate, AscHiMidLoLinear) for gate in gates.values()), "HiMidLo override was not applied" | ||
| 122 | + state = {"gates": gates, "forwards": set(), "gradients": set(), "steps": 0} | ||
| 123 | + states[id(self.engine)] = state | ||
| 124 | + | ||
| 125 | + for name, gate in gates.items(): | ||
| 126 | + | ||
| 127 | + def observe_forward(module, inputs, output, *, name=name): | ||
| 128 | + assert inputs[0].device.type == module.weight.device.type == "npu" | ||
| 129 | + assert inputs[0].dtype == module.weight.dtype == torch.bfloat16, "Router selected the FP32 fallback" | ||
| 130 | + assert output.dtype == torch.float32 | ||
| 131 | + state["forwards"].add(name) | ||
| 132 | + | ||
| 133 | + def observe_weight_gradient(gradient): | ||
| 134 | + assert gradient.dtype == torch.float32, "Router local WGRAD was rounded to BF16" | ||
| 135 | + state["gradients"].add(name) | ||
| 136 | + | ||
| 137 | + handles.append(module.weight.register_hook(observe_weight_gradient)) | ||
| 138 | + | ||
| 139 | + handles.append(gate.register_forward_hook(observe_forward)) | ||
| 140 | + | ||
| 141 | + @wraps(original_optim_step) | ||
| 142 | + def optim_step(self): | ||
| 143 | + state = states[id(self)] | ||
| 144 | + expected = set(state["gates"]) | ||
| 145 | + assert state["forwards"] == expected and state["gradients"] == expected | ||
| 146 | + for gate in state["gates"].values(): | ||
| 147 | + assert gate.weight.grad is not None and gate.weight.grad.dtype == torch.float32 | ||
| 148 | + result = original_optim_step(self) | ||
| 149 | + state["steps"] += 1 | ||
| 150 | + state["forwards"].clear() | ||
| 151 | + state["gradients"].clear() | ||
| 152 | + return result | ||
| 153 | + | ||
| 154 | + @wraps(original_train) | ||
| 155 | + def train(self): | ||
| 156 | + original_train(self) | ||
| 157 | + assert states[id(self.engine)]["steps"] == self.engine.num_completed_steps == self.config.training.steps == 10 | ||
| 158 | + print("HIMIDLO_TRAINING PASS: ten EP2/FSDP2 steps with BF16 routers and FP32 output/WGRAD", flush=True) | ||
| 159 | + | ||
| 160 | + TrainerEx.__init__, TrainerEx.train, TrainingEngine.optim_step = initialize, train, optim_step | ||
| 161 | + try: | ||
| 162 | + train_main() | ||
| 163 | + finally: | ||
| 164 | + TrainerEx.__init__, TrainerEx.train = original_init, original_train | ||
| 165 | + TrainingEngine.optim_step = original_optim_step | ||
| 166 | + for handle in handles: | ||
| 167 | + handle.remove() | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +if __name__ == "__main__": | ||
| 171 | + main() | ||
| @@ -40,6 +40,7 @@ from tests.integration_tests.deepseek_v4_1 import ( | |||
| 40 | build_deepseek_v4_1_test_list, | 40 | build_deepseek_v4_1_test_list, |
| 41 | ) | 41 | ) |
| 42 | from tests.integration_tests.ema import assert_ema_checkpoint_written, build_ema_test_list | 42 | from tests.integration_tests.ema import assert_ema_checkpoint_written, build_ema_test_list |
| 43 | +from tests.integration_tests.hi_mid_lo_linear import build_hi_mid_lo_linear_test_list | ||
| 43 | from tests.integration_tests.loss_compare import ( | 44 | from tests.integration_tests.loss_compare import ( |
| 44 | assert_losses_equal, | 45 | assert_losses_equal, |
| 45 | compare_checkpoint_metrics, | 46 | compare_checkpoint_metrics, |
| @@ -69,6 +70,7 @@ def build_models_test_list() -> list[OverrideDefinitions]: | |||
| 69 | + build_deepseek_v4_1_reference_multimodal_test_list() | 70 | + build_deepseek_v4_1_reference_multimodal_test_list() |
| 70 | + build_deepseek_v3_2_test_list() | 71 | + build_deepseek_v3_2_test_list() |
| 71 | + build_qwen3_5_test_list() | 72 | + build_qwen3_5_test_list() |
| 73 | + + build_hi_mid_lo_linear_test_list() | ||
| 72 | ) | 74 | ) |
| 73 | 75 | ||
| 74 | 76 | ||
| @@ -88,6 +90,7 @@ def build_engram_cp_test_list(): | |||
| 88 | # torchtitan-npu override: register the DeepSeek-V4, V4.1 and V3.2 NPU suites. | 90 | # torchtitan-npu override: register the DeepSeek-V4, V4.1 and V3.2 NPU suites. |
| 89 | _TEST_SUITES_FUNCTION = { | 91 | _TEST_SUITES_FUNCTION = { |
| 90 | "models": build_models_test_list, | 92 | "models": build_models_test_list, |
| 93 | + "hi_mid_lo_linear": build_hi_mid_lo_linear_test_list, | ||
| 91 | "deepseek_v3_2": build_deepseek_v3_2_test_list, | 94 | "deepseek_v3_2": build_deepseek_v3_2_test_list, |
| 92 | "deepseek_v4": build_deepseek_v4_test_list, | 95 | "deepseek_v4": build_deepseek_v4_test_list, |
| 93 | "deepseek_v4_1": build_deepseek_v4_1_test_list, | 96 | "deepseek_v4_1": build_deepseek_v4_1_test_list, |
| @@ -0,0 +1,134 @@ | |||
| 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 | +"""One-NPU fused HiMidLoLinear boundary and gradient-layout numerics. | ||
| 7 | + | ||
| 8 | +Requires the matched torch/torch_npu runtime and the fused NPU operator. The | ||
| 9 | +independent CPU FP64 projection checks both output and requested gradients; | ||
| 10 | +distributed router selection and training have separate integration coverage. | ||
| 11 | +""" | ||
| 12 | + | ||
| 13 | +import pytest | ||
| 14 | +import torch | ||
| 15 | + | ||
| 16 | +pytest.importorskip( | ||
| 17 | + "torchtitan.models.common.linear.hi_mid_lo_linear", reason="Requires released TorchTitan v0.4.0 APIs" | ||
| 18 | +) | ||
| 19 | +pytest.importorskip("torch_npu") | ||
| 20 | + | ||
| 21 | +from torchtitan_npu.override.common.hi_mid_lo_linear import AscHiMidLoLinear | ||
| 22 | + | ||
| 23 | +pytestmark = [ | ||
| 24 | + pytest.mark.smoke, | ||
| 25 | + pytest.mark.skipif(not torch.npu.is_available(), reason="Ascend NPU is required"), | ||
| 26 | +] | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def _upstream_gradients(tokens, out_features, layout, generator): | ||
| 30 | + """Create the view after transfer so the NPU gradient keeps its strides.""" | ||
| 31 | + if layout == "transposed": | ||
| 32 | + base = torch.randn(out_features, tokens, generator=generator, dtype=torch.float32) | ||
| 33 | + return base.T, base.to("npu").T | ||
| 34 | + if layout == "sliced": | ||
| 35 | + base = torch.randn(2 * tokens, 2 * out_features, generator=generator, dtype=torch.float32) | ||
| 36 | + return base[::2, ::2], base.to("npu")[::2, ::2] | ||
| 37 | + if layout == "expanded": | ||
| 38 | + base = torch.randn(1, out_features, generator=generator, dtype=torch.float32) | ||
| 39 | + return base.expand(tokens, -1), base.to("npu").expand(tokens, -1) | ||
| 40 | + base = torch.randn(tokens, out_features, generator=generator, dtype=torch.float32) | ||
| 41 | + return base, base.to("npu") | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +@pytest.mark.parametrize( | ||
| 45 | + ("mode", "tokens", "in_features", "out_features", "layout", "input_grad", "weight_grad"), | ||
| 46 | + [ | ||
| 47 | + ("hi_mid", 7, 37, 5, "contiguous", True, True), | ||
| 48 | + ("hi_mid_lo", 7, 37, 5, "contiguous", True, True), | ||
| 49 | + ("hi_mid", 3, 35, 17, "transposed", True, True), | ||
| 50 | + ("hi_mid_lo", 3, 35, 17, "sliced", True, True), | ||
| 51 | + ("hi_mid", 9, 37, 5, "expanded", True, True), | ||
| 52 | + ("hi_mid_lo", 9, 37, 5, "expanded", True, True), | ||
| 53 | + ("hi_mid", 1, 33, 7, "contiguous", True, True), | ||
| 54 | + ("hi_mid_lo", 1, 33, 7, "contiguous", True, True), | ||
| 55 | + ("hi_mid", 0, 33, 7, "contiguous", True, True), | ||
| 56 | + ("hi_mid_lo", 0, 33, 7, "contiguous", True, True), | ||
| 57 | + ("hi_mid_lo", 7, 37, 5, "transposed", True, False), | ||
| 58 | + ("hi_mid_lo", 3, 35, 17, "sliced", False, True), | ||
| 59 | + ], | ||
| 60 | + ids=[ | ||
| 61 | + "two-odd-narrow", | ||
| 62 | + "three-odd-narrow", | ||
| 63 | + "two-wide-transposed-grad", | ||
| 64 | + "three-wide-sliced-grad", | ||
| 65 | + "two-zero-stride-grad", | ||
| 66 | + "three-zero-stride-grad", | ||
| 67 | + "two-one-token", | ||
| 68 | + "three-one-token", | ||
| 69 | + "two-empty-tokens", | ||
| 70 | + "three-empty-tokens", | ||
| 71 | + "input-only-transposed-grad", | ||
| 72 | + "weight-only-sliced-grad", | ||
| 73 | + ], | ||
| 74 | +) | ||
| 75 | +def test_fused_hi_mid_lo_npu_matches_fp64_at_boundaries_and_gradient_layouts( | ||
| 76 | + mode, tokens, in_features, out_features, layout, input_grad, weight_grad | ||
| 77 | +): | ||
| 78 | + generator = torch.Generator().manual_seed(5127) | ||
| 79 | + input_cpu = torch.randn(tokens, in_features, generator=generator).bfloat16() | ||
| 80 | + weight_cpu = torch.randn(out_features, in_features, generator=generator).bfloat16() | ||
| 81 | + with torch.random.fork_rng(devices=[]): | ||
| 82 | + layer = AscHiMidLoLinear.Config( | ||
| 83 | + in_features=in_features, | ||
| 84 | + out_features=out_features, | ||
| 85 | + bias=False, | ||
| 86 | + backward_mode=mode, | ||
| 87 | + inplace_wgrad_accum=False, | ||
| 88 | + ).build().to(device="npu", dtype=torch.bfloat16) | ||
| 89 | + with torch.no_grad(): | ||
| 90 | + layer.weight.copy_(weight_cpu) | ||
| 91 | + layer.weight.requires_grad_(weight_grad) | ||
| 92 | + layer.weight.grad_dtype = torch.float32 | ||
| 93 | + input = input_cpu.to("npu").requires_grad_(input_grad) | ||
| 94 | + input_ref = input_cpu.double().requires_grad_(input_grad) | ||
| 95 | + weight_ref = weight_cpu.double().requires_grad_(weight_grad) | ||
| 96 | + upstream_cpu, upstream_npu = _upstream_gradients(tokens, out_features, layout, generator) | ||
| 97 | + | ||
| 98 | + if layout in {"transposed", "sliced"}: | ||
| 99 | + assert not upstream_npu.is_contiguous() | ||
| 100 | + elif layout == "expanded": | ||
| 101 | + assert upstream_npu.stride(0) == 0 | ||
| 102 | + | ||
| 103 | + expected = input_ref @ weight_ref.T | ||
| 104 | + actual = layer(input) | ||
| 105 | + actual.backward(upstream_npu) | ||
| 106 | + expected.backward(upstream_cpu.double()) | ||
| 107 | + torch.npu.synchronize() | ||
| 108 | + | ||
| 109 | + assert actual.shape == (tokens, out_features) | ||
| 110 | + assert actual.dtype is torch.float32 | ||
| 111 | + torch.testing.assert_close(actual.detach().cpu(), expected.detach().float(), rtol=3e-5, atol=2e-5) | ||
| 112 | + if input_grad: | ||
| 113 | + assert input.grad.dtype is torch.bfloat16 | ||
| 114 | + torch.testing.assert_close(input.grad.cpu(), input_ref.grad.bfloat16(), rtol=8e-3, atol=2e-3) | ||
| 115 | + else: | ||
| 116 | + assert input.grad is None | ||
| 117 | + if weight_grad: | ||
| 118 | + assert layer.weight.grad.dtype is torch.float32 | ||
| 119 | + gradient = layer.weight.grad.cpu() | ||
| 120 | + expected_gradient = weight_ref.grad | ||
| 121 | + assert bool(torch.isfinite(gradient).all()) | ||
| 122 | + if tokens == 0: | ||
| 123 | + torch.testing.assert_close(gradient, expected_gradient.float(), rtol=0, atol=0) | ||
| 124 | + else: | ||
| 125 | + relative_l2 = (gradient.double() - expected_gradient).norm() / expected_gradient.norm() | ||
| 126 | + assert relative_l2 < (1e-5 if mode == "hi_mid" else 1e-6) | ||
| 127 | + torch.testing.assert_close( | ||
| 128 | + gradient, | ||
| 129 | + expected_gradient.float(), | ||
| 130 | + rtol=1e-4, | ||
| 131 | + atol=5e-5 if mode == "hi_mid" else 1e-5, | ||
| 132 | + ) | ||
| 133 | + else: | ||
| 134 | + assert layer.weight.grad is None | ||
| @@ -0,0 +1,120 @@ | |||
| 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 | +"""One-NPU HiMidLo tiling numerics across fresh buffers and irregular layouts.""" | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | + | ||
| 11 | +pytest.importorskip( | ||
| 12 | + "torchtitan.models.common.linear.hi_mid_lo_linear", reason="Requires released TorchTitan v0.4.0 APIs" | ||
| 13 | +) | ||
| 14 | +pytest.importorskip("torch_npu") | ||
| 15 | + | ||
| 16 | +from torchtitan_npu.override.common.hi_mid_lo_linear import AscHiMidLoLinear | ||
| 17 | + | ||
| 18 | +pytestmark = [ | ||
| 19 | + pytest.mark.smoke, | ||
| 20 | + pytest.mark.skipif(not torch.npu.is_available(), reason="Ascend NPU is required"), | ||
| 21 | +] | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def _operands(tokens, features, outputs, *, seed, layout="contiguous", device): | ||
| 25 | + generator = torch.Generator().manual_seed(seed) | ||
| 26 | + input_cpu = torch.randn(tokens, features, generator=generator).bfloat16() | ||
| 27 | + weight_cpu = torch.randn(outputs, features, generator=generator).bfloat16() | ||
| 28 | + if layout == "expanded": | ||
| 29 | + upstream_cpu = torch.randn(1, outputs, generator=generator).expand(tokens, -1) | ||
| 30 | + else: | ||
| 31 | + upstream_cpu = torch.randn(tokens, outputs, generator=generator) | ||
| 32 | + | ||
| 33 | + if layout == "contiguous": | ||
| 34 | + input = input_cpu.to(device) | ||
| 35 | + weight = weight_cpu.to(device) | ||
| 36 | + upstream = upstream_cpu.to(device) | ||
| 37 | + else: | ||
| 38 | + # Slice after transfer: storage offsets are intentionally not 16-byte | ||
| 39 | + # aligned and the row strides differ from the contiguous warmup. | ||
| 40 | + input = torch.empty((tokens, features + 1), dtype=torch.bfloat16, device=device)[:, 1:] | ||
| 41 | + weight = torch.empty((outputs, features + 1), dtype=torch.bfloat16, device=device)[:, 1:] | ||
| 42 | + input.copy_(input_cpu) | ||
| 43 | + weight.copy_(weight_cpu) | ||
| 44 | + if layout == "expanded": | ||
| 45 | + upstream = upstream_cpu[:1].to(device).expand(tokens, -1) | ||
| 46 | + else: | ||
| 47 | + upstream = torch.empty((tokens, 2 * outputs + 1), dtype=torch.float32, device=device)[:, 1::2] | ||
| 48 | + upstream.copy_(upstream_cpu) | ||
| 49 | + return (input, weight, upstream), (input_cpu, weight_cpu, upstream_cpu) | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def _assert_backward_matches_fp64(actual, reference, *, num_pieces): | ||
| 53 | + input_cpu, weight_cpu, upstream_cpu = reference | ||
| 54 | + expected_dx = upstream_cpu.double() @ weight_cpu.double() | ||
| 55 | + expected_dw = upstream_cpu.double().T @ input_cpu.double() | ||
| 56 | + actual_dx, actual_dw = (tensor.detach().cpu() for tensor in actual) | ||
| 57 | + assert actual_dx.dtype is torch.bfloat16 | ||
| 58 | + assert actual_dw.dtype is torch.float32 | ||
| 59 | + assert bool(torch.isfinite(actual_dx).all()) | ||
| 60 | + assert bool(torch.isfinite(actual_dw).all()) | ||
| 61 | + torch.testing.assert_close(actual_dx, expected_dx.bfloat16(), rtol=8e-3, atol=2e-3) | ||
| 62 | + relative_l2 = (actual_dw.double() - expected_dw).norm() / expected_dw.norm() | ||
| 63 | + assert relative_l2 < (1e-5 if num_pieces == 2 else 1e-6) | ||
| 64 | + if num_pieces == 2: | ||
| 65 | + # Two pieces deliberately omit the low BF16 residual. Keep the full | ||
| 66 | + # FP64 relative-error requirement above, then isolate accumulation | ||
| 67 | + # accuracy from that quantization using an independent CPU oracle. | ||
| 68 | + hi = upstream_cpu.bfloat16().float() | ||
| 69 | + mid = (upstream_cpu - hi).bfloat16().float() | ||
| 70 | + effective_upstream = hi.double() + mid.double() | ||
| 71 | + component_reference = effective_upstream.T @ input_cpu.double() | ||
| 72 | + else: | ||
| 73 | + component_reference = expected_dw | ||
| 74 | + torch.testing.assert_close(actual_dw, component_reference.float(), rtol=1e-4, atol=1e-5) | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def _module_projection(operands, *, num_pieces): | ||
| 78 | + input, weight, upstream = operands | ||
| 79 | + with torch.random.fork_rng(devices=[]): | ||
| 80 | + layer = AscHiMidLoLinear.Config( | ||
| 81 | + in_features=input.shape[1], | ||
| 82 | + out_features=weight.shape[0], | ||
| 83 | + bias=False, | ||
| 84 | + backward_mode="hi_mid" if num_pieces == 2 else "hi_mid_lo", | ||
| 85 | + inplace_wgrad_accum=False, | ||
| 86 | + ).build().to(device=input.device, dtype=torch.bfloat16) | ||
| 87 | + # Keep the raw leaf parameter at the Function boundary, including its | ||
| 88 | + # noncontiguous storage layout; a view backward could round FP32 dW. | ||
| 89 | + layer.weight = torch.nn.Parameter(weight) | ||
| 90 | + layer.weight.grad_dtype = torch.float32 | ||
| 91 | + input.requires_grad_() | ||
| 92 | + output = layer(input) | ||
| 93 | + output.backward(upstream) | ||
| 94 | + return layer, input, output | ||
| 95 | + | ||
| 96 | + | ||
| 97 | +@pytest.mark.parametrize("num_pieces", (2, 3), ids=("two-pieces", "three-pieces")) | ||
| 98 | +@pytest.mark.parametrize("layout", ("contiguous", "sliced", "expanded"), ids=("tuned-tail", "unaligned", "zero-stride")) | ||
| 99 | +def test_hi_mid_lo_tiled_projection_matches_fp64_after_warmup(num_pieces, layout): | ||
| 100 | + device = torch.device("npu", torch.npu.current_device()) | ||
| 101 | + warm, _ = _operands(129, 131, 65, seed=613, device=device) | ||
| 102 | + # Retain warm operands and outputs so repeated launches after warmup use | ||
| 103 | + # distinct buffers rather than addresses recycled by the allocator. | ||
| 104 | + keep_alive = [_module_projection(warm, num_pieces=num_pieces)] | ||
| 105 | + torch.npu.synchronize() | ||
| 106 | + | ||
| 107 | + for seed in (718, 823): | ||
| 108 | + operands, reference = _operands(129, 131, 65, seed=seed, layout=layout, device=device) | ||
| 109 | + if layout == "sliced": | ||
| 110 | + assert operands[2].stride(1) == 2 | ||
| 111 | + assert operands[2].data_ptr() % 16 != 0 | ||
| 112 | + elif layout == "expanded": | ||
| 113 | + assert operands[2].stride(0) == 0 | ||
| 114 | + layer, input, output = _module_projection(operands, num_pieces=num_pieces) | ||
| 115 | + torch.npu.synchronize() | ||
| 116 | + expected_output = reference[0].double() @ reference[1].double().T | ||
| 117 | + assert output.dtype is torch.float32 | ||
| 118 | + torch.testing.assert_close(output.detach().cpu(), expected_output.float(), rtol=3e-5, atol=2e-5) | ||
| 119 | + _assert_backward_matches_fp64((input.grad, layer.weight.grad), reference, num_pieces=num_pieces) | ||
| 120 | + keep_alive.append((layer, input, output, operands)) | ||
| @@ -0,0 +1,127 @@ | |||
| 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 | +"""One-NPU BF16 HiMidLoLinear numerics with FP32 output and WGRAD. | ||
| 7 | + | ||
| 8 | +Requires the matched torch/torch_npu runtime with aten.mm.dtype support. These | ||
| 9 | +small eager projections exercise the device kernel; distributed training has | ||
| 10 | +separate integration coverage. | ||
| 11 | +""" | ||
| 12 | + | ||
| 13 | +import pytest | ||
| 14 | +import torch | ||
| 15 | +from torchtitan.config import ConfigLoader, apply_overrides | ||
| 16 | + | ||
| 17 | +pytest.importorskip("torchtitan.models.common.linear.hi_mid_lo_linear", reason="Requires released TorchTitan v0.4.0 APIs") | ||
| 18 | + | ||
| 19 | +from torchtitan.models.common.linear.hi_mid_lo_linear import HiMidLoLinear | ||
| 20 | + | ||
| 21 | +pytest.importorskip("torch_npu") | ||
| 22 | + | ||
| 23 | +from torchtitan_npu.override.common.hi_mid_lo_linear import AscHiMidLoLinear | ||
| 24 | + | ||
| 25 | +pytestmark = [ | ||
| 26 | + pytest.mark.smoke, | ||
| 27 | + pytest.mark.skipif(not torch.npu.is_available(), reason="Ascend NPU is required"), | ||
| 28 | +] | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def _autograd_node_names(output): | ||
| 32 | + pending = [output.grad_fn] | ||
| 33 | + visited = set() | ||
| 34 | + names = set() | ||
| 35 | + while pending: | ||
| 36 | + node = pending.pop() | ||
| 37 | + if node is None or node in visited: | ||
| 38 | + continue | ||
| 39 | + visited.add(node) | ||
| 40 | + names.add(type(node).__name__) | ||
| 41 | + pending.extend(child for child, _ in node.next_functions) | ||
| 42 | + return names | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +@pytest.mark.parametrize( | ||
| 46 | + ("mode", "tokens", "out_features", "num_linears", "input_grad", "weight_grad"), | ||
| 47 | + [ | ||
| 48 | + ("hi_mid", 32, 8, 1, True, True), | ||
| 49 | + ("hi_mid_lo", 32, 8, 1, True, True), | ||
| 50 | + ("hi_mid", 4, 32, 1, True, True), | ||
| 51 | + ("hi_mid_lo", 4, 32, 1, True, True), | ||
| 52 | + ("hi_mid_lo", 16, 4, 2, True, True), | ||
| 53 | + ("hi_mid_lo", 32, 8, 1, True, False), | ||
| 54 | + ("hi_mid_lo", 4, 32, 1, False, True), | ||
| 55 | + ], | ||
| 56 | + ids=["two-narrow", "three-narrow", "two-wide", "three-wide", "stacked", "input-only", "weight-only"], | ||
| 57 | +) | ||
| 58 | +def test_recipe_selected_hi_mid_lo_npu_retains_fp32_projection_and_wgrad( | ||
| 59 | + mode, tokens, out_features, num_linears, input_grad, weight_grad | ||
| 60 | +): | ||
| 61 | + with torch.random.fork_rng(devices=[]): | ||
| 62 | + config = ConfigLoader().load( | ||
| 63 | + ["--module", "torchtitan_npu.models.deepseek_v4.config_registry", "--config", "deepseek_v4_debugmodel"] | ||
| 64 | + ) | ||
| 65 | + config.model.lm_head = HiMidLoLinear.Config( | ||
| 66 | + in_features=32, | ||
| 67 | + out_features=out_features, | ||
| 68 | + num_linears=num_linears, | ||
| 69 | + bias=True, | ||
| 70 | + backward_mode=mode, | ||
| 71 | + inplace_wgrad_accum=False, | ||
| 72 | + ) | ||
| 73 | + config.override.imports = ["torchtitan_npu.override.common.hi_mid_lo_linear.asc"] | ||
| 74 | + apply_overrides(config.override, config) | ||
| 75 | + assert type(config.model.lm_head) is AscHiMidLoLinear.Config | ||
| 76 | + layer = config.model.lm_head.build().to(device="npu", dtype=torch.bfloat16) | ||
| 77 | + | ||
| 78 | + assert type(layer) is AscHiMidLoLinear | ||
| 79 | + generator = torch.Generator().manual_seed(1741) | ||
| 80 | + input_cpu = torch.randn(2, tokens // 2, 32, generator=generator).bfloat16() | ||
| 81 | + weight_cpu = torch.randn(layer.weight.shape, generator=generator).bfloat16() | ||
| 82 | + bias_cpu = torch.linspace(-0.75, 0.5, layer.bias.numel()).reshape(layer.bias.shape).bfloat16() | ||
| 83 | + with torch.no_grad(): | ||
| 84 | + layer.weight.copy_(weight_cpu) | ||
| 85 | + layer.bias.copy_(bias_cpu) | ||
| 86 | + layer.weight.requires_grad_(weight_grad) | ||
| 87 | + layer.weight.grad_dtype = torch.float32 | ||
| 88 | + input = input_cpu.to("npu").requires_grad_(input_grad) | ||
| 89 | + input_ref = input_cpu.double().requires_grad_(input_grad) | ||
| 90 | + weight_ref = weight_cpu.double().requires_grad_(weight_grad) | ||
| 91 | + bias_ref = bias_cpu.double().requires_grad_() | ||
| 92 | + if num_linears == 1: | ||
| 93 | + expected = torch.einsum("btd,od->bto", input_ref, weight_ref) + bias_ref | ||
| 94 | + else: | ||
| 95 | + expected = torch.einsum("btd,nod->btno", input_ref, weight_ref) + bias_ref | ||
| 96 | + upstream_cpu = torch.randn(expected.shape, generator=generator, dtype=torch.float32) | ||
| 97 | + | ||
| 98 | + actual = layer(input) | ||
| 99 | + # Selection alone cannot distinguish the NPU kernel from the portable fallback. | ||
| 100 | + assert "_AscHiMidLoLinearFunctionBackward" in _autograd_node_names(actual) | ||
| 101 | + actual.backward(upstream_cpu.to("npu")) | ||
| 102 | + expected.backward(upstream_cpu.double()) | ||
| 103 | + torch.npu.synchronize() | ||
| 104 | + | ||
| 105 | + assert actual.dtype is torch.float32 | ||
| 106 | + assert actual.shape == expected.shape | ||
| 107 | + actual_cpu = actual.detach().cpu() | ||
| 108 | + assert bool((actual_cpu != actual_cpu.bfloat16().float()).any()) | ||
| 109 | + torch.testing.assert_close(actual_cpu, expected.float(), rtol=3e-5, atol=2e-5) | ||
| 110 | + if input_grad: | ||
| 111 | + torch.testing.assert_close(input.grad.cpu(), input_ref.grad.bfloat16(), rtol=8e-3, atol=2e-3) | ||
| 112 | + else: | ||
| 113 | + assert input.grad is None | ||
| 114 | + if weight_grad: | ||
| 115 | + assert layer.weight.grad.dtype is torch.float32 | ||
| 116 | + grad_cpu = layer.weight.grad.cpu() | ||
| 117 | + assert bool((grad_cpu != grad_cpu.bfloat16().float()).any()) | ||
| 118 | + # Two pieces retain about 16 significant bits of grad_output; three | ||
| 119 | + # reconstruct it exactly before the GEMM's own accumulation rounding. | ||
| 120 | + relative_l2 = (grad_cpu.double() - weight_ref.grad).norm() / weight_ref.grad.norm() | ||
| 121 | + assert relative_l2 < (1e-5 if mode == "hi_mid" else 1e-6) | ||
| 122 | + torch.testing.assert_close( | ||
| 123 | + grad_cpu, weight_ref.grad.float(), rtol=1e-4, atol=5e-5 if mode == "hi_mid" else 1e-5 | ||
| 124 | + ) | ||
| 125 | + else: | ||
| 126 | + assert layer.weight.grad is None | ||
| 127 | + torch.testing.assert_close(layer.bias.grad.cpu(), bias_ref.grad.bfloat16(), rtol=8e-3, atol=2e-3) | ||
| @@ -0,0 +1,78 @@ | |||
| 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 | +"""The recipe-selected NPU linear retains the portable dense fallback.""" | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | +from torchtitan.config import ConfigLoader, apply_overrides | ||
| 11 | +from torchtitan.models.common.linear import Linear | ||
| 12 | + | ||
| 13 | +pytest.importorskip("torchtitan.models.common.linear.hi_mid_lo_linear", reason="Requires released TorchTitan v0.4.0 APIs") | ||
| 14 | + | ||
| 15 | +from torchtitan.models.common.linear.hi_mid_lo_linear import HiMidLoLinear | ||
| 16 | + | ||
| 17 | +from torchtitan_npu.override.common.hi_mid_lo_linear import AscHiMidLoLinear | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +@pytest.mark.parametrize( | ||
| 21 | + ("input_dtype", "weight_dtype"), | ||
| 22 | + [ | ||
| 23 | + (torch.bfloat16, torch.bfloat16), | ||
| 24 | + (torch.float32, torch.bfloat16), | ||
| 25 | + (torch.bfloat16, torch.float32), | ||
| 26 | + ], | ||
| 27 | + ids=["bf16", "fp32-input", "fp32-weight"], | ||
| 28 | +) | ||
| 29 | +def test_recipe_selected_hi_mid_lo_cpu_fallback_preserves_stacked_projection(input_dtype, weight_dtype): | ||
| 30 | + with torch.random.fork_rng(devices=[]): | ||
| 31 | + config = ConfigLoader().load( | ||
| 32 | + ["--module", "torchtitan_npu.models.deepseek_v4.config_registry", "--config", "deepseek_v4_debugmodel"] | ||
| 33 | + ) | ||
| 34 | + config.model.lm_head = HiMidLoLinear.Config( | ||
| 35 | + in_features=5, | ||
| 36 | + out_features=3, | ||
| 37 | + num_linears=2, | ||
| 38 | + bias=True, | ||
| 39 | + backward_mode="hi_mid_lo", | ||
| 40 | + inplace_wgrad_accum=False, | ||
| 41 | + ) | ||
| 42 | + ordinary_linear = next( | ||
| 43 | + node for _, node, _, _ in config.model.traverse(Linear.Config) if type(node) is Linear.Config | ||
| 44 | + ) | ||
| 45 | + config.override.imports = ["torchtitan_npu.override.common.hi_mid_lo_linear.asc"] | ||
| 46 | + | ||
| 47 | + apply_overrides(config.override, config) | ||
| 48 | + assert type(config.model.lm_head) is AscHiMidLoLinear.Config | ||
| 49 | + assert any(node is ordinary_linear for _, node, _, _ in config.model.traverse(Linear.Config)) | ||
| 50 | + layer = config.model.lm_head.build().to(dtype=weight_dtype) | ||
| 51 | + | ||
| 52 | + assert type(layer) is AscHiMidLoLinear | ||
| 53 | + assert layer.num_pieces == 3 | ||
| 54 | + assert layer.inplace_wgrad_accum is False | ||
| 55 | + generator = torch.Generator().manual_seed(732) | ||
| 56 | + input = torch.randn(2, 3, 5, generator=generator).to(input_dtype).requires_grad_() | ||
| 57 | + with torch.no_grad(): | ||
| 58 | + layer.weight.copy_(torch.randn(2, 3, 5, generator=generator)) | ||
| 59 | + layer.bias.copy_(torch.tensor([[0.125, -0.375, 0.625], [-0.25, 0.5, -0.875]])) | ||
| 60 | + # FSDP2 permits a parameter's gradient dtype to exceed its forward dtype. | ||
| 61 | + layer.weight.grad_dtype = torch.float32 | ||
| 62 | + input_ref = input.detach().double().requires_grad_() | ||
| 63 | + weight_ref = layer.weight.detach().double().requires_grad_() | ||
| 64 | + bias_ref = layer.bias.detach().double().requires_grad_() | ||
| 65 | + expected = torch.einsum("btd,nod->btno", input_ref, weight_ref) + bias_ref | ||
| 66 | + upstream = torch.randn(expected.shape, generator=generator, dtype=torch.float32) | ||
| 67 | + | ||
| 68 | + actual = layer(input) | ||
| 69 | + actual.backward(upstream) | ||
| 70 | + expected.backward(upstream.double()) | ||
| 71 | + | ||
| 72 | + assert actual.shape == (2, 3, 2, 3) | ||
| 73 | + assert actual.dtype is torch.float32 | ||
| 74 | + assert layer.weight.grad.dtype is torch.float32 | ||
| 75 | + torch.testing.assert_close(actual, expected.float(), rtol=2e-6, atol=2e-6) | ||
| 76 | + torch.testing.assert_close(input.grad, input_ref.grad.to(input_dtype), rtol=2e-6, atol=2e-6) | ||
| 77 | + torch.testing.assert_close(layer.weight.grad, weight_ref.grad.float(), rtol=2e-6, atol=2e-6) | ||
| 78 | + torch.testing.assert_close(layer.bias.grad, bias_ref.grad.to(weight_dtype), rtol=2e-6, atol=2e-6) | ||
| @@ -0,0 +1,310 @@ | |||
| 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 | +"""Single-launch NPU HiMidLo backward with on-chip gradient splitting. | ||
| 7 | + | ||
| 8 | +Each program owns either an input-gradient or weight-gradient tile. BF16 | ||
| 9 | +pieces stay on chip and weight-gradient accumulation remains FP32. | ||
| 10 | +""" | ||
| 11 | + | ||
| 12 | +import torch | ||
| 13 | +import triton | ||
| 14 | +import triton.language as tl | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +@triton.jit | ||
| 18 | +def _rounded_fp32(value): | ||
| 19 | + bits = value.to(tl.int16, bitcast=True).to(tl.int32) << 16 | ||
| 20 | + return bits.to(tl.float32, bitcast=True) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +@triton.jit | ||
| 24 | +def _gradient_tile( | ||
| 25 | + grad_ptr, | ||
| 26 | + operand_ptr, | ||
| 27 | + output_ptr, | ||
| 28 | + TILE_M, | ||
| 29 | + TILE_N, | ||
| 30 | + M: tl.constexpr, | ||
| 31 | + N: tl.constexpr, | ||
| 32 | + K: tl.constexpr, | ||
| 33 | + stride_gm: tl.constexpr, | ||
| 34 | + stride_gk: tl.constexpr, | ||
| 35 | + stride_bk: tl.constexpr, | ||
| 36 | + stride_bn: tl.constexpr, | ||
| 37 | + NUM_PIECES: tl.constexpr, | ||
| 38 | + BLOCK_M: tl.constexpr, | ||
| 39 | + BLOCK_N: tl.constexpr, | ||
| 40 | + BLOCK_K: tl.constexpr, | ||
| 41 | +): | ||
| 42 | + rows = TILE_M * BLOCK_M + tl.arange(0, BLOCK_M) | ||
| 43 | + cols = TILE_N * BLOCK_N + tl.arange(0, BLOCK_N) | ||
| 44 | + reduction = tl.arange(0, BLOCK_K) | ||
| 45 | + acc_hi = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) | ||
| 46 | + acc_mid = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) | ||
| 47 | + acc_lo = tl.zeros((BLOCK_M, BLOCK_N), tl.float32) | ||
| 48 | + for block in range(tl.cdiv(K, BLOCK_K)): | ||
| 49 | + offsets = block * BLOCK_K + reduction | ||
| 50 | + grad = tl.load( | ||
| 51 | + grad_ptr + rows[:, None] * stride_gm + offsets[None, :] * stride_gk, | ||
| 52 | + mask=(rows[:, None] < M) & (offsets[None, :] < K), | ||
| 53 | + other=0.0, | ||
| 54 | + ).to(tl.float32) | ||
| 55 | + operand = tl.load( | ||
| 56 | + operand_ptr + offsets[:, None] * stride_bk + cols[None, :] * stride_bn, | ||
| 57 | + mask=(offsets[:, None] < K) & (cols[None, :] < N), | ||
| 58 | + other=0.0, | ||
| 59 | + ) | ||
| 60 | + hi = grad.to(tl.bfloat16) | ||
| 61 | + rest = grad - _rounded_fp32(hi) | ||
| 62 | + mid = rest.to(tl.bfloat16) | ||
| 63 | + acc_hi = tl.dot(hi, operand, acc_hi) | ||
| 64 | + acc_mid = tl.dot(mid, operand, acc_mid) | ||
| 65 | + if NUM_PIECES == 3: | ||
| 66 | + lo = (rest - _rounded_fp32(mid)).to(tl.bfloat16) | ||
| 67 | + acc_lo = tl.dot(lo, operand, acc_lo) | ||
| 68 | + result = acc_hi + acc_mid | ||
| 69 | + if NUM_PIECES == 3: | ||
| 70 | + result += acc_lo | ||
| 71 | + tl.store( | ||
| 72 | + output_ptr + rows[:, None] * N + cols[None, :], | ||
| 73 | + result, | ||
| 74 | + mask=(rows[:, None] < M) & (cols[None, :] < N), | ||
| 75 | + ) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +@triton.jit | ||
| 79 | +def _write_dx( | ||
| 80 | + tile, | ||
| 81 | + grad_ptr, | ||
| 82 | + weight_ptr, | ||
| 83 | + dx_ptr, | ||
| 84 | + T: tl.constexpr, | ||
| 85 | + D: tl.constexpr, | ||
| 86 | + O: tl.constexpr, | ||
| 87 | + G_STRIDE_T: tl.constexpr, | ||
| 88 | + G_STRIDE_O: tl.constexpr, | ||
| 89 | + W_STRIDE_O: tl.constexpr, | ||
| 90 | + W_STRIDE_D: tl.constexpr, | ||
| 91 | + NUM_PIECES: tl.constexpr, | ||
| 92 | + TUNED: tl.constexpr, | ||
| 93 | +): | ||
| 94 | + block_m: tl.constexpr = 64 if TUNED else 32 | ||
| 95 | + block_n: tl.constexpr = 128 if TUNED else 64 | ||
| 96 | + block_k: tl.constexpr = (256 if O > T else 128) if TUNED else 32 | ||
| 97 | + columns = tl.cdiv(D, block_n) | ||
| 98 | + _gradient_tile( | ||
| 99 | + grad_ptr, | ||
| 100 | + weight_ptr, | ||
| 101 | + dx_ptr, | ||
| 102 | + tile // columns, | ||
| 103 | + tile % columns, | ||
| 104 | + T, | ||
| 105 | + D, | ||
| 106 | + O, | ||
| 107 | + G_STRIDE_T, | ||
| 108 | + G_STRIDE_O, | ||
| 109 | + W_STRIDE_O, | ||
| 110 | + W_STRIDE_D, | ||
| 111 | + NUM_PIECES, | ||
| 112 | + block_m, | ||
| 113 | + block_n, | ||
| 114 | + block_k, | ||
| 115 | + ) | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +@triton.jit | ||
| 119 | +def _write_dw( | ||
| 120 | + tile, | ||
| 121 | + grad_ptr, | ||
| 122 | + input_ptr, | ||
| 123 | + dw_ptr, | ||
| 124 | + T: tl.constexpr, | ||
| 125 | + D: tl.constexpr, | ||
| 126 | + O: tl.constexpr, | ||
| 127 | + G_STRIDE_T: tl.constexpr, | ||
| 128 | + G_STRIDE_O: tl.constexpr, | ||
| 129 | + X_STRIDE_T: tl.constexpr, | ||
| 130 | + X_STRIDE_D: tl.constexpr, | ||
| 131 | + NUM_PIECES: tl.constexpr, | ||
| 132 | + TUNED: tl.constexpr, | ||
| 133 | +): | ||
| 134 | + block_m: tl.constexpr = 64 if TUNED else 16 | ||
| 135 | + block_n: tl.constexpr = 128 if TUNED else 64 | ||
| 136 | + block_k: tl.constexpr = (128 if O > T else 256) if TUNED else 64 | ||
| 137 | + columns = tl.cdiv(D, block_n) | ||
| 138 | + _gradient_tile( | ||
| 139 | + grad_ptr, | ||
| 140 | + input_ptr, | ||
| 141 | + dw_ptr, | ||
| 142 | + tile // columns, | ||
| 143 | + tile % columns, | ||
| 144 | + O, | ||
| 145 | + D, | ||
| 146 | + T, | ||
| 147 | + G_STRIDE_O, | ||
| 148 | + G_STRIDE_T, | ||
| 149 | + X_STRIDE_T, | ||
| 150 | + X_STRIDE_D, | ||
| 151 | + NUM_PIECES, | ||
| 152 | + block_m, | ||
| 153 | + block_n, | ||
| 154 | + block_k, | ||
| 155 | + ) | ||
| 156 | + | ||
| 157 | + | ||
| 158 | +@triton.jit | ||
| 159 | +def _combined_cube_backward( | ||
| 160 | + grad_ptr, | ||
| 161 | + input_ptr, | ||
| 162 | + weight_ptr, | ||
| 163 | + dx_ptr, | ||
| 164 | + dw_ptr, | ||
| 165 | + T: tl.constexpr, | ||
| 166 | + D: tl.constexpr, | ||
| 167 | + O: tl.constexpr, | ||
| 168 | + G_STRIDE_T: tl.constexpr, | ||
| 169 | + G_STRIDE_O: tl.constexpr, | ||
| 170 | + X_STRIDE_T: tl.constexpr, | ||
| 171 | + X_STRIDE_D: tl.constexpr, | ||
| 172 | + W_STRIDE_O: tl.constexpr, | ||
| 173 | + W_STRIDE_D: tl.constexpr, | ||
| 174 | + NUM_PIECES: tl.constexpr, | ||
| 175 | + NEEDS_DX: tl.constexpr, | ||
| 176 | + NEEDS_DW: tl.constexpr, | ||
| 177 | + DX_TILES: tl.constexpr, | ||
| 178 | + TUNED: tl.constexpr, | ||
| 179 | +): | ||
| 180 | + tile = tl.program_id(0) | ||
| 181 | + if NEEDS_DX and NEEDS_DW: | ||
| 182 | + if tile < DX_TILES: | ||
| 183 | + _write_dx( | ||
| 184 | + tile, | ||
| 185 | + grad_ptr, | ||
| 186 | + weight_ptr, | ||
| 187 | + dx_ptr, | ||
| 188 | + T, | ||
| 189 | + D, | ||
| 190 | + O, | ||
| 191 | + G_STRIDE_T, | ||
| 192 | + G_STRIDE_O, | ||
| 193 | + W_STRIDE_O, | ||
| 194 | + W_STRIDE_D, | ||
| 195 | + NUM_PIECES, | ||
| 196 | + TUNED, | ||
| 197 | + ) | ||
| 198 | + else: | ||
| 199 | + _write_dw( | ||
| 200 | + tile - DX_TILES, | ||
| 201 | + grad_ptr, | ||
| 202 | + input_ptr, | ||
| 203 | + dw_ptr, | ||
| 204 | + T, | ||
| 205 | + D, | ||
| 206 | + O, | ||
| 207 | + G_STRIDE_T, | ||
| 208 | + G_STRIDE_O, | ||
| 209 | + X_STRIDE_T, | ||
| 210 | + X_STRIDE_D, | ||
| 211 | + NUM_PIECES, | ||
| 212 | + TUNED, | ||
| 213 | + ) | ||
| 214 | + elif NEEDS_DX: | ||
| 215 | + _write_dx( | ||
| 216 | + tile, | ||
| 217 | + grad_ptr, | ||
| 218 | + weight_ptr, | ||
| 219 | + dx_ptr, | ||
| 220 | + T, | ||
| 221 | + D, | ||
| 222 | + O, | ||
| 223 | + G_STRIDE_T, | ||
| 224 | + G_STRIDE_O, | ||
| 225 | + W_STRIDE_O, | ||
| 226 | + W_STRIDE_D, | ||
| 227 | + NUM_PIECES, | ||
| 228 | + TUNED, | ||
| 229 | + ) | ||
| 230 | + elif NEEDS_DW: | ||
| 231 | + _write_dw( | ||
| 232 | + tile, | ||
| 233 | + grad_ptr, | ||
| 234 | + input_ptr, | ||
| 235 | + dw_ptr, | ||
| 236 | + T, | ||
| 237 | + D, | ||
| 238 | + O, | ||
| 239 | + G_STRIDE_T, | ||
| 240 | + G_STRIDE_O, | ||
| 241 | + X_STRIDE_T, | ||
| 242 | + X_STRIDE_D, | ||
| 243 | + NUM_PIECES, | ||
| 244 | + TUNED, | ||
| 245 | + ) | ||
| 246 | + | ||
| 247 | + | ||
| 248 | +def _backward( | ||
| 249 | + input: torch.Tensor, | ||
| 250 | + weight: torch.Tensor, | ||
| 251 | + grad_output: torch.Tensor, | ||
| 252 | + num_pieces: int, | ||
| 253 | + needs_input_grad: bool, | ||
| 254 | + needs_weight_grad: bool, | ||
| 255 | +) -> tuple[torch.Tensor | None, torch.Tensor | None]: | ||
| 256 | + """Launch the existing cube tiles for both gradients in a single grid.""" | ||
| 257 | + tokens, in_features = input.shape | ||
| 258 | + out_features = weight.shape[0] | ||
| 259 | + | ||
| 260 | + grad_input = grad_weight = None | ||
| 261 | + with torch.npu.device(input.device): | ||
| 262 | + if needs_input_grad: | ||
| 263 | + grad_input = torch.empty(input.shape, dtype=torch.bfloat16, device=input.device) | ||
| 264 | + if needs_weight_grad: | ||
| 265 | + grad_weight = torch.empty(weight.shape, dtype=torch.float32, device=weight.device) | ||
| 266 | + if not tokens or not in_features or not out_features: | ||
| 267 | + if needs_input_grad and not out_features: | ||
| 268 | + grad_input.zero_() | ||
| 269 | + if needs_weight_grad: | ||
| 270 | + grad_weight.zero_() | ||
| 271 | + return grad_input, grad_weight | ||
| 272 | + if not needs_input_grad and not needs_weight_grad: | ||
| 273 | + return grad_input, grad_weight | ||
| 274 | + | ||
| 275 | + # Larger mixed Vector/Cube tiles reduce synchronization and program count. | ||
| 276 | + # Keep the original layout for small or strided projections: some Ascend | ||
| 277 | + # compiler versions cannot lower the larger tiles for irregular strides. | ||
| 278 | + tuned = ( | ||
| 279 | + tokens >= 128 | ||
| 280 | + and in_features >= 128 | ||
| 281 | + and input.stride() == (in_features, 1) | ||
| 282 | + and weight.stride() == (in_features, 1) | ||
| 283 | + and grad_output.stride() == (out_features, 1) | ||
| 284 | + ) | ||
| 285 | + feature_tiles = triton.cdiv(in_features, 128 if tuned else 64) | ||
| 286 | + dx_tiles = triton.cdiv(tokens, 64 if tuned else 32) * feature_tiles if needs_input_grad else 0 | ||
| 287 | + dw_tiles = triton.cdiv(out_features, 64 if tuned else 16) * feature_tiles if needs_weight_grad else 0 | ||
| 288 | + _combined_cube_backward[(dx_tiles + dw_tiles,)]( | ||
| 289 | + grad_output, | ||
| 290 | + input, | ||
| 291 | + weight, | ||
| 292 | + grad_input if needs_input_grad else input, | ||
| 293 | + grad_weight if needs_weight_grad else grad_output, | ||
| 294 | + tokens, | ||
| 295 | + in_features, | ||
| 296 | + out_features, | ||
| 297 | + grad_output.stride(0), | ||
| 298 | + grad_output.stride(1), | ||
| 299 | + input.stride(0), | ||
| 300 | + input.stride(1), | ||
| 301 | + weight.stride(0), | ||
| 302 | + weight.stride(1), | ||
| 303 | + num_pieces, | ||
| 304 | + needs_input_grad, | ||
| 305 | + needs_weight_grad, | ||
| 306 | + dx_tiles, | ||
| 307 | + tuned, | ||
| 308 | + enable_fp_fusion=False, | ||
| 309 | + ) | ||
| 310 | + return grad_input, grad_weight | ||
| @@ -0,0 +1,94 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""Override: NPU BF16 projection with fused FP32-gradient backward.""" | ||
| 8 | + | ||
| 9 | +from dataclasses import dataclass | ||
| 10 | + | ||
| 11 | +import spmd_types as spmd | ||
| 12 | +import torch | ||
| 13 | +from torch.autograd.function import once_differentiable | ||
| 14 | +from torchtitan.config import derive, override | ||
| 15 | +from torchtitan.distributed.batch_invariant import is_in_batch_invariant_mode | ||
| 16 | +from torchtitan.models.common.linear.hi_mid_lo_linear import HiMidLoLinear, _HiMidLoLinearFunction | ||
严重(S1): 这里在模块顶层 import 上游 另外 建议:把 torchtitan/torch 版本升级与本 PR 作为同一合并单元落地;若必须分步,至少在 import 前做版本检查并抛出可读的 RuntimeError,而不是裸 ImportError。 问题编号:R1212-002 审查版本: ![]() ![]() | |||
| 17 | +from torchtitan.models.common.linear.inplace_wgrad_accum import uses_inplace_wgrad_accum | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +class AscHiMidLoLinear(HiMidLoLinear): | ||
| 21 | + """Use BF16 NPU GEMMs with FP32 output and fused hi/mid/lo backward.""" | ||
| 22 | + | ||
| 23 | + @dataclass(kw_only=True, slots=True) | ||
| 24 | + class Config(HiMidLoLinear.Config): | ||
| 25 | + pass | ||
| 26 | + | ||
| 27 | + def _linear(self, input: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None) -> torch.Tensor: | ||
| 28 | + if ( | ||
| 29 | + input.device.type != "npu" | ||
| 30 | + or input.dtype != torch.bfloat16 | ||
| 31 | + or weight.dtype != torch.bfloat16 | ||
| 32 | + or is_in_batch_invariant_mode() | ||
| 33 | + ): | ||
| 34 | + return super()._linear(input, weight, bias) | ||
| 35 | + | ||
| 36 | + output = _AscHiMidLoLinearFunction.apply( | ||
| 37 | + input.reshape(-1, input.shape[-1]), | ||
| 38 | + weight, | ||
| 39 | + self.num_pieces, | ||
| 40 | + uses_inplace_wgrad_accum(self.inplace_wgrad_accum, weight, self), | ||
| 41 | + ) | ||
| 42 | + output = output.reshape(*input.shape[:-1], output.shape[-1]) | ||
| 43 | + return output if bias is None else output + bias.flatten().float() | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +@spmd.register_local_autograd_function | ||
| 47 | +class _AscHiMidLoLinearFunction(_HiMidLoLinearFunction): | ||
| 48 | + """Keep the original parameter at the SPMD autograd boundary.""" | ||
| 49 | + | ||
| 50 | + @staticmethod | ||
| 51 | + def forward( # pyrefly: ignore[bad-override] | ||
| 52 | + ctx, | ||
| 53 | + input_TD: torch.Tensor, | ||
| 54 | + weight: torch.Tensor, | ||
| 55 | + num_pieces: int, | ||
| 56 | + inplace_wgrad_accum: bool, | ||
| 57 | + ) -> torch.Tensor: | ||
| 58 | + # An intervening view's backward could round FP32 dW before FSDP receives it. | ||
| 59 | + weight_OD = weight.flatten(0, -2) | ||
| 60 | + ctx.weight_shape = weight.shape | ||
| 61 | + ctx.use_bf16_gemm = True | ||
| 62 | + ctx.num_pieces = num_pieces | ||
| 63 | + ctx.save_for_backward(input_TD, weight_OD) | ||
| 64 | + ctx.weight_param = weight if inplace_wgrad_accum else None | ||
| 65 | + return torch.mm(input_TD, weight_OD.T, out_dtype=torch.float32) | ||
| 66 | + | ||
| 67 | + @staticmethod | ||
| 68 | + @once_differentiable | ||
| 69 | + def backward(ctx, grad_output_TO: torch.Tensor): | ||
| 70 | + # The wide in-place accumulation path owns an existing gradient buffer. | ||
| 71 | + if ctx.weight_param is not None: | ||
| 72 | + return _HiMidLoLinearFunction.backward(ctx, grad_output_TO) | ||
| 73 | + | ||
| 74 | + from torchtitan_npu.ops.triton.hi_mid_lo_linear import _backward | ||
| 75 | + | ||
| 76 | + input_TD, weight_OD = ctx.saved_tensors | ||
| 77 | + grad_input, grad_weight = _backward( | ||
| 78 | + input_TD, | ||
| 79 | + weight_OD, | ||
| 80 | + grad_output_TO, | ||
| 81 | + ctx.num_pieces, | ||
| 82 | + ctx.needs_input_grad[0], | ||
| 83 | + ctx.needs_input_grad[1], | ||
| 84 | + ) | ||
| 85 | + if grad_weight is not None: | ||
| 86 | + grad_weight = grad_weight.view(ctx.weight_shape) | ||
| 87 | + return grad_input, grad_weight, None, None | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +@override( | ||
| 91 | + target=HiMidLoLinear.Config, exact=True, description="NPU BF16 projection with fused FP32 HiMidLoLinear gradients" | ||
| 92 | +) | ||
| 93 | +def asc(cfg: HiMidLoLinear.Config) -> AscHiMidLoLinear.Config: | ||
| 94 | + return derive(cfg, AscHiMidLoLinear.Config) | ||


一般(S2): 【文档同步】需要补充或更新文档。
本 PR 的文档同步要求:
docs/AGENTS.md规定feature_guides/负责"某项模型、并行、算子或优化能力的行为、启用方式、限制和验证",本 PR 新增的是一个需要用户显式启用、带明确 dtype/设备限制且有性能前提的融合路径,却没有任何文档改动(PR 的文档 checkbox 也未勾选);同时torchtitan_npu/override/README.md的目录树是按文件枚举common/的,新增文件后已经和实际目录不一致。docs/feature_guides/fused_ops.md:88:在"当前实现示例"列表里补一条 HiMidLoLinear 条目,写清启用入口、仅限 NPU+BF16(CPU/混合 dtype/batch-invariant 回退上游、inplace WGRAD 走上游反向),并注明实测大 shape 仍慢于原生 FP32 fallback、故保持 opt-in。torchtitan_npu/override/README.md:74:在common/目录树(第 69–77 行)里补上本 PR 新增的hi_mid_lo_linear.py,使清单与目录一致。问题编号:R1212-004
审查版本:
56ce7beae756ab34e8d63cbbd1b204de2f199816