105f1dc09e
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>
179 lines
6.0 KiB
Python
179 lines
6.0 KiB
Python
"""ADR-0027 T4: torch.multiprocessing.spawn semantics.
|
|
|
|
Phase 1: imports `ctx.multiprocessing.spawn` which doesn't exist yet —
|
|
tests fail. Phase 2 (D1) lands the namespace + _MultiprocessingNamespace
|
|
+ SpawnException, and these pass.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import textwrap
|
|
|
|
import pytest
|
|
from greenlet import greenlet
|
|
|
|
|
|
def _write_minimal_ccl_yaml(tmp_path) -> str:
|
|
body = textwrap.dedent("""\
|
|
defaults:
|
|
algorithm: ring_allreduce_tcm
|
|
buffer_kind: tcm
|
|
backpressure: sleep
|
|
n_slots: 4
|
|
slot_size: 4096
|
|
vc_chunk_size: 256
|
|
ipcq_credit_size_bytes: 16
|
|
|
|
algorithms:
|
|
ring_allreduce_tcm:
|
|
module: kernbench.ccl.algorithms.ring_allreduce
|
|
topology: ring_1d
|
|
buffer_kind: tcm
|
|
n_elem: 8
|
|
""")
|
|
yaml_path = tmp_path / "ccl.yaml"
|
|
yaml_path.write_text(body)
|
|
return str(tmp_path)
|
|
|
|
|
|
def _make_ctx(topology):
|
|
from kernbench.runtime_api.context import RuntimeContext
|
|
from kernbench.runtime_api.types import DeviceSelector
|
|
from kernbench.sim_engine.engine import GraphEngine
|
|
|
|
engine = GraphEngine(topology.topology_obj, enable_data=True)
|
|
return RuntimeContext(
|
|
engine=engine,
|
|
target_device=DeviceSelector("all"),
|
|
correlation_id="test_t4",
|
|
spec=topology.topology_obj.spec,
|
|
)
|
|
|
|
|
|
# ── D1.3 namespace attach ────────────────────────────────────────────
|
|
|
|
|
|
def test_multiprocessing_namespace_attached(topology):
|
|
"""RuntimeContext.__post_init__ attaches ctx.multiprocessing (D1.3)."""
|
|
with _make_ctx(topology) as ctx:
|
|
assert hasattr(ctx, "multiprocessing"), (
|
|
"ADR-0027 D1.3: ctx.multiprocessing must exist"
|
|
)
|
|
assert hasattr(ctx.multiprocessing, "spawn"), (
|
|
"ctx.multiprocessing must expose a spawn(fn, args, nprocs) method"
|
|
)
|
|
|
|
|
|
# ── D1.1 / D1.2: spawn shape + rank binding ──────────────────────────
|
|
|
|
|
|
def test_spawn_invokes_fn_once_per_rank(topology):
|
|
"""spawn(fn, args, nprocs) calls fn(rank, *args) once for each rank."""
|
|
with _make_ctx(topology) as ctx:
|
|
calls: list[tuple[int, tuple]] = []
|
|
|
|
def _worker(rank: int, world_size: int) -> None:
|
|
calls.append((rank, (world_size,)))
|
|
|
|
ctx.multiprocessing.spawn(_worker, args=(3,), nprocs=3)
|
|
|
|
assert sorted(r for r, _ in calls) == [0, 1, 2]
|
|
for _, (ws,) in calls:
|
|
assert ws == 3
|
|
|
|
|
|
def test_spawn_binds_greenlet_local_rank(topology):
|
|
"""Inside the worker, torch.distributed.get_rank() returns the rank
|
|
bound to the greenlet (ADR-0024 D9 + D1.2)."""
|
|
with _make_ctx(topology) as ctx:
|
|
# Distributed context needs to be initialised so get_rank is valid.
|
|
# For T4 we don't run a real collective; just check rank lookup.
|
|
observed: list[tuple[int, int]] = []
|
|
|
|
def _worker(rank: int):
|
|
g = greenlet.getcurrent()
|
|
bound = ctx.distributed._rank_by_greenlet.get(g)
|
|
observed.append((rank, bound))
|
|
|
|
ctx.multiprocessing.spawn(_worker, args=(), nprocs=2)
|
|
|
|
for rank, bound in observed:
|
|
assert rank == bound, (
|
|
f"rank {rank} must be bound to greenlet-local rank {rank}; "
|
|
f"got {bound}"
|
|
)
|
|
|
|
|
|
# ── D1.2 exception cleanup ───────────────────────────────────────────
|
|
|
|
|
|
def test_spawn_exception_raises_spawn_exception_with_root_cause(topology):
|
|
"""D0.4-(4): worker raise → siblings SystemExit + SpawnException(errors)."""
|
|
with _make_ctx(topology) as ctx:
|
|
from kernbench.runtime_api.multiprocessing import SpawnException
|
|
|
|
def _worker(rank: int):
|
|
if rank == 1:
|
|
raise ValueError(f"rank {rank} boom")
|
|
|
|
with pytest.raises(SpawnException) as exc_info:
|
|
ctx.multiprocessing.spawn(_worker, args=(), nprocs=3)
|
|
|
|
# Root cause rank is captured.
|
|
assert 1 in exc_info.value.errors
|
|
assert isinstance(exc_info.value.errors[1], ValueError)
|
|
|
|
|
|
def test_spawn_exception_clears_pending_queues(topology):
|
|
"""D0.4-(4): on raise, _pending_worker_waits and collective queue clear."""
|
|
with _make_ctx(topology) as ctx:
|
|
from kernbench.runtime_api.multiprocessing import SpawnException
|
|
|
|
def _worker(rank: int):
|
|
raise RuntimeError("fail")
|
|
|
|
with pytest.raises(SpawnException):
|
|
ctx.multiprocessing.spawn(_worker, args=(), nprocs=2)
|
|
|
|
assert ctx._pending_worker_waits == []
|
|
|
|
|
|
# ── D1.4 migration compat: ccl_allreduce runs via mp.spawn ───────────
|
|
|
|
|
|
def test_ccl_allreduce_hand_rolled_loop_replaced_by_mp_spawn(
|
|
topology, tmp_path, monkeypatch, spec,
|
|
):
|
|
"""D1.4: benches/ccl_allreduce.py's hand-rolled greenlet loop must still
|
|
produce correct behaviour after migration to torch.multiprocessing.spawn.
|
|
|
|
Minimal smoke — just that ``bench.run(ctx)`` completes without the
|
|
loop short-circuiting or leaving pending queues dirty.
|
|
"""
|
|
monkeypatch.chdir(_write_minimal_ccl_yaml(tmp_path))
|
|
import benches.ccl_allreduce as bench
|
|
|
|
calls: list[tuple[int, int]] = []
|
|
|
|
def _fake_worker(rank, world_size, torch):
|
|
calls.append((rank, world_size))
|
|
|
|
monkeypatch.setattr(bench, "worker", _fake_worker)
|
|
|
|
with _make_ctx(topology) as ctx:
|
|
bench.run(ctx)
|
|
|
|
expected_ws = int(spec["system"]["sips"]["count"])
|
|
ranks = sorted(r for r, _ in calls)
|
|
assert ranks == list(range(expected_ws))
|
|
assert ctx._pending_worker_waits == []
|
|
|
|
|
|
# ── _drain_pending function is exported ──────────────────────────────
|
|
|
|
|
|
def test_drain_pending_exported():
|
|
"""D0.4: _drain_pending must be importable from runtime_api.multiprocessing."""
|
|
from kernbench.runtime_api.multiprocessing import _drain_pending
|
|
assert callable(_drain_pending)
|