Files
kernbench2/src/kernbench/runtime_api/multiprocessing.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

153 lines
5.6 KiB
Python

"""``torch.multiprocessing.spawn``-compatible namespace (ADR-0027 D1).
Real-PyTorch API *signature* parity only — execution model is a cooperative
greenlet scheduler in a single Python process (D1.0). Non-goals: process
isolation, independent address space, failure isolation, OS-level scheduler
fairness, mp.Queue/Lock.
Attached to ``RuntimeContext`` as ``ctx.multiprocessing`` in
``__post_init__`` (D1.3).
"""
from __future__ import annotations
from typing import Any, Callable
class SpawnException(RuntimeError):
"""Raised from ``_MultiprocessingNamespace.spawn`` on worker failure.
``errors`` contains only root-cause ranks — the rank(s) whose body
raised. Sibling greenlets terminated via ``throw(SystemExit)`` during
cleanup are NOT recorded (SystemExit does not satisfy ``except
Exception`` in the entry wrapper).
"""
def __init__(self, errors: dict[int, Exception]):
self.errors = errors
first = next(iter(errors.items()), None)
msg = (
f"spawn failed on ranks {sorted(errors.keys())}"
+ (
f": rank {first[0]} raised {first[1]!r}"
if first is not None
else ""
)
)
super().__init__(msg)
def _drain_pending(ctx: Any) -> None:
"""Drain worker-wait + collective-pending queues in main context (D0.4/D0.5).
Loop-until-empty: runs until both queues are simultaneously empty. Safe
under the current model where main-context ``ctx.wait`` never re-enqueues
(D0.5 main-context non-reentrance invariant); also safe under future
extensions where drain can add sub-handles (SimPy causality gives finite
depth).
"""
distributed = getattr(ctx, "distributed", None)
backend = getattr(distributed, "_backend", None) if distributed else None
def _collective_nonempty() -> bool:
if backend is None:
return False
pending = getattr(backend, "_pending_collective_handles", None)
return bool(pending)
while ctx._pending_worker_waits or _collective_nonempty():
# (a) Worker-driven waits (D0.1). FIFO.
while ctx._pending_worker_waits:
h = ctx._pending_worker_waits.pop(0)
if h not in ctx._completed:
wait_fn = getattr(ctx.engine, "wait", None)
if wait_fn is not None:
wait_fn(h)
# Populate _completed so fast-path in ctx.wait short-circuits
# on the return leg.
ctx._completed.add(h)
# (b) Collective backend queue (ADR-0027 D0.4-(2)).
if backend is not None:
pending_list = getattr(backend, "_pending_collective_handles", None)
if pending_list is not None:
while pending_list:
h, _sip_id, meta = pending_list.pop(0)
# Main context: ctx.wait drives engine directly and does
# NOT re-enqueue (D0.5 invariant).
ctx.wait(h, _meta=meta)
class _MultiprocessingNamespace:
"""torch.multiprocessing-compat facade bound to a RuntimeContext."""
def __init__(self, ctx: Any) -> None:
self._ctx = ctx
def spawn(
self,
fn: Callable,
args: tuple = (),
nprocs: int = 1,
join: bool = True,
) -> None:
"""Spawn ``nprocs`` worker greenlets, each calling ``fn(rank, *args)``.
Mirrors ``torch.multiprocessing.spawn`` signature (minus ``daemon``).
Runs the D0.4 round-robin scheduler loop until all workers finish,
draining pending queues between rounds.
"""
from greenlet import greenlet
ctx = self._ctx
dist = ctx.distributed
gs: list = []
errors: dict[int, Exception] = {}
for rank in range(nprocs):
def _entry(r: int = rank) -> None:
try:
fn(r, *args)
except Exception as e:
errors[r] = e
raise
g = greenlet(_entry)
if dist is not None and hasattr(dist, "_bind_rank"):
dist._bind_rank(g, rank)
gs.append(g)
try:
while True:
alive = [g for g in gs if not g.dead]
if not alive:
break
for g in alive:
if not g.dead:
g.switch()
_drain_pending(ctx)
except Exception as outer:
# D0.4-(4) sibling cleanup. Abort live greenlets, clear state.
for other in gs:
if not other.dead:
try:
other.throw(SystemExit)
except BaseException:
# SystemExit inherits BaseException; greenlet.throw
# re-raises in caller if target doesn't catch it.
# Silent — we're already in cleanup.
pass
backend = getattr(dist, "_backend", None)
if backend is not None:
if hasattr(backend, "_barrier") and hasattr(backend._barrier, "reset"):
try:
backend._barrier.reset()
except Exception:
pass
pending_collective = getattr(
backend, "_pending_collective_handles", None,
)
if pending_collective is not None:
pending_collective.clear()
ctx._pending_worker_waits.clear()
raise SpawnException(errors) from outer
# join=True: we already waited for all workers above.