Files
kernbench2/benches/ccl_allreduce.py
T
ywkang 105f1dc09e ADR-0027: Megatron TP API + worker-wait generalization + mp.spawn
Implements ADR-0027 Phase 2 end-to-end. All 559 tests pass (was 523 +
1 xfail; ring_default_ws strict-xfail is now resolved).

D0 — Worker-wait generalization (context.py):
- _pending_worker_waits queue on RuntimeContext.
- ctx.wait(h) in worker context defers to main via g.parent.switch().
  Fast-path for already-completed handles.
- Worker API is unchanged: tensor deploy, launch, etc. still look
  synchronous; they're transparently cooperatively scheduled.
- Solves ADR-0024 Phase B kernel-greenlet orphan bug (env.run now
  only ever drives from main; kernel _parent is always main).

D0.5 — Host-read barrier (tensor.py):
- Explicit _HOST_READ_BARRIERS registry (T5.g closed-set via code
  review, not reflection-magic).
- numpy/data/__getitem__/__repr__ drain pending worker-waits before
  host-observable read.
- copy_: source-side barrier via source.numpy(). Target-side write
  barrier is intentionally NOT applied — global pending target barrier
  prematurely drains cross-rank collectives → deadlock.
- Collective pending is excluded from barrier drain condition
  (collective is cross-rank; its own yield in all_reduce covers the
  invariant naturally).

D1 — torch.multiprocessing.spawn (runtime_api/multiprocessing.py):
- API signature parity with real PyTorch spawn; execution is
  cooperative greenlet scheduler (process isolation etc. are explicit
  non-goals per D1.0).
- _drain_pending drains worker-waits then collectives in one barrier,
  loop-until-empty.
- Round-based exception handling with SystemExit sibling abort +
  SpawnException(errors) wrapping root-cause ranks.
- RuntimeContext attaches ctx.multiprocessing in __post_init__.
- benches/ccl_allreduce.py hand-rolled loop collapses to one
  torch.multiprocessing.spawn call.

D2–D6 — kernbench.tp package:
- parallel_state: initialize_model_parallel, get_*_rank,
  get_*_world_size, with weak active-ctx registry in context.py.
- layers: ColumnParallelLinear, RowParallelLinear (shape-only
  primitives — fp16 gemm via tl.load + tl.dot + tl.store).
- kernels: _gemm_kernel used by TP layers (self-contained; no bench
  dependency).
- primitives / mappings stubs per D6/D8.

