Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / auto_parallel / _layer_census.py: 96%

670 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"""Census of what a layer of each kind keeps for its backward, on a fake layer. 

16 

17The census builds one decoder layer of a Transformers model under 

18``FakeTensorMode``, so it allocates no memory, runs its forward and its 

19backward at micro-batch 1, and counts bytes: those the autograd graph saves 

20between the two passes, and the most the backward holds live at once, less 

21the parameters and their gradients, which the memory model counts on its 

22own. It runs the kernels the runtime runs: flash attention, which saves its 

23inputs, its output and two fp32 softmax statistics per head and token, and 

24HyperParallel's chunked gated-delta-rule kernel, which saves the queries, 

25keys, values, the cumulated gates, beta and one chunk matrix. A layer built 

26with half the heads and half the feed-forward widths, as a tensor-parallel 

27rank of 2 holds it, tells the bytes tensor parallelism splits from those it 

28does not. These records describe a layer without checkpointing. The 

29trainer's selective checkpointing now selects explicit module regions, 

30not a model-wide operator policy, so a per-kind census cannot infer its 

31saved bytes or recomputed FLOP shares and leaves those fields unstated. 

32 

33What a layer saves is also told apart by the op of ND's op vector whose 

34backward takes it (:class:`_SavedOps`), the records of shared decision S1 as 

35the census fills them: the delta rule's, the attention kernel's (its 

36inputs and output for the batched matmuls, its fp32 statistics for the 

37softmax), a dropout's mask, what a norm saves, what the feed-forward's 

38activation function saves, and the rest by the part of the layer saving it, 

39the attention's projections or the feed-forward's. 

40 

41The output layer's census runs the final norm, the output projection and 

42Transformers' causal-LM loss, which casts the logits to fp32, as 

43HyperParallel's trainer runs them by default, dropping the model's logits 

44before the backward as the trainer does; half the vocabulary tells the 

45bytes a vocabulary-parallel loss splits. 

46 

47Where a train.yaml replaces Transformers' modules with HyperParallel's 

48fused ones (``plan_overrides`` with ``replace.kind: module``: its RMSNorm, its 

49grouped-query attention, its grouped experts), the census runs those 

50instead, so what it measures is what the trainer saves 

51(:func:`replacement_specs`). Their kernels are ``torch_npu``'s, which a 

52host cannot call, so they run under the kernels' shape contracts 

53(:mod:`hyper_parallel.auto_parallel._npu_contracts`). A factory that needs 

54a library the host lacks leaves the census with a layer the run does not 

55build, which it refuses (:exc:`CensusUnavailable`): Transformers' own 

56modules keep other bytes. The FLOP census (:func:`census_flops`) stays on 

57Transformers' own modules: it counts the arithmetic the time model prices, 

58which fusing a module does not change, and a fused kernel runs matmuls no 

59dispatch sees. 

60 

61A model whose layers cannot run alone is measured over its whole stack 

62(:func:`census_stack`): DeepSeek-V4.1's layers read what earlier layers 

63wrote in the same forward, and carry a hyper-connection dimension and a 

64mixing state between them. The model the trainer builds runs its own forward 

65and backward once, each save counting toward the layer that makes it, and a 

66kind's record is the mean of its layers'. 

67 

68A layer's parameters are counted by part, as ND prices its parts: the 

69attention's, the norms', the dense feed-forward's, the routed experts', the 

70shared expert's and the router's (:func:`census_parameters`), for verify 

71mode to set beside what ND prices. So are its forward FLOPs 

72(:func:`census_flops`): each matmul's toward the part of the layer that 

73runs it, flash attention's toward the scores, at every pair of tokens, as 

74the runtime's kernel computes them under an explicit causal mask, and the 

75gated delta rule's through Transformers' own chunked implementation, whose 

76matmuls the runtime's kernel runs alike. 

77""" 

78from __future__ import annotations 

79 

80import contextlib 

81import copy 

82import functools 

83import importlib 

84import inspect 

85import itertools 

86import logging 

87import weakref 

88from typing import ( 

89 Any, 

90 Callable, 

91 Dict, 

92 FrozenSet, 

93 Iterable, 

94 Iterator, 

95 List, 

96 Mapping, 

97 NamedTuple, 

98 Optional, 

99 Sequence, 

100 Tuple, 

101) 

102 

103import torch 

104from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode 

105from torch.utils._python_dispatch import TorchDispatchMode 

106from torch.utils._pytree import tree_flatten 

107from torch.utils.checkpoint import DefaultDeviceType 

108 

109from hyper_parallel.auto_parallel._model_spec import KindActivations 

110from hyper_parallel.auto_parallel._npu_contracts import npu_contracts 

111 

112logger = logging.getLogger(__name__) 

113 

114 

115class CensusUnavailable(RuntimeError): 

116 """A census cannot run here: this host cannot build the modules the run installs.""" 

117 

118 

119class LayerTraffic(NamedTuple): 

120 """What one forward of a layer moves, by part: its bytes, the parameters among them, and its ops. 

121 

122 Bytes of the whole layer on a micro-batch of one sequence, as 

123 :func:`census_flops` counts its FLOPs, so that the two quantities can be 

124 set beside each other part by part. ``parameter`` is the share of 

125 ``moved`` that is the layer's own weights, which a strategy shards where 

126 it leaves the activations alone, and ``launches`` is how many ops the 

127 forward dispatches, views excluded. 

128 """ 

129 

130 moved: Dict[str, float] 

131 parameter: Dict[str, float] 

132 launches: Dict[str, int] 

133 

134# The Transformers attention implementation the census registers its flash 

135# attention under: a name Transformers does not take for a flash 

136# attention's, as it does not take HyperParallel's default, sdpa, so a model 

137# runs sdpa's path, and DeepSeek-V3's values are not padded to its queries' 

138# width. 

139_FLASH = "nd_census_attention" 

140 

141# The config fields a tensor-parallel rank holds a share of. 

142_TP_FIELDS = ( 

143 "num_attention_heads", "num_key_value_heads", "intermediate_size", "moe_intermediate_size", 

144 "shared_expert_intermediate_size", "linear_num_key_heads", "linear_num_value_heads", 

145) 

146 

147# The softmax statistics flash attention keeps per head and token. 

148_FLASH_STATS = 8 

149 

150# The gated delta rules a run can take, named as the runtime names them 

151# (``components/modules/gated_delta_net.py``): Transformers' own chunked 

152# implementation, and HyperParallel's kernel, whose saved set the census holds 

153# as a contract. The runtime defaults to eager and so does the census. 

154_EAGER_GDN = "eager" 

155_HYPER_GDN = "triton" 

156_GDN_BACKENDS = (_EAGER_GDN, _HYPER_GDN) 

157 

158# Both attention contracts save fp32 softmax statistics separately from 

159# their inputs and outputs; the per-op census classifies those saves alike. 

160_ATTENTION_KERNELS = ("nd_census::flash_attention", "nd_census_npu::fusion_attention") 

161 

162_SELECTIVE_CENSUS_UNAVAILABLE = ( 

163 "operator-level selective census is no longer supported: activation checkpointing selects module regions, " 

164 "which this per-kind census does not model; request a plain census instead" 

165) 

166 

167# The per-head query and key norms an attention holds, which ND prices with 

168# the layer's norms. 

169_QK_NORMS = ("q_norm", "k_norm") 

170 

171 

