Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / parallelism_invariant / row_parallel_linear / linear.py: 45%

142 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

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"""Prepared PIK execution with fixed forward arithmetic and first-order gradients.""" 

16from __future__ import annotations 

17 

18import hashlib 

19import json 

20import math 

21from dataclasses import dataclass 

22from typing import Any 

23 

24import torch 

25import torch.distributed as dist 

26from torch.autograd.function import once_differentiable 

27 

28from ..utils.batch_invariant import initialize_batch_invariant, normalize_policy 

29 

30from .collectives import combine_partials, gather_sequence_gradient 

31from .gemm import local_gemm 

32from .plan import PikPlan 

33 

34 

35@dataclass(frozen=True) 

36class PikContext: 

37 """Caller-owned static metadata; never caches weights, activations or process groups globally. 

38 

39 All participating ranks prepare together, then call with compatible shapes and ordering. 

40 None group means single-rank execution even inside a larger distributed job. 

41 """ 

42 

43 plan: PikPlan 

44 global_k: int 

45 output_features: int 

46 group: Any 

47 world_size: int 

48 rank: int 

49 device_index: int 

50 sequence_parallel: bool = False 

51 sequence_dim: int = 0 

52 transport: str = "all_gather" 

53 

54 def token_axis(self, x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None) -> int: 

55 """Check prepared local geometry and return the token axis.""" 

56 _validate_input_tensors(x, weight, self) 

57 local_k = self.global_k // self.world_size 

58 if x.shape[-1] != local_k or tuple(weight.shape) != (self.output_features, local_k): 

59 raise ValueError("PIK local shapes disagree with the prepared global shape") 

60 axis = self.sequence_dim % x.ndim 

61 if not -x.ndim <= self.sequence_dim < x.ndim or axis == x.ndim - 1: 

62 raise ValueError("sequence_dim must select a token axis") 

63 if self.sequence_parallel and x.shape[axis] % self.world_size: 

64 raise ValueError("SP sequence length must be divisible by TP; pad before PIK") 

65 if self.transport == "all_to_all" and math.prod(x.shape[:-1]) % self.world_size: 

66 raise ValueError("AllToAll requires flattened token rows divisible by TP") 

67 if bias is not None and (bias.device != x.device or tuple(bias.shape) != (self.output_features,) 

68 or bias.dtype not in (torch.bfloat16, torch.float32)): 

69 raise ValueError("bias must be [N] BF16/FP32 on the input NPU") 

70 return axis 

71 

72 def restore_output(self, root: torch.Tensor, token_shape: tuple[int, ...], axis: int, 

73 bias: torch.Tensor | None) -> torch.Tensor: 

74 """Cast the root before adding bias, then restore the original token axes.""" 

75 output = root.to(torch.bfloat16) 

76 if bias is not None: 

77 output = output + bias.to(torch.bfloat16) 

78 shape = list(token_shape) 

79 if self.sequence_parallel: 

80 shape[0] //= self.world_size 

81 return output.reshape(*shape, self.output_features).movedim(0, axis).contiguous() 

82 

83 

84def _preparation_contract(plan, global_k, world, output_features, sequence_parallel, sequence_dim, transport, 

85 policy, group) -> dict: 

86 """Validate local preparation before every rank joins contract agreement.""" 

87 normalized = normalize_policy(policy or {}) 

88 initialize_batch_invariant(normalized) 

89 if not isinstance(plan, PikPlan): 

90 raise ValueError("plan must be PikPlan") 

91 plan.validate(global_k, world) 

92 if isinstance(output_features, bool) or not isinstance(output_features, int) or output_features < 1: 

93 raise ValueError("output_features must be a positive integer") 

94 if (not isinstance(sequence_parallel, bool) or isinstance(sequence_dim, bool) 

95 or not isinstance(sequence_dim, int)): 

96 raise ValueError("sequence_parallel must be bool and sequence_dim must be int") 

97 if transport not in ("all_gather", "all_to_all"): 

98 raise ValueError("transport must be all_gather or all_to_all") 

99 if group is not None: 

100 backends = {entry.strip() for entry in dist.get_backend_config(group).lower().split(",")} 

