main
py 71 lines 2.79 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 """Layout plumbing for DeepSeek V4.1 mega attention.
4
5 The kernel's Q and O layouts are produced by permuting ``wq_b`` rows and
6 ``wo_a`` columns once at load, so what has to hold is that the permuted GEMMs
7 agree with a reference that permutes the activation instead.
8 """
9
10 import torch
11
12 from vllm.models.deepseek_v41.common.ops.fused_layout import (
13 WV_GROUP_SIZE,
14 o_fused_chunk_permutation,
15 o_fused_permutation,
16 permute_q_to_fused,
17 permute_wo_a_,
18 permute_wq_b_,
19 q_fused_permutation,
20 )
21
22 HEAD_DIM = 512
23
24
25 def test_permuted_wq_b_gemm_matches_permuted_activation():
26 """Permuting wq_b's rows makes the Q GEMM emit the fused layout directly."""
27 torch.manual_seed(0)
28 num_heads, q_lora_rank, num_tokens = 16, 64, 5
29 weight = torch.randn(num_heads * HEAD_DIM, q_lora_rank)
30 # One scale row per weight row, as an MXFP8 wq_b shard carries.
31 scale = torch.randint(
32 0, 256, (num_heads * HEAD_DIM, q_lora_rank // 32), dtype=torch.uint8
33 )
34 qr = torch.randn(num_tokens, q_lora_rank)
35 orig_weight, orig_scale = weight.clone(), scale.clone()
36
37 standard = (qr @ weight.T).view(num_tokens, num_heads, HEAD_DIM)
38 expected = permute_q_to_fused(standard)
39
40 permute_wq_b_(weight, scale, num_heads)
41 fused = (qr @ weight.T).view(num_tokens, num_heads, HEAD_DIM)
42 torch.testing.assert_close(fused, expected)
43 # The scale has to follow its row, or dequant reads another row's scale.
44 perm = q_fused_permutation(num_heads, HEAD_DIM)
45 torch.testing.assert_close(weight, orig_weight[perm])
46 torch.testing.assert_close(scale, orig_scale[perm])
47
48
49 def test_permuted_wo_a_consumes_fused_output():
50 """Permuting wo_a's input columns lets it read the kernel's O layout."""
51 torch.manual_seed(1)
52 out_features, num_tokens = 32, 4
53 in_features = WV_GROUP_SIZE * HEAD_DIM
54 weight = torch.randn(out_features, in_features)
55 scale = torch.randint(0, 256, (out_features, in_features // 32), dtype=torch.uint8)
56 standard_o = torch.randn(num_tokens, in_features)
57 orig_weight, orig_scale = weight.clone(), scale.clone()
58
59 expected = standard_o @ weight.T
60 # The kernel emits the same values in the fused chunk order.
61 perm = o_fused_permutation(WV_GROUP_SIZE, HEAD_DIM)
62 fused_o = standard_o[:, perm]
63
64 permute_wo_a_(weight, scale, WV_GROUP_SIZE)
65 torch.testing.assert_close(weight, orig_weight[:, perm])
66 torch.testing.assert_close(
67 scale, orig_scale[:, o_fused_chunk_permutation(WV_GROUP_SIZE, HEAD_DIM)]
68 )
69 # Unlike wq_b, this permutation sits inside the 4096-term reduction, so the
70 # summation order changes and the result differs in the last few ulps.
71 torch.testing.assert_close(fused_o @ weight.T, expected, rtol=1e-3, atol=1e-3)