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>
This commit is contained in:
2026-04-12 19:36:59 -07:00
parent ff2c677a9c
commit 998cc85762
60 changed files with 9196 additions and 80 deletions
+125 -7
View File
@@ -9,6 +9,39 @@ from kernbench.common.types import Completion, RequestHandle, SimEngine
from .types import DeviceSelector
def _world_size_from_spec(spec: dict | None) -> int:
"""Derive world_size from topology spec: sips × cubes × pes_per_cube."""
spec = spec or {}
sips = int(spec.get("system", {}).get("sips", {}).get("count", 1))
cm = spec.get("sip", {}).get("cube_mesh", {})
cubes_per_sip = int(cm.get("w", 1)) * int(cm.get("h", 1))
pl = spec.get("cube", {}).get("pe_layout", {})
corners = pl.get("corners", [])
pe_per_corner = int(pl.get("pe_per_corner", 1))
pes_per_cube = pe_per_corner * max(len(corners), 1)
return sips * cubes_per_sip * pes_per_cube
def _numpy_to_dtype_str(np_dtype) -> str:
"""Map numpy dtype → kernbench dtype string used by Tensor."""
import numpy as np
kind_map = {
np.float16: "f16",
np.float32: "f32",
np.int8: "i8",
np.int16: "i16",
np.int32: "i32",
np.uint8: "u8",
np.uint16: "u16",
np.uint32: "u32",
}
for np_type, s in kind_map.items():
if np.dtype(np_dtype) == np.dtype(np_type):
return s
raise ValueError(f"unsupported numpy dtype: {np_dtype!r}")
@dataclass
class RuntimeContext:
engine: SimEngine
@@ -23,6 +56,66 @@ class RuntimeContext:
_tensor_counter: int = field(default=0, init=False)
_traces: list[dict] = field(default_factory=list, init=False)
_tensors: list[Any] = field(default_factory=list, init=False)
distributed: Any = field(default=None, init=False) # DistributedContext for CCL benches
_ipcq_plan: dict = field(default_factory=dict, init=False) # ADR-0023 install plan
def __post_init__(self) -> None:
# Eagerly attach a DistributedContext so bench code can do
# ``dist = torch.distributed`` + ``dist.init_process_group(...)``
# without needing a separate launcher to install it.
from kernbench.runtime_api.distributed import DistributedContext
dc = DistributedContext()
dc._ctx_ref = self # back-reference for AhbmCCLBackend to reach ctx.launch etc.
self.distributed = dc
def install_ipcq(
self,
algorithm: str | None = None,
ccl_yaml: str | None = None,
world_size_override: int | None = None,
rank_to_pe: list[tuple[int, int, int]] | None = None,
) -> dict:
"""Install IPCQ neighbor tables on all participating PEs (ADR-0023 D10).
Loads ``ccl.yaml`` (or the path provided), resolves the chosen
algorithm (or ``defaults.algorithm`` if None), and pushes per-PE
IpcqInitMsg into every PE_IPCQ component via the engine.
Args:
algorithm: name of the algorithm in ccl.yaml (or use defaults).
ccl_yaml: optional path to ccl.yaml.
world_size_override: if set, replace the algorithm's world_size.
Returns the install plan dict (rank → (sip,cube,pe), neighbor table).
"""
import importlib
from kernbench.ccl.install import (
install_ipcq as _install,
load_ccl_config,
resolve_algorithm_config,
)
cfg = load_ccl_config(ccl_yaml)
merged = resolve_algorithm_config(cfg, algorithm)
if world_size_override is not None:
merged["world_size"] = world_size_override
elif "world_size" not in merged:
# Derive from topology.yaml when neither the algorithm entry
# nor ``defaults`` carries ``world_size`` (matches pytorch DDP
# where env vars determine ranks, not the ccl config file).
merged["world_size"] = _world_size_from_spec(self.spec)
algo_module = None
try:
algo_module = importlib.import_module(merged["module"])
except ModuleNotFoundError:
pass
plan = _install(
self.engine, self.spec, merged,
algo_module=algo_module, rank_to_pe=rank_to_pe,
)
self._ipcq_plan = plan
self._ipcq_config = merged
return plan
def __enter__(self):
return self
@@ -258,6 +351,24 @@ class RuntimeContext:
"""Allocate a tensor in HBM without initialization (like torch.empty)."""
return self._create_tensor(shape, dtype, name, pattern=None, dp=dp)
def from_numpy(self, arr: Any):
"""Create a host-side tensor wrapping a numpy array.
Mirrors ``torch.from_numpy``. The returned tensor is NOT deployed
to any PE — it lives in an in-memory host staging buffer. Use
``target.copy_(host_tensor)`` to scatter its contents into a
sharded, deployed tensor.
"""
import numpy as np
from kernbench.runtime_api.tensor import Tensor
arr_c = np.ascontiguousarray(arr)
dtype_str = _numpy_to_dtype_str(arr_c.dtype)
t = Tensor(shape=tuple(arr_c.shape), dtype=dtype_str, name="host")
t._host_buffer = arr_c
t._memory_store = getattr(self.engine, "_memory_store", None)
return t
def _create_tensor(
self,
shape: tuple[int, ...],
@@ -418,13 +529,12 @@ class RuntimeContext:
TensorArgShard,
)
from kernbench.runtime_api.tensor import Tensor
from kernbench.triton_emu.registry import register_kernel
from kernbench.triton_emu.registry import _kernels, register_kernel
# Register kernel (idempotent)
try:
register_kernel(kernel_name, kernel_fn)
except ValueError:
pass
# Register kernel (idempotent overwrite — last call wins).
# Tests can re-register the same kernel_name with a different
# function; the user's most recent launch must use the latest fn.
_kernels[kernel_name] = kernel_fn
# Collect tensors and scalars
tensor_args: list[Tensor] = []
@@ -506,6 +616,7 @@ class RuntimeContext:
# Per-SIP kernel launch: each SIP gets TensorArgs with local va_base
last_handle = None
_pending_handles: list[tuple[Any, int]] = []
for sip_id in sorted(sip_set):
sip_kernel_args: list = []
sip_cube_set: set[int] = set()
@@ -566,10 +677,17 @@ class RuntimeContext:
target_cubes=target_cubes,
target_pe=target_pe,
))
# Defer wait until all SIPs are submitted (multi-SIP CCL needs
# all participating PEs to be live concurrently — waiting
# per-SIP would deadlock when ranks span SIP boundaries).
_pending_handles.append((h, sip_id))
last_handle = h
# Drain pending handles now that every SIP has a launch posted.
for h, sip_id in _pending_handles:
self.wait(h, _meta={
"phase": "kernel", "name": kernel_name,
"sip": sip_id, "target_pe": target_pe,
})
last_handle = h
return last_handle