Merged
[perf] Unify 4D SDPA inputs of DSV4.1 ViT for auto-routing to FA #1076
1Fire4Add on Oct 22
[perf] Unify 4D SDPA inputs of DSV4.1 ViT for auto-routing to FA #1076
Merged
Total: 2 files changed+84-13
| @@ -0,0 +1,79 @@ | |||
| 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 | +import pytest | ||
| 7 | +import torch | ||
| 8 | +import torch.nn.functional as F | ||
| 9 | + | ||
| 10 | +from torchtitan_npu.models.deepseek_v4_1.vision.encoder import VisionAttention, _vision_rope_batch | ||
| 11 | + | ||
| 12 | +pytestmark = pytest.mark.cpu | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def _dense_reference(module, x, cos, sin, lengths): | ||
| 16 | + """Per-image dense attention, excluding padded queries and keys entirely.""" | ||
| 17 | + | ||
| 18 | + def rotate(tensor, image_cos, image_sin): | ||
| 19 | + real, imag = tensor.chunk(2, dim=-1) | ||
| 20 | + return torch.cat((real * image_cos - imag * image_sin, imag * image_cos + real * image_sin), dim=-1) | ||
| 21 | + | ||
| 22 | + outputs = [] | ||
| 23 | + for index, length in enumerate(lengths): | ||
| 24 | + qkv = F.linear(x[index], module.wqkv.weight, module.wqkv.bias) | ||
| 25 | + q, k, v = qkv.reshape(x.shape[1], 3, module.num_heads, module.head_dim).unbind(1) | ||
| 26 | + q, k = rotate(q, cos[index], sin[index])[:length], rotate(k, cos[index], sin[index])[:length] | ||
| 27 | + scores = torch.einsum("qhd,khd->hqk", q, k) * module.head_dim**-0.5 | ||
| 28 | + attended = torch.einsum("hqk,khd->qhd", scores.softmax(-1), v[:length]) | ||
| 29 | + attended = F.pad(attended.flatten(1), (0, 0, 0, x.shape[1] - length)) | ||
| 30 | + outputs.append(F.linear(attended, module.wo.weight, module.wo.bias)) | ||
| 31 | + return torch.stack(outputs) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +@pytest.mark.parametrize( | ||
| 35 | + ("unbatched", "grids"), | ||
| 36 | + [(True, [[2, 3]]), (False, [[2, 3]]), (False, [[1, 3]]), (False, [[2, 3], [1, 3]])], | ||
| 37 | + ids=["unbatched", "single-image", "padded-single-image", "padded-images"], | ||
| 38 | +) | ||
| 39 | +def test_vision_attention_4d_sdpa_matches_dense_outputs_and_gradients(monkeypatch, unbatched, grids): | ||
| 40 | + with torch.random.fork_rng(devices=[]): | ||
| 41 | + torch.manual_seed(42) | ||
| 42 | + attention = VisionAttention.Config(dim=8, num_heads=2).build() | ||
| 43 | + attention.init_states(buffer_device=torch.device("cpu")) | ||
| 44 | + generator = torch.Generator().manual_seed(17) | ||
| 45 | + inputs = torch.randn(len(grids), 6, 8, generator=generator) | ||
| 46 | + lengths = [height * width for height, width in grids] | ||
| 47 | + valid = torch.arange(6)[None, :] < torch.tensor(lengths)[:, None] | ||
| 48 | + cos, sin = _vision_rope_batch(torch.tensor(grids), 6, 2, 10000.0, inputs.device) | ||
| 49 | + reference_inputs = inputs.clone().requires_grad_() | ||
| 50 | + inputs = (inputs[0] if unbatched else inputs).requires_grad_() | ||
| 51 | + original_sdpa = F.scaled_dot_product_attention | ||
| 52 | + | ||
| 53 | + def sdpa_spy(q, k, v, **kwargs): | ||
| 54 | + # Keep the real CPU operation; this only checks the backend-facing layout. | ||
| 55 | + assert q.shape == k.shape == v.shape == (len(grids), 2, 6, 4) | ||
| 56 | + return original_sdpa(q, k, v, **kwargs) | ||
| 57 | + | ||
| 58 | + monkeypatch.setattr(F, "scaled_dot_product_attention", sdpa_spy) | ||
| 59 | + actual = attention( | ||
| 60 | + inputs, | ||
| 61 | + cos[0] if unbatched else cos, | ||
| 62 | + sin[0] if unbatched else sin, | ||
| 63 | + valid[0] if unbatched else valid, | ||
| 64 | + ) | ||
| 65 | + expected = _dense_reference(attention, reference_inputs, cos, sin, lengths) | ||
| 66 | + if unbatched: | ||
| 67 | + expected = expected[0] | ||
| 68 | + torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-5) | ||
| 69 | + | ||
| 70 | + upstream = torch.randn(actual.shape, generator=generator) | ||
| 71 | + parameters = tuple(attention.parameters()) | ||
| 72 | + actual_grads = torch.autograd.grad(actual, (inputs, *parameters), upstream) | ||
| 73 | + expected_grads = torch.autograd.grad(expected, (reference_inputs, *parameters), upstream) | ||
| 74 | + expected_input_grad = expected_grads[0][0] if unbatched else expected_grads[0] | ||
| 75 | + torch.testing.assert_close(actual_grads[0], expected_input_grad, atol=1e-6, rtol=1e-5) | ||
| 76 | + for (name, _), actual_grad, expected_grad in zip( | ||
| 77 | + attention.named_parameters(), actual_grads[1:], expected_grads[1:], strict=True | ||
| 78 | + ): | ||
| 79 | + torch.testing.assert_close(actual_grad, expected_grad, atol=1e-6, rtol=1e-5, msg=name) | ||
| @@ -113,13 +113,14 @@ class VisionAttention(Module): | |||
| 113 | v = v.view(p, self.num_heads, self.head_dim) | 113 | v = v.view(p, self.num_heads, self.head_dim) |
| 114 | q = self.rotary(q, cos, sin) | 114 | q = self.rotary(q, cos, sin) |
| 115 | k = self.rotary(k, cos, sin) | 115 | k = self.rotary(k, cos, sin) |
| 116 | + # Keep the batch dimension so SDPA can select a fused attention backend. | ||
建议保留一句数值注记:现注释只说明性能动机("Keep the batch dimension so SDPA can select a fused attention backend")。建议补一句"有意接受与 3D math 参考路径的 BF16 数值偏差(精度结论见 PR1076 / 门禁基线变更记录)"。被删注释中"参考实现张量契约是 3D"这一信息值得以某种形式保留——它正是门禁 FAIL 的解释,缺失它,后人可能以"对齐门禁"为由把 3D 特例重新加回来,造成反复。 ![]() ![]() | |||
| 116 | out = F.scaled_dot_product_attention( | 117 | out = F.scaled_dot_product_attention( |
| 117 | - q.transpose(0, 1), | 118 | + q.transpose(0, 1).unsqueeze(0), |
| 118 | - k.transpose(0, 1), | 119 | + k.transpose(0, 1).unsqueeze(0), |
| 119 | - v.transpose(0, 1), | 120 | + v.transpose(0, 1).unsqueeze(0), |
| 120 | dropout_p=0.0, | 121 | dropout_p=0.0, |
| 121 | ) | 122 | ) |
| 122 | - return self.wo(out.transpose(0, 1).reshape(p, dim)) | 123 | + return self.wo(out.squeeze(0).transpose(0, 1).reshape(p, dim)) |
严重(S1): 【数值验收】单图分支改用四维 SDPA 会把 ViT 从 math 路径切到 NPU 融合注意力,属于改变模型输出/梯度的计算变更,但项目要求的口径尚未通过:PR 自述的 §3.2 对比中,32 层 ViT + FullAC 相对原 SDPA 有 211/265 项未通过(输出 MEAN_RE=6.179496% > 门槛 2%,输入梯度 COS=0.99982072 < 0.9999),而《精度对齐开发指南》第 4 节要求 问题编号:R1076-001 ![]() ![]() | |||
| 123 | 124 | ||
| 124 | n, p, dim = x.shape | 125 | n, p, dim = x.shape |
| 125 | qkv = self.wqkv(x) | 126 | qkv = self.wqkv(x) |
| @@ -132,15 +133,6 @@ class VisionAttention(Module): | |||
| 132 | k = self.rotary(k, cos, sin).transpose(1, 2) | 133 | k = self.rotary(k, cos, sin).transpose(1, 2) |
| 133 | v = v.transpose(1, 2) | 134 | v = v.transpose(1, 2) |
| 134 | mask = valid[:, None, :, None] & valid[:, None, None, :] | 135 | mask = valid[:, None, :, None] & valid[:, None, None, :] |
| 135 | - # The reference's tensor contract is [heads, patches, dim] with no batch | ||
| 136 | - # dimension: passing an extra batch dimension or an all-true mask can | ||
| 137 | - # select a different SDPA kernel and change BF16 rounding even though the | ||
| 138 | - # result is mathematically the same. | ||
| 139 | - if n == 1 and bool(valid[0].all()): | ||
| 140 | - out = F.scaled_dot_product_attention(q[0], k[0], v[0], dropout_p=0.0) | ||
| 141 | - return self.wo(out.transpose(0, 1).reshape(p, dim)).unsqueeze(0) | ||
| 142 | - # On this backend F.scaled_dot_product_attention already dispatches to the | ||
| 143 | - # Ascend fused attention kernel, so there is no separate fused call to make. | ||
| 144 | out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0) | 136 | out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0) |
| 145 | return self.wo(out.transpose(1, 2).reshape(n, p, dim)) | 137 | return self.wo(out.transpose(1, 2).reshape(n, p, dim)) |
| 146 | 138 | ||


PR 模板勾选"Bug 修复",与
[perf]标题及实际性质(性能优化/重构)不一致,建议修正勾选项。