Merged
feat(dsv4): support context parallelism in fused compressor #911
feat(dsv4): support context parallelism in fused compressor #911
Merged
xuyujunAdd on Sep 23
Total: 2 files changed+206-49
@@ -75,7 +75,9 @@ def compressor_factory(monkeypatch):
75 registry = importlib.import_module("torchtitan.config.override")75 registry = importlib.import_module("torchtitan.config.override")
76 with monkeypatch.context() as scoped, torch.random.fork_rng():76 with monkeypatch.context() as scoped, torch.random.fork_rng():
77 scoped.setattr(registry, "_REGISTRY", registry._REGISTRY.copy())77 scoped.setattr(registry, "_REGISTRY", registry._REGISTRY.copy())
78- scoped.setitem(sys.modules, "cann_ops_transformer.ops.compressor", types.ModuleType("compressor"))78+ fake_module = types.ModuleType("compressor")
79+ fake_module.compressor = lambda *args, **kwargs: pytest.fail("unexpected CANN compressor call")
80+ scoped.setitem(sys.modules, "cann_ops_transformer.ops.compressor", fake_module)
79 torch.manual_seed(93)81 torch.manual_seed(93)
80 82 
81 def build(ratio, indexer=False):83 def build(ratio, indexer=False):
@@ -93,27 +95,16 @@ def compressor_factory(monkeypatch):
93 module.norm.to(torch.float16)95 module.norm.to(torch.float16)
94 return module96 return module
95 97 
96- yield build98+ try:
99+ yield build
100+ finally:
101+ torch._dynamo.reset()
97 102 
98 103 
99@pytest.mark.parametrize("ratio,indexer", [(4, False), (4, True), (128, False)], ids=["c4-attention", "c4-indexer", "c128"])104@pytest.mark.parametrize("ratio,indexer", [(4, False), (4, True), (128, False)], ids=["c4-attention", "c4-indexer", "c128"])
100-def test_compressor_cann_schema_document_outputs_and_gradients(compressor_factory, monkeypatch, ratio, indexer):105+@pytest.mark.parametrize("api", ["torch-op", "python-wrapper"])
101- module = compressor_factory(ratio, indexer)106+def test_compressor_cann_schema_document_outputs_and_gradients(compressor_factory, monkeypatch, ratio, indexer, api):
102- module.wgate.weight.requires_grad_(not indexer)
103- reference = copy.deepcopy(module)
104- lengths = [2 * ratio + 1, ratio - 1, ratio + 2]
105- cu = [0]
106- for length in lengths:
107- cu.append(cu[-1] + length)
108- boundaries = torch.tensor(cu, dtype=torch.int32)
109- metadata = build_compressed_varlen_metadata(
110- VarlenMetadata(cu_seq_q=boundaries, cu_seq_k=boundaries, max_q=max(lengths), max_k=max(lengths)), (ratio,)
111- )
112- generator = torch.Generator().manual_seed(21)
113- x = (torch.randn(1, cu[-1], module.wkv.in_features, generator=generator) * 0.1).half().requires_grad_()
114- reference_x = x.detach().clone().requires_grad_()
115 calls = []107 calls = []
116- perturbation = torch.linspace(-0.02, 0.03, module.head_dim)
117 108 
118 def fake_cann(x, wkv, wgate, state_cache, ape, cmp_ratio=4, *, state_block_table=None,109 def fake_cann(x, wkv, wgate, state_cache, ape, cmp_ratio=4, *, state_block_table=None,
119 cu_seqlens=None, seqused=None, start_pos=None, coff=1, cache_mode=1):110 cu_seqlens=None, seqused=None, start_pos=None, coff=1, cache_mode=1):
@@ -134,9 +125,29 @@ def test_compressor_cann_schema_document_outputs_and_gradients(compressor_factor
134 # Poison unused TND capacity so consuming it fails output comparisons.125 # Poison unused TND capacity so consuming it fails output comparisons.
135 return torch.cat((pooled, pooled.new_full((len(lengths), module.head_dim), float("nan"))))126 return torch.cat((pooled, pooled.new_full((len(lengths), module.head_dim), float("nan"))))
136 127 
137- monkeypatch.setattr(128+ if api == "torch-op":
138- torch.ops.cann_ops_transformer, "compressor", types.SimpleNamespace(default=fake_cann), raising=False129+ monkeypatch.setattr(
130+ torch.ops.cann_ops_transformer, "compressor", types.SimpleNamespace(default=fake_cann), raising=False
131+ )
132+ else:
133+ monkeypatch.setattr(torch.ops, "cann_ops_transformer", types.SimpleNamespace())
134+ monkeypatch.setattr(sys.modules["cann_ops_transformer.ops.compressor"], "compressor", fake_cann)
135+ 
136+ module = compressor_factory(ratio, indexer)
137+ module.wgate.weight.requires_grad_(not indexer)
138+ reference = copy.deepcopy(module)
139+ lengths = [2 * ratio + 1, ratio - 1, ratio + 2]
140+ cu = [0]
141+ for length in lengths:
142+ cu.append(cu[-1] + length)
143+ boundaries = torch.tensor(cu, dtype=torch.int32)
144+ metadata = build_compressed_varlen_metadata(
145+ VarlenMetadata(cu_seq_q=boundaries, cu_seq_k=boundaries, max_q=max(lengths), max_k=max(lengths)), (ratio,)
139 )146 )
147+ generator = torch.Generator().manual_seed(21)
148+ x = (torch.randn(1, cu[-1], module.wkv.in_features, generator=generator) * 0.1).half().requires_grad_()
149+ reference_x = x.detach().clone().requires_grad_()
150+ perturbation = torch.linspace(-0.02, 0.03, module.head_dim)
140 151 
141 actual = module(x, metadata)152 actual = module(x, metadata)
142 raw = _document_pool(reference_x[0], reference.wkv.weight, reference.wgate.weight, reference.ape, cu, ratio)153 raw = _document_pool(reference_x[0], reference.wkv.weight, reference.wgate.weight, reference.ape, cu, ratio)
@@ -157,26 +168,148 @@ def test_compressor_cann_schema_document_outputs_and_gradients(compressor_factor
157 torch.testing.assert_close(actual_grad, expected_grad, rtol=0.006, atol=0.004)168 torch.testing.assert_close(actual_grad, expected_grad, rtol=0.006, atol=0.004)
158 169 
159 170 
160-@pytest.mark.parametrize("reason", ["empty", "cp"], ids=str)171+def test_compressor_empty_plan(compressor_factory):
161-def test_compressor_empty_plan_and_cp(compressor_factory, reason):
162 module = compressor_factory(4)172 module = compressor_factory(4)
163- length = 3 if reason == "empty" else 8173+ boundaries = torch.tensor([0, 3], dtype=torch.int32)
164- boundaries = torch.tensor([0, length], dtype=torch.int32)
165 metadata = build_compressed_varlen_metadata(174 metadata = build_compressed_varlen_metadata(
166- VarlenMetadata(cu_seq_q=boundaries, cu_seq_k=boundaries, max_q=length, max_k=length), (4,)175+ VarlenMetadata(cu_seq_q=boundaries, cu_seq_k=boundaries, max_q=3, max_k=3), (4,)
167 )176 )
168- if reason == "cp":177+ x = torch.ones(1, 3, module.wkv.in_features, dtype=torch.float16, requires_grad=True)
169- # CP may have no exchange on a rank; window presence still forces fallback.
170- metadata.window = object()
171- x = torch.ones(1, length, module.wkv.in_features, dtype=torch.float16, requires_grad=True)
172- if reason == "cp":
173- with pytest.raises(ValueError, match="without context parallelism"):
174- module(x, metadata)
175- return
176- expected = module._forward(x, metadata)
177 actual = module(x, metadata)178 actual = module(x, metadata)
178- torch.testing.assert_close(actual, expected, rtol=0, atol=0)179+ torch.testing.assert_close(actual, module._forward(x, metadata), rtol=0, atol=0)
179 assert actual.shape == (0, module.head_dim)180 assert actual.shape == (0, module.head_dim)
180 actual.sum().backward()181 actual.sum().backward()
181- assert x.grad is not None
182 torch.testing.assert_close(x.grad, torch.zeros_like(x), rtol=0, atol=0)182 torch.testing.assert_close(x.grad, torch.zeros_like(x), rtol=0, atol=0)
183+ 
184+ 
185+@pytest.mark.parametrize("api", ["torch-op", "python-wrapper"])
186+def test_compressor_available_api_compiles(compressor_factory, monkeypatch, api):
187+ def fake_cann(x, wkv, wgate, state_cache, ape, cmp_ratio=4, **kwargs):
188+ width = wkv.shape[0] // 2
189+ values = F.linear(x.float(), wkv.float()).reshape(-1, cmp_ratio, 2, width)
190+ scores = F.linear(x.float(), wgate.float()).reshape_as(values) + ape.reshape(1, cmp_ratio, 2, width)
191+ return (values[:, :, 1] * scores[:, :, 1].softmax(dim=1)).sum(dim=1).to(x.dtype)
192+ 
193+ if api == "torch-op":
194+ monkeypatch.setattr(
195+ torch.ops.cann_ops_transformer, "compressor", types.SimpleNamespace(default=fake_cann), raising=False
196+ )
197+ else:
198+ monkeypatch.setattr(torch.ops, "cann_ops_transformer", types.SimpleNamespace())
199+ monkeypatch.setattr(sys.modules["cann_ops_transformer.ops.compressor"], "compressor", fake_cann)
200+ module = compressor_factory(4).float()
201+ reference = copy.deepcopy(module)
202+ boundaries = torch.tensor([0, 8], dtype=torch.int32)
203+ metadata = build_compressed_varlen_metadata(
204+ VarlenMetadata(cu_seq_q=boundaries, cu_seq_k=boundaries, max_q=8, max_k=8), (4,)
205+ )
206+ 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+ 
209+ actual = torch.compile(module, backend="aot_eager", fullgraph=True, dynamic=True)(x, metadata)
210+ expected = reference(reference_x, metadata)
211+ torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6)
212+ actual.sum().backward()
213+ expected.sum().backward()
214+ torch.testing.assert_close(x.grad, reference_x.grad, rtol=1e-4, atol=1e-5)
215+ for name in ("wkv.weight", "wgate.weight", "ape", "norm.weight"):
216+ torch.testing.assert_close(module.get_parameter(name).grad, reference.get_parameter(name).grad, rtol=1e-4, atol=1e-5)
217+ 
218+ 
219+@pytest.mark.parametrize("ratio,indexer", [(4, False), (4, True), (128, False)], ids=["c4-attention", "c4-indexer", "c128"])
220+@pytest.mark.parametrize("headtail", [False, True], ids=["contiguous", "headtail"])
221+@pytest.mark.parametrize("empty_rank", [False, True], ids=["packed", "empty-rank"])
222+@pytest.mark.parametrize("compile_model", [False, True], ids=["eager", "aot-eager"])
223+def test_compressor_cp_outputs_and_gradients(compressor_factory, monkeypatch, ratio, indexer, headtail, empty_rank, compile_model):
224+ from torch.distributed.tensor.experimental._context_parallel._load_balancer import _HeadTailLoadBalancer
225+ from torchtitan_npu.models.deepseek_v4.token_dispatcher import build_cp_plan
226+ 
227+ module = compressor_factory(ratio, indexer).float()
228+ reference = copy.deepcopy(module)
229+ cp_size, total = 4, 8 * ratio
230+ # Misaligned documents, an empty document, and a document without full blocks.
231+ cu = [0, ratio - 1, 3 * ratio + 1, 3 * ratio + 1, total]
232+ if empty_rank:
233+ cu = [*range(total // cp_size + 1), total]
234+ boundaries = torch.tensor(cu, dtype=torch.int32)
235+ varlen = VarlenMetadata(cu_seq_q=boundaries, cu_seq_k=boundaries, max_q=total, max_k=total)
236+ lb = _HeadTailLoadBalancer(total, cp_size, "cpu") if headtail else None
237+ perm = lb._generate_indices(restore=False).reshape(-1) if lb else torch.arange(total)
238+ metadata = [types.SimpleNamespace(varlen=v, plans=p, window=w) for v, p, w in (
239+ 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+ )]
242+ generator = torch.Generator().manual_seed(42)
243+ x = (torch.randn(total, module.wkv.in_features, generator=generator) * 0.1).requires_grad_()
244+ reference_x = x.detach().clone().requires_grad_()
245+ shards = x[perm].reshape(cp_size, total // cp_size, -1)
246+ calls = []
247+ 
248+ def fake_cann(x, wkv, wgate, state_cache, ape, cmp_ratio=4, *, state_block_table=None,
249+ cu_seqlens=None, seqused=None, start_pos=None, coff=1, cache_mode=1):
250+ calls.append(x.shape[0])
251+ 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 over
254+ # the original unsliced documents instead of consuming the CP plan.
255+ width = wkv.shape[0] // coff
256+ values = F.linear(x.float(), wkv.float()).reshape(-1, cmp_ratio, coff * width)
257+ scores = F.linear(x.float(), wgate.float()).reshape_as(values) + ape
258+ if coff == 2:
259+ previous = (torch.arange(values.shape[0]) - 1).clamp_min(0)
260+ first = torch.zeros(values.shape[0], dtype=torch.bool).scatter(0, cu_seqlens[:-1].long() // cmp_ratio, True)
261+ left_values = values[previous, :, :width].masked_fill(first[:, None, None], 0)
262+ left_scores = scores[previous, :, :width].masked_fill(first[:, None, None], float("-inf"))
263+ values = torch.cat((left_values, values[:, :, width:]), dim=1)
264+ scores = torch.cat((left_scores, scores[:, :, width:]), dim=1)
265+ return (values * scores.softmax(1)).sum(1).to(x.dtype)
266+ 
267+ monkeypatch.setattr(module.implementation, "_compressor_fn", fake_cann)
268+ global_raw = _document_pool(reference_x, reference.wkv.weight, reference.wgate.weight, reference.ape, cu, ratio)
269+ positions = torch.cat([torch.arange(0, (b - a) // ratio * ratio, ratio) for a, b in zip(cu[:-1], cu[1:])])
270+ global_expected = _postprocess(reference, global_raw, positions)
271+ losses, expected_losses = [], []
272+ exchange_calls = []
273+ for rank, meta in enumerate(metadata):
274+ plan = meta.plans[ratio]
275+ 
276+ def exchange(payload, in_splits, out_splits):
277+ exchange_calls.append(rank)
278+ pieces = []
279+ for peer, peer_meta in enumerate(metadata):
280+ ex = peer_meta.plans[ratio].exchange
281+ begin = sum(ex.send_splits[:rank])
282+ end = begin + ex.send_splits[rank]
283+ pieces.append(shards[peer][ex.send_indices[begin:end]])
284+ return torch.cat(pieces)
285+ 
286+ monkeypatch.setattr(module.token_dispatcher, "_all_to_all", exchange)
287+ run = torch.compile(module, backend="aot_eager", fullgraph=True, dynamic=True) if compile_model else module
288+ actual = run(shards[rank:rank + 1], meta)[plan.compressed_rows]
289+ # Independently map kept block positions to the unsliced document oracle.
290+ foreign = []
291+ for peer, peer_meta in enumerate(metadata):
292+ ex = peer_meta.plans[ratio].exchange
293+ begin = sum(ex.send_splits[:rank])
294+ end = begin + ex.send_splits[rank]
295+ foreign.append(perm[peer * (total // cp_size) + ex.send_indices[begin:end]])
296+ received = torch.cat(foreign)[plan.exchange.recv_offsets]
297+ augmented = torch.cat((perm[rank * (total // cp_size):(rank + 1) * (total // cp_size)], received))
298+ starts = augmented[plan.gather_indices].reshape(-1, ratio)[:, 0][plan.compressed_rows]
299+ expected_indices = []
300+ for start in starts.tolist():
301+ doc = next(i for i, (a, b) in enumerate(zip(cu[:-1], cu[1:])) if a <= start < b)
302+ expected_indices.append(sum((cu[i + 1] - cu[i]) // ratio for i in range(doc)) + (start - cu[doc]) // ratio)
303+ expected = global_expected[torch.tensor(expected_indices, dtype=torch.int64)]
304+ # CP segments and full documents use different CPU GEMM batch shapes.
305+ torch.testing.assert_close(actual, expected, rtol=1e-5, atol=2e-6)
306+ grad = torch.randn(actual.shape, generator=generator)
307+ losses.append((actual * grad).sum())
308+ expected_losses.append((expected * grad).sum())
309+ sum(losses).backward()
310+ sum(expected_losses).backward()
311+ assert len(calls) == sum(m.plans[ratio].gather_indices.numel() > 0 for m in metadata)
312+ assert exchange_calls == list(range(cp_size))
313+ torch.testing.assert_close(x.grad, reference_x.grad, rtol=1e-4, atol=1e-5)
314+ for name in ("wkv.weight", "wgate.weight", "ape", "norm.weight"):
315+ torch.testing.assert_close(module.get_parameter(name).grad, reference.get_parameter(name).grad, rtol=1e-4, atol=1e-5)
@@ -8,24 +8,24 @@
8from __future__ import annotations8from __future__ import annotations
9 9 
10import importlib10import importlib
11-from dataclasses import dataclass11+from dataclasses import dataclass, replace
12from typing import Any12from typing import Any
13 13 
14import torch14import torch
15 15 
16from torchtitan_npu.models.deepseek_v4.compressor import Compressor, CompressorImplementation16from torchtitan_npu.models.deepseek_v4.compressor import Compressor, CompressorImplementation
17+from torchtitan_npu.models.deepseek_v4.metadata import CompressedVarlenMetadata
17 18 
18 19 
19-def _state_inputs(metadata: Any, x: torch.Tensor, *, ratio: int, head_dim: int):20+def _state_inputs(cu_seqlens: torch.Tensor, x: torch.Tensor, *, max_length: int, ratio: int, head_dim: int):
20- varlen = metadata.varlen21+ cu_seqlens = cu_seqlens.to(device=x.device, dtype=torch.int32).contiguous()
21- cu_seqlens = varlen.cu_seq_q.to(device=x.device, dtype=torch.int32).contiguous()
22 lengths = cu_seqlens[1:] - cu_seqlens[:-1]22 lengths = cu_seqlens[1:] - cu_seqlens[:-1]
23 block_size = 8 if ratio == 4 else 1623 block_size = 8 if ratio == 4 else 16
24 coff = 2 if ratio == 4 else 124 coff = 2 if ratio == 4 else 1
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((varlen.max_k + block_size - 1) // block_size, 1)),28+ (lengths.numel(), 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,22 +40,46 @@ 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- # Register the optional kernel only when the fused component is built.43+ # Import registers the operator when this CANN package provides one.
44- importlib.import_module("cann_ops_transformer.ops.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
45 47 
46 def forward(self, compressor: Compressor, x: torch.Tensor, attention_masks: Any) -> torch.Tensor:48 def forward(self, compressor: Compressor, x: torch.Tensor, attention_masks: Any) -> torch.Tensor:
47 plan = attention_masks.plans[compressor.compress_ratio]49 plan = attention_masks.plans[compressor.compress_ratio]
48- if getattr(attention_masks, "window", None) is not None or plan.exchange is not None:
49- raise ValueError("CANN compressor requires a full document stream without context parallelism")
50 if plan.gather_indices is None or plan.block_positions is None:50 if plan.gather_indices is None or plan.block_positions is None:
51 raise ValueError("CANN compressor requires complete compression metadata")51 raise ValueError("CANN compressor requires complete compression metadata")
52- if plan.gather_indices.numel() == 0:52+ if plan.exchange is not None:
53- return compressor._forward(x, attention_masks)53+ # Exchange only missing boundary tokens before the fused projections.
54+ # Plan segments include the C4 predecessor block; restarting each
55+ # 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)
57+ x = compressor.token_dispatcher.gather(x, plan)
58+ if plan.gather_indices.numel() == 0:
59+ # CompressorGrad rejects empty inputs. The collective must still
60+ # run, including on ranks with no local compressed blocks.
61+ local_metadata = CompressedVarlenMetadata(
62+ varlen=attention_masks.varlen,
63+ plans={compressor.compress_ratio: replace(plan, exchange=None)},
64+ )
65+ return compressor._forward(x, local_metadata)
66+ assert plan.first_indices is not None
67+ cu_seqlens = torch.cat(
68+ (
69+ plan.first_indices * compressor.compress_ratio,
70+ plan.first_indices.new_full((1,), plan.gather_indices.numel()),
71+ )
72+ )
73+ else:
74+ if plan.gather_indices.numel() == 0:
75+ return compressor._forward(x, attention_masks)
76+ cu_seqlens = attention_masks.varlen.cu_seq_q
77+ max_length = attention_masks.varlen.max_k
54 78 
55 state_block_table, state_cache, cu_seqlens, lengths = _state_inputs(79 state_block_table, state_cache, cu_seqlens, lengths = _state_inputs(
56- attention_masks, x, ratio=compressor.compress_ratio, head_dim=compressor.head_dim80+ cu_seqlens, x, max_length=max_length, ratio=compressor.compress_ratio, head_dim=compressor.head_dim
57 )81 )
58- pooled = torch.ops.cann_ops_transformer.compressor.default(82+ pooled = self._compressor_fn(
59 x.reshape(-1, x.shape[-1]).contiguous(),83 x.reshape(-1, x.shape[-1]).contiguous(),
60 compressor.wkv.weight,84 compressor.wkv.weight,
61 compressor.wgate.weight,85 compressor.wgate.weight,