Skip to content

Perf phase 2: batched matmul, CUDA IPC messaging, stream-ordered nodes, compile-once JIT - #15

Open
AdvaitTahilyani wants to merge 34 commits into
perf-phase1from
perf-phase2
Open

AdvaitTahilyani wants to merge 34 commits into
perf-phase1from
perf-phase2

Conversation

@AdvaitTahilyani

Copy link
Copy Markdown

Stacked on #14.

  • einsum: a native BATCHED_MATMUL op (cuBLAS strided-batched on GPU, Eigen on CPU) replaces the per-batch matmul loop.
  • GPU messaging: same-host processes exchange tiles through CUDA IPC. A startup probe checks each pair and falls back to pooled pinned staging; cross-host traffic also uses the pinned pool (CNUM_GPU_IPC, CNUM_GPU_STAGE).
  • Per-op overhead: nodes complete at enqueue, ordered by stream events. Fully overwritten outputs skip zero-fill, and the client flushes every 64 ops (CNUM_AUTO_FLUSH).
  • JIT: cached kernels embed the cubin. Servers sharing a cache compile each kernel once using lock claims, and a DAG's kernels compile in parallel.

Large problems vs gpu-backend (A100, steady state, same arguments):

1 GPU 4 GPUs
einsum -n 800 6.8 s → 0.68 s —
cfd 4096² 3.8 s → 2.2 s 4.8 s → 2.6 s
gemm -n 4096 — 50 s → 1.2 s
black_scholes_greeks — 30 s → 4.3 s
lstm_backward 2.0 s → 1.6 s 106 s → 0.9 s
linreg / logreg — 28 s → 3.9 / 4.1 s

Cold starts are faster too: black_scholes_greeks at its default size goes 612 → 122 ms.

Tested: CPU +p1/+p2 (15/15, 25/25, 26/26); A100 +p1 and +p4 with one GPU per process (15/15, 25/25, 26/26); 2 nodes (8/8, 25/25); compute-sanitizer clean; fault injection for IPC probe failure, JIT locks and corrupt cache entries.

🤖 Generated with Claude Code

AdvaitTahilyani and others added 29 commits October 27, 2026 23:56
Each result chare receives the (batch, m, all k) and (batch, all k, n) boxes
of the two 3-D operands point-to-point, reusing the CONVOLVE/FLIP box
gathering, and runs one strided batched GEMM: cuBLAS gemmStridedBatched for
float/complex on NVIDIA, a Kokkos kernel for ints, Eigen on CPU. A chare that
already holds its boxes reads them in place. Operands may be in any layout
with the batch dim not last, so transposed operands need no transpose.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The per-element index arithmetic dominated multi-chare batched matmuls on CPU
(einsum 100^3 at +p2: 75 -> 24 ms per iteration).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contractions with batch labels used one SUMMA per batch element (about 1,500
GEMMs and 4,500 slice copies in the cuPyNumeric einsum example); they are now
one BATCHED_MATMUL node with operand layouts chosen to avoid transposes. The
broadcast-product shortcut for small batched products is gone. N-D matmul goes
through the same path. Simulator model included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_bmm: every operand layout, grouped and >3-D labels, multi-chare sizes,
offset and stepped views, all BLAS dtypes, N-D matmul and chained results.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
allocate_or_reuse/ensure_array take a zero flag. New outputs of fused
elementwise kernels (fast path, and the fragment path when the aligned cells
cover the output tile), the local-GEMM result of MATMATMUL and CONVOLVE/FLIP
results skip it; a reused buffer then needs no deep_copy with its two device
synchronizes and a new one no initialization kernel and fence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A node no longer waits for a HAPI callback on its compute stream (an event
the scheduler polls) before its successors start: the successors queue on
the same stream. Each node starts by ordering the chare's compute stream
after its comm stream and the Kokkos default instance and the comm stream
after the compute stream (event record/wait, no host wait), so packs for
sends and reuse of retired buffers stay ordered. Received buffers are still
freed from a HAPI callback, after the kernels that read them. The default
instance is ordered after the compute stream where it reads compute
results (REDUCE dot, MATMUL partial sums); barriers fence the device so the
client's synchronize still waits for the GPU.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replaces the host-blocking fence of the Kokkos default instance before
every cuBLAS GEMM with an event the compute stream waits on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Charm++'s CkDeviceBuffer path (netlrts, CMK_GPU_COMM=0) stages every message
through a fresh cudaMallocHost buffer on both sides, blocks the sender in
cudaStreamSynchronize and frees with cudaFreeHost. device_pack_send now copies
a send to another process on the same host into a block of an exported
cudaMalloc slab (CUDA IPC) and sends its handle and offset (receive_ipc); the
receiver maps the slab once, copies device to device on its comm stream and
returns the block with the send_complete callback. Works with the default
one-visible-GPU-per-process launch. CNUM_GPU_IPC=0 restores the old path;
CNUM_GPU_IPC_MB bounds the slabs (default 1024).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Messages to another host (and to the same host with CNUM_GPU_IPC=0) are
copied asynchronously into a pinned block from a size-class pool and sent as
a plain message (receive_staged); the receiver copies into a pooled pinned
block and then to the device. Blocks are released from the stream callback
after their copy, so no cudaMallocHost/cudaFreeHost or blocking sync per
message. CNUM_GPU_STAGE=0 disables it, CNUM_GPU_STAGE_MB bounds the cache
(default 512).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With 256, loops of a few ops per iteration (gemm, richardson_lucy, cg
between gets) record their whole timed region before the first flush, so
the backend starts only when the client is done. Flushing at 64 lets it
execute while the client records. Warm, 1 A100 (af=256 -> 64): gemm
24 -> 17 ms, cg 89 -> 61 ms; CPU build: no port slower beyond noise,
gemm 36 -> 22 ms, kmeans 253 -> 207 ms, lstm_backward 45 -> 37 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the pools

