Merged
[fix] Fix DeepSeek V4.1 Inductor fullgraph compilation with CP and forced MoE load balancing #1456
1Fire4Add on 3 days ago
[fix] Fix DeepSeek V4.1 Inductor fullgraph compilation with CP and forced MoE load balancing #1456
Merged
Total: 16 files changed+78-55
| @@ -7,10 +7,11 @@ | |||
| 7 | 7 | ||
| 8 | __all__ = ["ModuleSwapConfig"] | 8 | __all__ = ["ModuleSwapConfig"] |
| 9 | 9 | ||
| 10 | -from dataclasses import dataclass | 10 | +from dataclasses import dataclass, field |
| 11 | -from typing import ClassVar | ||
| 12 | 11 | ||
| 12 | +from torchao.core.config import AOBaseConfig | ||
| 13 | from torchao.quantization.qat import QATConfig, QATStep | 13 | from torchao.quantization.qat import QATConfig, QATStep |
| 14 | +from torchao.quantization.qat.fake_quantize_config import FakeQuantizeConfigBase | ||
| 14 | 15 | ||
| 15 | 16 | ||
| 16 | # ``slots=True`` must not come back: ConfigJSONEncoder serializes AOBaseConfig | 17 | # ``slots=True`` must not come back: ConfigJSONEncoder serializes AOBaseConfig |
| @@ -19,9 +20,9 @@ from torchao.quantization.qat import QATConfig, QATStep | |||
| 19 | class ModuleSwapConfig(QATConfig): | 20 | class ModuleSwapConfig(QATConfig): |
| 20 | """Base config for transforms which replace a module's forward behavior.""" | 21 | """Base config for transforms which replace a module's forward behavior.""" |
| 21 | 22 | ||
| 22 | - base_config: ClassVar[None] = None | 23 | + base_config: AOBaseConfig | None = field(default=None, init=False, repr=False, compare=False) |
| 23 | - activation_config: ClassVar[None] = None | 24 | + activation_config: FakeQuantizeConfigBase | None = field(default=None, init=False, repr=False, compare=False) |
| 24 | - weight_config: ClassVar[None] = None | 25 | + weight_config: FakeQuantizeConfigBase | None = field(default=None, init=False, repr=False, compare=False) |
| 25 | step: QATStep = QATStep.PREPARE | 26 | step: QATStep = QATStep.PREPARE |
| 26 | 27 | ||
| 27 | def __post_init__(self) -> None: | 28 | def __post_init__(self) -> None: |
| @@ -138,8 +138,8 @@ def save_hf_safetensors( | |||
| 138 | 138 | ||
| 139 | normalized = _normalize_state_dict(state_dict) | 139 | normalized = _normalize_state_dict(state_dict) |
| 140 | 140 | ||
| 141 | - # MXTensor -> qdata/scale + metadata; plain tensors pass through. | 141 | + # TorchAO 0.17 annotates a nested dict but iterates over tensor values. |
| 142 | - tensors_data, metadata = flatten_tensor_state_dict(normalized) | 142 | + tensors_data, metadata = flatten_tensor_state_dict(normalized) # pyrefly: ignore [bad-argument-type] |
| 143 | # transformers <5 rejects a non-empty __metadata__ (flatten always fills it) | 143 | # transformers <5 rejects a non-empty __metadata__ (flatten always fills it) |
| 144 | # lacking a "format" tag; save_pretrained stamps it, so we mirror that here. | 144 | # lacking a "format" tag; save_pretrained stamps it, so we mirror that here. |
| 145 | metadata["format"] = "pt" | 145 | metadata["format"] = "pt" |
| @@ -36,7 +36,14 @@ markers = [ | |||
| 36 | ] | 36 | ] |
| 37 | 37 | ||
| 38 | [tool.pyrefly] | 38 | [tool.pyrefly] |
| 39 | -project-excludes = ["**/tests/**", "CI", "torchtitan_npu/ops/pypto", "torchtitan_npu/ops/triton", "scripts"] | 39 | +project-excludes = [ |
| 40 | + "**/tests/**", "CI", "scripts", | ||
| 41 | + # torch.compile debug dumps written by the rope-compile unit tests. | ||
| 42 | + "torch_compile_debug", | ||
| 43 | + # Kernel DSL tensor annotations are not Python type annotations. | ||
| 44 | + "torchtitan_npu/ops/pypto", "torchtitan_npu/ops/pypto_pro", | ||
| 45 | + "torchtitan_npu/ops/triton", "torchtitan_npu/ops/tilelang", | ||
| 46 | +] | ||
| 40 | ignore-missing-imports = [ | 47 | ignore-missing-imports = [ |
| 41 | "attn_gym", | 48 | "attn_gym", |
| 42 | "attn_gym.*", | 49 | "attn_gym.*", |
| @@ -98,7 +98,7 @@ def _subgroup_worker(rank: int, rendezvous: str, intra: int) -> None: | |||
| 98 | ) | 98 | ) |
| 99 | # The splits are the ones the production metadata build produced for this subgroup. | 99 | # The splits are the ones the production metadata build produced for this subgroup. |
| 100 | assert local.xchg is not None | 100 | assert local.xchg is not None |
| 101 | - _compare(mesh, local.xchg.cmp.send_split, local.xchg.cmp.recv_split) | 101 | + _compare(mesh, local.xchg.cmp.send_counts.tolist(), local.xchg.cmp.recv_counts.tolist()) |
| 102 | finally: | 102 | finally: |
| 103 | dist.destroy_process_group() | 103 | dist.destroy_process_group() |
| 104 | 104 | ||
| @@ -58,7 +58,7 @@ def _exchange(tensors: list[torch.Tensor], plans) -> list[torch.Tensor]: | |||
| 58 | for rank, plan in enumerate(plans): | 58 | for rank, plan in enumerate(plans): |
| 59 | ordered = tensors[rank][torch.argsort(plan.recv_index)] | 59 | ordered = tensors[rank][torch.argsort(plan.recv_index)] |
| 60 | offset = 0 | 60 | offset = 0 |
| 61 | - for peer, count in enumerate(plan.recv_split): | 61 | + for peer, count in enumerate(plan.recv_counts.tolist()): |
| 62 | sent[rank, peer] = ordered[offset : offset + count] | 62 | sent[rank, peer] = ordered[offset : offset + count] |
| 63 | offset += count | 63 | offset += count |
| 64 | outputs = [] | 64 | outputs = [] |
| @@ -74,7 +74,7 @@ def _restore(tensors: list[torch.Tensor], plans) -> list[torch.Tensor]: | |||
| 74 | for rank, plan in enumerate(plans): | 74 | for rank, plan in enumerate(plans): |
| 75 | ordered = tensors[rank] if plan.send_index is None else tensors[rank][plan.send_index] | 75 | ordered = tensors[rank] if plan.send_index is None else tensors[rank][plan.send_index] |
| 76 | offset = 0 | 76 | offset = 0 |
| 77 | - for peer, count in enumerate(plan.send_split): | 77 | + for peer, count in enumerate(plan.send_counts.tolist()): |
| 78 | sent[rank, peer] = ordered[offset : offset + count] | 78 | sent[rank, peer] = ordered[offset : offset + count] |
| 79 | offset += count | 79 | offset += count |
| 80 | return [torch.cat([sent[source, rank] for source in range(len(plans))])[plan.recv_index] | 80 | return [torch.cat([sent[source, rank] for source in range(len(plans))])[plan.recv_index] |
| @@ -88,12 +88,12 @@ def test_the_plan_splits_the_slab_and_the_peers_agree(cp_size): | |||
| 88 | # Every row of this rank's slab is addressed to exactly one peer. | 88 | # Every row of this rank's slab is addressed to exactly one peer. |
| 89 | assert int(plan.recv_index.numel()) == slab | 89 | assert int(plan.recv_index.numel()) == slab |
| 90 | assert sorted(plan.recv_index.tolist()) == list(range(slab)) | 90 | assert sorted(plan.recv_index.tolist()) == list(range(slab)) |
| 91 | - assert sum(plan.send_split) == slab | 91 | + assert plan.send_counts.sum().item() == slab |
| 92 | - assert sum(plan.recv_split) == slab | 92 | + assert plan.recv_counts.sum().item() == slab |
| 93 | # What one rank sends is what its peer expects: the two sides of the same table. | 93 | # What one rank sends is what its peer expects: the two sides of the same table. |
| 94 | for sender in range(cp_size): | 94 | for sender in range(cp_size): |
| 95 | for receiver in range(cp_size): | 95 | for receiver in range(cp_size): |
| 96 | - assert plans[sender].send_split[receiver] == plans[receiver].recv_split[sender] | 96 | + assert plans[sender].send_counts[receiver] == plans[receiver].recv_counts[sender] |
| 97 | 97 | ||
| 98 | 98 | ||
| 99 | @pytest.mark.parametrize("cp_size", [2, 4]) | 99 | @pytest.mark.parametrize("cp_size", [2, 4]) |
| @@ -171,4 +171,4 @@ def test_the_movement_keeps_the_container_grid(monkeypatch): | |||
| 171 | assert out.shape == tensor.shape | 171 | assert out.shape == tensor.shape |
| 172 | # Split vectors describe this forward: input is sent, output is received. | 172 | # Split vectors describe this forward: input is sent, output is received. |
| 173 | plan = plans[0] | 173 | plan = plans[0] |
| 174 | - assert seen == [((slab, 3), tuple(plan.send_split), tuple(plan.recv_split))] | 174 | + assert seen == [((slab, 3), tuple(plan.send_counts.tolist()), tuple(plan.recv_counts.tolist()))] |
| @@ -51,8 +51,8 @@ def _to_chunks(tensor: torch.Tensor, plan, *, group) -> torch.Tensor: | |||
| 51 | 51 | ||
| 52 | moved = all_to_all_single( | 52 | moved = all_to_all_single( |
| 53 | tensor.squeeze(0)[torch.argsort(plan.recv_index)], | 53 | tensor.squeeze(0)[torch.argsort(plan.recv_index)], |
| 54 | - output_split_sizes=plan.send_split, | 54 | + output_split_sizes=plan.send_counts.tolist(), |
| 55 | - input_split_sizes=plan.recv_split, | 55 | + input_split_sizes=plan.recv_counts.tolist(), |
| 56 | group=group, | 56 | group=group, |
| 57 | ) | 57 | ) |
| 58 | if plan.send_index is not None: | 58 | if plan.send_index is not None: |
| @@ -163,7 +163,10 @@ def _window_worker(rank, rendezvous, layout): | |||
| 163 | 163 | ||
| 164 | attention = CPAttention(Module()) | 164 | attention = CPAttention(Module()) |
| 165 | attention.group = dist.group.WORLD | 165 | attention.group = dist.group.WORLD |
| 166 | - head, tail = attention._exchange_window(keys, metadata.xchg.swa) | 166 | + plan = metadata.xchg.swa |
| 167 | + # A rank without a remote halo must still participate in compiled checkpoint replay. | ||
| 168 | + assert plan.send_counts.sum().item() > 0 and plan.recv_counts.sum().item() > 0 | ||
| 169 | + head, tail = attention._exchange_window(keys, plan) | ||
| 167 | loss = head.square().sum() * (rank + 1) | 170 | loss = head.square().sum() * (rank + 1) |
| 168 | if tail is not None: | 171 | if tail is not None: |
| 169 | loss = loss + tail.square().sum() * (rank + 4) | 172 | loss = loss + tail.square().sum() * (rank + 4) |
| @@ -166,8 +166,8 @@ def test_the_plan_matches_the_row(cu, cp_size): | |||
| 166 | matrix = _oracle_splits(cu, cp_size, seq_len) | 166 | matrix = _oracle_splits(cu, cp_size, seq_len) |
| 167 | assert matrix.sum().item() == cu[-1], "the splits must partition the row" | 167 | assert matrix.sum().item() == cu[-1], "the splits must partition the row" |
| 168 | for rank, plan in enumerate(_plans(cu, cp_size)): | 168 | for rank, plan in enumerate(_plans(cu, cp_size)): |
| 169 | - assert list(plan.send_split) == matrix[:, rank].tolist() | 169 | + assert plan.send_counts.tolist() == matrix[:, rank].tolist() |
| 170 | - assert list(plan.recv_split) == matrix[rank].tolist() | 170 | + assert plan.recv_counts.tolist() == matrix[rank].tolist() |
| 171 | 171 | ||
| 172 | 172 | ||
| 173 | @pytest.mark.parametrize("cu, cp_size", _CASES) | 173 | @pytest.mark.parametrize("cu, cp_size", _CASES) |
| @@ -200,8 +200,8 @@ def test_the_movement_is_a_permutation_of_the_slab(cu, cp_size): | |||
| 200 | chunk = (torch.tensor(cu[1:]) - torch.tensor(cu[:-1])) // cp_size | 200 | chunk = (torch.tensor(cu[1:]) - torch.tensor(cu[:-1])) // cp_size |
| 201 | for rank, plan in enumerate(_plans(cu, cp_size)): | 201 | for rank, plan in enumerate(_plans(cu, cp_size)): |
| 202 | assert sorted(plan.recv_index.tolist()) == list(range(seq_len)) | 202 | assert sorted(plan.recv_index.tolist()) == list(range(seq_len)) |
| 203 | - assert sum(plan.send_split) == seq_len | 203 | + assert plan.send_counts.sum().item() == seq_len |
| 204 | - assert sum(plan.recv_split) == seq_len | 204 | + assert plan.recv_counts.sum().item() == seq_len |
| 205 | # A document's chunk is one interval and spans at most two slabs; the closed form | 205 | # A document's chunk is one interval and spans at most two slabs; the closed form |
| 206 | # leans on that, so the property is pinned rather than assumed. | 206 | # leans on that, so the property is pinned rather than assumed. |
| 207 | start = torch.tensor(cu[:-1]) + rank * chunk | 207 | start = torch.tensor(cu[:-1]) + rank * chunk |
| @@ -243,11 +243,11 @@ def _emulate(tensors: list[torch.Tensor], plans: list[FlattenMetadata], *, inver | |||
| 243 | t if inverse and p.send_index is None else t[p.send_index] if inverse else t[torch.argsort(p.recv_index)] | 243 | t if inverse and p.send_index is None else t[p.send_index] if inverse else t[torch.argsort(p.recv_index)] |
| 244 | for t, p in zip(tensors, plans, strict=True) | 244 | for t, p in zip(tensors, plans, strict=True) |
| 245 | ] | 245 | ] |
| 246 | - splits = [(p.send_split, p.recv_split) if inverse else (p.recv_split, p.send_split) for p in plans] | 246 | + counts = [p.send_counts if inverse else p.recv_counts for p in plans] |
| 247 | offsets = [] | 247 | offsets = [] |
| 248 | - for send, _ in splits: | 248 | + for send_counts in counts: |
| 249 | running, rows = [0], 0 | 249 | running, rows = [0], 0 |
| 250 | - for value in send: | 250 | + for value in send_counts.tolist(): |
| 251 | rows += value | 251 | rows += value |
| 252 | running.append(rows) | 252 | running.append(rows) |
| 253 | offsets.append(running) | 253 | offsets.append(running) |
| @@ -331,8 +331,8 @@ def test_the_cp_transform_carries_the_plan_and_recuts_the_frames(): | |||
| 331 | masks = _masks(row, cp_size, cp_rank) | 331 | masks = _masks(row, cp_size, cp_rank) |
| 332 | plan = masks.xchg.cmp | 332 | plan = masks.xchg.cmp |
| 333 | assert plan is not None | 333 | assert plan is not None |
| 334 | - assert list(plan.recv_split) == _oracle_splits([0, 8, 24], cp_size, slab)[cp_rank].tolist() | 334 | + assert plan.recv_counts.tolist() == _oracle_splits([0, 8, 24], cp_size, slab)[cp_rank].tolist() |
| 335 | - assert sum(plan.recv_split) == slab | 335 | + assert plan.recv_counts.sum().item() == slab |
| 336 | assert sorted(plan.recv_index.tolist()) == list(range(slab)) | 336 | assert sorted(plan.recv_index.tolist()) == list(range(slab)) |
| 337 | # The key stream's positions are this rank's window, counted row by row. | 337 | # The key stream's positions are this rank's window, counted row by row. |
| 338 | assert masks.position_k.reshape(-1).tolist() == _oracle_flatten_positions([0, 8, 24], cp_size, cp_rank) | 338 | assert masks.position_k.reshape(-1).tolist() == _oracle_flatten_positions([0, 8, 24], cp_size, cp_rank) |
| @@ -246,7 +246,7 @@ def _set_determinism_preserving_eager_flex(*args, **kwargs): | |||
| 246 | 246 | ||
| 247 | 247 | ||
| 248 | def apply() -> None: | 248 | def apply() -> None: |
| 249 | - flex_attention._FLEX_ATTENTION_DISABLE_COMPILE_DEBUG = True # pyrefly: ignore [bad-assignment] | 249 | + flex_attention._FLEX_ATTENTION_DISABLE_COMPILE_DEBUG = True # pyrefly: ignore [missing-attribute, bad-assignment] |
| 250 | 250 | ||
| 251 | _install_eager_flex_attention() | 251 | _install_eager_flex_attention() |
| 252 | dist_utils.set_determinism = _set_determinism_preserving_eager_flex | 252 | dist_utils.set_determinism = _set_determinism_preserving_eager_flex |
| @@ -259,7 +259,7 @@ def apply() -> None: | |||
| 259 | common_attention._compiled_create_block_mask = _eager_create_block_mask | 259 | common_attention._compiled_create_block_mask = _eager_create_block_mask |
| 260 | 260 | ||
| 261 | if hasattr(flex_attention, "_validate_device"): | 261 | if hasattr(flex_attention, "_validate_device"): |
| 262 | - flex_attention._validate_device = ( # pyrefly: ignore [bad-assignment] | 262 | + flex_attention._validate_device = ( # pyrefly: ignore [missing-attribute, bad-assignment] |
| 263 | lambda query, key, value: None | 263 | lambda query, key, value: None |
| 264 | ) | 264 | ) |
| 265 | 265 | ||
| @@ -32,7 +32,7 @@ def reset_failed_iteration(model_parts): | |||
| 32 | # FSDP sets the root flag on its first forward, before initializing | 32 | # FSDP sets the root flag on its first forward, before initializing |
| 33 | # communication state. Untouched model parts have no work to reset. | 33 | # communication state. Untouched model parts have no work to reset. |
| 34 | if isinstance(model, FSDPModule) and model._get_fsdp_state()._is_root is not None: | 34 | if isinstance(model, FSDPModule) and model._get_fsdp_state()._is_root is not None: |
| 35 | - model.reset_iter_state() | 35 | + model.reset_iter_state() # pyrefly: ignore [missing-attribute] |
| 36 | for parameter in model.parameters(): | 36 | for parameter in model.parameters(): |
| 37 | parameter.grad = None | 37 | parameter.grad = None |
| 38 | for module in model.modules(): | 38 | for module in model.modules(): |
| @@ -42,7 +42,7 @@ def reset_failed_iteration(model_parts): | |||
| 42 | unsharded = getattr(fsdp_param, "_unsharded_param", None) | 42 | unsharded = getattr(fsdp_param, "_unsharded_param", None) |
| 43 | if unsharded is not None: | 43 | if unsharded is not None: |
| 44 | unsharded.grad = None | 44 | unsharded.grad = None |
| 45 | - fsdp_param.unsharded_accumulated_grad = None | 45 | + fsdp_param.unsharded_accumulated_grad = None # pyrefly: ignore [read-only] |
| 46 | reset_rejected_moe_state(model_parts) | 46 | reset_rejected_moe_state(model_parts) |
| 47 | 47 | ||
| 48 | 48 | ||
| @@ -199,7 +199,7 @@ class CompressedSparseInnerAttention(Module): | |||
| 199 | # Bound to a local so the guard below can narrow it. | 199 | # Bound to a local so the guard below can narrow it. |
| 200 | aux_loss = self.aux_loss | 200 | aux_loss = self.aux_loss |
| 201 | aux = AuxRequest(lse=True) if aux_loss is not None and self.training else None | 201 | aux = AuxRequest(lse=True) if aux_loss is not None and self.training else None |
| 202 | - result = gather_attn( | 202 | + result = gather_attn( # pyrefly: ignore [no-matching-overload] |
| 203 | q.transpose(1, 2), | 203 | q.transpose(1, 2), |
| 204 | swa_k.reshape(bsz, 1, seqlen, head_dim), | 204 | swa_k.reshape(bsz, 1, seqlen, head_dim), |
| 205 | sparse_kv, | 205 | sparse_kv, |
| @@ -44,11 +44,10 @@ class CPAttention(_CPKernel): | |||
| 44 | local = win_k.squeeze(0) | 44 | local = win_k.squeeze(0) |
| 45 | received = all_to_all_single( | 45 | received = all_to_all_single( |
| 46 | local.index_select(0, metadata.send_index), | 46 | local.index_select(0, metadata.send_index), |
| 47 | - output_split_sizes=metadata.recv_split, | 47 | + output_split_sizes=metadata.recv_counts.tolist(), |
| 48 | - input_split_sizes=metadata.send_split, | 48 | + input_split_sizes=metadata.send_counts.tolist(), |
| 49 | group=self.group, | 49 | group=self.group, |
| 50 | ) | 50 | ) |
| 51 | - # Empty receives must remain in autograd; repeated keys accumulate at their owner. | ||
| 52 | available = torch.cat((local, received)) | 51 | available = torch.cat((local, received)) |
| 53 | head = available.index_select(0, metadata.head_index).unsqueeze(0) | 52 | head = available.index_select(0, metadata.head_index).unsqueeze(0) |
| 54 | tail = None if metadata.tail_index is None else available.index_select(0, metadata.tail_index).unsqueeze(0) | 53 | tail = None if metadata.tail_index is None else available.index_select(0, metadata.tail_index).unsqueeze(0) |
| @@ -153,7 +152,10 @@ class ContextParallelCompressorMixin: | |||
| 153 | if metadata.send_index is not None: | 152 | if metadata.send_index is not None: |
| 154 | tokens = tokens.index_select(0, metadata.send_index) | 153 | tokens = tokens.index_select(0, metadata.send_index) |
| 155 | received = all_to_all_single( | 154 | received = all_to_all_single( |
| 156 | - tokens, output_split_sizes=metadata.recv_split, input_split_sizes=metadata.send_split, group=self.group | 155 | + tokens, |
| 156 | + output_split_sizes=metadata.recv_counts.tolist(), | ||
| 157 | + input_split_sizes=metadata.send_counts.tolist(), | ||
| 158 | + group=self.group, | ||
| 157 | ) | 159 | ) |
| 158 | return received.index_select(0, metadata.recv_index).unsqueeze(0) | 160 | return received.index_select(0, metadata.recv_index).unsqueeze(0) |
| 159 | 161 | ||
| @@ -36,10 +36,11 @@ def _xchg_metadata(token_locations, requested_tokens, *, rank): | |||
| 36 | outgoing = [tokens[owners[tokens] == rank] for tokens in requested_tokens] | 36 | outgoing = [tokens[owners[tokens] == rank] for tokens in requested_tokens] |
| 37 | wanted = requested_tokens[rank] | 37 | wanted = requested_tokens[rank] |
| 38 | incoming = [wanted[owners[wanted] == peer] for peer in range(len(requested_tokens))] | 38 | incoming = [wanted[owners[wanted] == peer] for peer in range(len(requested_tokens))] |
| 39 | + # Tensor counts keep the split values symbolic inside the compiled exchange. | ||
| 39 | return ( | 40 | return ( |
| 40 | token_locations[torch.cat(outgoing)] % local_length, | 41 | token_locations[torch.cat(outgoing)] % local_length, |
| 41 | - [tokens.numel() for tokens in outgoing], | 42 | + torch.tensor([tokens.numel() for tokens in outgoing], dtype=torch.int64, device="cpu"), |
| 42 | - [tokens.numel() for tokens in incoming], | 43 | + torch.tensor([tokens.numel() for tokens in incoming], dtype=torch.int64, device="cpu"), |
| 43 | torch.cat(incoming), | 44 | torch.cat(incoming), |
| 44 | ) | 45 | ) |
| 45 | 46 | ||
| @@ -48,9 +49,9 @@ def _xchg_metadata(token_locations, requested_tokens, *, rank): | |||
| 48 | class FlattenMetadata: | 49 | class FlattenMetadata: |
| 49 | """Restore the compressor's contiguous global token interval.""" | 50 | """Restore the compressor's contiguous global token interval.""" |
| 50 | 51 | ||
| 52 | + send_counts: torch.Tensor | ||
| 53 | + recv_counts: torch.Tensor | ||
| 51 | send_index: torch.Tensor | None | 54 | send_index: torch.Tensor | None |
| 52 | - send_split: list[int] | ||
| 53 | - recv_split: list[int] | ||
| 54 | recv_index: torch.Tensor | 55 | recv_index: torch.Tensor |
| 55 | 56 | ||
| 56 | @classmethod | 57 | @classmethod |
| @@ -58,13 +59,13 @@ class FlattenMetadata: | |||
| 58 | token_locations = torch.argsort(permutation.flatten()) | 59 | token_locations = torch.argsort(permutation.flatten()) |
| 59 | local_length = permutation.numel() // cp_size | 60 | local_length = permutation.numel() // cp_size |
| 60 | requested = list(torch.arange(permutation.numel(), device=permutation.device).split(local_length)) | 61 | requested = list(torch.arange(permutation.numel(), device=permutation.device).split(local_length)) |
| 61 | - send_index, send_split, recv_split, received_tokens = _xchg_metadata(token_locations, requested, rank=cp_rank) | 62 | + send_index, send_counts, recv_counts, received_tokens = _xchg_metadata(token_locations, requested, rank=cp_rank) |
| 62 | if torch.equal(send_index, torch.arange(local_length, device=permutation.device)): | 63 | if torch.equal(send_index, torch.arange(local_length, device=permutation.device)): |
| 63 | send_index = None | 64 | send_index = None |
| 64 | return cls( | 65 | return cls( |
| 65 | send_index=send_index, | 66 | send_index=send_index, |
| 66 | - send_split=send_split, | 67 | + send_counts=send_counts, |
| 67 | - recv_split=recv_split, | 68 | + recv_counts=recv_counts, |
| 68 | recv_index=torch.argsort(received_tokens), | 69 | recv_index=torch.argsort(received_tokens), |
| 69 | ) | 70 | ) |
| 70 | 71 | ||
| @@ -73,9 +74,9 @@ class FlattenMetadata: | |||
| 73 | class WindowMetadata: | 74 | class WindowMetadata: |
| 74 | """Fetch missing window tokens; head/tail index [local keys, received keys].""" | 75 | """Fetch missing window tokens; head/tail index [local keys, received keys].""" |
| 75 | 76 | ||
| 77 | + send_counts: torch.Tensor | ||
| 78 | + recv_counts: torch.Tensor | ||
| 76 | send_index: torch.Tensor | 79 | send_index: torch.Tensor |
| 77 | - send_split: list[int] | ||
| 78 | - recv_split: list[int] | ||
| 79 | head_index: torch.Tensor | 80 | head_index: torch.Tensor |
| 80 | tail_index: torch.Tensor | None | 81 | tail_index: torch.Tensor | None |
| 81 | 82 | ||
| @@ -96,16 +97,20 @@ class WindowMetadata: | |||
| 96 | if tail_prefix is not None: | 97 | if tail_prefix is not None: |
| 97 | tokens = torch.cat((tokens, tail_prefix.token_ids(peer))) | 98 | tokens = torch.cat((tokens, tail_prefix.token_ids(peer))) |
| 98 | tokens = tokens.unique(sorted=True) | 99 | tokens = tokens.unique(sorted=True) |
| 99 | - requested.append(tokens[token_locations[tokens] // local_length != peer]) | 100 | + remote = tokens[token_locations[tokens] // local_length != peer] |
| 100 | - send_index, send_split, recv_split, received_tokens = _xchg_metadata(token_locations, requested, rank=cp_rank) | 101 | + # Route one actual local key through the collective as well. Even a rank |
| 102 | + # with no remote halo must participate when checkpointing replays it. | ||
| 103 | + local_key = permutation.reshape(cp_size, local_length)[peer, :1] | ||
| 104 | + requested.append(torch.cat((remote, local_key))) | ||
| 105 | + send_index, send_counts, recv_counts, received_tokens = _xchg_metadata(token_locations, requested, rank=cp_rank) | ||
| 101 | token_to_buffer = token_locations % local_length | 106 | token_to_buffer = token_locations % local_length |
| 102 | token_to_buffer[received_tokens] = ( | 107 | token_to_buffer[received_tokens] = ( |
| 103 | torch.arange(received_tokens.numel(), device=permutation.device) + local_length | 108 | torch.arange(received_tokens.numel(), device=permutation.device) + local_length |
| 104 | ) | 109 | ) |
| 105 | return cls( | 110 | return cls( |
| 106 | send_index=send_index, | 111 | send_index=send_index, |
| 107 | - send_split=send_split, | 112 | + send_counts=send_counts, |
| 108 | - recv_split=recv_split, | 113 | + recv_counts=recv_counts, |
| 109 | head_index=token_to_buffer[head_window.token_ids(cp_rank)], | 114 | head_index=token_to_buffer[head_window.token_ids(cp_rank)], |
| 110 | tail_index=None if tail_window is None else token_to_buffer[tail_window.token_ids(cp_rank)], | 115 | tail_index=None if tail_window is None else token_to_buffer[tail_window.token_ids(cp_rank)], |
| 111 | ) | 116 | ) |
| @@ -212,7 +212,7 @@ class CompressedSparseInnerAttention2(Module): | |||
| 212 | cmp_k.squeeze(0), | 212 | cmp_k.squeeze(0), |
| 213 | topk_indices.squeeze(0), | 213 | topk_indices.squeeze(0), |
| 214 | topk_scores.squeeze(0), | 214 | topk_scores.squeeze(0), |
| 215 | - gathered.lse.squeeze(0).transpose(0, 1), | 215 | + gathered.lse.squeeze(0).transpose(0, 1), # pyrefly: ignore [missing-attribute] |
| 216 | cu_seqlens, | 216 | cu_seqlens, |
| 217 | cu_seqlens_k, | 217 | cu_seqlens_k, |
| 218 | softmax_scale=self.softmax_scale, | 218 | softmax_scale=self.softmax_scale, |
| @@ -68,8 +68,7 @@ def _apply_compile_v4_1(model, *, compile_config: CompileConfig) -> None: | |||
| 68 | this collapses back to a plain call. The regional-inductor helper is | 68 | this collapses back to a plain call. The regional-inductor helper is |
| 69 | intentionally not used: V4.1's sparse core is the gather_attn | 69 | intentionally not used: V4.1's sparse core is the gather_attn |
| 70 | reference implementation (no FlexAttention), for which it is the | 70 | reference implementation (no FlexAttention), for which it is the |
| 71 | - identity. The shared per-block code object plus role-level graphs keep | 71 | + identity. |
| 72 | - the recompile count within the stock recompile_limit. | ||
| 73 | 72 | ||
| 74 | V4.1-specific pieces beyond the shared semantics: | 73 | V4.1-specific pieces beyond the shared semantics: |
| 75 | - dynamic=False: shapes are static for a fixed seq_len; dynamic | 74 | - dynamic=False: shapes are static for a fixed seq_len; dynamic |
| @@ -137,7 +136,13 @@ def _apply_compile_v4_1(model, *, compile_config: CompileConfig) -> None: | |||
| 137 | ) | 136 | ) |
| 138 | 137 | ||
| 139 | for layer_id, transformer_block in model.layers.named_children(): | 138 | for layer_id, transformer_block in model.layers.named_children(): |
| 140 | - transformer_block.compile(backend=compile_config.backend, fullgraph=fullgraph, dynamic=False) | 139 | + transformer_block.compile( |
| 140 | + backend=compile_config.backend, | ||
| 141 | + fullgraph=fullgraph, | ||
| 142 | + dynamic=False, | ||
| 143 | + # Heterogeneous blocks share CheckpointWrapper.forward and its Dynamo cache. | ||
| 144 | + isolate_recompiles=compile_config.backend == "inductor" and force_balanced_moe, | ||
| 145 | + ) | ||
| 141 | 146 | ||
| 142 | logger.info( | 147 | logger.info( |
| 143 | f"Compiling each V4.1 TransformerBlock with torch.compile " | 148 | f"Compiling each V4.1 TransformerBlock with torch.compile " |
| @@ -32,8 +32,8 @@ def _patch_dram_bandwidth() -> None: | |||
| 32 | def get_npu_dram_gbps() -> int: | 32 | def get_npu_dram_gbps() -> int: |
| 33 | return _NPU_DRAM_GBPS | 33 | return _NPU_DRAM_GBPS |
| 34 | 34 | ||
| 35 | - inductor_utils.get_gpu_dram_gbps = get_npu_dram_gbps # pyrefly: ignore [bad-assignment] | 35 | + inductor_utils.get_gpu_dram_gbps = get_npu_dram_gbps # pyrefly: ignore [missing-attribute, bad-assignment] |
| 36 | - runtime_estimation.get_gpu_dram_gbps = get_npu_dram_gbps # pyrefly: ignore [bad-assignment] | 36 | + runtime_estimation.get_gpu_dram_gbps = get_npu_dram_gbps # pyrefly: ignore [missing-attribute, bad-assignment] |
| 37 | _DRAM_PATCHED = True | 37 | _DRAM_PATCHED = True |
| 38 | logger.info( | 38 | logger.info( |
| 39 | "[NPU Runtime Estimation Patch] using %s GB/s DRAM bandwidth fallback", | 39 | "[NPU Runtime Estimation Patch] using %s GB/s DRAM bandwidth fallback", |
一般(S2): 【文档同步】需要补充或更新文档。
本 PR 的文档同步要求: 本区间移除了
FlattenMetadata/WindowMetadata上的send_split/recv_split属性,只保留send_counts/recv_counts张量字段(torchtitan_npu/models/deepseek_v4/metadata.py:52-53、77-78),但两份已有文档仍按旧属性名描述;读者按文档访问会得到AttributeError。按docs/AGENTS.md,功能/开发者文档应描述当前已实现事实。docs/feature_guides/deepseek_v4_tnd.md:73:把send_index/send_split/recv_split更新为send_index/send_counts/recv_counts。docs/developer_guides/context_parallel.md:76:把send_split/recv_split更新为send_counts/recv_counts,并说明它们是 CPU 张量、在 collective 调用处用.tolist()转成分段列表。问题编号:R1456-005
审查版本:
49a8b22700ec8bfd33d89f9a3a93138eeef4bbf0