101 if dist.get_backend(group) != "hccl" and "npu:hccl" not in backends: 

102 raise ValueError("PIK requires an HCCL backend for NPU tensors") 

103 return {**plan.contract(), "global_k": global_k, "n": output_features, 

104 "sp": sequence_parallel, "axis": sequence_dim, "transport": transport, 

105 "policy": normalized} 

106 

107 

108def prepare_pik(global_k: int, output_features: int, *, plan: PikPlan | None = None, 

109 group: Any = None, sequence_parallel: bool = False, sequence_dim: int = 0, 

110 transport: str = "all_gather", policy: dict | None = None) -> PikContext: 

111 """Initialize Level 3 and agree on the static contract outside compilation/capture. 

112 

113 Args: 

114 global_k: Full K before TP sharding; ranks own consecutive K intervals. 

115 output_features: Complete output feature count N. 

116 plan: Fixed global leaves and BMM physical layout. 

117 group: Explicit caller-owned HCCL TP group; None means TP1. 

118 sequence_parallel: Return the rank's contiguous sequence-axis slice. 

119 sequence_dim: Input token axis to scatter, before flattening. 

120 transport: all_gather reference or all_to_all; no shape-dependent auto selection. 

121 policy: Existing shared Level 3 policy, including memory-fill choice. 

122 

123 Returns: 

124 Immutable context passed to pik_linear. No collective occurs in its constructor. 

125 

126 Raises: 

127 ValueError: Any rank rejects the contract, or ranks disagree. 

128 """ 

129 if torch.compiler.is_compiling(): 

130 raise RuntimeError("prepare_pik must run before compilation") 

131 if group is not None and not dist.is_initialized(): 

132 raise ValueError("explicit group requires initialized distributed runtime") 

133 world = dist.get_world_size(group) if group is not None else 1 

134 rank = dist.get_rank(group) if group is not None else 0 

135 if world < 1 or rank < 0: 

136 raise ValueError("caller must belong to the TP group") 

137 device = torch.device("npu", torch.npu.current_device()) 

138 plan = PikPlan() if plan is None else plan 

139 error, contract = None, {} 

140 try: 

141 contract = _preparation_contract(plan, global_k, world, output_features, sequence_parallel, 

142 sequence_dim, transport, policy, group) 

143 except (ValueError, RuntimeError) as exception: 

144 error = exception 

145 if world > 1: 

146 digest = hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).digest() 

147 control = torch.tensor([int(error is not None), *digest], device=device, dtype=torch.int32) 

148 received = torch.empty(world * control.numel(), device=device, dtype=torch.int32) 

149 dist.all_gather_into_tensor(received, control, group=group) 

150 records = received.reshape(world, -1).cpu().tolist() 

151 if any(row[0] for row in records): 

152 detail = str(error) if error is not None else "peer validation failed" 

153 raise ValueError(f"PIK preparation rejected by a TP rank: {detail}") from error 

154 if any(row != records[0] for row in records[1:]): 

155 raise ValueError("PIK static contracts differ across TP ranks") 

156 if error is not None: 

157 raise error 

158 return PikContext(plan, global_k, output_features, group, world, rank, device.index, 

159 sequence_parallel, sequence_dim, transport) 

160 

161 

162def _validate_input_tensors(x, weight, context) -> None: 

163 """Check local tensor rank, device and dtype before validating sharded geometry.""" 

164 if x.ndim < 2 or weight.ndim != 2 or any(size < 1 for size in x.shape): 

165 raise ValueError("PIK expects nonempty [...,K_local] input and [N,K_local] weight") 

166 if x.device.type != "npu" or x.device.index != context.device_index or weight.device != x.device: 

167 raise ValueError("PIK tensors must reside on the prepared NPU") 

168 if x.dtype != torch.bfloat16 or weight.dtype != torch.bfloat16: 

169 raise ValueError("PIK inputs and weights must be BF16") 

170 

171 

172def _forward(x, weight, bias, context, axis): 

173 """Compute local leaves, combine rank roots, then cast and add bias. 

174 

175 x [..., K/TP] and weight [N, K/TP] produce flattened FP32 rank roots [M, N]. 

176 The fixed global leaf tree determines the sum; TP only changes ownership. 

177 SP returns M/TP rows, while ordinary TP returns all M rows. 

178 """ 