- gpu_comm.cpp: from set_proxies, rank 0 of each process exports a small
  buffer; processes with the same hostname and boot id (not Charm++'s
  IP-based host test) map and read each peer's buffer, and the working
  (sender, receiver) pairs are all-gathered into peer_ok, which gpu_ipc_peer
  consults. Failed pairs and messages sent before the probe completes are
  staged through pinned host memory; the probe never aborts.
  CNUM_GPU_IPC_PROBE_FAIL="src-dst,..." injects failures for testing.
- IPC arena: split free blocks of larger classes, return alignment gaps to
  smaller classes, do not retry a failed slab cudaMalloc, warn once when
  falling back to staging.
- Pinned pool: cudaMallocHost/cudaFreeHost outside the lock;
  CNUM_GPU_STAGE_MB caps only the cached blocks.
- Clamp CNUM_GPU_IPC_MB and CNUM_GPU_STAGE_MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…C at exit

~PartitionImpl drops pending IPC send blocks instead of returning them to
the free lists (a receiver may still be copying); the group destructor
unmaps peer slabs and frees slabs and cached pinned blocks before
Kokkos::finalize. Note that lastKnown relies on partitions not migrating.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- cuBLAS path falls back to the naive kernel when a size or leading dim
  exceeds INT_MAX, with a one-time notice when a float/complex product does.
- The naive kernel accumulates ints unsigned, so wraparound is defined.
- einsum picks operand layouts by role codes, not list identity.
- einsum with an empty operand computes its zeros/empty result on the host
  (it raised in a reshape before); empty 2-D matmul goes there too instead of
  hanging the server.
- test_bmm: int8/int32/uint32/int64 wraparound, bool counts > 255, zero-size
  M/N/K/batch for einsum, matmul and out=.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Kernels embedded PTX that the driver assembled at load time, with the cubin
kept in a second cache file. Now generateNVIDIAHost assembles each PTX object
with the driver's JIT (same optimization level as mgpuModuleLoadJIT used) and
embeds the cubin, so a cached kernel is one file and loads without the JIT
or a second read. The cache key adds the device's sm and the driver version;
the target directory names the device's sm when it differs from the PTX
target. If assembly fails the PTX stays and mgpuModuleLoadJIT handles it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ArrayDAGGroup::compile hands all new kernels of a DAG to jit_compile_batch.
- Misses compile in parallel on a pool of threads (CNUM_JIT_THREADS, default
  min(8, CPUs of the process); 1 GiB stacks, which replaces the CPU build's
  big-stack helper thread; one MLIR context per thread). LLVM targets are
  registered before the threads start: concurrent registration corrupted
  the target registry (threads spun in lookupTarget).
