Files
kernbench2/src/kernbench/tp/layers.py
T
ywkang 687c98086d ADR housekeeping: category prefixes, lifecycle folders, retroactive 0034-0037
Filename + lifecycle:
- ADR rename to ADR-NNNN-<cat>-title.md with 8 3-letter category prefixes
  (dev / mem / lat / prog / algo / par / api / ver). Numbers stay immutable.
- ADR Lifecycle split into 3 folders, documented in CLAUDE.md Part 2:
  docs/adr/ (Accepted), docs/adr-proposed/ (Proposed/Stub/Draft),
  docs/adr-history/ (Superseded/Merged). Status field gains "Draft" for
  retroactive docs pending verification.

Merges (one ADR per topic, no change-history annotations):
- ADR-0017 absorbs ADR-0019 (Cube NOC + per-PE HBM connectivity, 10 D-items)
- ADR-0014 absorbs ADR-0021 (PE pipeline execution model, 8 D-items incl.
  TileToken self-routing and multi-op composite epilogue scope)
- ADR-0023 absorbs docs/ipcq-dma-codesign-hw.md as new "HW Realization
  Notes (Informative)" section (D16-D23 + Open HW Questions). codesign-hw.md
  deleted; ADR-0019/0021 moved to adr-history with one-line stub status

Retroactive documentation (G4 closures, code-verified):
- ADR-0037 forwarding component (TransitComponent: first-flit overhead,
  serial worker, path-based routing, single impl/multiple names)
- ADR-0036 IO_CPU component (target_start_ns global barrier stamping,
  per-cube fan-out, response aggregation)
- ADR-0035 M_CPU & M_CPU.DMA component (3 fan-out paths, DMA Resources,
  target_start_ns passthrough)
- ADR-0034 HBM controller internal design (per-PC state, address-based
  selection, flit-aware per-flit commit, async finalize, command-only
  fallback path)

Content updates:
- ADR-0010 expanded to full CLI surface (run/probe/web), retitled
  "Command Line Interface and Execution Semantics"
- ADR-0007 D2 rewritten to current state; ADR-0015 supersession notes pruned
- ADR-0005 wrapped in Decision header with D1-D5; ADR-0022 metadata
  block replaced with standard Status header
- ADR-0024 trimmed to rank=SIP launcher essentials (D1-D4);
  ADR-0027 cleaned of supersession history
- ADR-0033 D6 cleanup: address-based PC selection moved out of future-work
  (now documented in ADR-0034 D3); related D1/D3 wording realigned
- Cross-references back-filled in 5 ADRs (G3 gaps closed)

Onboarding docs split:
- docs/onboarding/ created
- moved: hw-architecture-overview.md, latency-model.md, di-presentation.md,
  ccl-author-guide{,.en}.md
- references updated in README, ADR-0023{,.en}, src/kernbench/ccl/__init__.py

Source / test / yaml: ADR-NNNN cross-references in docstrings and YAML
comments updated after the merges (ADR-0021->0014 D6, ADR-0019->0017 D8).
No behavior change.

Tooling:
- tools/verify_adr_lang_pairs.py + tests/test_verify_adr_lang_pairs.py
  (ADR EN/KO pair invariant checker)
