1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Static arithmetic and layout contract for Level 3 PIK."""
16from __future__ import annotations
17
18from dataclasses import dataclass
19
20
21def _positive(value: int, name: str) -> None:
22 if isinstance(value, bool) or not isinstance(value, int) or value < 1:
23 raise ValueError(f"{name} must be a positive integer")
24
25
26@dataclass(frozen=True)
27class PikPlan:
28 """Fix global leaves and the BMM input layout across TP layouts.
29
30 Leaf outputs and the final root are BF16. Every internal tree node is FP32.
31 Changing num_leaves changes the numerical contract, not just performance.
32 """
33
34 num_leaves: int = 8
35 leaf_layout: str = "strided"
36
37 def __post_init__(self) -> None:
38 """Reject unsupported numerical and physical layouts."""
39 _positive(self.num_leaves, "num_leaves")
40 if self.num_leaves & (self.num_leaves - 1):
41 raise ValueError("num_leaves must be a power of two")
42 if self.leaf_layout not in ("strided", "packed"):
43 raise ValueError("leaf_layout must be strided or packed")
44
45 def validate(self, global_k: int, world_size: int) -> None:
46 """Require each rank to own a contiguous complete subtree."""
47 _positive(global_k, "global_k")
48 _positive(world_size, "world_size")
49 if self.num_leaves % world_size:
50 raise ValueError("TP must divide the fixed global leaf count")
51 if global_k % self.num_leaves:
52 raise ValueError("global K must be divisible by num_leaves")
53
54 def contract(self) -> dict:
55 """Return the serializable contract checked before data communication."""
56 return {"num_leaves": self.num_leaves, "leaf_layout": self.leaf_layout,
57 "provider": "torch_npu_level3_bmm", "leaf_dtype": "bfloat16",
58 "tree_dtype": "float32", "root_dtype": "bfloat16",
59 "bias": "bf16_after_root_cast", "tree": "balanced_adjacent_lower_left"}