- Servers sharing the disk cache (the processes of a job, also across nodes
  and other jobs) compile each kernel once: a compiler claims an entry with
  <entry>.o.lock (O_EXCL, host and pid inside, mtime refreshed every 2 s),
  claims at most a pool's worth at a time, and the others load the published
  entry. Different GPU targets have different entries.
- A waiter breaks a claim whose holder is gone or a zombie on the same host,
  whose mtime stood still for 30 s or is 2 min old, and compiles without a
  claim after CNUM_JIT_WAIT_S (60) s; a failed compile releases the claim.
- Eviction removes .lock files an hour old, like .tmp files.
- CNUM_JIT_TIME prints a store phase and one line per batch with misses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
join_streams orders the comm stream after compute at node start, but a
node's own halo packs (queued after that) were not ordered before the
compute it launches from on_comm_done or right after sending, so an
in-place update such as u[1:-1] = 0.5 * (u[:-2] + u[2:]) could send new
values. on_comm_done, and execute_dag_node after its sends, now order the
compute stream after the comm stream and the default instance; so does
reusing a retired buffer without zero-fill (a pack of it may still run).
test_inplace_halo: iterated in-place 1-D/2-D/3-D stencils over several
chares vs NumPy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Debug switch: outputs that skip the zero-fill start as NaN/-1 instead of
whatever the buffer held, so an op that misses elements fails its tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… event calls

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- gpu_comm_shutdown sets a closed flag instead of freeing slabs and clearing
  the block table: a late comm_free/send_complete/receive_ipc could free an
  interior slab pointer or index the cleared slabs, and a peer may still be
  copying from our slabs. When closed, gpu_ipc_free/forget are no-ops for
  arena blocks, no new IPC sends or peer mappings are made (receive_ipc
  drops the message), and slabs, mappings and pinned blocks are left to
  process exit. gpu_ipc_handle checks its index.
- The probe sets the Kokkos device before its CUDA calls and copies the
  reduction records with memcpy.
- pinned_free ignores unknown pointers; no slabs-full warning with
  CNUM_GPU_IPC_MB=0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed staging

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-shaped roots

Review follow-up to the eviction safety change:
- only <sha256>.o / <sha256>.cubin entries, their cacheTmpName temporaries and
  <sha256>.o.lock claims are ever deleted; build ids must be 16/32/40/64 hex
  digits (or <size>-<mtime>) and target tags the exact targetCacheDir form
- entries of the pre-target layout are aged like other entries, not deleted
  outright; cubin/ is removed once unused for the age limit
- a pre-existing non-empty root is marked only if its whole tree has the cache
  layout (or with CNUM_JIT_CACHE_ADOPT=1); an unmarked root is reported once
- the root is normalized (absolute, no dots or trailing separator), and the
  current build directory is recognized by name, so it is never rmdir'ed
- an own /tmp/cnum-jit-<uid> with group/other bits is chmod'ed 0700
- INVALID_SOURCE and UNSUPPORTED_PTX_VERSION count as invalid entries

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review follow-up:
- every cache load in a batch is soft: an invalid entry is removed and
  recompiled, one that does not load here for other reasons (e.g. out of
  memory) is compiled locally and kept
- waiters poll by opening files (no stale negative NFS lookups) with a
  10-200 ms backoff; a claim is stale once its mtime stood still for 30 s
  (6 s for a holder on this host, which also covers holders stuck in exit),
  and the 2-minute age rule needs an observed 5 s standstill (clock skew);
  without a claim after CNUM_JIT_WAIT_S, now 600 s
- target directories name the driver version (d<version>), so pre-warm only
  sees entries this driver built, and it skips names that are not entries