172def _flash_outputs(query: torch.Tensor, key: torch.Tensor, 

173 value: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

174 """Flash attention's outputs, shapes only: each head's, as wide as its values, and two fp32 statistics.""" 

175 del key 

176 batch, heads, seq, _ = query.shape 

177 stats = [torch.empty(batch, heads, seq, _FLASH_STATS, dtype=torch.float32, device=query.device) 

178 for _ in range(2)] 

179 return query.new_empty(batch, heads, seq, value.shape[-1]), stats[0], stats[1] 

180 

181 

182# Keep flash attention opaque, as the runtime's kernel is, so its autograd 

183# contract rather than an eager decomposition determines the saved tensors. 

184_FLASH_KERNEL = torch.library.custom_op( 

185 "nd_census::flash_attention", mutates_args=(), 

186 schema="(Tensor query, Tensor key, Tensor value) -> (Tensor, Tensor, Tensor)")(_flash_outputs) 

187_FLASH_KERNEL.register_fake(_flash_outputs) 

188 

189 

190def _flash_saves(ctx: Any, inputs: Tuple[torch.Tensor, ...], output: Tuple[torch.Tensor, ...]) -> None: 

191 """Keep the inputs, the output and the statistics, which no gradient reaches.""" 

192 ctx.mark_non_differentiable(*output[1:]) 

193 ctx.save_for_backward(*inputs, *output) 

194 

195 

196def _flash_backward(ctx: Any, *grads: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

197 """Gradients of the inputs' shapes.""" 

198 del grads 

199 query, key, value = ctx.saved_tensors[:3] 

200 return torch.empty_like(query), torch.empty_like(key), torch.empty_like(value) 

201 

202 

203_FLASH_KERNEL.register_autograd(_flash_backward, setup_context=_flash_saves) 

204 

205 

206def _flash_attention(module, query, key, value, attention_mask, **kwargs): # pylint: disable=unused-argument 

207 """A Transformers attention function running the census's flash attention, grouped K and V unexpanded.""" 

208 return _FLASH_KERNEL(query, key, value)[0].transpose(1, 2).contiguous(), None 

209 

210 

211class _GatedDeltaRule(torch.autograd.Function): 

212 """HyperParallel's chunked gated-delta-rule kernel's saved set, shapes only.""" 

213 

214 @staticmethod 

215 def forward(ctx: Any, query: torch.Tensor, key: torch.Tensor, # pylint: disable=arguments-differ 

216 value: torch.Tensor, gate: torch.Tensor, beta: torch.Tensor, chunk: int) -> torch.Tensor: 

217 """Save the inputs, the cumulated gates, beta and a chunk matrix; return an output of the values' shape.""" 

218 batch, seq, heads, _ = key.shape 

219 # The cumulated gates follow the gate's own shape: Qwen3.5 passes per 

220 # value-head gates while the chunk matrix follows the key heads. 

221 gates = torch.empty_like(gate, dtype=torch.float32) 

222 chunks = torch.empty(batch, seq, heads, chunk, dtype=key.dtype, device=query.device) 

223 ctx.save_for_backward(query, key, value, gates, beta, chunks) 

224 del gate 

225 return torch.empty_like(value) 

226 

227 @staticmethod 

228 def backward(ctx: Any, # pylint: disable=arguments-differ 

229 grad: torch.Tensor) -> Tuple[Optional[torch.Tensor], ...]: 

230 """Return gradients of the inputs' shapes, and none of the chunk size.""" 

231 del grad 

232 query, key, value, gates, beta, _ = ctx.saved_tensors 

233 return (torch.empty_like(query), torch.empty_like(key), torch.empty_like(value), 

234 torch.empty_like(gates), torch.empty_like(beta), None) 

235 

236 

237def _gated_delta_rule(modeling: Any) -> Callable[..., Tuple[torch.Tensor, None]]: 

238 """The drop-in for a Transformers ``chunk_gated_delta_rule`` running :class:`_GatedDeltaRule`.""" 

239 l2norm = getattr(modeling, "l2norm", None) 

240 

241 def run(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, g: torch.Tensor, beta: torch.Tensor, 

242 chunk_size: int = 64, use_qk_l2norm_in_kernel: bool = False, 

243 **_kwargs: Any) -> Tuple[torch.Tensor, None]: 

244 """Run the kernel's contract as Transformers calls its kernel, with no final state.""" 

245 if use_qk_l2norm_in_kernel and l2norm is not None: 

246 query, key = l2norm(query, dim=-1, eps=1e-6), l2norm(key, dim=-1, eps=1e-6) 

247 return _GatedDeltaRule.apply(query, key, value, g, beta, chunk_size), None 

248 

249 return run 

250 

251 

252# Reading a scalar off a fake tensor raises, since it holds no data. Transformers' 

253# grouped_mm fallback reads its group offsets so in its backward, and it takes that 

254# fallback on CPU with torch 2.8 or older, the 910C's 2.7.1 among them. 

255_SCALAR_READ = torch.ops.aten._local_scalar_dense.default # pylint: disable=protected-access 

256 

257 

258class _LiveBytes(TorchDispatchMode): 

259 """The storages the ops it sees allocate, and the bytes they hold while they live.""" 

260 

261 def __init__(self) -> None: 

262 """Start with no storage counted.""" 

263 super().__init__() 

264 self.sizes: Dict[Tuple[int, int], int] = {} 

265 self.generation: Dict[int, int] = {} 

266 self.events: list = [] 

267 

268 def key(self, tensor: torch.Tensor) -> Tuple[int, int]: 

269 """The storage behind *tensor*, in the lifetime it has now.""" 

270 address = tensor.untyped_storage()._cdata # pylint: disable=protected-access 

271 return address, self.generation.get(address, 0) 

272 

273 def track(self, tensor: torch.Tensor) -> None: 

274 """Count *tensor*'s storage from now until it is freed.""" 

275 storage = tensor.untyped_storage() 

276 key = self.key(tensor) 

277 if key in self.sizes: 

278 return 

279 self.sizes[key] = storage.nbytes() 

280 self.events.append((key, self.sizes[key])) 

281 weakref.finalize(storage, self._free, key) 

282 

283 def _free(self, key: Tuple[int, int]) -> None: 

284 size = self.sizes.pop(key, None) 

285 self.generation[key[0]] = key[1] + 1 

286 if size: 

287 self.events.append((key, -size)) 

288 

289 def __torch_dispatch__(self, func, types, args=(), kwargs=None): # pylint: disable=unused-argument 

290 if func is _SCALAR_READ and isinstance(args[0], FakeTensor): 

291 return 0 # shapes alone price the memory, whatever the scalar 

292 out = func(*args, **(kwargs or {})) 

293 for tensor in tree_flatten(out)[0]: 

294 if isinstance(tensor, torch.Tensor): 

295 self.track(tensor) 

296 return out 

297 

298 def peak(self, start: int, excluded: Iterable[Tuple[int, int]], apart: Iterable[Tuple[int, int]] = ()) -> int: 

299 """The bytes live when the most are, from event *start* on, leaving out the *excluded* storages. 

300 

301 The storages *apart* count toward finding that moment, not toward 

302 the bytes returned. 

303 """ 

304 excluded, apart = set(excluded), set(apart) 

305 live = held = 0 

306 for key, delta in self.events[:start]: 

307 if key not in excluded: 

308 live += delta 

309 held += delta if key in apart else 0 

310 top, bytes_at_top = live, live - held 

311 for key, delta in self.events[start:]: 

312 if key in excluded: 

313 continue 

314 live += delta 

315 held += delta if key in apart else 0 

316 if live > top: 

317 top, bytes_at_top = live, live - held 

318 return bytes_at_top 

319 

320 

321@contextlib.contextmanager 

322def _checkpoints_on_cpu() -> Iterator[None]: 

323 """Run activation checkpointing as a CPU's while a census runs. 

324 

325 A census's tensors are fake and on the CPU, so a checkpoint over them 

326 takes the default device type, which ``torch_npu`` sets to its own when 

327 it imports. Replaying the forward would then open the NPU's autocast 

328 and start a device the census never uses, and that a host whose NPU 

329 cannot start fails on. The default is put back on the way out. 

330 """ 

331 previous = DefaultDeviceType.get_device_type() 

332 DefaultDeviceType.set_device_type("cpu") 

333 try: 

334 yield 

335 finally: 

336 DefaultDeviceType.set_device_type(previous) 

337 

338 

339def _measure(params: Sequence[torch.Tensor], inputs: Iterable[torch.Tensor], 

340 forward: Callable[[], torch.Tensor], backward: Callable[[torch.Tensor], None], 

341 grad_inputs: Iterable[torch.Tensor] = (), checkpointed: bool = False, 

342 shared: Iterable[torch.Tensor] = (), ops: Optional["_SavedOps"] = None) -> Tuple[int, int]: 

343 """Bytes a forward saves for its backward, and the activations the backward holds when it holds the most. 

344 

345 Args: 

346 params: The parameters of what runs. 

347 inputs: The tensors the forward takes, which count from its start. 

348 forward: Runs the forward and returns its output. 

349 backward: Runs the backward from that output. 

350 grad_inputs: The tensors the backward takes, which count from its 

351 start. 

352 checkpointed: Whether the forward runs under activation 

353 checkpointing, whose own hooks hold what it keeps. 

354 shared: Tensors the model shares between its layers, which a 

355 checkpointed forward's count leaves out. 

356 ops: Where given, tells each storage the forward saves apart by 

357 the op that first saves it, counting its bytes into 

358 ``ops.saved``, which then sums to the bytes returned. 

359 

360 Returns: 

361 The bytes the forward saves and still holds once it has run, its 

362 inputs included, and the bytes of activations live when the 

363 backward peaks, its output left out. A graph the forward drops 

364 before it ends, as a selection that keeps only the indices it picks 

365 drops its scores, is freed then in a run and is no backward's. A 

366 checkpointed forward keeps what is live once it has run, but for 

367 the *shared* tensors: its inputs and the outputs its policy saves. 

368 The parameters, which the forward's views of them bring into the 

369 tracker, are the memory model's to count, and so are their 

370 gradients, which hooks on the parameters tell apart from the 

371 activations' however they are shaped: the gradients the backward 

372 hands each parameter and the one it keeps. They settle when the 

373 backward peaks, and the bytes returned are the activations held 

374 then. 

375 """ 

376 stored = {p.untyped_storage()._cdata for p in params} # pylint: disable=protected-access 

377 # Counted by the storage in the lifetime it has now, as the tracker counts 

378 # them: a fake tensor's storage is cheap and short lived, so one the 

379 # forward has freed can hand its address to a later save, and counting by 

380 # address alone lost whichever of the two it saw first. Which pair 

381 # collided depended on what had run before, so a layer did not measure the 

382 # same twice. 

383 saved: Dict[Tuple[int, int], int] = {} 

384 saved_op: Dict[Tuple[int, int], str] = {} 

385 

386 def pack(tensor: torch.Tensor) -> torch.Tensor: 

387 """Count a tensor autograd saves, unless it is a parameter's, toward the op that first saves it.""" 

388 # Named before the storage is read, which dispatches ops of its own. 

389 op = ops.op(tensor) if ops is not None else None 

390 address = tensor.untyped_storage()._cdata # pylint: disable=protected-access 

391 if address not in stored: 

392 key = live.key(tensor) 

393 if op is not None: 

394 saved_op.setdefault(key, op) 

395 saved[key] = tensor.untyped_storage().nbytes() 

396 # Detached, so a graph holds the bytes it saves and not the tensor: an 

397 # op saving its own output would otherwise hold itself through that 

398 # output's grad_fn, a cycle no collector sees, which kept every graph 

399 # a forward drops alive into the backward. On the DeepSeek-V4.1 crop 

400 # at 4096 tokens that was the Indexer selection's scores, 8.9 GiB a 

401 # rank a run frees as soon as the indices are taken. 

402 return tensor.detach() 

403 

404 live = _LiveBytes() 

405 grads: List[Tuple[int, int]] = [] 

406 handles = [p.register_hook(lambda grad: grads.append(live.key(grad))) for p in params] 

407 try: 

408 with _checkpoints_on_cpu(), live, ops or contextlib.nullcontext(), \ 

409 torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor): 

410 for tensor in inputs: 

411 live.track(tensor) 

412 out = forward() 

413 start = len(live.events) 

414 left_out = {live.key(out), *(live.key(p) for p in params)} 

415 not_kept = left_out | {live.key(tensor) for tensor in shared} 

416 kept = sum(size for key, size in live.sizes.items() if key not in not_kept) 

417 held = {key: size for key, size in saved.items() if key in live.sizes} 

418 for tensor in grad_inputs: 

419 live.track(tensor) 

420 backward(out) 

421 finally: 

422 for handle in handles: 

423 handle.remove() 

424 # A storage's bytes count toward the op that first saved it, read from the 

425 # same record as the total, so the two agree whatever a fake tensor does 

426 # with a storage address it has freed. 

427 for address, size in held.items(): 

428 op = saved_op.get(address) 

429 if op is not None: 

430 ops.saved[op] = ops.saved.get(op, 0) + size 

431 grads += [live.key(p.grad) for p in params if p.grad is not None] 

432 return kept if checkpointed else sum(held.values()), live.peak(start, left_out, grads) 

433 

434 

435# The ops a matmul runs as. 

436_MATMULS = ("mm", "addmm", "bmm", "_grouped_mm", "baddbmm") 

437 

438 

439class _SavedOps(TorchDispatchMode): 

440 """What each tensor a layer's forward saves is saved for: the op of ND's op vector whose backward takes it. 

441 

442 The delta rule's saves are its own (``linrec``); the attention kernel's 

443 are its batched matmuls' (``attBMM``), its fp32 statistics the 

444 softmax's; a dropout's mask is its own; what a norm saves, the norm's 

445 (``normOp``), and what the feed-forward's activation function saves, 

446 the function's (``ffAct``). The rest counts toward the part of the 

447 layer saving it: the attention's projections (``attMM``), the 

448 feed-forward's (``ffMM``), or ``other`` for the layer's own code. 

449 """ 

450 

451 def __init__(self, layer: Any) -> None: 

452 """Follow which of *layer*'s modules runs, and when its delta rule does.""" 

453 super().__init__() 

454 self.saved: Dict[str, int] = {} 

455 self.running: List[str] = [] 

456 self.func: Any = None 

457 self.delta_rule = False 

458 self.modules = dict(layer.named_modules()) 

459 for name, module in self.modules.items(): 

460 if name: 

461 module.register_forward_pre_hook(functools.partial(self._enter, name)) 

462 module.register_forward_hook(self._leave) 

463 if hasattr(module, "chunk_gated_delta_rule"): 

464 module.chunk_gated_delta_rule = self._rule(module.chunk_gated_delta_rule) 

465 

466 def _rule(self, rule: Callable[..., Any]) -> Callable[..., Any]: 

467 """*rule*, noting that it runs.""" 

468 def run(*args: Any, **kwargs: Any) -> Any: 

469 """The delta rule, its saves told apart as its own while it runs.""" 

470 self.delta_rule = True 

471 try: 

472 return rule(*args, **kwargs) 

473 finally: 

474 self.delta_rule = False 

475 return run 

476 

477 def _enter(self, name: str, *_: Any) -> None: 

478 """Note that the module at *name* runs.""" 

479 self.running.append(name) 

480 

481 def _leave(self, *_: Any) -> None: 

482 """Note that the innermost module running has returned.""" 

483 self.running.pop() 

484 

485 def __torch_dispatch__(self, func, types, args=(), kwargs=None): # pylint: disable=unused-argument 

486 # A tensor's metadata is read through prims, and _measure detaches 

487 # each save, both between an op and its saves. 

488 if func.namespace != "prim" and func is not torch.ops.aten.detach.default: 

489 self.func = func 

490 return func(*args, **(kwargs or {})) 

491 

492 def op(self, tensor: torch.Tensor) -> str: 

493 """The op that saves *tensor*, which the forward saves now.""" 

494 if self.delta_rule: 

495 return "linrec" 

496 if self.func in _attention_ops(): 

497 return "softmax" if tensor.dtype == torch.float32 else "attBMM" 

498 if self.func is torch.ops.aten.native_dropout.default: 

499 return "dropout" 

500 if self.func is torch.ops.nd_census_npu.rms_norm.default: 

501 return "normOp" 

502 if self.func is torch.ops.nd_census_npu.swiglu.default: 

503 return "ffAct" 

504 name = self.running[-1] if self.running else "" 

505 module = self.modules.get(name) 

506 if name and "norm" in type(module).__name__.lower(): 

507 return "normOp" 

508 part = name.split(".", maxsplit=1)[0] 

509 if not part: 

510 return "other" 

511 attention = "attn" in part or "attention" in part 

512 if not attention and type(module).__module__ in ("transformers.activations", "torch.nn.modules.activation"): 

513 return "ffAct" 

514 return "attMM" if attention else "ffMM" 

515 

516 

517def _matmul_flops(func: Any, args: Sequence[Any]) -> int: 

518 """The FLOPs of *func* on *args* where it is a matmul, and 0 otherwise.""" 

519 matmuls = (torch.ops.aten.mm.default, torch.ops.aten.addmm.default, torch.ops.aten.bmm.default) 

520 grouped = getattr(torch.ops.aten, "_grouped_mm", None) # first shipped in torch 2.8 

521 if func not in (matmuls if grouped is None else (*matmuls, grouped.default)): 

522 return 0 

523 first, second = args[1:3] if func is torch.ops.aten.addmm.default else args[:2] 

524 return 2 * first.numel() * second.shape[-1] 

525 

526 

527def _kernel_op(name: str) -> Any: 

528 """The census kernel *name*, ``namespace::kernel``, as an op.""" 

529 namespace, kernel = name.split("::") 

530 return getattr(getattr(torch.ops, namespace), kernel).default 

531 

532 

533@functools.lru_cache(maxsize=None) 

534def _attention_ops() -> FrozenSet[Any]: 

535 """The census's attention kernels, as ops.""" 

536 return frozenset(_kernel_op(name) for name in _ATTENTION_KERNELS) 

537 

538 

539def _import(path: str, where: str) -> Any: 

540 """The object a dotted *path* names. 

541 

542 Raises: 

543 ValueError: If the path names no module or no attribute of one. 

544 """ 

545 module, _, name = str(path).rpartition(".") 

546 try: 

547 return getattr(importlib.import_module(module), name) 

548 except (ImportError, AttributeError, ValueError) as exc: 

549 raise ValueError(f"{where}: cannot import {path!r}: {exc}") from exc 

550 

551 

552def replacement_specs(plan_overrides: Any) -> Tuple[Any, ...]: 

553 """The module replacements a train.yaml's ``plan_overrides`` install, as replacement rules. 

554 

555 Args: 

556 plan_overrides: The ``plan_overrides`` list, as plain mappings. 

557 

558 Returns: 

559 One :class:`~hyper_parallel.models.replacement.ModuleReplacementSpec` 

560 per entry that states ``replace.kind: module``, in the order stated; the 

561 entries that state a sharding action alone, or a replacement 

562 conditioned on a run the census does not price (``when``), are left 

563 out. 

564 

565 Raises: 

566 ValueError: If a replacement names a module or factory that cannot be 

567 imported, or uses a removed replacement field. 

568 """ 

569 from hyper_parallel.components.modules.family import resolve_module_family_target # pylint: disable=C0415 

570 from hyper_parallel.models.replacement import ModuleReplacementSpec, module_replacement # pylint: disable=C0415 

571 

572 specs = [] 

573 for index, entry in enumerate(plan_overrides or ()): 

574 where = f"plan_overrides[{index}]" 

575 if not isinstance(entry, Mapping): 

576 continue 

577 removed = { 

578 "replace_module", "module_type", "exact_type", "local_compute_fn", 

579 "inner_wrapper", "inner_target", "inner_out_src", 

580 } 

581 if removed.intersection(entry): 

582 raise ValueError(f"{where}: old replacement fields are no longer supported") 

583 action = entry.get("replace") 

584 if not isinstance(action, Mapping) or action.get("kind") != "module" or entry.get("when") is not None: 

585 continue 

586 if "implementation" not in action: 

587 raise ValueError(f"{where}.replace requires implementation") 

588 match = entry.get("match") 

589 patterns = (match,) if isinstance(match, str) else tuple(match or ()) 

590 implementation = action["implementation"] 

591 target_path = implementation.get("_target_") if isinstance(implementation, Mapping) else implementation 

592 requested = _import(target_path, where) 

593 args = {key: value for key, value in implementation.items() if key != "_target_"} if isinstance( 

594 implementation, Mapping) else {} 

595 selected, args = resolve_module_family_target(requested, args) 

596 if args: 

597 @module_replacement 

598 def factory( 

599 *, module: torch.nn.Module, module_fqn: str, context: Mapping[str, Any], 

600 _selected: Any = selected, _args: tuple[tuple[str, Any], ...] = tuple(args.items()), 

601 ) -> torch.nn.Module: 

602 """Construct the selected family variant with ordinary YAML arguments.""" 

603 return _selected(module=module, module_fqn=module_fqn, context=context, **dict(_args)) 

604 factory.__name__ = selected.__name__ 

605 factory.__qualname__ = selected.__qualname__ 

606 factory.__module__ = selected.__module__ 

607 setattr(factory, "_hp_config", repr(sorted(args.items()))) 

608 else: 

609 factory = selected 

610 source_type = action.get("source_type") 

611 specs.append(ModuleReplacementSpec( 

612 match=patterns, 

613 factory=factory, 

614 module_type=_import(source_type, where) if source_type is not None else None, 

615 exact_type=bool(action.get("exact_type", False)), 

616 )) 

617 return tuple(specs) 

618 

619 

620class _Holder(torch.nn.Module): 

621 """A module tree holding one part where a model holds it, so a rule's patterns match its path.""" 

622 

623 def __init__(self, **parts: Any) -> None: 

624 """Hold each part of *parts* under ``model``, a layer in a list as a model's stack holds it.""" 

625 super().__init__() 

626 self.model = torch.nn.Module() 

627 for name, part in parts.items(): 

628 setattr(self.model, name, torch.nn.ModuleList([part]) if name == "layers" else part) 

629 

630 

631def _matching(spec: Any, names: Sequence[str]) -> Any: 

632 """*spec* with the patterns that match a module of *names*, or ``None`` where none does.""" 

633 import fnmatch # pylint: disable=C0415 

634 

635 import dataclasses # pylint: disable=C0415 

636 

637 kept = tuple(pattern for pattern in spec.match 

638 if any(fnmatch.fnmatchcase(name, pattern) for name in names)) 

639 return None if not kept else dataclasses.replace(spec, match=kept) 

640 

641 

642def _replaced(holder: _Holder, specs: Sequence[Any]) -> None: 

643 """Install on *holder* the replacements of *specs* whose patterns match one of its modules. 

644 

645 A rule's other patterns name modules no fake part holds, such as a 

646 model's final norm beside a layer, and are left out rather than refused. 

647 

648 Raises: 

649 CensusUnavailable: If a factory needs a library this host lacks, such 

650 as an attention built on a native extension. Transformers' own 

651 modules are not what the run trains, and measuring them would 

652 attribute their saved tensors to a fused layer nobody ran. 

653 """ 

654 from hyper_parallel.models.replacement import ( # pylint: disable=C0415 

655 apply_module_replacements, 

656 compile_module_replacements, 

657 ) 

658 

659 names = [name for name, _ in holder.named_modules()] 

660 kept = [found for found in (_matching(spec, names) for spec in specs) if found is not None] 

661 if not kept: 

662 return 

663 try: 

664 apply_module_replacements(holder, compile_module_replacements(holder, kept), 

665 weights_mapping=[], context={}, capture_checkpoint_metadata=False) 

666 except (ImportError, OSError) as exc: 

667 raise CensusUnavailable( 

668 f"this host cannot build the modules the run installs " 

669 f"({[spec.factory.__name__ for spec in kept]}: {exc}); " 

670 f"run the cost model where they build, or drop context.census and let the formulas price them" 

671 ) from exc 

672 

673 

674# Model families whose attention a census cannot price here, by model type, 

675# with what is missing. Their layers build and run on this host, through 

676# Transformers' own eager path, and that path is not the one the run takes: 

677# measuring it prices a layer nobody runs, as a replacement this host cannot 

678# build does (:func:`_replaced`, F53). A family belongs here only while no 

679# contract in :mod:`~hyper_parallel.auto_parallel._npu_contracts` states what 

680# its kernels save; stating one is what takes it out again. 

681_NO_ACTIVATION_CONTRACT: Dict[str, str] = { 

682 # Empty while every family with kernels of its own has its contracts 

683 # stated. DeepSeek-V4 was the entry that forced this guard and now has 

684 # them (:data:`_FAMILY_CONTRACTS`); the next family to arrive with a 

685 # kernel and no contract belongs here rather than being priced from the 

686 # path its run does not take. 

687} 

688 

689# The families whose own modules call kernels this host has not got, with the 

690# contracts their census runs under. A family here is measured as its run 

691# behaves; a family in :data:`_NO_ACTIVATION_CONTRACT` is refused instead. 

692_FAMILY_CONTRACTS = ("deepseek_v4",) 

693 

694# The families whose layers a census cannot run one at a time, by model type, 

695# with why. Their census runs the model's own forward over the whole stack 

696# (:func:`census_stack`), which calls each layer as the model calls it. 

697_STACK_FAMILIES: Dict[str, str] = { 

698 "deepseek_v4": ( 

699 "31 of the DeepSeek-V4.1 crop's 40 layers consume compressed keys and values, or an Indexer " 

700 "key, that a source layer wrote earlier in the same forward and refuse to run without it; the " 

701 "hidden state carries a hyper-connection dimension beside a mixing state; and the rotary " 

702 "embedding is a pair of flavours the model picks between" 

703 ), 

704} 

705 

706 

707@contextlib.contextmanager 

708def _family_contracts(config: Any) -> Iterator[None]: 

709 """The contracts the modules of *config*'s family run under, for what runs inside. 

710 

711 DeepSeek-V4.1's sparse attention is chosen on the device the tensors are 

712 on, so a census, whose tensors are fake and on none, would take the 

713 reference beside the kernel and measure a layer no run builds: the 

714 attention's contract stands in. The Indexer's selection keeps nothing a 

715 backward reads on either path, fused or reference, since a run frees its 

716 scores' graph as soon as the indices are taken; its contract runs 

717 the selection without recording that graph, and the census measures the 

718 same bytes with it as without. 

719 

720 Whether this tree builds the model at all is the stack census's to 

721 refuse (:func:`_model_class`): a layer's parameters do not depend on 

722 which kernel runs it and are counted from the same fake layer. 

723 """ 

724 if str(getattr(config, "model_type", "")) not in _FAMILY_CONTRACTS: 

725 yield 

726 return 

727 from hyper_parallel.auto_parallel._npu_contracts import ( # pylint: disable=C0415 

728 v41_attention_contract, 

729 v41_indexer_contract, 

730 ) 

731 rope = int(getattr(config, "qk_rope_head_dim", 0) or 0) 

732 with v41_attention_contract(rope), v41_indexer_contract(): 

733 yield 

734 

735 

736def _no_contract(config: Any) -> None: 

737 """Refuse a census of one layer of a model whose kernels no contract states, or whose layers cannot run alone. 

738 

739 Raises: 

740 CensusUnavailable: If *config*'s family is one of 

741 :data:`_NO_ACTIVATION_CONTRACT`, or one of 

742 :data:`_STACK_FAMILIES`, whose census is the whole stack's 

743 (:func:`census_stack`). A layer's parameters do not depend on 

744 which kernel runs it and are counted as ever 

745 (:func:`census_parameters`); what it keeps for its backward 

746 does, so this refuses rather than answer with the bytes of a 

747 layer the run does not build. 

748 """ 

749 family = str(getattr(config, "model_type", "")) 

750 missing = _NO_ACTIVATION_CONTRACT.get(family) 

751 if missing is not None: 

752 raise CensusUnavailable( 

753 f"no census of a {config.model_type} layer: {missing}; state the kernels' contracts, " 

754 f"or drop context.census and read the formulas' memory as an estimate, not as a bound" 

755 ) 

756 alone = _STACK_FAMILIES.get(family) 

757 if alone is not None: 

758 raise CensusUnavailable( 

759 f"no census of one {family} layer, whose layers cannot be priced one at a time: {alone}. " 

760 f"census_activations measures the whole stack instead (census_stack)" 

761 ) 

762 

763 

764def _modeling(config: Any) -> Any: 

765 """The Transformers modeling module of *config*'s model.""" 

766 model_type = str(config.model_type) 

767 names = [model_type] 

768 if model_type.endswith("_text"): 

769 names.append(model_type[:-len("_text")]) 

770 for name in names: 

771 try: 

772 return importlib.import_module(f"transformers.models.{name}.modeling_{name}") 

773 except ImportError: 

774 continue 

775 raise ValueError(f"no Transformers modeling module for model type {model_type!r}") 

776 

777 

778def _classes(modeling: Any) -> Tuple[type, type]: 

779 """The decoder layer and the language model's rotary embedding of *modeling*.""" 

780 classes = {name: cls for name, cls in vars(modeling).items() if isinstance(cls, type)} 

781 layers = [cls for name, cls in classes.items() if name.endswith("DecoderLayer")] 

782 rotary = [cls for name, cls in classes.items() 

783 if name.endswith("RotaryEmbedding") and "Vision" not in name] 

784 rotary.sort(key=lambda cls: "Text" not in cls.__name__) 

785 if not layers or not rotary: 

786 raise ValueError(f"{modeling.__name__} states no decoder layer or rotary embedding") 

787 return layers[0], rotary[0] 

788 

789 

790def tp_config(config: Any, tp: int) -> Any: 

791 """*config* as one of *tp* tensor-parallel ranks holds its layers: heads and widths divided. 

792 

793 Two of the fields divided can be one field. A Transformers config class 

794 may declare an ``attribute_map``, and DeepSeek-V4's maps 

795 ``intermediate_size`` onto ``moe_intermediate_size``, so a model whose 

796 feed-forward is all experts states one width under two names. Dividing 

797 each name in turn then divides that width by *tp* twice, and the layer 

798 built as a rank's share is a quarter as wide at TP 2 rather than half, 

799 which makes the split the census derives from the pair too large and ND 

800 over-reward tensor parallelism. Qwen3-MoE keeps the two apart, which is 

801 why this stayed hidden. Each underlying attribute is divided once. 

802 """ 

803 config = copy.deepcopy(config) 

804 config.head_dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads 

805 aliases = getattr(type(config), "attribute_map", None) or {} 

806 divided = set() 

807 for name in _TP_FIELDS: 

808 target = aliases.get(name, name) 

809 if target in divided: 

810 continue 

811 value = getattr(config, name, None) 

812 if isinstance(value, int) and not isinstance(value, bool) and value > 0: 

813 setattr(config, name, max(1, value // tp)) 

814 divided.add(target) 

815 return config 

816 

817 

818def _grid_rotary(rotary: Any) -> bool: 

819 """Whether *rotary* embeds a position on three grids, time, height and width, as a multimodal model's does. 

820 

821 Qwen3.5's and Qwen3-VL's hold the grids' ``mrope_section``; Qwen2-VL's 

822 config states it. 

823 """ 

824 if getattr(rotary, "mrope_section", None) is not None: 

825 return True 

826 config = getattr(rotary, "config", None) 

827 return any(isinstance(getattr(config, name, None), Mapping) and "mrope_section" in getattr(config, name) 

828 for name in ("rope_parameters", "rope_scaling")) 

829 

830 

831def _positions(rotary: Any, hidden: torch.Tensor, seq_length: int) -> Tuple[torch.Tensor, Any]: 

832 """The position ids of a sequence of *seq_length* tokens, and the embeddings *rotary* gives them. 

833 

834 A rotary on three grids (:func:`_grid_rotary`) is handed a row of ids 

835 for each grid, as its model hands them, a text token's index on all 

836 three; the layers keep the one row. Transformers 5.17 and 5.18 refuse 

837 the single row the versions before them expanded themselves. 

838 """ 

839 position_ids = torch.arange(seq_length).unsqueeze(0) 

840 rotary_ids = position_ids[None].expand(3, *position_ids.shape) if _grid_rotary(rotary) else position_ids 

841 with torch.no_grad(): 

842 return position_ids, rotary(hidden, rotary_ids) 

843 

844 

845def _run(layer: Any, hidden: torch.Tensor, positions: Tuple[torch.Tensor, Any], 

846 call: Optional[Callable[..., Any]] = None) -> torch.Tensor: 

847 """One forward of *layer*, as its model calls it at *positions*, through *call* if given.""" 

848 position_ids, position_embeddings = positions 

849 accepted = inspect.signature(layer.forward).parameters 

850 kwargs = {name: value for name, value in ( 

851 ("position_embeddings", position_embeddings), ("position_ids", position_ids), 

852 ("attention_mask", None), ("use_cache", False)) if name in accepted} 

853 out = (call or layer)(hidden, **kwargs) 

854 return out[0] if isinstance(out, tuple) else out 

855 

856 

857# The function a gated-delta-rule attention of Transformers 5.15 and later 

858# calls by name, which its modeling module defines; earlier versions hold the 

859# rule in the module's ``chunk_gated_delta_rule``. 

860_DELTA_RULE_FUNCTION = "torch_chunk_gated_delta_rule" 

861 

862 

863def delta_rule_module(module: Any) -> bool: 

864 """Whether *module* runs a gated delta rule, whichever way its Transformers version calls it. 

865 

866 Up to 5.14 the module holds the rule in ``chunk_gated_delta_rule``; from 

867 5.15 its forward calls its modeling module's ``torch_chunk_gated_delta_rule`` 

868 by name, and the module holds nothing. 

869 """ 

870 if hasattr(module, "chunk_gated_delta_rule"): 

871 return True 

872 forward = inspect.unwrap(getattr(type(module), "forward", None) or (lambda: None)) 

873 return _DELTA_RULE_FUNCTION in getattr(getattr(forward, "__code__", None), "co_names", ()) 

874 

875 

876@contextlib.contextmanager 

877def _delta_rule_held(modeling: Any, layer: Any, rule: Callable[..., Any]) -> Iterator[None]: 

878 """Have *layer*'s delta rule module run *rule* through its ``chunk_gated_delta_rule``, while the context lasts. 

879 

880 The census swaps and follows the rule through that attribute. A module 

881 of Transformers 5.15 or later, which calls its modeling module's function 

882 by name, gets the attribute too, and the name runs it. 

883 

884 Raises: 

885 ValueError: If the layer holds more than one such module, which the 

886 name could not tell apart. 

887 """ 

888 modules = [module for module in layer.modules() if delta_rule_module(module)] 

889 for module in modules: 

890 module.chunk_gated_delta_rule = rule 

891 by_name = getattr(modeling, _DELTA_RULE_FUNCTION, None) 

892 if not modules or by_name is None: 

893 yield 

894 return 

895 if len(modules) > 1: 

896 raise ValueError(f"{type(layer).__name__} holds {len(modules)} gated delta rule modules, and " 

897 f"{_DELTA_RULE_FUNCTION} cannot tell which one calls it") 

898 module = modules[0] 

899 

900 def by_attribute(*args: Any, **kwargs: Any) -> Any: 

901 """The module's rule as the attribute holds it when called: the census wraps it afterwards.""" 

902 return module.chunk_gated_delta_rule(*args, **kwargs) 

903 

904 setattr(modeling, _DELTA_RULE_FUNCTION, by_attribute) 

905 try: 

906 yield 

907 finally: 

908 setattr(modeling, _DELTA_RULE_FUNCTION, by_name) 

909 

910 

911@contextlib.contextmanager 

912def _fake_layer(config: Any, layer_index: int, gdn_backend: str = _EAGER_GDN, 

913 replacements: Sequence[Any] = ()) -> Iterator[Tuple[Any, Any]]: 

914 """Layer *layer_index* of *config* and its model's rotary embedding, on fake tensors and the runtime's kernels. 

915 

916 *gdn_backend* names the gated delta rule the layer runs, as the runtime 

917 names it: ``"eager"`` for Transformers' own chunked implementation, 

918 ``"triton"`` for HyperParallel's kernel's contract, which saves the rule's 

919 inputs, the cumulated gates, beta and one chunk matrix and nothing more. 

920 Eager is the default because it is the rule a run reaches: the runtime's 

921 dispatcher defaults to it (``components/modules/gated_delta_net.py``, 

922 ``chunk_gated_delta_rule``), the only caller that can select the kernel is 

923 the context-parallel wrapper, which defaults to eager as well, and no 

924 recipe states a backend. The two are not interchangeable: a layer keeping 

925 the kernel's saved set keeps less than half as much. 

926 

927 Where *replacements* are given, the modules they name are HyperParallel's 

928 fused ones, running under the kernels' contracts for as long as the layer 

929 does. Eager is Transformers' own Python rule, never a kernel a hub or the 

930 ``fla`` package would put in its place. 

931 

932 Raises: 

933 ValueError: If *gdn_backend* names no backend the runtime has. 

934 """ 

935 if gdn_backend not in _GDN_BACKENDS: 

936 raise ValueError( 

937 f"unsupported GDN backend {gdn_backend!r}; " 

938 f"expected one of {sorted(_GDN_BACKENDS)}." 

939 ) 

940 modeling = _modeling(config) 

941 layer_cls, rotary_cls = _classes(modeling) 

942 config = copy.deepcopy(config) 

943 config._attn_implementation = _FLASH # pylint: disable=protected-access 

944 config._experts_implementation = "grouped_mm" # pylint: disable=protected-access 

945 modeling.ALL_ATTENTION_FUNCTIONS.register(_FLASH, _flash_attention) 

946 with npu_contracts() if replacements else contextlib.nullcontext(), \ 

947 _family_contracts(config), \ 

948 FakeTensorMode(allow_non_fake_inputs=True): 

949 default = torch.get_default_dtype() 

950 torch.set_default_dtype(torch.bfloat16) 

951 try: 

952 layer = layer_cls(config, layer_index) 

953 rotary = rotary_cls(config=config) 

954 finally: 

955 torch.set_default_dtype(default) 

956 rule = (_gated_delta_rule(modeling) if gdn_backend == _HYPER_GDN 

957 else inspect.unwrap(getattr(modeling, _DELTA_RULE_FUNCTION, None) or (lambda: None))) 

958 with _delta_rule_held(modeling, layer, rule): 

959 if replacements: 

960 holder = _Holder(layers=layer) 

961 _replaced(holder, replacements) 

962 layer = holder.model.layers[0] 

963 layer.train() 

964 yield layer, rotary 

965 

966 

967class _ByPart(TorchDispatchMode): 

968 """A walk over a layer's forward that attributes each op to the part of the layer running it.""" 

969 

970 def __init__(self, layer: Any, recurrent: bool = True) -> None: 

971 """Follow which of *layer*'s modules runs, and which tensors are its parameters. 

972 

973 *recurrent* is whether an attention of this layer has a recurrence to 

974 name: where it has none, an op of the attention that no weight takes 

975 part in is the attention's own, its mask or its rotary. A walk that 

976 counts only matmuls leaves it at the default, because a weightless 

977 matmul under an attention is a recurrence or a score, and a score is 

978 counted on its own. 

979 """ 

980 super().__init__() 

981 self.recurrent = recurrent 

982 self.params = {param.untyped_storage()._cdata # pylint: disable=protected-access 

983 for param in layer.parameters()} 

984 self.running: List[str] = [] 

985 for name, module in layer.named_modules(): 

986 if name: 

987 module.register_forward_pre_hook(functools.partial(self._enter, name)) 

988 module.register_forward_hook(self._leave) 

989 

990 def _enter(self, name: str, *_: Any) -> None: 

991 """Note that the module at *name* runs.""" 

992 self.running.append(name) 

993 

994 def _leave(self, *_: Any) -> None: 

995 """Note that the innermost module running has returned.""" 

996 self.running.pop() 

997 

998 def _part(self, args: Sequence[Any]) -> str: 

999 """The part an op on *args* runs for: its module's, or an attention's recurrence where no weight takes part.""" 

1000 part = _parameter_part(f"{self.running[-1]}.weight") if self.running else "ffn" 

1001 weighted = any(isinstance(arg, torch.Tensor) 

1002 and arg.untyped_storage()._cdata in self.params # pylint: disable=protected-access 

1003 for arg in args) 

1004 if part == "attention" and not weighted and self.recurrent: 

1005 return "linrec" 

1006 return part 

1007 

1008 

1009class _PartFlops(_ByPart): 

1010 """A layer's forward FLOPs by part: its matmuls' toward the part running them, flash attention's the scores'.""" 

1011 

1012 def __init__(self, layer: Any) -> None: 

1013 """Count no FLOPs yet, and follow *layer*'s modules.""" 

1014 super().__init__(layer) 

1015 self.flops: Dict[str, int] = {} 

1016 

1017 def _add(self, part: str, flops: int) -> None: 

1018 """Count *flops* toward *part*.""" 

1019 self.flops[part] = self.flops.get(part, 0) + flops 

1020 

1021 def __torch_dispatch__(self, func, types, args=(), kwargs=None): # pylint: disable=unused-argument 

1022 out = func(*args, **(kwargs or {})) 

1023 if func is torch.ops.nd_census.flash_attention.default: 

1024 query, key, value = args[:3] 

1025 batch, heads, seq, width = query.shape 

1026 self._add("scores", 2 * batch * heads * seq * key.shape[2] * (width + value.shape[-1])) 

1027 elif flops := _matmul_flops(func, args): 

1028 self._add(self._part(args), flops) 

1029 return out 

1030 

1031 

1032class _PartTraffic(_ByPart): 

1033 """The bytes a layer's forward moves by part, the parameters among them, and the ops it dispatches. 

1034 

1035 An op reads the tensors it is given and writes the tensors it returns. 

1036 A view writes nothing and reads nothing: it renames bytes its producer 

1037 already wrote, and no kernel runs for it, so it counts for neither. A 

1038 tensor given to an op twice is read twice, as the count is of the op's 

1039 arguments rather than of the storages behind them. 

1040 

1041 The parameters are counted again on their own, because a strategy 

1042 divides their traffic where it leaves the activations' alone: the degree 

1043 sharding a parameter divides the bytes read of it, and the routed 

1044 experts' part is the one the expert-parallel degree divides. 

1045 """ 

1046 

1047 def __init__(self, layer: Any, recurrent: bool = True) -> None: 

1048 """Move nothing yet, and follow *layer*'s modules.""" 

1049 super().__init__(layer, recurrent=recurrent) 

1050 self.moved: Dict[str, float] = {} 

1051 self.parameter: Dict[str, float] = {} 

1052 self.launches: Dict[str, int] = {} 

1053 

1054 def __torch_dispatch__(self, func, types, args=(), kwargs=None): # pylint: disable=unused-argument 

1055 kwargs = kwargs or {} 

1056 out = func(*args, **kwargs) 

1057 if func.namespace == "prim" or getattr(func, "is_view", False): 

1058 return out 

1059 part = ("scores" if func is torch.ops.nd_census.flash_attention.default 

1060 else self._part(args)) 

1061 moved = parameter = 0 

1062 for tensor in tree_flatten((args, kwargs))[0]: 

1063 if not isinstance(tensor, torch.Tensor): 

1064 continue 

1065 size = tensor.numel() * tensor.element_size() 

1066 moved += size 

1067 if tensor.untyped_storage()._cdata in self.params: # pylint: disable=protected-access 

1068 parameter += size 

1069 for tensor in tree_flatten(out)[0]: 

1070 if isinstance(tensor, torch.Tensor): 

1071 moved += tensor.numel() * tensor.element_size() 

1072 self.moved[part] = self.moved.get(part, 0.0) + moved 

1073 self.parameter[part] = self.parameter.get(part, 0.0) + parameter 

1074 self.launches[part] = self.launches.get(part, 0) + 1 

1075 return out 

1076 

1077 

1078def census_flops(config: Any, layer_index: int, seq_length: int) -> Dict[str, int]: 

1079 """The forward FLOPs of layer *layer_index* of *config* on one sequence, by part. 

1080 

1081 Args: 

1082 config: The language model's Transformers config. 

1083 layer_index: The layer to build, which settles its kind. 

1084 seq_length: Tokens of the sequence it runs. 

1085 

1086 Returns: 

1087 The FLOPs of each part that runs a matmul: the attention's 

1088 projections (``attention``), its scores and values at every pair of 

1089 tokens (``scores``), a linear attention's recurrence (``linrec``), 

1090 and the parts of the feed-forward :func:`_parameter_part` names. 

1091 """ 

1092 with _fake_layer(config, layer_index) as (layer, rotary): 

1093 hidden = torch.randn(1, seq_length, config.hidden_size, dtype=torch.bfloat16) 

1094 positions = _positions(rotary, hidden, seq_length) 

1095 counter = _PartFlops(layer) 

1096 with counter: 

1097 _run(layer, hidden, positions) 

1098 return counter.flops 

1099 

1100 

1101def census_traffic(config: Any, layer_index: int, seq_length: int, 

1102 gdn_backend: str = _EAGER_GDN) -> LayerTraffic: 

1103 """What one forward of layer *layer_index* of *config* moves, by the part of the layer moving it. 

1104 

1105 The quantity the time model counts is matmul FLOPs, and the cluster's 

1106 kernel tables put those at 6.3 to 7.1% of a profiled step of this model. 

1107 This counts the other quantity a step could be priced by, on the same 

1108 forward and with no device, so that a measured round can set each 

1109 beside the time it took. 

1110 

1111 Args: 

1112 config: The language model's Transformers config. 

1113 layer_index: The layer to build, which settles its kind. 

1114 seq_length: Tokens of the micro-batch of one sequence it runs. 

1115 gdn_backend: The gated delta rule the run takes (:func:`_fake_layer`). 

1116 It is the largest single choice here: Transformers' own chunked 

1117 rule runs a matmul a chunk and the kernel's contract is one op. 

1118 

1119 Returns: 

1120 A :class:`LayerTraffic` of the whole layer at tensor and context 

1121 parallelism 1, by the parts :func:`census_flops` prices 

1122 (:class:`_PartTraffic`). 

1123 """ 

1124 with _fake_layer(config, layer_index, gdn_backend=gdn_backend) as (layer, rotary): 

1125 hidden = torch.randn(1, seq_length, config.hidden_size, dtype=torch.bfloat16) 

1126 positions = _positions(rotary, hidden, seq_length) 

1127 # The rule's own module is what a layer has a recurrence by, as 

1128 # _fake_layer finds it to settle which rule the layer runs. 

1129 recurrent = any(delta_rule_module(module) for module in layer.modules()) 

1130 counter = _PartTraffic(layer, recurrent=recurrent) 

1131 with counter: 

1132 _run(layer, hidden, positions) 

1133 return LayerTraffic(counter.moved, counter.parameter, counter.launches) 

1134 

1135 

1136def census_layer(config: Any, layer_index: int, seq_length: int, selective: bool = False, 

1137 ops: Optional[Dict[str, int]] = None, 

1138 replacements: Sequence[Any] = (), 

1139 gdn_backend: str = _EAGER_GDN) -> Tuple[int, int]: 

1140 """Bytes layer *layer_index* of *config* keeps for its backward, and the most its backward holds. 

1141 

1142 Args: 

1143 config: The language model's Transformers config. 

1144 layer_index: The layer to build, which settles its kind. 

1145 seq_length: Tokens of the micro-batch of one sequence it runs. 

1146 selective: Retired operator-level selective flag. True is refused: 

1147 the trainer now selects module regions this census does not model. 

1148 ops: Where given, and the layer runs without checkpointing, takes 

1149 the bytes it saves by the op saving them (:class:`_SavedOps`). 

1150 replacements: The module replacements a run installs 

1151 (:func:`replacement_specs`). 

1152 gdn_backend: The gated delta rule the run takes (:func:`_fake_layer`). 

1153 

1154 Returns: 

1155 The bytes the forward keeps for the backward, its input included, 

1156 and the bytes of activations the backward holds when it holds the 

1157 most, its own gradients included, less the parameters and those 

1158 gradients. 

1159 

1160 Raises: 

1161 CensusUnavailable: If no contract states what this model's kernels 

1162 save (:func:`_no_contract`), or selective is requested. 

1163 """ 

1164 if selective: 

1165 raise CensusUnavailable(_SELECTIVE_CENSUS_UNAVAILABLE) 

1166 _no_contract(config) 

1167 with _fake_layer(config, layer_index, gdn_backend=gdn_backend, 

1168 replacements=replacements) as (layer, rotary): 

1169 hidden = torch.randn(1, seq_length, config.hidden_size, dtype=torch.bfloat16, requires_grad=True) 

1170 grad = torch.randn(1, seq_length, config.hidden_size, dtype=torch.bfloat16) 

1171 if replacements: 

1172 # A fused kernel keeps a constant per device, such as the mask 

1173 # the attention runs its causal sparse mode with, which the 

1174 # runtime allocates once for every layer and micro-batch: one 

1175 # forward allocates them before the layer's own bytes are 

1176 # counted, so they count toward no layer. 

1177 with torch.no_grad(): 

1178 _run(layer, hidden, _positions(rotary, hidden, seq_length)) 

1179 saved_ops = None if ops is None else _SavedOps(layer) 

1180 measured = _measure(list(layer.parameters()), (hidden,), 

1181 lambda: _run(layer, hidden, _positions(rotary, hidden, seq_length)), 

1182 lambda out: out.backward(grad), grad_inputs=(grad,), ops=saved_ops) 

1183 if saved_ops is not None: 

1184 ops.update(saved_ops.saved) 

1185 return measured 

1186 

1187 

1188def census_saved_ops(config: Any, layer_index: int, seq_length: int, 

1189 replacements: Sequence[Any] = ()) -> Dict[str, float]: 

1190 """What layer *layer_index* of *config* keeps for its backward for each op, per token, the whole layer. 

1191 

1192 Args: 

1193 config: The language model's Transformers config. 

1194 layer_index: The layer to build, which settles its kind. 

1195 seq_length: Tokens of the micro-batch of one sequence it runs. 

1196 replacements: The module replacements a run installs 

1197 (:func:`replacement_specs`). 

1198 

1199 Returns: 

1200 ``{op: bytes per token}``, by the op saving them 

1201 (:class:`_SavedOps`), which sum to what the layer keeps. 

1202 """ 

1203 ops: Dict[str, int] = {} 

1204 census_layer(config, layer_index, seq_length, ops=ops, replacements=replacements) 

1205 return {op: size / seq_length for op, size in ops.items()} 

1206 

1207 

1208def census_recomputed(config: Any, layer_index: int, seq_length: int) -> Tuple[float, float]: 

1209 """Refuse the retired operator-policy census of recomputed matmul FLOPs. 

1210 

1211 Args: 

1212 config: The language model's Transformers config. 

1213 layer_index: The layer to build, which settles its kind. 

1214 seq_length: Tokens of the micro-batch of one sequence it runs. 

1215 

1216 Raises: 

1217 CensusUnavailable: The trainer's module-region plan is not an 

1218 operator policy and cannot be inferred from these arguments. 

1219 """ 

1220 raise CensusUnavailable(_SELECTIVE_CENSUS_UNAVAILABLE) 

1221 

1222 

1223def _parameter_part(name: str) -> str: 

1224 """The part of a decoder layer the parameter at path *name* belongs to, as ND prices the parts. 

1225 

1226 The layer's norms and its attention's per-head query and key norms are 

1227 its norms; the rest of a child named for attention is its attention. 

1228 Of the feed-forward, a shared expert's parameters, the routed experts' 

1229 and the router's are parts of their own, and the rest is the dense 

1230 feed-forward's. 

1231 """ 

1232 segments = name.split(".") 

1233 module = segments[-2] if len(segments) > 1 else "" 

1234 if "norm" in segments[0] or module in _QK_NORMS: 

1235 return "norm" 

1236 if "attn" in segments[0] or "attention" in segments[0]: 

1237 return "attention" 

1238 if any("shared" in segment for segment in segments): 

1239 return "shared" 

1240 if "experts" in segments: 

1241 return "routed" 

1242 if module in ("gate", "router"): 

1243 return "router" 

1244 return "ffn" 

1245 

1246 

1247def census_parameters(config: Any, layer_index: int, replacements: Sequence[Any] = ()) -> Dict[str, int]: 

1248 """The parameters of layer *layer_index* of *config*, by part. 

1249 

1250 Args: 

1251 config: The language model's Transformers config. 

1252 layer_index: The layer to build, which settles its kind. 

1253 replacements: The module replacements a run installs 

1254 (:func:`replacement_specs`). A replacement holds the 

1255 parameters its source held, fused or renamed, so it counts the 

1256 same. 

1257 

1258 Returns: 

1259 The parameter count of each part the layer has 

1260 (:func:`_parameter_part`). 

1261 """ 

1262 parts: Dict[str, int] = {} 

1263 with _fake_layer(config, layer_index, replacements=replacements) as (layer, _): 

1264 for name, param in layer.named_parameters(): 

1265 part = _parameter_part(name) 

1266 parts[part] = parts.get(part, 0) + param.numel() 

1267 return parts 

1268 

1269 

1270def census_final_norm(config: Any, replacements: Sequence[Any] = ()) -> int: 

1271 """The parameters of *config*'s final norm, of the class of a layer's input norm.""" 

1272 with _fake_layer(config, 0, replacements=replacements) as (layer, _): 

1273 return sum(param.numel() for param in layer.input_layernorm.parameters()) 

1274 

1275 

1276def census_output(config: Any, seq_length: int, replacements: Sequence[Any] = ()) -> Tuple[int, int]: 

1277 """Bytes the output layer of *config* keeps for its backward, and the most its backward holds. 

1278 

1279 Args: 

1280 config: The language model's Transformers config. 

1281 seq_length: Tokens of the micro-batch of one sequence it runs. 

1282 replacements: The module replacements a run installs 

1283 (:func:`replacement_specs`), of which the final norm's is the 

1284 one that reaches the output layer. 

1285 

1286 Returns: 

1287 As :func:`census_layer`: the final norm's input included, the 

1288 output table and its gradient left out. 

1289 """ 

1290 modeling = _modeling(config) 

1291 layer_cls, _ = _classes(modeling) 

1292 loss_function = importlib.import_module("transformers.loss.loss_utils").ForCausalLMLoss 

1293 with npu_contracts() if replacements else contextlib.nullcontext(), \ 

1294 FakeTensorMode(allow_non_fake_inputs=True): 

1295 default = torch.get_default_dtype() 

1296 torch.set_default_dtype(torch.bfloat16) 

1297 try: 

1298 # The final norm is of the class of a layer's input norm. 

1299 norm = layer_cls(config, 0).input_layernorm 

1300 head = torch.nn.Linear(config.hidden_size, config.vocab_size, bias=False) 

1301 finally: 

1302 torch.set_default_dtype(default) 

1303 if replacements: 

1304 holder = _Holder(norm=norm) 

1305 _replaced(holder, replacements) 

1306 norm = holder.model.norm 

1307 hidden = torch.randn(1, seq_length, config.hidden_size, dtype=torch.bfloat16, requires_grad=True) 

1308 labels = torch.randint(0, config.vocab_size, (1, seq_length)) 

1309 # The loss alone holds the logits: the trainer drops the model's 

1310 # output before the backward. 

1311 return _measure([*norm.parameters(), *head.parameters()], (hidden,), 

1312 lambda: loss_function(head(norm(hidden)), labels, config.vocab_size), 

1313 lambda loss: loss.backward()) 

1314 

1315 

1316def census_output_activations(config: Any, seq_length: int = 4096, 

1317 replacements: Sequence[Any] = ()) -> KindActivations: 

1318 """What the output layer of *config* keeps and holds, per token, with its vocabulary and half of it. 

1319 

1320 Args: 

1321 config: The language model's Transformers config. 

1322 seq_length: The tokens the census runs the layer at. 

1323 replacements: The module replacements a run installs 

1324 (:func:`replacement_specs`). 

1325 

1326 Returns: 

1327 The layer's :class:`KindActivations`, whose TP part is the part a 

1328 vocabulary-parallel loss over two ranks halves. 

1329 """ 

1330 half = copy.deepcopy(config) 

1331 half.vocab_size = max(1, config.vocab_size // 2) 

1332 (saved_1, working_1), (saved_2, working_2) = ( 

1333 census_output(each, seq_length, replacements) for each in (config, half)) 

1334 return KindActivations( 

1335 saved=max(0.0, 2 * saved_2 - saved_1) / seq_length, 

1336 saved_tp=max(0.0, 2 * (saved_1 - saved_2)) / seq_length, 

1337 working=max(0.0, 2 * working_2 - working_1) / seq_length, 

1338 working_tp=max(0.0, 2 * (working_1 - working_2)) / seq_length, 

1339 seq_length=int(seq_length), 

1340 ) 

1341 

1342 

1343class _FakeScalars(TorchDispatchMode): 

1344 """A scalar read of a fake tensor answered with zero, as :class:`_LiveBytes` answers it. 

1345 

1346 A model can read a value out of a tensor while it builds, as 

1347 DeepSeek-V4.1's Engram reads its token map's pad entry to build its hash 

1348 mapping, which a fake tensor refuses. The value settles a padding id, 

1349 never a shape the census counts. 

1350 """ 

1351 

1352 def __torch_dispatch__(self, func, types, args=(), kwargs=None): # pylint: disable=unused-argument 

1353 if func is _SCALAR_READ and isinstance(args[0], FakeTensor): 

1354 return 0 

1355 return func(*args, **(kwargs or {})) 

1356 

1357 

1358def _model_class(config: Any) -> Tuple[Any, bool]: 

1359 """What the trainer builds *config* as, by its ``from_config``: its family's own class, else Transformers'. 

1360 

1361 The trainer's builder discovers the family's registration, asks the 

1362 model registry for a class registered by the architecture the config 

1363 names, and builds Transformers' own model where none is. 

1364 

1365 Returns: 

1366 The class, and whether it is Transformers' own. 

1367 

1368 Raises: 

1369 CensusUnavailable: If the config names an architecture neither the 

1370 registry nor Transformers builds, as a DeepSeek-V4.1 config does 

1371 on a tree that does not carry that model: Transformers' 

1372 DeepSeek-V4 in its place would price a different model. 

1373 """ 

1374 import transformers # pylint: disable=C0415 

1375 from hyper_parallel.models._transformers.config_resolver import get_is_hf_model # pylint: disable=C0415 

1376 from hyper_parallel.models.registry import _resolve_custom_model_cls # pylint: disable=C0415 

1377 

1378 architecture = (getattr(config, "architectures", None) or [""])[0] or "" 

1379 if not get_is_hf_model(config): 

1380 return _resolve_custom_model_cls(architecture), False 

1381 if architecture and not hasattr(transformers, architecture): 

1382 raise CensusUnavailable( 

1383 f"the config names {architecture}, which neither this tree's model registry nor Transformers " 

1384 f"builds; price it from a tree carrying the model, or drop context.census and read the " 

1385 f"formulas' memory as an estimate, not as a bound" 

1386 ) 

1387 return transformers.AutoModelForCausalLM, True 

1388 

1389 

1390class _Stack: 

1391 """Which layer of a stack runs, forward and backward, and where in a tracker's log each backward runs.""" 

1392 

1393 def __init__(self, layers: Sequence[Any], clock: Callable[[], int]) -> None: 

1394 """Follow *layers* through both passes, placing their backwards by *clock*.""" 

1395 self.running: List[int] = [] 

1396 self.windows: Dict[int, List[int]] = {} 

1397 self.clock = clock 

1398 self.handles: List[Any] = [] 

1399 for index, layer in enumerate(layers): 

1400 self.handles += [ 

1401 layer.register_forward_pre_hook(functools.partial(self._enter, index)), 

1402 layer.register_forward_hook(self._leave), 

1403 layer.register_full_backward_pre_hook(functools.partial(self._enter_backward, index)), 

1404 layer.register_full_backward_hook(self._leave_backward), 

1405 ] 

1406 self.backward: List[int] = [] 

1407 

1408 # A hook's return replaces what the module takes or gives, so each of 

1409 # these returns None. 

1410 

1411 def _enter(self, index: int, *_: Any) -> None: 

1412 """Note that the layer at *index* runs its forward.""" 

1413 self.running.append(index) 

1414 

1415 def _leave(self, *_: Any) -> None: 

1416 """Note that the innermost layer running its forward has returned.""" 

1417 if self.running: 

1418 self.running.pop() 

1419 

1420 def _enter_backward(self, index: int, *_: Any) -> None: 

1421 """Open the window of the layer at *index*, whose backward starts.""" 

1422 self.backward.append(index) 

1423 self.windows.setdefault(index, [self.clock(), self.clock()]) 

1424 

1425 def _leave_backward(self, *_: Any) -> None: 

1426 """Close the window of the layer whose backward has returned.""" 

1427 if self.backward: 

1428 index = self.backward.pop() 

1429 self.windows[index][1] = self.clock() 

1430 

1431 @property 

1432 def layer(self) -> Optional[int]: 

1433 """The outermost layer running its forward, or None.""" 

1434 return self.running[0] if self.running else None 

1435 

1436 def remove(self) -> None: 

1437 """Remove every hook this placed.""" 

1438 for handle in self.handles: 

1439 handle.remove() 

1440 

1441 

1442def census_stack(config: Any, seq_length: int, replacements: Sequence[Any] = ()) -> List[Tuple[int, int]]: 

1443 """What each layer of *config* keeps for its backward, and the most its backward holds, from one pass of the stack. 

1444 

1445 For a model whose layers cannot run alone (:data:`_STACK_FAMILIES`): the 

1446 model the trainer builds (:func:`_model_class`), on fake tensors and 

1447 under its family's contracts, runs its own forward over a micro-batch of 

1448 one sequence and then its backward, so each layer is called as its model 

1449 calls it, with what earlier layers wrote, its hidden and mixing states 

1450 and the rotary flavours the model computes. Each save counts toward the 

1451 layer whose forward makes it first, and a layer keeps those of its saves 

1452 still live when the forward ends (:func:`_measure`'s rule). Its backward 

1453 holds what it keeps and the most it holds beyond every layer's saves, 

1454 the parameters and their gradients while it runs. The embedding's and 

1455 the final norm's saves count toward no layer: the output layer's census 

1456 prices the end of the model. 

1457 

1458 Args: 

1459 config: The language model's Transformers config. 

1460 seq_length: Tokens of the micro-batch of one sequence it runs. 

1461 replacements: The module replacements a run installs 

1462 (:func:`replacement_specs`). 

1463 

1464 Returns: 

1465 ``(kept, held)`` bytes of each decoder layer, in model order. 

1466 

1467 Raises: 

1468 CensusUnavailable: If this tree cannot build the model the config 

1469 names (:func:`_model_class`), or a module a replacement installs 

1470 (:func:`_replaced`). 

1471 """ 

1472 model_cls, native = _model_class(config) 

1473 config = copy.deepcopy(config) 

1474 if native: 

1475 # Transformers' own model runs its attention through the interface, 

1476 # as _fake_layer's layer does, so it runs the kernel's contract. 

1477 config._attn_implementation = _FLASH # pylint: disable=protected-access 

1478 _modeling(config).ALL_ATTENTION_FUNCTIONS.register(_FLASH, _flash_attention) 

1479 with npu_contracts() if replacements else contextlib.nullcontext(), _family_contracts(config), \ 

1480 FakeTensorMode(allow_non_fake_inputs=True), _FakeScalars(): 

1481 default = torch.get_default_dtype() 

1482 torch.set_default_dtype(torch.bfloat16) 

1483 try: 

1484 model = model_cls.from_config(config) 

1485 finally: 

1486 torch.set_default_dtype(default) 

1487 # The experts run as grouped matmuls, as every layer _fake_layer 

1488 # builds does. Transformers falls back to its eager experts for a 

1489 # class whose module it does not know, a loop over the experts with 

1490 # token counts no fake tensor has; the experts read this per call. 

1491 model.config._experts_implementation = "grouped_mm" # pylint: disable=protected-access 

1492 if replacements: 

1493 _replaced(model, replacements) 

1494 model.train() 

1495 backbone = model.get_decoder() 

1496 params = list(model.parameters()) 

1497 stored = {p.untyped_storage()._cdata for p in params} # pylint: disable=protected-access 

1498 live = _LiveBytes() 

1499 follow = _Stack(backbone.layers, lambda: len(live.events)) 

1500 saved_by: Dict[Tuple[int, int], int] = {} 

1501 

1502 def pack(tensor: torch.Tensor) -> torch.Tensor: 

1503 """Count a tensor autograd saves, unless it is a parameter's, toward the layer saving it first.""" 

1504 if tensor.untyped_storage()._cdata not in stored and follow.layer is not None: # pylint: disable=W0212 

1505 saved_by.setdefault(live.key(tensor), follow.layer) 

1506 # Detached, as _measure returns it: a graph the forward drops is freed. 

1507 return tensor.detach() 

1508 

1509 grads: List[Tuple[int, int]] = [] 

1510 handles = [p.register_hook(lambda grad: grads.append(live.key(grad))) for p in params] 

1511 kept = [0] * len(backbone.layers) 

1512 try: 

1513 with live, torch.autograd.graph.saved_tensors_hooks(pack, lambda tensor: tensor): 

1514 out = backbone(input_ids=torch.zeros(1, seq_length, dtype=torch.long)).last_hidden_state 

1515 for key, index in saved_by.items(): 

1516 kept[index] += live.sizes.get(key, 0) 

1517 out.sum().backward() 

1518 finally: 

1519 follow.remove() 

1520 for handle in handles: 

1521 handle.remove() 

1522 grads += [live.key(p.grad) for p in params if p.grad is not None] 

1523 # What every layer keeps, the gradients and the parameters left out, the 

1524 # rest is what a layer's backward holds beyond them while it runs. 

1525 excluded = set(saved_by) | set(grads) | {key for key, _ in live.events if key[0] in stored} 

1526 beyond = list(itertools.accumulate(0 if key in excluded else delta for key, delta in live.events)) 

1527 held = [] 

1528 for index, size in enumerate(kept): 

1529 begin, end = follow.windows.get(index, (0, 0)) 

1530 held.append(size + max(beyond[begin:end], default=0)) 

1531 return list(zip(kept, held)) 

1532 

1533 

1534def _stack_activations(config: Any, layers: Iterable[Mapping[str, Any]], seq_length: int, 

1535 replacements: Sequence[Any] = ()) -> Dict[str, KindActivations]: 

1536 """What a layer of each kind of *layers* keeps and holds, per token, from the stack at TP 1 and TP 2. 

1537 

1538 A kind's record is the mean of its layers', which is what the memory 

1539 model applies to each of them: with one record a kind, the stack's total 

1540 comes back whole. The parts tensor parallelism splits follow from the 

1541 pair as :func:`census_activations` derives them. No selective part is 

1542 stated: a selective layer of these kinds is priced by the formulas. 

1543 """ 

1544 kinds = [str(group["kind"]) for group in layers if not group.get("mtp") for _ in range(int(group["count"]))] 

1545 logger.info("census of the whole stack of %d layers at %d tokens, at TP 1 and TP 2: a %s layer " 

1546 "cannot run alone", len(kinds), seq_length, config.model_type) 

1547 one, two = (census_stack(tp_config(config, tp), seq_length, replacements) for tp in (1, 2)) 

1548 if len(one) != len(kinds): 

1549 raise ValueError(f"the model builds {len(one)} decoder layers, where its spec states {len(kinds)}") 

1550 out: Dict[str, KindActivations] = {} 

1551 for kind in dict.fromkeys(kinds): 

1552 members = [index for index, each in enumerate(kinds) if each == kind] 

1553 (kept_1, held_1), (kept_2, held_2) = ( 

1554 tuple(sum(stack[index][part] for index in members) / len(members) for part in (0, 1)) 

1555 for stack in (one, two)) 

1556 out[kind] = KindActivations( 

1557 saved=max(0.0, 2 * kept_2 - kept_1) / seq_length, 

1558 saved_tp=max(0.0, 2 * (kept_1 - kept_2)) / seq_length, 

1559 working=max(0.0, 2 * held_2 - held_1) / seq_length, 

1560 working_tp=max(0.0, 2 * (held_1 - held_2)) / seq_length, 

1561 seq_length=int(seq_length), 

1562 ) 

1563 return out 

1564 

1565 

1566def census_activations(config: Any, layers: Iterable[Mapping[str, Any]], seq_length: int = 4096, 

1567 replacements: Sequence[Any] = (), 

1568 gdn_backend: str = _EAGER_GDN) -> Dict[str, KindActivations]: 

1569 """What a layer of each kind of *layers* keeps and holds, per token, at TP 1 and TP 2. 

1570 

1571 Args: 

1572 config: The language model's Transformers config. 

1573 layers: The model spec's layer stack, groups in model order; MTP 

1574 groups are left out. 

1575 seq_length: The tokens the census runs a layer at. 

1576 replacements: The module replacements a run installs 

1577 (:func:`replacement_specs`). 

1578 gdn_backend: The gated delta rule the run takes (:func:`_fake_layer`). 

1579 

1580 Returns: 

1581 Each kind's :class:`KindActivations`: of the bytes a layer at TP 2 

1582 holds, the part TP splits is half the part at TP 1, and what it keeps 

1583 for each op, its records per op. Selective fields remain unstated: 

1584 a module-region checkpoint plan cannot be inferred from a layer kind. 

1585 A family whose layers cannot run 

1586 alone (:data:`_STACK_FAMILIES`) is measured over its whole stack 

1587 instead (:func:`census_stack`), and its records state the plain 

1588 layer's bytes only. 

1589 

1590 Raises: 

1591 CensusUnavailable: If this tree cannot build what the run builds. 

1592 """ 

1593 if str(getattr(config, "model_type", "")) in _STACK_FAMILIES: 

1594 return _stack_activations(config, layers, seq_length, replacements) 

1595 firsts: Dict[str, int] = {} 

1596 index = 0 

1597 for group in layers: 

1598 if group.get("mtp"): 

1599 continue 

1600 firsts.setdefault(str(group["kind"]), index) 

1601 index += int(group["count"]) 

1602 out: Dict[str, KindActivations] = {} 

1603 for kind, layer_index in firsts.items(): 

1604 ops_1: Dict[str, int] = {} 

1605 ops_2: Dict[str, int] = {} 

1606 (saved_1, working_1), (saved_2, working_2) = ( 

1607 census_layer(tp_config(config, tp), layer_index, seq_length, ops=ops, 

1608 replacements=replacements, gdn_backend=gdn_backend) 

1609 for tp, ops in ((1, ops_1), (2, ops_2))) 

1610 out[kind] = KindActivations( 

1611 saved=max(0.0, 2 * saved_2 - saved_1) / seq_length, 

1612 saved_tp=max(0.0, 2 * (saved_1 - saved_2)) / seq_length, 

1613 working=max(0.0, 2 * working_2 - working_1) / seq_length, 

1614 working_tp=max(0.0, 2 * (working_1 - working_2)) / seq_length, 

1615 seq_length=int(seq_length), 

1616 ops={op: max(0.0, 2 * ops_2.get(op, 0) - ops_1[op]) / seq_length for op in sorted(ops_1)}, 

1617 ops_tp={op: max(0.0, 2 * (ops_1[op] - ops_2.get(op, 0))) / seq_length for op in sorted(ops_1)}, 

1618 ) 

1619 return out