Files
kernbench2/tests/test_ccl_topologies.py
ywkang 998cc85762 Add PE-level IPCQ collective infra + unified ccl_allreduce bench (ADR-0023)
Major changes:

PE-level IPCQ infrastructure:
- New PE_IPCQ component: ring-buffer control plane with 4-direction
  neighbor mapping, head/tail pointers, backpressure (poll/sleep).
- PE_DMA extended with vc_comm channel for IPCQ outbound/inbound DMA,
  including in-flight data snapshot (D9) and op_log recording at
  outbound time for Phase 2 replay correctness.
- IpcqDmaToken piggyback model: data + metadata travel together,
  atomic visibility at receiver (invariant I6).
- Credit return fast path: bottleneck-BW latency, no fabric vc_comm.

Phase 2 data execution (ADR-0020 integration):
- op_log extended: DmaWriteCmd now captures src_space/src_addr for
  Phase 2 dma_write copy; ipcq_copy ops recorded at outbound time.
- DataExecutor replays dma_write + ipcq_copy in t_start order.
- Engine._flush_data_phase: incremental cursor-based replay after
  each engine.wait() so host reads see post-Phase-2 data.
- KernelRunner Phase 1 writes disabled when op_log is active to
  prevent stale data from corrupting the MemoryStore snapshot.

TLContext / kernel API:
- tl.send(dir, src=TensorHandle), tl.recv(dir, shape, dtype),
  tl.recv_async, tl.wait(RecvFuture), copy_to_dst mode.
- TensorHandle operator overloading (add/sub/mul/div) via thread-local
  active TLContext → MathCmd dispatch through PE_MATH.
- PE-local scratch allocator for math output handles.
- tl.load returns space="hbm" handles for correct Phase 2 addressing.
- Additional math functions: maximum, minimum, fma, clamp, softmax, cdiv.

Unified ccl_allreduce bench (PyTorch-compat host code):
- Single benches/ccl_allreduce.py with run() + worker(rank, ws, torch)
  split matching real PyTorch DDP worker pattern.
- torch.distributed facade: init_process_group, get_world_size,
  get_rank, get_backend, all_reduce, barrier — only real PyTorch names.
- AhbmCCLBackend: eager install_ipcq at init, all_reduce dispatches
  kernel via tensor shard metadata (n_elem from shards[0].nbytes).
- world_size derived from topology spec (sips × cubes × pes_per_cube)
  with optional algorithm-level override in ccl.yaml.

Tensor API (PyTorch-compat surface):
- Tensor.numpy(): gather-aware (all shards via VA-based addressing).
- Tensor.copy_(source): scatter from host tensor into sharded target.
- RuntimeContext.from_numpy(arr): host-side staging tensor.
- Tensor.data property fixed to use numpy() (was shards[0]-only).

Algorithm modules moved to src/kernbench/ccl/algorithms/:
- ring_allreduce, mesh_allreduce, tree_allreduce, hello_send.
- Each module exports kernel_args(world_size, n_elem) helper.
- ccl.yaml module paths updated to kernbench.ccl.algorithms.*.

Dead code removed:
- 7 per-variant bench files (ccl_allreduce_{tcm,hbm,sram}, etc.).
- _run_ccl_bench greenlet-per-SIP scheduler.
- benches.loader.is_ccl_bench + run_rank detection.
- benches/ccl/ directory.

Tests:
- New test_ccl_allreduce_matrix.py: 7 parametrized cases
  (ring×3 buffers, ring 8/16, mesh 4, tree 7).
- New test_runtime_api_tensor.py: copy_/numpy/from_numpy unit tests.
- Existing tests updated for new import paths + world_size_override.

Docs:
- Korean ccl-author-guide.md and ADR-0023 paths updated.
- New English versions: ccl-author-guide.en.md, ADR-0023.en.md.

502 tests pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-12 19:36:59 -07:00

165 lines
5.1 KiB
Python