- compile jobs release their claim on every exit path and exceptions stay in
  the pool; the heartbeat refreshes locks outside the claims mutex
- compile threads run on the process's CPUs as of startup, also when Charm++
  pins the PE thread (+setcpuaffinity)
- temporary names add a per-process counter (compile threads publish at once)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…o-fill, flush every 64 ops

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…, are dead

A killed GPU process keeps its pid for seconds while CUDA tears down, and a
holder killed between creating and writing its lock leaves it empty; both
made waiters fall back to the 30 s standstill rule. Now a holder whose task
is exiting (PF_EXITING) counts as dead, and an empty lock is broken after a
6 s standstill like a same-host one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…bedded cubins

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	CODEMAP.md

@adityapb adityapb left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: approve with nits.

This is a static review. Line numbers are at this PR's head.

I traced the concurrency-sensitive parts and found no race:

  • IPC blocks: they are reused only after the receiver's copy completes.
  • Stream ordering: every node joins its streams at start, and host consumers fence.
  • Zero-fill skip: it fires only when the output is fully written.
  • BATCHED_MATMUL: leading dims, strides and message counts check out.
  • Compile locks: a stale lock costs at most a duplicate compile.
  1. [minor] A runtime IPC mapping failure aborts the job (gpu_comm.hpp:186-198).
    • The startup probe maps only a 4 KB buffer. The receiver later maps a 256 MB slab and calls CkAbort if that fails.
    • There is no fallback or NACK on the receive side.
    • Still at #44.
  2. [minor] A zero-size matmul or einsum builds the dense result on the client.
    • Where: einsum.py:454-460, reached from charmnumeric.py:1462.
    • Example: ones((50000,0)) @ ones((0,50000)) allocates a 20 GB zeros array in the client process and uploads it.
    • Fix: when the zero-size label is contracted, the result is just a native zeros(shape).
    • Still at #44.
  3. [minor, performance] The IPC arena never merges freed blocks (gpu_comm.hpp:153-163).
    • After bursts of small messages split the big blocks, large same-host messages fall back to host staging for the rest of the job.
    • Fixed in #17.
  4. Nits:
    • CPU integer batched GEMM relies on signed overflow, which is undefined behaviour, for wraparound (executor_signal.cpp:1049). The GPU kernel deliberately accumulates in unsigned.
    • Per-thread MLIR contexts are never freed and now intern each kernel's cubin (jit.cpp:139, :1327), so memory grows in a long-lived server.
    • CODEMAP says non-NVIDIA builds use a Kokkos kernel for ints, but they use the naive kernel for every dtype.

…igned; clearer IPC map error

A zero-size contraction returns a native zeros(shape) instead of building the dense
result on the client. The CPU integer batched GEMM multiplies as unsigned so wraparound
is defined. The receive-side IPC mapping failure names the slab and the remedy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@AdvaitTahilyani

Copy link
Copy Markdown
Author
  1. IPC mapping failure on the receive side: follow-up for the NACK/staging fallback: it needs new entry methods on all three partition ranks plus a resend path on the sender, too invasive here. The abort now names the slab, size and both processes, and gives the remedy (CNUM_GPU_IPC=0), in acebbd3.
  2. Zero-size contracted matmul/einsum: fixed in acebbd3 (native zeros(shape) when only contracted labels are empty; tests in test_einsum.py, including a tracemalloc check that the client does not build the result).
  3. IPC arena never merges freed blocks: fixed in Memory: fix leaks and allocation churn at large sizes #17 already.
    4a. CPU integer batched GEMM signed overflow: fixed in acebbd3 (multiplied as unsigned).
    4b. Per-thread MLIR contexts never freed: follow-up: recycling a context safely needs the compiler's modules and ExecutionEngines to be proven independent of it; growth is bounded by the number of distinct kernels.
    4c. CODEMAP wording on non-NVIDIA int kernels: fixed in acebbd3.

Validated: nc build; CPU regress at +p1: orig 15/15, ports 25/25, ops 26/26, no problems. The gpu_comm.hpp message change is GPU-only and not compiled in the nc build.

AdvaitTahilyani and others added 4 commits November 10, 2026 15:59
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants