Merged
[fix](dsv4): avoid unbacked shape guards in fused Compressor #935
[fix](dsv4): avoid unbacked shape guards in fused Compressor #935
Merged
xuyujunAdd on Sep 24
Total: 6 files changed+198-10
@@ -0,0 +1,122 @@
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+"""Exercise the CANN fake boundary without loading CANN or an NPU kernel."""
7+ 
8+import sys
9+import types
10+ 
11+import pytest
12+import torch
13+from torch._subclasses.fake_tensor import FakeTensorMode
14+from torch.fx.experimental.symbolic_shapes import GuardOnDataDependentSymNode, ShapeEnv
15+ 
16+from torchtitan_npu.ops.ascendc.compressor import _compressor_forward_fake, load_compressor
17+ 
18+ 
19+@pytest.mark.parametrize("ratio,coff", [(4, 2), (128, 1)])
20+@pytest.mark.parametrize("shape,batch", [((16, 8), 2), ((3, 8), 3), ((0, 8), 0), ((2, 17, 8), 2)])
21+def test_compressor_fake_shapes_and_dtypes(ratio, coff, shape, batch):
22+ with FakeTensorMode():
23+ x = torch.empty(shape, dtype=torch.bfloat16)
24+ weight = torch.empty((coff * 16, 8))
25+ outputs = _compressor_forward_fake(
26+ x, weight, weight, torch.empty((1, 8, 4 * 16)), torch.empty((ratio, coff * 16)),
27+ ratio, cu_seqlens=torch.empty((batch + 1,), dtype=torch.int32), coff=coff,
28+ )
29+ if len(shape) == 3:
30+ prefix = (shape[0], (shape[1] + ratio - 1) // ratio)
31+ else:
32+ prefix = (min(shape[0], shape[0] // ratio + batch),)
33+ assert outputs[0].shape == (*prefix, 16)
34+ assert outputs[0].dtype == torch.bfloat16
35+ for saved in outputs[1:]:
36+ assert saved.shape == (*prefix, coff * ratio, 16)
37+ assert saved.dtype == torch.float32
38+ 
39+ 
40+@pytest.fixture(scope="module")
41+def cann_boundary():
42+ @torch.library.custom_op("test_compressor_compat::forward", mutates_args=())
43+ def forward(x: torch.Tensor, cu: torch.Tensor, ratio: int) -> torch.Tensor:
44+ rows = min(x.shape[0], x.shape[0] // ratio + cu.shape[0] - 1)
45+ return x.sum().expand(rows, x.shape[1]).clone()
46+ 
47+ def setup_context(ctx, inputs, output):
48+ ctx.save_for_backward(inputs[0])
49+ 
50+ def backward(ctx, grad):
51+ (x,) = ctx.saved_tensors
52+ return torch.ones_like(x) * grad.sum(), None, None
53+ 
54+ forward.register_autograd(backward, setup_context=setup_context)
55+ return forward
56+ 
57+ 
58+@pytest.mark.parametrize("ratio", [4, 128])
59+@pytest.mark.parametrize("checkpointed", [False, True])
60+def test_loader_replaces_unbacked_fake_and_preserves_autograd(monkeypatch, cann_boundary, ratio, checkpointed):
61+ # Match the failing Python min in CANN's fake, not a traced Python kernel.
62+ def original_fake(x, cu, ratio):
63+ return x.new_empty((min(x.shape[0], x.shape[0] // ratio + cu.shape[0] - 1), x.shape[1]))
64+ 
65+ cann_boundary.register_fake(original_fake)
66+ 
67+ def symbolic_call():
68+ env = ShapeEnv()
69+ tokens, documents = env.create_unbacked_symint(), env.create_unbacked_symint()
70+ with FakeTensorMode(shape_env=env):
71+ torch._constrain_as_size(tokens, min=1)
72+ torch._constrain_as_size(documents, min=2)
73+ return cann_boundary(torch.empty((tokens, 8)), torch.empty((documents,), dtype=torch.int32), ratio)
74+ 
75+ with pytest.raises(GuardOnDataDependentSymNode):
76+ symbolic_call()
77+ 
78+ # Adapt the small CPU test schema to CANN's real fake signature. Registration
79+ # still passes through the production loader and PyTorch dispatcher.
80+ register_fake = torch.library.register_fake
81+ 
82+ def register(op, fake):
83+ def adapted(x, cu, ratio):
84+ weight = x.new_empty((x.shape[1], x.shape[1]))
85+ return fake(x, weight, weight, x, x, ratio, cu_seqlens=cu)[0]
86+ return register_fake(op, adapted)
87+ 
88+ monkeypatch.setattr(torch.library, "register_fake", register)
89+ namespace = types.SimpleNamespace(_compressor_forward=torch.ops.test_compressor_compat.forward)
90+ monkeypatch.setattr(torch.ops, "cann_ops_transformer", namespace)
91+ module = types.ModuleType("cann_ops_transformer.ops.compressor")
92+ module.compressor = cann_boundary
93+ monkeypatch.setitem(sys.modules, module.__name__, module)
94+ assert load_compressor() is cann_boundary
95+ assert load_compressor() is cann_boundary # Construction for another layer is safe.
96+ symbolic_call()
97+ # Reproduce the unsupported sym_min result reported by the A5 fake call.
98+ # Scope it to fake dispatch: the shape rule must still return valid sizes.
99+ with monkeypatch.context() as scoped:
100+ scoped.setattr(torch, "sym_min", lambda *args: NotImplemented)
101+ symbolic_call()
102+ 
103+ from torch.utils.checkpoint import checkpoint
104+ 
105+ def run(x, cu, ratio):
106+ if checkpointed:
107+ return checkpoint(cann_boundary, x, cu, ratio, use_reentrant=False)
108+ return cann_boundary(x, cu, ratio)
109+ 
110+ compiled = torch.compile(run, backend="aot_eager", fullgraph=True, dynamic=True)
111+ for tokens, batch in [(16, 2), (8, 8)]:
112+ x = torch.randn((tokens, 8), requires_grad=True)
113+ reference_x = x.detach().clone().requires_grad_()
114+ cu = torch.zeros(batch + 1, dtype=torch.int32)
115+ setattr(x, "_dynamo_unbacked_indices", {0}) # noqa: B010
116+ setattr(cu, "_dynamo_unbacked_indices", {0}) # noqa: B010
117+ actual = compiled(x, cu, ratio)
118+ expected = cann_boundary(reference_x, cu, ratio)
119+ torch.testing.assert_close(actual, expected)
120+ actual.sum().backward()
121+ expected.sum().backward()
122+ torch.testing.assert_close(x.grad, reference_x.grad)
@@ -203,6 +203,7 @@ def test_compressor_available_api_compiles(compressor_factory, monkeypatch, api)
203 metadata = build_compressed_varlen_metadata(203 metadata = build_compressed_varlen_metadata(
204 VarlenMetadata(cu_seq_q=boundaries, cu_seq_k=boundaries, max_q=8, max_k=8), (4,)204 VarlenMetadata(cu_seq_q=boundaries, cu_seq_k=boundaries, max_q=8, max_k=8), (4,)
205 )205 )
206+ setattr(metadata.plans[4].gather_indices, "_dynamo_unbacked_indices", {0}) # noqa: B010
206 x = torch.randn(1, 8, module.wkv.in_features, generator=torch.Generator().manual_seed(17)).requires_grad_()207 x = torch.randn(1, 8, module.wkv.in_features, generator=torch.Generator().manual_seed(17)).requires_grad_()
207 reference_x = x.detach().clone().requires_grad_()208 reference_x = x.detach().clone().requires_grad_()
208 209 
@@ -239,6 +240,11 @@ def test_compressor_cp_outputs_and_gradients(compressor_factory, monkeypatch, ra
239 build_cp_plan(varlen, lb, rank=r, cp_size=cp_size, shard_len=total // cp_size,240 build_cp_plan(varlen, lb, rank=r, cp_size=cp_size, shard_len=total // cp_size,
240 window_size=4, ratios=[ratio]) for r in range(cp_size)241 window_size=4, ratios=[ratio]) for r in range(cp_size)
241 )]242 )]
243+ if compile_model:
244+ for meta in metadata:
245+ indices = meta.plans[ratio].gather_indices
246+ if indices.numel() > 0:
247+ setattr(indices, "_dynamo_unbacked_indices", {0}) # noqa: B010
242 generator = torch.Generator().manual_seed(42)248 generator = torch.Generator().manual_seed(42)
243 x = (torch.randn(total, module.wkv.in_features, generator=generator) * 0.1).requires_grad_()249 x = (torch.randn(total, module.wkv.in_features, generator=generator) * 0.1).requires_grad_()
244 reference_x = x.detach().clone().requires_grad_()250 reference_x = x.detach().clone().requires_grad_()
@@ -249,7 +255,6 @@ def test_compressor_cp_outputs_and_gradients(compressor_factory, monkeypatch, ra
249 cu_seqlens=None, seqused=None, start_pos=None, coff=1, cache_mode=1):255 cu_seqlens=None, seqused=None, start_pos=None, coff=1, cache_mode=1):
250 calls.append(x.shape[0])256 calls.append(x.shape[0])
251 assert start_pos is None and cache_mode == 1257 assert start_pos is None and cache_mode == 1
252- assert x.shape[0] > 0, "CompressorGrad does not support empty inputs"
253 # Tensor-only CPU kernel substitute; the independent oracle loops over258 # Tensor-only CPU kernel substitute; the independent oracle loops over
254 # the original unsliced documents instead of consuming the CP plan.259 # the original unsliced documents instead of consuming the CP plan.
255 width = wkv.shape[0] // coff260 width = wkv.shape[0] // coff
@@ -92,6 +92,10 @@ class CompressedBlockLayout:
92 the eager plan-build boundary so ``_assemble_tnd`` avoids a per-layer92 the eager plan-build boundary so ``_assemble_tnd`` avoids a per-layer
93 ``.item()`` D2H sync inside the compiled region."""93 ``.item()`` D2H sync inside the compiled region."""
94 94 
95+ is_empty_host: bool = False
96+ """Host-side empty-plan flag for paths whose fused kernel rejects empty input.
97+ A Python branch cannot inspect the unbacked ``gather_indices`` length."""
98+ 
95 block_remainder: torch.Tensor | None99 block_remainder: torch.Tensor | None
96 """Per-sequence block remainder (int32), ``[n_seqs]``: ``len[i] % ratio``100 """Per-sequence block remainder (int32), ``[n_seqs]``: ``len[i] % ratio``
97 trailing tokens of sequence ``i`` fall short of one full block and101 trailing tokens of sequence ``i`` fall short of one full block and
@@ -287,6 +291,7 @@ def build_kernel_layout(
287 plans[ratio] = CompressedBlockLayout(291 plans[ratio] = CompressedBlockLayout(
288 cu_seqlens_cmp_k=cu_seqs,292 cu_seqlens_cmp_k=cu_seqs,
289 n_cmp_blocks_host=sum(length // ratio for length in lengths),293 n_cmp_blocks_host=sum(length // ratio for length in lengths),
294+ is_empty_host=not pieces,
290 block_remainder=torch.tensor(295 block_remainder=torch.tensor(
291 [length % ratio for length in lengths],296 [length % ratio for length in lengths],
292 dtype=torch.int32,297 dtype=torch.int32,
@@ -358,6 +358,7 @@ def _assemble_block_plan(
358 cmp_k_global_gather_indices = [slots[(seg[0], b)] for seg in segs for b in range(seg[2] // ratio)]358 cmp_k_global_gather_indices = [slots[(seg[0], b)] for seg in segs for b in range(seg[2] // ratio)]
359 return CompressedBlockLayout(359 return CompressedBlockLayout(
360 cu_seqlens_cmp_k=cu_cmp_t,360 cu_seqlens_cmp_k=cu_cmp_t,
361+ is_empty_host=block_total == 0,
361 block_remainder=torch.tensor(rem, dtype=torch.int32, device=device),362 block_remainder=torch.tensor(rem, dtype=torch.int32, device=device),
362 gather_indices=_tensor(order, device),363 gather_indices=_tensor(order, device),
363 block_positions=block_positions,364 block_positions=block_positions,
@@ -0,0 +1,58 @@
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+"""CANN Compressor entry point with symbolic-safe output shape inference."""
7+ 
8+import importlib
9+ 
10+import torch
11+ 
12+ 
13+def _compressor_forward_fake(
14+ x,
15+ wkv,
16+ wgate,
17+ state_cache,
18+ ape,
19+ cmp_ratio,
20+ state_block_table=None,
21+ cu_seqlens: torch.Tensor | None = None,
22+ seqused=None,
23+ start_pos=None,
24+ coff=1,
25+ cache_mode=1,
26+ grad_enabled=False,
27+):
28+ # Match CANN's output capacity, including partial blocks in packed input.
29+ # Python min in older CANN packages guards on independent unbacked sizes.
30+ head_dim = wkv.shape[0] // coff
31+ if x.ndim == 3:
32+ prefix = (x.shape[0], (x.shape[1] + cmp_ratio - 1) // cmp_ratio)
33+ else:
34+ assert cu_seqlens is not None
35+ batch_size = cu_seqlens.shape[0] - 1
36+ tokens = x.shape[0]
37+ capacity = tokens // cmp_ratio + batch_size
38+ # min(a, b) for integer sizes, without Python guards or sym_min dispatch
39+ # (which can return NotImplemented in the compiled CANN fake call).
40+ prefix = ((tokens + capacity - abs(tokens - capacity)) // 2,)
41+ pooled_shape = (*prefix, head_dim)
42+ saved_shape = (*prefix, coff * cmp_ratio, head_dim)
43+ return (
44+ x.new_empty(pooled_shape),
45+ x.new_empty(saved_shape, dtype=torch.float32),
46+ x.new_empty(saved_shape, dtype=torch.float32),
47+ )
48+ 
49+ 
50+def load_compressor():
51+ """Load only for the selected override; preserve CANN kernels and autograd."""
52+ module = importlib.import_module("cann_ops_transformer.ops.compressor")
53+ forward_op = getattr(torch.ops.cann_ops_transformer, "_compressor_forward", None)
54+ if forward_op is not None:
55+ # Remove when supported CANN packages use symbolic-safe shape inference.
56+ torch.library.register_fake(forward_op.default, _compressor_forward_fake)
57+ compressor_op = getattr(torch.ops.cann_ops_transformer, "compressor", None)
58+ return compressor_op.default if compressor_op is not None else module.compressor
@@ -7,7 +7,6 @@
7 7 
8from __future__ import annotations8from __future__ import annotations
9 9 
10-import importlib
11from dataclasses import dataclass, replace10from dataclasses import dataclass, replace
12from typing import Any11from typing import Any
13 12 
@@ -15,6 +14,7 @@ import torch
15 14 
16from torchtitan_npu.models.deepseek_v4.compressor import Compressor, CompressorImplementation15from torchtitan_npu.models.deepseek_v4.compressor import Compressor, CompressorImplementation
17from torchtitan_npu.models.deepseek_v4.metadata import CompressedVarlenMetadata16from torchtitan_npu.models.deepseek_v4.metadata import CompressedVarlenMetadata
17+from torchtitan_npu.ops.ascendc.compressor import load_compressor
18 18 
19 19 
20def _state_inputs(cu_seqlens: torch.Tensor, x: torch.Tensor, *, max_length: int, ratio: int, head_dim: int):20def _state_inputs(cu_seqlens: torch.Tensor, x: torch.Tensor, *, max_length: int, ratio: int, head_dim: int):
@@ -25,7 +25,7 @@ def _state_inputs(cu_seqlens: torch.Tensor, x: torch.Tensor, *, max_length: int,
25 # CANN tiling requires state_block_table despite its optional schema.25 # CANN tiling requires state_block_table despite its optional schema.
26 # In cache_mode=1, block ID 0 skips cache writes for full-document training.26 # In cache_mode=1, block ID 0 skips cache writes for full-document training.
27 state_block_table = torch.zeros(27 state_block_table = torch.zeros(
28- (lengths.numel(), max((max_length + block_size - 1) // block_size, 1)),28+ (lengths.numel(), torch.sym_max((max_length + block_size - 1) // block_size, 1)),
29 dtype=torch.int32,29 dtype=torch.int32,
30 device=x.device,30 device=x.device,
31 )31 )
@@ -40,10 +40,7 @@ class AscCompressor(CompressorImplementation):
40 40 
41 def __init__(self, config: Config) -> None:41 def __init__(self, config: Config) -> None:
42 super().__init__(config)42 super().__init__(config)
43- # Import registers the operator when this CANN package provides one.43+ self._compressor_fn = load_compressor()
44- compressor_module = importlib.import_module("cann_ops_transformer.ops.compressor")
45- compressor_op = getattr(torch.ops.cann_ops_transformer, "compressor", None)
46- self._compressor_fn = compressor_op.default if compressor_op is not None else compressor_module.compressor
47 44 
48 def forward(self, compressor: Compressor, x: torch.Tensor, attention_masks: Any) -> torch.Tensor:45 def forward(self, compressor: Compressor, x: torch.Tensor, attention_masks: Any) -> torch.Tensor:
49 plan = attention_masks.plans[compressor.compress_ratio]46 plan = attention_masks.plans[compressor.compress_ratio]
@@ -53,9 +50,9 @@ class AscCompressor(CompressorImplementation):
53 # Exchange only missing boundary tokens before the fused projections.50 # Exchange only missing boundary tokens before the fused projections.
54 # Plan segments include the C4 predecessor block; restarting each51 # Plan segments include the C4 predecessor block; restarting each
55 # segment masks its first overlap exactly as the reference does.52 # segment masks its first overlap exactly as the reference does.
56- max_length = min(plan.gather_indices.numel(), x.shape[1] + 2 * compressor.compress_ratio)53+ max_length = torch.sym_min(plan.gather_indices.numel(), x.shape[1] + 2 * compressor.compress_ratio)
57 x = compressor.token_dispatcher.gather(x, plan)54 x = compressor.token_dispatcher.gather(x, plan)
58- if plan.gather_indices.numel() == 0:55+ if plan.is_empty_host:
59 # CompressorGrad rejects empty inputs. The collective must still56 # CompressorGrad rejects empty inputs. The collective must still
60 # run, including on ranks with no local compressed blocks.57 # run, including on ranks with no local compressed blocks.
61 local_metadata = CompressedVarlenMetadata(58 local_metadata = CompressedVarlenMetadata(
@@ -71,7 +68,7 @@ class AscCompressor(CompressorImplementation):
71 )68 )
72 )69 )
73 else:70 else:
74- if plan.gather_indices.numel() == 0:71+ if plan.is_empty_host:
75 return compressor._forward(x, attention_masks)72 return compressor._forward(x, attention_masks)
76 cu_seqlens = attention_masks.varlen.cu_seq_q73 cu_seqlens = attention_masks.varlen.cu_seq_q
77 max_length = attention_masks.varlen.max_k74 max_length = attention_masks.varlen.max_k