"""Tests for CCL builtin topology generators (ADR-0023 D11)."""
import pytest
from kernbench.ccl.topologies import (
mesh_2d,
none,
resolve_topology,
ring_1d,
ring_1d_unidir,
tree_binary,
)
# ── ring_1d ──────────────────────────────────────────────────────────
def test_ring_1d_4_ranks():
assert ring_1d(0, 4) == {"E": 1, "W": 3}
assert ring_1d(1, 4) == {"E": 2, "W": 0}
assert ring_1d(2, 4) == {"E": 3, "W": 1}
assert ring_1d(3, 4) == {"E": 0, "W": 2}
def test_ring_1d_2_ranks():
assert ring_1d(0, 2) == {"E": 1, "W": 1}
assert ring_1d(1, 2) == {"E": 0, "W": 0}
# ── ring_1d_unidir ───────────────────────────────────────────────────
def test_ring_1d_unidir():
assert ring_1d_unidir(0, 4) == {"E": 1}
assert ring_1d_unidir(3, 4) == {"E": 0}
# ── mesh_2d ──────────────────────────────────────────────────────────
def test_mesh_2d_2x2():
# 2x2 mesh:
# 0 1
# 2 3
assert mesh_2d(0, 4) == {"N": 2, "S": 2, "E": 1, "W": 1}
assert mesh_2d(1, 4) == {"N": 3, "S": 3, "E": 0, "W": 0}
assert mesh_2d(2, 4) == {"N": 0, "S": 0, "E": 3, "W": 3}
assert mesh_2d(3, 4) == {"N": 1, "S": 1, "E": 2, "W": 2}
def test_mesh_2d_4x4():
# 4x4 mesh: rank = r*4 + c
n = mesh_2d(5, 16) # r=1, c=1
assert n["N"] == 1 # ((1-1)%4)*4 + 1
assert n["S"] == 9 # ((1+1)%4)*4 + 1
assert n["W"] == 4 # 1*4 + (1-1)%4
assert n["E"] == 6 # 1*4 + (1+1)%4
def test_mesh_2d_non_square_raises():
with pytest.raises(ValueError):
mesh_2d(0, 5)
# ── tree_binary ──────────────────────────────────────────────────────
def test_tree_binary_root():
n = tree_binary(0, 7)
assert "parent" not in n
assert n["child_left"] == 1
assert n["child_right"] == 2
def test_tree_binary_internal():
n = tree_binary(1, 7)
assert n["parent"] == 0
assert n["child_left"] == 3
assert n["child_right"] == 4
def test_tree_binary_leaf():
n = tree_binary(6, 7)
assert n["parent"] == 2
assert "child_left" not in n
assert "child_right" not in n
# ── none ─────────────────────────────────────────────────────────────
def test_none_returns_empty():
assert none(0, 4) == {}
assert none(3, 7) == {}
# ── resolve_topology ─────────────────────────────────────────────────
def test_resolve_topology_builtin():
fn = resolve_topology("ring_1d")
assert fn(0, 4) == {"E": 1, "W": 3}
def test_resolve_topology_unknown_raises():
with pytest.raises(ValueError):
resolve_topology("nonsense")
def test_resolve_topology_with_neighbors_override_pattern_a():
"""Algorithm module with neighbors() that mutates builtin map."""
class FakeModule:
@staticmethod
def neighbors(rank, world_size, neighbor_map):
if rank % 2 == 1:
neighbor_map.pop("W", None)
return neighbor_map
fn = resolve_topology("ring_1d", algo_module=FakeModule)
assert fn(0, 4) == {"E": 1, "W": 3}
assert fn(1, 4) == {"E": 2} # W removed
def test_resolve_topology_with_neighbors_override_pattern_b():
"""Algorithm module with neighbors() that returns brand-new dict."""
class FakeModule:
@staticmethod
def neighbors(rank, world_size, neighbor_map):
return {"E": (rank + 2) % world_size}
fn = resolve_topology("ring_1d", algo_module=FakeModule)
assert fn(0, 4) == {"E": 2}
assert fn(3, 4) == {"E": 1}
def test_resolve_topology_with_neighbors_override_pattern_c_none():
"""Algorithm module's neighbors() returns None → builtin used as-is."""
class FakeModule:
@staticmethod
def neighbors(rank, world_size, neighbor_map):
return None
fn = resolve_topology("ring_1d", algo_module=FakeModule)
assert fn(0, 4) == {"E": 1, "W": 3}
def test_resolve_topology_none_with_neighbors_override():
"""topology=none + custom neighbors() builds from scratch."""
class FakeModule:
@staticmethod
def neighbors(rank, world_size, neighbor_map):
assert neighbor_map == {} # builtin returned empty
return {"E": (rank + 1) % world_size}
fn = resolve_topology("none", algo_module=FakeModule)
assert fn(0, 4) == {"E": 1}
def test_resolve_topology_module_without_neighbors():
"""Algorithm module without neighbors() function works normally."""
class FakeModule:
pass # no neighbors attribute
fn = resolve_topology("ring_1d", algo_module=FakeModule)
assert fn(0, 4) == {"E": 1, "W": 3}