Data-path fixes (surfaced by TP gemm + all_reduce sequence):
- sim_engine/op_log.py: dma_write snapshot is skipped for TCM
  sources (PE scratch is repopulated by Phase 2 math/gemm replay —
  capturing Phase-1-time snapshot picked up STALE data from prior
  kernel's output aliased at the same scratch addr, causing the later
  kernel's dma_write to overwrite Phase 2 result with stale value).
- sim_engine/op_log.py + sim_engine/data_executor.py: per-operand
  space recorded on GemmCmd and composite gemm records so HBM-resident
  operands (tl.load output) don't default to TCM during replay.
- runtime_api/context.py: ctx.zeros writes zero-init to MemoryStore
  at VA keys so kernels reading via VA see deterministic init even
  without explicit copy_().

Tests (Phase 1 + Phase 2):
- test_worker_wait_drain (T3): orphan invariant + resume + multi-rank
  drain + idempotency + exception propagation.
- test_mp_spawn (T4): spawn shape + bind + SpawnException scope.
- test_host_read_barrier (T5): barrier contract per entry-point +
  closed-set registry check.
- test_tp_parallel_state (T1): initialize + rank lookup.
- test_tp_layers (T2): shape + deterministic numerical correctness
  (concat-matmul equality for RowParallel, not mean-only).
- test_tp_mlp (T6): full 2-layer MLP with deterministic weight
  numerical match + rank-consistency post all-reduce.
- test_ccl_allreduce_matrix: ring_default_ws xfail removed (T7).

Regression: 523 pre + 35 new + 1 ex-xfail = 559 passed, 1 intentional
skip (T3.e historical failure documentation).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:31:13 -07:00

166 lines
6.8 KiB
Python

"""CCL all-reduce bench (ADR-0024 Phase A).
Driven entirely by ``ccl.yaml`` + ``topology.yaml``:
- ``defaults.algorithm`` in ``ccl.yaml`` picks which kernel to run.
- ``world_size`` resolution: explicit override in ccl.yaml > defaults >
topology's SIP count. ADR-0024 D1: topology fallback is the SIP count
(each rank = one SIP, TP boundary).
- ``run()`` is hybrid:
- If ``world_size == topology SIP count`` (the intended new path):
spawn one greenlet per rank, bind it via ``dist._bind_rank``, and
each worker calls ``torch.ahbm.set_device(rank)`` + runs its portion
of the collective. Cross-rank IPCQ exchange handles the reduce.
- Legacy path (``world_size > SIP count``, via explicit ccl.yaml
override): single worker at rank 0 with the full tensor distributed
across all participating PEs via ``_derive_dp``. Retained for
backward compatibility with existing kernel / topology tests.
"""
from __future__ import annotations
import numpy as np
from kernbench.ccl.install import load_ccl_config, resolve_algorithm_config
from kernbench.policy.placement.dp import DPPolicy
# Default per-rank tile size if ccl.yaml doesn't override it.
DEFAULT_N_ELEM = 32
def _derive_dp(spec: dict, world_size: int) -> DPPolicy:
"""Legacy DPPolicy for world_size > SIP count (rank = flat PE index).
Used only in the ccl.yaml-override path so the existing matrix tests
with explicit world_size (8, 16, 7 etc.) keep working. ADR-0026:
DPPolicy is intra-device only, so this legacy path now always stays
within a single SIP and distributes the override world_size across
that SIP's cubes and PEs.
"""
pl = spec["cube"]["pe_layout"]
pes_per_cube = int(pl["pe_per_corner"]) * len(pl["corners"])
cm = spec["sip"]["cube_mesh"]
cubes_per_sip = int(cm["w"]) * int(cm["h"])
if world_size <= pes_per_cube:
return DPPolicy(
cube="replicate", pe="column_wise",
num_cubes=1, num_pes=world_size,
)
if world_size <= cubes_per_sip * pes_per_cube:
return DPPolicy(
cube="column_wise", pe="column_wise",
num_cubes=world_size // pes_per_cube,
)
return DPPolicy(cube="column_wise", pe="column_wise")
def worker(rank: int, world_size: int, torch) -> None:
"""Per-rank worker (new TP path) OR single-worker legacy driver.
Behaviour depends on whether this call originates from the
multi-greenlet launcher (new path) or from the legacy single-call
fallback; distinguished by which ``dp`` layout applies.
"""
cfg = resolve_algorithm_config(load_ccl_config())
algo_name = cfg["algorithm"]
n_elem = int(cfg.get("n_elem", DEFAULT_N_ELEM))
spec = torch.spec or {}
n_sips = int(spec.get("system", {}).get("sips", {}).get("count", 1))
if world_size == n_sips:
# ADR-0024 new path: rank = SIP, worker sees its SIP's
# representative PE via torch.ahbm.set_device.
torch.ahbm.set_device(rank)
dp = DPPolicy(cube="replicate", pe="replicate",
num_cubes=1, num_pes=1)
tensor = torch.zeros(
(1, n_elem), dtype="f16", dp=dp, name=f"ccl_in_r{rank}",
)
# Each rank initialises its tile with (rank + 1); after all_reduce
# every rank sees sum(1..world_size).
init = np.full((1, n_elem), float(rank + 1), dtype=np.float16)
tensor.copy_(torch.from_numpy(init))
torch.distributed.all_reduce(tensor, op="sum")
result = tensor.numpy()
expected = float(sum(range(1, world_size + 1)))
all_ok = bool(np.allclose(result, expected, rtol=1e-1, atol=1e-1))
if rank == 0:
if all_ok:
print(f" {algo_name} (ws={world_size}): {world_size} OK")
else:
print(
f" [FAIL] rank {rank} "
f"(ws={world_size}, algo={algo_name}): "
f"got mean={float(result.reshape(-1).mean()):.3f}, "
f"expected={expected:.3f}"
)
print(
f" {algo_name} (ws={world_size}): "
f"0 OK / {world_size} FAIL"
)
return
# Legacy path: world_size overridden via ccl.yaml to exceed SIP count.
# Single-worker at rank 0; whole tensor distributed across all
# participating PEs using the derived DPPolicy. Matches pre-ADR-0024
# behaviour.
dp = _derive_dp(spec, world_size)
tensor = torch.zeros(
(1, world_size * n_elem), dtype="f16", dp=dp, name="ccl_in",
)
init = np.zeros((1, world_size * n_elem), dtype=np.float16)
for r in range(world_size):
init[0, r * n_elem : (r + 1) * n_elem] = float(r + 1)
tensor.copy_(torch.from_numpy(init))
torch.distributed.all_reduce(tensor, op="sum")
result = tensor.numpy()
expected = float(sum(range(1, world_size + 1)))
all_ok = bool(np.allclose(result, expected, rtol=1e-1, atol=1e-1))
if rank == 0:
if all_ok:
print(f" {algo_name} (ws={world_size}): {world_size} OK")
else:
flat = result.reshape(-1)
n_fail = 0
for r in range(world_size):
slice_r = flat[r * n_elem : (r + 1) * n_elem]
if not np.allclose(slice_r, expected, rtol=1e-1, atol=1e-1):
n_fail += 1
if n_fail <= 5:
print(
f" [FAIL] rank {r} "
f"(ws={world_size}, algo={algo_name}): "
f"got mean={float(slice_r.mean()):.3f}, "
f"expected={expected:.3f}"
)
print(
f" {algo_name} (ws={world_size}): "
f"{world_size - n_fail} OK / {n_fail} FAIL"
)
def run(torch) -> None:
"""CLI entry — dispatch to multi-greenlet path when ws == SIP count,
else fall back to single-worker legacy path for ccl.yaml override compat.
"""
dist = torch.distributed
dist.init_process_group(backend="ahbm")
world_size = dist.get_world_size()
spec = torch.spec or {}
n_sips = int(spec.get("system", {}).get("sips", {}).get("count", 1))
if world_size == n_sips:
# ADR-0027 D1: ``torch.multiprocessing.spawn`` replaces the prior
# hand-rolled greenlet loop. The spawn namespace absorbs the
# scheduler drain (D0.4) so kernel_runner's spawned kernel greenlets
# correctly get main as their parent (ADR-0024 Phase B blocker
# resolved via D0 worker-wait generalisation).
torch.multiprocessing.spawn(
worker, args=(world_size, torch), nprocs=world_size,
)
else:
# Legacy single-worker path (ccl.yaml world_size override).
worker(rank=dist.get_rank(), world_size=world_size, torch=torch)