179 ordered = x.movedim(axis, 0) 

180 flat = ordered.reshape(-1, ordered.shape[-1]) 

181 partial = local_gemm(flat, weight, plan=context.plan, 

182 local_leaves=context.plan.num_leaves // context.world_size) 

183 root = combine_partials(partial, context.group, context.world_size, context.rank, 

184 scatter=context.sequence_parallel, transport=context.transport) 

185 

186 return context.restore_output(root, ordered.shape[:-1], axis, bias) 

187 

188 

189class _PikLinear(torch.autograd.Function): 

190 """Standard first-order linear gradients through a fixed, rounded forward.""" 

191 

192 @staticmethod 

193 def forward(ctx: Any, x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None, 

194 context: PikContext, axis: int) -> torch.Tensor: 

195 """Save original local tensors so callers retain parameter/optimizer ownership.""" 

196 ctx.save_for_backward(x, weight) 

197 ctx.context, ctx.axis = context, axis 

198 ctx.bias_dtype = bias.dtype if bias is not None else None 

199 return _forward(x, weight, bias, context, axis) 

200 

201 @staticmethod 

202 @once_differentiable 

203 def backward(ctx: Any, gradient: torch.Tensor) -> tuple: 

204 """Gather disjoint SP dY, then evaluate conventional local dX/dW/dB.""" 

205 x, weight = ctx.saved_tensors 

206 context = ctx.context 

207 if context.sequence_parallel and context.world_size > 1: 

208 gradient = gather_sequence_gradient(gradient, context.group, context.world_size, ctx.axis) 

209 dy = gradient.reshape(-1, weight.shape[0]).contiguous() 

210 flat_x = x.reshape(-1, x.shape[-1]) 

211 dx = (dy @ weight).reshape(x.shape) if ctx.needs_input_grad[0] else None 

212 dw = dy.T @ flat_x if ctx.needs_input_grad[1] else None 

213 db = dy.sum(0).to(ctx.bias_dtype) if ctx.needs_input_grad[2] else None 

214 return dx, dw, db, None, None 

215 

216 

217def pik_linear(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None = None, 

218 *, context: PikContext) -> torch.Tensor: 

219 """Compute fixed-tree X@W.T using local K shards and a prepared static context. 

220 

221 SP returns this rank's slice along context.sequence_dim. Its backward gathers dY; 

222 replicated output backward expects the same full dY on TP ranks. Bias gradient is 

223 already complete and must not be summed across TP again. Gradients follow usual 

224 first-order rounded-linear semantics; no cross-TP gradient-bit guarantee is made. 

225 All ranks must call with compatible shapes and ordering; no CPU agreement occurs 

226 here. Prepare, policy checks, kernel warmup and process-group lifecycle are outside 

227 capture. The operator does not own or cache caller weights. 

228 """ 

229 axis = context.token_axis(x, weight, bias) 

230 return _PikLinear.apply(x, weight, bias, context, axis) 

231 

232 

233def pik_linear_inference(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor | None = None, 

234 *, context: PikContext) -> torch.Tensor: 

235 """Use a BF16 SUM for no-grad, strided, two-leaf TP2 inference. 

236 

237 Gradient-enabled calls delegate to pik_linear and its distributed backward. 

238 """ 

239 if (torch.is_grad_enabled() or context.world_size != 2 or context.plan.num_leaves != 2 

240 or context.plan.leaf_layout != "strided" or context.transport != "all_gather"): 

241 return pik_linear(x, weight, bias, context=context) 

242 

243 axis = context.token_axis(x, weight, bias) 

244 ordered = x.movedim(axis, 0) 

245 root = torch.nn.functional.linear(ordered.reshape(-1, ordered.shape[-1]), weight) 

246 # With two BF16 leaves the sum has the same final BF16 rounding as the FP32 tree root. 

247 dist.all_reduce(root, group=context.group) 

248 if context.sequence_parallel: 

249 local_rows = root.shape[0] // context.world_size 

250 root = root.narrow(0, context.rank * local_rows, local_rows) 

251 return context.restore_output(root, ordered.shape[:-1], axis, bias)