- .claude/commands/report.md tracked (/report slash command)
- .gitignore: allow .claude/commands/*.md while keeping settings files ignored

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 01:15:55 -07:00

151 lines
5.0 KiB
Python

"""Megatron-style parallel layers (ADR-0027 D4/D5).
- ``ColumnParallelLinear``: weight's out_features axis split across TP ranks.
forward(x) is local gemm; no collective.
- ``RowParallelLinear``: weight's in_features axis split across TP ranks.
forward(x) ends with ``dist.all_reduce`` to sum partial products.
Both layers use the intra-device ``DPPolicy`` (ADR-0026). TP shard
ownership is determined by ``torch.ahbm.set_device(rank)`` (ADR-0024 D3).
Yield-safety contract (ADR-0027 D4/D5): every forward path contains at
least one ``ctx.wait`` (via ``torch.launch``) or one collective; this
keeps the scheduler loop making progress.
"""
from __future__ import annotations
from typing import Any
from kernbench.policy.placement.dp import DPPolicy
from kernbench.tp.kernels import _gemm_kernel
from kernbench.tp.parallel_state import (
get_tensor_model_parallel_world_size,
)
class ColumnParallelLinear:
"""Weight's K (out_features) axis distributed across TP ranks.
forward(x):
x: (M, N) — full-replicated across ranks
W_k: (N, K / world_size) — this rank's slice (on its SIP)
y_k = x @ W_k → (M, K / world_size)
"""
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = False,
dtype: str = "f16",
torch: Any = None,
) -> None:
if torch is None:
raise TypeError("ColumnParallelLinear requires torch=<RuntimeContext>")
ws = get_tensor_model_parallel_world_size()
if out_features % ws != 0:
raise ValueError(
f"out_features ({out_features}) must be divisible by TP world "
f"size ({ws})"
)
self.in_features = in_features
self.out_features = out_features
self.k_local = out_features // ws
self.dtype = dtype
self._torch = torch
# Per-rank weight slice. ``set_device(rank)`` (ADR-0024 D3) places
# it on SIP ``rank``. Intra-SIP layout comes from DPPolicy (ADR-0026).
self.weight = torch.zeros(
(in_features, self.k_local),
dtype=dtype,
dp=DPPolicy(cube="replicate", pe="replicate",
num_cubes=1, num_pes=1),
name="col_parallel_w",
)
# Bias omitted in initial scope (ADR-0027 D9).
self.bias = None
if bias:
raise NotImplementedError(
"bias=True is deferred (ADR-0027 D9 initial scope)"
)
def forward(self, x):
M = int(x.shape[0])
out = self._torch.empty(
(M, self.k_local),
dtype=x.dtype,
dp=DPPolicy(cube="replicate", pe="replicate",
num_cubes=1, num_pes=1),
name="col_parallel_out",
)
self._torch.launch(
"col_parallel_gemm",
_gemm_kernel,
x, self.weight, out,
M, self.in_features, self.k_local,
)
return out
class RowParallelLinear:
"""Weight's N (in_features) axis distributed across TP ranks.
forward(x):
x: (M, N / world_size) — rank-local slice (ColumnParallel output)
W_k: (N / world_size, K) — this rank's slice
y_k = x @ W_k → (M, K) — partial sum
y = all_reduce(y_k, op="sum") → (M, K) on every rank
"""
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = False,
dtype: str = "f16",
torch: Any = None,
) -> None:
if torch is None:
raise TypeError("RowParallelLinear requires torch=<RuntimeContext>")
ws = get_tensor_model_parallel_world_size()
if in_features % ws != 0:
raise ValueError(
f"in_features ({in_features}) must be divisible by TP world "
f"size ({ws})"
)
self.in_features = in_features
self.out_features = out_features
self.n_local = in_features // ws
self.dtype = dtype
self._torch = torch
self.weight = torch.zeros(
(self.n_local, out_features),
dtype=dtype,
dp=DPPolicy(cube="replicate", pe="replicate",
num_cubes=1, num_pes=1),
name="row_parallel_w",
)
self.bias = None
if bias:
raise NotImplementedError(
"bias=True is deferred (ADR-0027 D9 initial scope)"
)
def forward(self, x):
M = int(x.shape[0])
y_partial = self._torch.empty(
(M, self.out_features),
dtype=x.dtype,
dp=DPPolicy(cube="replicate", pe="replicate",
num_cubes=1, num_pes=1),
name="row_parallel_partial",
)
self._torch.launch(
"row_parallel_gemm",
_gemm_kernel,
x, self.weight, y_partial,
M, self.n_local, self.out_features,
)
self._torch.distributed.all_reduce(y_partial, op="sum")
return y_partial