Skip to content

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold

Python
44.2 KB
Raw Blame
diff --git tensorfold/cuda/roce.cpp tensorfold/cuda/roce.cpp
new file mode 100644
index 0000000..285de55
--- /dev/null
+++ tensorfold/cuda/roce.cpp
@@ -0,0 +1,23 @@
+#include <torch/extension.h>
+#include <c10/cuda/CUDAGuard.h>
+
+void roce_gather_cuda(const at::Tensor&, at::Tensor&, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t,
+                      int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t, int64_t,
+                      int64_t, int64_t);
+
+void gather(const at::Tensor& in, at::Tensor out, int64_t shard_packs, int64_t nbytes, int64_t row_packs,
+            int64_t recv_base, int64_t flag_base, int64_t send_base, int64_t ctrl, int64_t slot_bytes, int64_t epoch,
+            int64_t stage_ctr, int64_t tail_ctr, int64_t poison, int64_t spin_limit, int64_t world, int64_t rank,
+            int64_t slots, int64_t flag_stride, int64_t n_hca, int64_t grid, int64_t threads) {
+    TORCH_CHECK(in.is_cuda() && out.is_cuda() && in.is_contiguous() && out.is_contiguous(),
+                "roce gather: contiguous CUDA tensors");
+    TORCH_CHECK(reinterpret_cast<uintptr_t>(in.data_ptr()) % 16 == 0 &&
+                reinterpret_cast<uintptr_t>(out.data_ptr()) % 16 == 0, "roce gather: 16-byte aligned tensors");
+    const at::cuda::CUDAGuard guard(in.device());
+    roce_gather_cuda(in, out, shard_packs, nbytes, row_packs, recv_base, flag_base, send_base, ctrl, slot_bytes, epoch,
+                     stage_ctr, tail_ctr, poison, spin_limit, world, rank, slots, flag_stride, n_hca, grid, threads);
+}
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+    m.def("gather", &gather, "one-shot RoCE all-gather (b12x's RoCEnante protocol)");
+}
diff --git tensorfold/cuda/roce.cu tensorfold/cuda/roce.cu
new file mode 100644
index 0000000..541c9d6
--- /dev/null
+++ tensorfold/cuda/roce.cu
@@ -0,0 +1,143 @@
+// One-shot RoCE all-gather between DGX Sparks: the GPU side of b12x's "RoCEnante" protocol
+// (https://github.com/local-inference-lab/b12x, b12x/comm/roce/_allgather_cute.py at commit
+// 8a99d639410e39d5f39cb4037675331beceea1d4, Copyright the b12x contributors, Apache License 2.0),
+// reimplemented in CUDA C++ from its CuTe DSL kernel with the same stages and memory orderings.
+//
+// The pinned host region (roce_proxy.c) holds, per rank: recv[src][slot], flag[src][slot][hca], send[slot] and a
+// control record {seq, nbytes, error seq, missing peer, nbytes of slot 0, nbytes of slot 1, missing hca}. One launch:
+//   1. every block stages its share of the local shard into send[seq & 1];
+//   2. the last block to finish staging (a free-running arrival counter) publishes nbytes and rings ctrl.seq after
+//      a system fence; the proxy thread RDMA-writes the payload to every peer, then a flag per HCA stripe;
+//   3. one thread per (peer, HCA) spins on that stripe's flag with system-scope acquire loads (a limit poisons);
+//   4. every block copies the shards in rank order: its own from the input, the peers' from the NIC-written slots;
+//   5. the last block to finish advances the device epoch, so CUDA graphs replay the exchange.
+
+#include <ATen/ATen.h>
+#include <ATen/cuda/CUDAContext.h>
+#include <c10/cuda/CUDAGuard.h>
+#include <cuda_runtime.h>
+#include <stdint.h>
+
+namespace {
+
+__device__ __forceinline__ uint32_t ld_relaxed_gpu(const uint32_t* p) {
+    uint32_t v;
+    asm volatile("ld.relaxed.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory");
+    return v;
+}
+__device__ __forceinline__ uint32_t ld_relaxed_sys(const uint32_t* p) {
+    uint32_t v;
+    asm volatile("ld.relaxed.sys.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory");
+    return v;
+}
+__device__ __forceinline__ uint32_t ld_acquire_sys(const uint32_t* p) {
+    uint32_t v;
+    asm volatile("ld.acquire.sys.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory");
+    return v;
+}
+__device__ __forceinline__ uint4 ld_relaxed_sys_v4(const uint4* p) {
+    uint4 v;
+    asm volatile("ld.relaxed.sys.global.v4.u32 {%0, %1, %2, %3}, [%4];"
+                 : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w) : "l"(p) : "memory");
+    return v;
+}
+__device__ __forceinline__ void st_relaxed_sys(uint32_t* p, uint32_t v) {
+    asm volatile("st.relaxed.sys.global.u32 [%0], %1;" ::"l"(p), "r"(v) : "memory");
+}
+__device__ __forceinline__ void st_release_gpu(uint32_t* p, uint32_t v) {
+    asm volatile("st.release.gpu.global.u32 [%0], %1;" ::"l"(p), "r"(v) : "memory");
+}
+__device__ __forceinline__ uint32_t atom_add_relaxed_gpu(uint32_t* p, uint32_t v) {
+    uint32_t old;
+    asm volatile("atom.relaxed.gpu.global.add.u32 %0, [%1], %2;" : "=r"(old) : "l"(p), "r"(v) : "memory");
+    return old;
+}
+__device__ __forceinline__ void fence_sc_sys() { asm volatile("fence.sc.sys;" ::: "memory"); }
+__device__ __forceinline__ void fence_sc_gpu() { asm volatile("fence.sc.gpu;" ::: "memory"); }
+
+// ctrl record, in 32-bit words
+constexpr int C_SEQ = 0, C_NBYTES = 1, C_ERROR = 2, C_PEER = 3, C_SLOT_NBYTES = 4, C_HCA = 6;
+
+__global__ void gather_kernel(const uint4* __restrict__ in, uint4* __restrict__ out, int shard_packs, uint32_t nbytes,
+                              int row_packs, char* recv_base, char* flag_base, char* send_base, uint32_t* ctrl,
+                              long long slot_bytes, uint32_t* epoch, uint32_t* stage_ctr, uint32_t* tail_ctr,
+                              uint32_t* poison, uint32_t spin_limit, int world, int rank, int slots, int flag_stride,
+                              int n_hca) {
+    const int tid = threadIdx.x;
+    const uint32_t seq = ld_relaxed_gpu(epoch) + 1u;
+    const uint32_t slot = seq & 1u;
+    uint4* send_slot = reinterpret_cast<uint4*>(send_base + (long long)slot * slot_bytes);
+    const int index = blockIdx.x * blockDim.x + tid, stride = gridDim.x * blockDim.x;
+    // a recorded timeout poisons the runtime: later launches do nothing until the host raises
+    if (ld_relaxed_gpu(poison) != 0u) return;
+
+    for (int i = index; i < shard_packs; i += stride) send_slot[i] = in[i];                         // 1. stage
+    __syncthreads();
+    if (tid == 0) {                                                                                 // 2. doorbell
+        fence_sc_sys();
+        const uint32_t prior = atom_add_relaxed_gpu(stage_ctr, 1u);
+        if ((prior + 1u) % gridDim.x == 0u) {
+            st_relaxed_sys(ctrl + C_NBYTES, nbytes);
+            st_relaxed_sys(ctrl + C_SLOT_NBYTES + slot, nbytes);
+            fence_sc_sys();
+            st_relaxed_sys(ctrl + C_SEQ, seq);
+        }
+    }
+    if (tid < world * n_hca) {                                                                      // 3. wait
+        const int peer = tid / n_hca, hca = tid - peer * n_hca;
+        if (peer != rank) {
+            const uint32_t* flag = reinterpret_cast<const uint32_t*>(
+                flag_base + (((long long)peer * slots + slot) * n_hca + hca) * flag_stride);
+            uint32_t polls = 0;
+            while (ld_acquire_sys(flag) != seq) {
+                if (++polls >= spin_limit) {
+                    st_relaxed_sys(ctrl + C_PEER, (uint32_t)peer);
+                    st_relaxed_sys(ctrl + C_HCA, (uint32_t)hca);
+                    st_relaxed_sys(ctrl + C_ERROR, seq);
+                    st_release_gpu(poison, seq);
+                    break;
+                }
+            }
+        }
+    }
+    __syncthreads();
+    if (ld_relaxed_gpu(poison) == 0u) {                                                             // 4. copy out
+        const int out_row_packs = world * row_packs;
+        for (int source = 0; source < world; ++source) {
+            const uint4* peer_slot = reinterpret_cast<const uint4*>(
+                recv_base + ((long long)source * slots + slot) * slot_bytes);
+            for (int i = index; i < shard_packs; i += stride) {
+                const int row = i / row_packs, col = i - row * row_packs;
+                const uint4 w = source == rank ? in[i] : ld_relaxed_sys_v4(peer_slot + i);
+                out[(long long)row * out_row_packs + (long long)source * row_packs + col] = w;
+            }
+        }
+    }
+    fence_sc_gpu();                                                                                 // 5. epoch
+    __syncthreads();
+    if (tid == 0) {
+        const uint32_t prior = atom_add_relaxed_gpu(tail_ctr, 1u);
+        if ((prior + 1u) % gridDim.x == 0u) {
+            fence_sc_gpu();
+            if (ld_relaxed_sys(ctrl + C_ERROR) == 0u) st_release_gpu(epoch, seq);
+        }
+    }
+}
+
+}  // namespace
+
+void roce_gather_cuda(const at::Tensor& in, at::Tensor& out, int64_t shard_packs, int64_t nbytes, int64_t row_packs,
+                      int64_t recv_base, int64_t flag_base, int64_t send_base, int64_t ctrl, int64_t slot_bytes,
+                      int64_t epoch, int64_t stage_ctr, int64_t tail_ctr, int64_t poison, int64_t spin_limit,
+                      int64_t world, int64_t rank, int64_t slots, int64_t flag_stride, int64_t n_hca, int64_t grid,
+                      int64_t threads) {
+    auto stream = at::cuda::getCurrentCUDAStream();
+    gather_kernel<<<(unsigned)grid, (unsigned)threads, 0, stream>>>(
+        reinterpret_cast<const uint4*>(in.data_ptr()), reinterpret_cast<uint4*>(out.data_ptr()), (int)shard_packs,
+        (uint32_t)nbytes, (int)row_packs, reinterpret_cast<char*>(recv_base), reinterpret_cast<char*>(flag_base),
+        reinterpret_cast<char*>(send_base), reinterpret_cast<uint32_t*>(ctrl), (long long)slot_bytes,
+        reinterpret_cast<uint32_t*>(epoch), reinterpret_cast<uint32_t*>(stage_ctr),
+        reinterpret_cast<uint32_t*>(tail_ctr), reinterpret_cast<uint32_t*>(poison), (uint32_t)spin_limit, (int)world,
+        (int)rank, (int)slots, (int)flag_stride, (int)n_hca);
+    C10_CUDA_KERNEL_LAUNCH_CHECK();
+}
diff --git tensorfold/cuda/roce.py tensorfold/cuda/roce.py
new file mode 100644
index 0000000..52bc376
--- /dev/null
+++ tensorfold/cuda/roce.py
@@ -0,0 +1,200 @@
+"""One-shot RoCE all-gather for two DGX Sparks: b12x's "RoCEnante" transport (https://github.com/local-inference-lab/b12x,
+Apache License 2.0; the C proxy is theirs, roce_proxy.c; the GPU side is roce.cu, rewritten from their CuTe kernel).
+
+A decode round's all-gathers are small (a verify window's partials: rows x 4,096 fp32) and NCCL spends most of each
+in fixed latency (~30-50 us). Here the GB10 GPU writes its shard into pinned host memory the ConnectX-7 RDMA-writes
+to the peer, and reads the peer's shard from its own pinned memory in place: one kernel, no NCCL proxy handoff.
+``RoceComm`` sends gathers of up to ``max_bytes`` a rank this way and the rest through NCCL, with the same output
+layout (rank order), the same bits, and a device-side epoch so CUDA graphs replay it.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import hashlib
+import os
+import shutil
+import subprocess
+import threading
+from functools import lru_cache
+from pathlib import Path
+
+import torch
+
+_SOURCE = Path(__file__).with_name("roce_proxy.c")
+_LOCK = threading.Lock()
+SLOT_ALIGN = 4096
+PACK = 16
+THREADS = 512
+BLOCKS = 8                               # the largest grid; smaller shards launch fewer (power-of-two) blocks
+SPIN_LIMIT = 20_000_000                  # flag polls (~1 us each) before a wait poisons the runtime: ~20 s
+
+
+def _cache_dir() -> Path:
+    root = os.environ.get("TORCH_EXTENSIONS_DIR") or os.path.join(os.path.expanduser("~"), ".cache", "tensorfold")
+    return Path(root) / "roce"
+
+
+@lru_cache(maxsize=1)
+def proxy_library() -> ctypes.CDLL:
+    """Build roce_proxy.c with the host C compiler and libibverbs once per source hash, and bind it."""
+
+    with _LOCK:
+        source = _SOURCE.read_bytes()
+        target = _cache_dir() / f"roce_proxy-{hashlib.sha256(source).hexdigest()[:16]}.so"
+        if not target.exists():
+            cc = next((c for c in (os.environ.get("CC"), "gcc", "cc", "clang") if c and shutil.which(c)), None)
+            if cc is None:
+                raise RuntimeError("the RoCE all-gather needs a C compiler and libibverbs headers")
+            target.parent.mkdir(parents=True, exist_ok=True)
+            tmp = target.with_name(f".{target.name}.{os.getpid()}")
+            cmd = [cc, "-O2", "-std=gnu11", "-shared", "-fPIC", "-o", str(tmp), str(_SOURCE), "-libverbs", "-lpthread"]
+            done = subprocess.run(cmd, capture_output=True, text=True)
+            if done.returncode != 0:
+                raise RuntimeError("building the RoCE proxy failed: " + " ".join(cmd) + "\n" + done.stderr)
+            os.replace(tmp, target)
+        lib = ctypes.CDLL(str(target), use_errno=True)
+    u64, p, i = ctypes.c_uint64, ctypes.c_void_p, ctypes.c_int
+    for name, res, args in (
+            ("roce_abi_version", i, []), ("roce_layout", i, [i, u64, ctypes.POINTER(u64)]),
+            ("roce_blob_bytes", u64, []),
+            ("roce_create", p, [i, i, ctypes.POINTER(ctypes.c_char_p), i, i, i, p, u64, u64, ctypes.c_char_p, u64]),
+            ("roce_local_blob", i, [p, p, u64]), ("roce_connect", i, [p, p, u64]), ("roce_start", i, [p]),
+            ("roce_stop", None, [p]), ("roce_failed", i, [p]), ("roce_error", ctypes.c_char_p, [p]),
+            ("roce_destroy", None, [p])):
+        fn = getattr(lib, name)
+        fn.restype, fn.argtypes = res, args
+    if lib.roce_abi_version() != 4:
+        raise RuntimeError("unexpected RoCE proxy ABI version")
+    return lib
+
+
+@lru_cache(maxsize=1)
+def _ext():
+    from tensorfold.cuda.build import load
+
+    here = Path(__file__).parent
+    return load(name="tensorfold_roce_v1", sources=[str(here / "roce.cpp"), str(here / "roce.cu")],
+                extra_cuda_cflags=["-O3"], verbose=False)
+
+
+def _hcas() -> list[str]:
+    raw = os.environ.get("TF_ROCE_HCA") or os.environ.get("NCCL_IB_HCA") or ""
+    names = [x.strip().lstrip("=^").split(":")[0] for x in raw.split(",") if x.strip()]
+    if not names:
+        root = Path("/sys/class/infiniband")
+        names = [d.name for d in sorted(root.glob("*")) if "ACTIVE" in (d / "ports/1/state").read_text()]
+    return names[:2]
+
+
+class RoceGather:
+    """One rank's side of the exchange: the pinned region, the proxy thread and the gather launches."""
+
+    def __init__(self, comm, rank: int, world: int, max_bytes: int = 256 << 10) -> None:
+        lib = proxy_library()
+        self.lib, self.rank, self.world, self.max_bytes = lib, rank, world, int(max_bytes)
+        self.slot_bytes = -(-self.max_bytes // SLOT_ALIGN) * SLOT_ALIGN
+        out = (ctypes.c_uint64 * 7)()
+        if lib.roce_layout(world, self.slot_bytes, out) != 0:
+            raise ValueError(f"RoCE layout refused world {world}, slot {self.slot_bytes}")
+        recv_off, flag_off, send_off, ctrl_off, total, self.flag_stride, self.slots = (int(v) for v in out)
+        self.region = torch.zeros(total, dtype=torch.uint8, pin_memory=True)   # flags and ctrl start at 0
+        base = self.region.data_ptr()
+        self.recv, self.flag, self.send, self.ctrl = base + recv_off, base + flag_off, base + send_off, base + ctrl_off
+        self.ctrl_words = self.region[ctrl_off:ctrl_off + 28].view(torch.int32).numpy()
+        self.classes = BLOCKS.bit_length()
+        # epoch, stage arrivals and tail arrivals by power-of-two grid, poison
+        self.counters = torch.zeros(2 + 2 * self.classes, dtype=torch.int32, device="cuda")
+        self.hcas = _hcas()
+        gid = int(os.environ.get("TF_ROCE_GID_INDEX") or os.environ.get("NCCL_IB_GID_INDEX") or 3)
+        tc = int(os.environ.get("NCCL_IB_TC", "0"), 0)
+        names = (ctypes.c_char_p * len(self.hcas))(*[n.encode() for n in self.hcas])
+        err = ctypes.create_string_buffer(512)
+        self.ctx = lib.roce_create(world, rank, names, len(self.hcas), gid, tc, ctypes.c_void_p(base), total,
+                                   self.slot_bytes, err, len(err))
+        failed = 0 if self.ctx else 1
+        blob_len = int(lib.roce_blob_bytes())
+        blob = ctypes.create_string_buffer(blob_len)
+        if not failed and lib.roce_local_blob(self.ctx, blob, blob_len) != 0:
+            failed = 1
+        # both ranks' verdict, geometry and connection blob through the existing communicator
+        words = -(-blob_len // 4)
+        mine = torch.zeros(4 + words, dtype=torch.int32)
+        mine[:4] = torch.tensor([failed, len(self.hcas), self.slot_bytes >> 12, self.flag_stride])
+        raw = torch.frombuffer(bytearray(blob.raw.ljust(words * 4, b"\0")), dtype=torch.int32)
+        mine[4:] = raw
+        got = torch.empty(world * mine.numel(), dtype=torch.int32, device="cuda")
+        comm.all_gather(mine.cuda(), got)
+        rows = got.view(world, -1).cpu()
+        if int(rows[:, 0].sum()) or len(set(tuple(r[1:4].tolist()) for r in rows)) != 1:
+            why = err.value.decode(errors="replace") if not self.ctx else "the ranks' RoCE geometry differs"
+            self.close()
+            raise RuntimeError(f"RoCE all-gather setup failed on some rank: {why}")
+        blobs = b"".join(bytes(r[4:].numpy().tobytes())[:blob_len] for r in rows)
+        ok = lib.roce_connect(self.ctx, blobs, len(blobs)) == 0 and lib.roce_start(self.ctx) == 0
+        verdict = torch.tensor([0 if ok else 1], dtype=torch.int32, device="cuda")
+        both = torch.empty(world, dtype=torch.int32, device="cuda")
+        comm.all_gather(verdict, both)
+        if int(both.sum()):
+            why = lib.roce_error(self.ctx).decode(errors="replace") if self.ctx else ""
+            self.close()
+            raise RuntimeError(f"RoCE all-gather could not connect: {why}")
+
+    def fits(self, send: torch.Tensor) -> bool:
+        n = send.numel() * send.element_size()
+        return 0 < n <= self.max_bytes and n % PACK == 0 and send.data_ptr() % PACK == 0 and send.is_contiguous()
+
+    def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None:
+        nbytes = send.numel() * send.element_size()
+        packs = nbytes // PACK
+        need = max(1, -(-packs // (2 * THREADS)))
+        grid = min(1 << (need - 1).bit_length(), BLOCKS)
+        klass = grid.bit_length() - 1
+        c = self.counters.data_ptr()
+        _ext().gather(send, recv, packs, nbytes, packs, self.recv, self.flag, self.send, self.ctrl, self.slot_bytes,
+                      c, c + 4 * (1 + klass), c + 4 * (1 + self.classes + klass), c + 4 * (1 + 2 * self.classes),
+                      SPIN_LIMIT, self.world, self.rank, self.slots, self.flag_stride, len(self.hcas), grid, THREADS)
+        if not torch.cuda.is_current_stream_capturing():
+            self.check()
+
+    def check(self) -> None:
+        """Raise if a wait timed out on the GPU or the proxy thread failed."""
+
+        if self.ctrl_words[2] != 0 or (self.ctx and self.lib.roce_failed(self.ctx)):
+            peer, hca = int(self.ctrl_words[3]), int(self.ctrl_words[6])
+            why = self.lib.roce_error(self.ctx).decode(errors="replace") if self.ctx else ""
+            raise RuntimeError(f"RoCE all-gather failed (sequence {int(self.ctrl_words[2])}, peer {peer}, hca {hca})"
+                               f"{': ' + why if why else ''}")
+
+    def close(self) -> None:
+        if getattr(self, "ctx", None):
+            self.lib.roce_stop(self.ctx)
+            self.lib.roce_destroy(self.ctx)
+            self.ctx = None
+
+
+class RoceComm:
+    """NCCL with small all-gathers over RoCE: the same call, output layout and bits."""
+
+    def __init__(self, nccl, rank: int, world: int, max_bytes: int | None = None) -> None:
+        self.nccl, self.rank, self.world = nccl, rank, world
+        limit = int(os.environ.get("TF_ROCE_MAX_KB", "256")) << 10 if max_bytes is None else max_bytes
+        self.roce = RoceGather(nccl, rank, world, limit)
+        self.small = self.large = 0
+
+    def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None:
+        if self.roce.fits(send) and recv.is_contiguous() and recv.data_ptr() % PACK == 0:
+            self.small += 1
+            self.roce.all_gather(send, recv)
+        else:
+            self.large += 1
+            self.nccl.all_gather(send, recv)
+
+    def barrier(self) -> None:
+        self.nccl.barrier()
+
+    def check(self) -> None:
+        self.roce.check()
+
+    def __getattr__(self, name):
+        return getattr(self.nccl, name)
diff --git tensorfold/cuda/roce_proxy.c tensorfold/cuda/roce_proxy.c
new file mode 100644
index 0000000..5e605ae
--- /dev/null
+++ tensorfold/cuda/roce_proxy.c
@@ -0,0 +1,621 @@
+// Adapted from b12x (https://github.com/local-inference-lab/b12x), b12x/comm/roce/_roce_proxy.c at commit
+// 8a99d639410e39d5f39cb4037675331beceea1d4: "RoCEnante", Copyright the b12x contributors, Apache License 2.0
+// (http://www.apache.org/licenses/LICENSE-2.0). Unchanged except this header. Used by tensorfold/cuda/roce.py.
+
+// RDMA proxy for the b12x RoCE one-shot all-reduce.
+//
+// One rank owns one pinned host region laid out as:
+//
+//   recv[src][slot]  (world * SLOTS * slot_bytes)  filled by peers' RDMA writes
+//   flag[src][slot][hca] sequence number written on each HCA after that HCA's
+//                         payload stripe
+//   send[slot]       (SLOTS * slot_bytes)          staged by the local GPU kernel
+//   ctrl             (FLAG_STRIDE)                 {u32 seq, u32 nbytes, u32 error,
+//                                                   u32 missing_peer} doorbell; the
+//                                                  last two are set by the kernel
+//                                                  when a wait times out
+//
+// The GPU kernel stages its input into send[seq & 1], publishes nbytes and seq
+// in ctrl, then spins on flag[peer][seq & 1][hca] for every peer and HCA.  The
+// proxy thread
+// below spins on ctrl.seq and, for every peer, stripes the payload across every
+// HCA.  Each stripe is followed by its own 4-byte seq write on the same reliable
+// QP, so its flag cannot become visible before its payload.  The GPU waits for
+// every stripe flag before consuming the receive slot.  Nothing on the receive
+// path involves the host.
+//
+// This file is compiled by b12x.comm.roce._proxy at first use with the host
+// gcc and libibverbs; it must stay plain C with no CUDA dependency.
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <infiniband/verbs.h>
+#include <pthread.h>
+#include <sched.h>
+#include <stdatomic.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#define ROCE_MAX_PEERS 16
+#define ROCE_MAX_HCAS 2
+#define ROCE_SLOTS 2
+#define ROCE_FLAG_STRIDE 128
+#define ROCE_PORT 1
+#define ROCE_SEND_DEPTH 256
+#define ROCE_ABI_VERSION 4
+// Model graphs leave sub-millisecond gaps between collectives.  Keep the
+// proxy hot across those gaps; sleeping there adds one scheduler wakeup to
+// every collective on the graph's critical path.
+#define ROCE_IDLE_SPINS 20000000
+
+typedef struct {
+    uint64_t region_addr;
+    uint32_t rkey[ROCE_MAX_HCAS];
+    uint16_t lid[ROCE_MAX_HCAS];
+    uint8_t gid[ROCE_MAX_HCAS][16];
+    uint32_t mtu[ROCE_MAX_HCAS];
+    uint32_t qp_num[ROCE_MAX_HCAS][ROCE_MAX_PEERS];
+} roce_blob_t;
+
+typedef struct {
+    struct ibv_context *ctx;
+    struct ibv_pd *pd;
+    struct ibv_mr *mr;
+    struct ibv_cq *cq;
+    struct ibv_qp *qp[ROCE_MAX_PEERS];
+    uint32_t outstanding[ROCE_MAX_PEERS];
+    uint64_t writes_completed;
+    uint64_t bytes_posted;
+    union ibv_gid gid;
+    uint16_t lid;
+    enum ibv_mtu mtu;
+} roce_hca_t;
+
+typedef struct {
+    int world;
+    int rank;
+    int n_hca;
+    int gid_index;
+    int traffic_class;
+    roce_hca_t hca[ROCE_MAX_HCAS];
+    uint8_t *region;
+    size_t region_bytes;
+    size_t slot_bytes;
+    size_t recv_off;
+    size_t flag_off;
+    size_t send_off;
+    size_t ctrl_off;
+    int started;
+    uint64_t peer_addr[ROCE_MAX_PEERS];
+    uint32_t peer_rkey[ROCE_MAX_HCAS][ROCE_MAX_PEERS];
+    pthread_t thread;
+    atomic_int running;
+    atomic_int failed;
+    uint32_t last_seq;
+    uint64_t ops_posted;
+    uint64_t writes_completed;
+    char err[512];
+} roce_ctx_t;
+
+void roce_destroy(roce_ctx_t *c);
+
+static void set_err(roce_ctx_t *c, const char *what, int e) {
+    snprintf(c->err, sizeof(c->err), "%s: %s", what, e ? strerror(e) : "failed");
+}
+
+int roce_abi_version(void) { return ROCE_ABI_VERSION; }
+
+int roce_layout(int world, uint64_t slot_bytes, uint64_t *out) {
+    // out = {recv_off, flag_off, send_off, ctrl_off, total_bytes, flag_stride, slots}
+    if (world < 2 || world > ROCE_MAX_PEERS || slot_bytes == 0 || (slot_bytes % 4096) != 0) {
+        return -1;
+    }
+    // Reject a layout whose arithmetic would wrap; the caller sizes slots from
+    // configuration, so a wrapped region must fail here rather than at the NIC.
+    uint64_t recv_bytes, flag_bytes, send_bytes, send_off, ctrl_off, total;
+    if (slot_bytes > ((uint64_t)1 << 40) ||
+        __builtin_mul_overflow((uint64_t)world * ROCE_SLOTS, slot_bytes, &recv_bytes) ||
+        __builtin_mul_overflow(
+            (uint64_t)world * ROCE_SLOTS * ROCE_MAX_HCAS,
+            (uint64_t)ROCE_FLAG_STRIDE,
+            &flag_bytes) ||
+        __builtin_mul_overflow((uint64_t)ROCE_SLOTS, slot_bytes, &send_bytes) ||
+        __builtin_add_overflow(recv_bytes, flag_bytes, &send_off) ||
+        __builtin_add_overflow(send_off, send_bytes, &ctrl_off) ||
+        __builtin_add_overflow(ctrl_off, (uint64_t)ROCE_FLAG_STRIDE, &total)) {
+        return -1;
+    }
+    uint64_t recv_off = 0;
+    uint64_t flag_off = recv_off + recv_bytes;
+    out[0] = recv_off;
+    out[1] = flag_off;
+    out[2] = send_off;
+    out[3] = ctrl_off;
+    out[4] = total;
+    out[5] = ROCE_FLAG_STRIDE;
+    out[6] = ROCE_SLOTS;
+    return 0;
+}
+
+uint64_t roce_blob_bytes(void) { return sizeof(roce_blob_t); }
+
+static int open_hca(roce_ctx_t *c, int h, const char *name) {
+    int num = 0;
+    struct ibv_device **list = ibv_get_device_list(&num);
+    if (list == NULL) {
+        set_err(c, "ibv_get_device_list", errno);
+        return -1;
+    }
+    struct ibv_device *dev = NULL;
+    for (int i = 0; i < num; i++) {
+        if (strcmp(ibv_get_device_name(list[i]), name) == 0) {
+            dev = list[i];
+            break;
+        }
+    }
+    if (dev == NULL) {
+        ibv_free_device_list(list);
+        snprintf(c->err, sizeof(c->err), "RDMA device %s not found", name);
+        return -1;
+    }
+    roce_hca_t *hca = &c->hca[h];
+    hca->ctx = ibv_open_device(dev);
+    ibv_free_device_list(list);
+    if (hca->ctx == NULL) {
+        set_err(c, "ibv_open_device", errno);
+        return -1;
+    }
+    struct ibv_port_attr port;
+    if (ibv_query_port(hca->ctx, ROCE_PORT, &port) != 0) {
+        set_err(c, "ibv_query_port", errno);
+        return -1;
+    }
+    if (port.state != IBV_PORT_ACTIVE) {
+        snprintf(c->err, sizeof(c->err), "RDMA device %s port %d is not active", name, ROCE_PORT);
+        return -1;
+    }
+    hca->lid = port.lid;
+    hca->mtu = port.active_mtu;
+    if (ibv_query_gid(hca->ctx, ROCE_PORT, c->gid_index, &hca->gid) != 0) {
+        set_err(c, "ibv_query_gid", errno);
+        return -1;
+    }
+    hca->pd = ibv_alloc_pd(hca->ctx);
+    if (hca->pd == NULL) {
+        set_err(c, "ibv_alloc_pd", errno);
+        return -1;
+    }
+    hca->mr = ibv_reg_mr(hca->pd, c->region, c->region_bytes,
+                         IBV_ACCESS_LOCAL_WRITE | IBV_ACCESS_REMOTE_WRITE);
+    if (hca->mr == NULL) {
+        set_err(c, "ibv_reg_mr(pinned region)", errno);
+        return -1;
+    }
+    hca->cq = ibv_create_cq(hca->ctx, ROCE_SEND_DEPTH * ROCE_MAX_PEERS, NULL, NULL, 0);
+    if (hca->cq == NULL) {
+        set_err(c, "ibv_create_cq", errno);
+        return -1;
+    }
+    for (int p = 0; p < c->world; p++) {
+        if (p == c->rank) {
+            continue;
+        }
+        struct ibv_qp_init_attr attr;
+        memset(&attr, 0, sizeof(attr));
+        attr.send_cq = hca->cq;
+        attr.recv_cq = hca->cq;
+        attr.qp_type = IBV_QPT_RC;
+        attr.cap.max_send_wr = ROCE_SEND_DEPTH;
+        attr.cap.max_recv_wr = 1;
+        attr.cap.max_send_sge = 1;
+        attr.cap.max_recv_sge = 1;
+        attr.cap.max_inline_data = 16;
+        hca->qp[p] = ibv_create_qp(hca->pd, &attr);
+        if (hca->qp[p] == NULL) {
+            set_err(c, "ibv_create_qp", errno);
+            return -1;
+        }
+        struct ibv_qp_attr init;
+        memset(&init, 0, sizeof(init));
+        init.qp_state = IBV_QPS_INIT;
+        init.pkey_index = 0;
+        init.port_num = ROCE_PORT;
+        init.qp_access_flags = IBV_ACCESS_REMOTE_WRITE;
+        int rc = ibv_modify_qp(hca->qp[p], &init,
+                               IBV_QP_STATE | IBV_QP_PKEY_INDEX | IBV_QP_PORT | IBV_QP_ACCESS_FLAGS);
+        if (rc != 0) {
+            set_err(c, "ibv_modify_qp(INIT)", rc);
+            return -1;
+        }
+    }
+    return 0;
+}
+
+roce_ctx_t *roce_create(int world, int rank, const char *const *hca_names, int n_hca,
+                        int gid_index, int traffic_class, void *region, uint64_t region_bytes,
+                        uint64_t slot_bytes, char *err, uint64_t err_len) {
+    uint64_t layout[7];
+    if (roce_layout(world, slot_bytes, layout) != 0 || layout[4] > region_bytes ||
+        rank < 0 || rank >= world || n_hca < 1 || n_hca > ROCE_MAX_HCAS ||
+        traffic_class < 0 || traffic_class > 255) {
+        snprintf(err, err_len, "invalid roce runtime geometry");
+        return NULL;
+    }
+    roce_ctx_t *c = calloc(1, sizeof(*c));
+    if (c == NULL) {
+        snprintf(err, err_len, "out of memory");
+        return NULL;
+    }
+    c->world = world;
+    c->rank = rank;
+    c->n_hca = n_hca;
+    c->gid_index = gid_index;
+    c->traffic_class = traffic_class;
+    c->region = region;
+    c->region_bytes = region_bytes;
+    c->slot_bytes = slot_bytes;
+    c->recv_off = layout[0];
+    c->flag_off = layout[1];
+    c->send_off = layout[2];
+    c->ctrl_off = layout[3];
+    for (int h = 0; h < n_hca; h++) {
+        if (open_hca(c, h, hca_names[h]) != 0) {
+            snprintf(err, err_len, "%s", c->err);
+            roce_destroy(c);
+            return NULL;
+        }
+    }
+    return c;
+}
+
+int roce_local_blob(roce_ctx_t *c, void *out, uint64_t out_len) {
+    if (out_len < sizeof(roce_blob_t)) {
+        return -1;
+    }
+    roce_blob_t blob;
+    memset(&blob, 0, sizeof(blob));
+    blob.region_addr = (uint64_t)(uintptr_t)c->region;
+    for (int h = 0; h < c->n_hca; h++) {
+        blob.rkey[h] = c->hca[h].mr->rkey;
+        blob.lid[h] = c->hca[h].lid;
+        blob.mtu[h] = (uint32_t)c->hca[h].mtu;
+        memcpy(blob.gid[h], c->hca[h].gid.raw, 16);
+        for (int p = 0; p < c->world; p++) {
+            blob.qp_num[h][p] = (p == c->rank) ? 0 : c->hca[h].qp[p]->qp_num;
+        }
+    }
+    memcpy(out, &blob, sizeof(blob));
+    return 0;
+}
+
+static int connect_qp(roce_ctx_t *c, int h, int p, const roce_blob_t *peer) {
+    roce_hca_t *hca = &c->hca[h];
+    struct ibv_qp_attr rtr;
+    memset(&rtr, 0, sizeof(rtr));
+    rtr.qp_state = IBV_QPS_RTR;
+    rtr.path_mtu = (enum ibv_mtu)(peer->mtu[h] < (uint32_t)hca->mtu ? peer->mtu[h] : (uint32_t)hca->mtu);
+    rtr.dest_qp_num = peer->qp_num[h][c->rank];
+    rtr.rq_psn = 0;
+    rtr.max_dest_rd_atomic = 1;
+    rtr.min_rnr_timer = 12;
+    rtr.ah_attr.is_global = 1;
+    rtr.ah_attr.dlid = peer->lid[h];
+    rtr.ah_attr.sl = 0;
+    rtr.ah_attr.src_path_bits = 0;
+    rtr.ah_attr.port_num = ROCE_PORT;
+    memcpy(rtr.ah_attr.grh.dgid.raw, peer->gid[h], 16);
+    rtr.ah_attr.grh.sgid_index = (uint8_t)c->gid_index;
+    rtr.ah_attr.grh.hop_limit = 64;
+    rtr.ah_attr.grh.traffic_class = (uint8_t)c->traffic_class;
+    rtr.ah_attr.grh.flow_label = 0;
+    int rc = ibv_modify_qp(hca->qp[p], &rtr,
+                           IBV_QP_STATE | IBV_QP_AV | IBV_QP_PATH_MTU | IBV_QP_DEST_QPN |
+                               IBV_QP_RQ_PSN | IBV_QP_MAX_DEST_RD_ATOMIC | IBV_QP_MIN_RNR_TIMER);
+    if (rc != 0) {
+        set_err(c, "ibv_modify_qp(RTR)", rc);
+        return -1;
+    }
+    struct ibv_qp_attr rts;
+    memset(&rts, 0, sizeof(rts));
+    rts.qp_state = IBV_QPS_RTS;
+    rts.timeout = 14;
+    rts.retry_cnt = 7;
+    rts.rnr_retry = 7;
+    rts.sq_psn = 0;
+    rts.max_rd_atomic = 1;
+    rc = ibv_modify_qp(hca->qp[p], &rts,
+                       IBV_QP_STATE | IBV_QP_TIMEOUT | IBV_QP_RETRY_CNT | IBV_QP_RNR_RETRY |
+                           IBV_QP_SQ_PSN | IBV_QP_MAX_QP_RD_ATOMIC);
+    if (rc != 0) {
+        set_err(c, "ibv_modify_qp(RTS)", rc);
+        return -1;
+    }
+    return 0;
+}
+
+int roce_connect(roce_ctx_t *c, const void *blobs, uint64_t blobs_len) {
+    if (blobs_len < sizeof(roce_blob_t) * (uint64_t)c->world) {
+        snprintf(c->err, sizeof(c->err), "peer blob buffer too small");
+        return -1;
+    }
+    const roce_blob_t *all = (const roce_blob_t *)blobs;
+    for (int p = 0; p < c->world; p++) {
+        if (p == c->rank) {
+            continue;
+        }
+        c->peer_addr[p] = all[p].region_addr;
+        for (int h = 0; h < c->n_hca; h++) {
+            c->peer_rkey[h][p] = all[p].rkey[h];
+            if (connect_qp(c, h, p, &all[p]) != 0) {
+                return -1;
+            }
+        }
+    }
+    return 0;
+}
+
+static int drain_cq(roce_ctx_t *c, int h) {
+    struct ibv_wc wc[32];
+    int n = ibv_poll_cq(c->hca[h].cq, 32, wc);
+    if (n < 0) {
+        set_err(c, "ibv_poll_cq", errno);
+        return -1;
+    }
+    for (int i = 0; i < n; i++) {
+        if (wc[i].status != IBV_WC_SUCCESS) {
+            snprintf(c->err, sizeof(c->err),
+                     "RDMA write to rank %u failed: %s (vendor_err 0x%x, seq %u)",
+                     (unsigned)wc[i].wr_id, ibv_wc_status_str(wc[i].status),
+                     wc[i].vendor_err, c->last_seq);
+            return -1;
+        }
+        c->hca[h].outstanding[wc[i].wr_id] -= 1;
+        c->hca[h].writes_completed += 1;
+        c->writes_completed += 1;
+    }
+    return 0;
+}
+
+static int post_op(roce_ctx_t *c, uint32_t seq, uint32_t nbytes) {
+    if (nbytes == 0 || nbytes % 16 != 0) {
+        snprintf(c->err, sizeof(c->err),
+                 "RoCE payload size must be a positive multiple of 16 bytes, got %u",
+                 nbytes);
+        return -1;
+    }
+    uint32_t slot = seq & 1u;
+    uint8_t *send = c->region + c->send_off + (size_t)slot * c->slot_bytes;
+    uint32_t seq_copy = seq;
+    uint32_t total_packs = nbytes / 16;
+    for (int p = 0; p < c->world; p++) {
+        if (p == c->rank) {
+            continue;
+        }
+        uint32_t pack_offset = 0;
+        for (int h = 0; h < c->n_hca; h++) {
+            roce_hca_t *hca = &c->hca[h];
+            // Two work requests per stripe; keep the queue at most a quarter
+            // full so a provider that needs extra entries can never fail a post.
+            while (hca->outstanding[p] >= ROCE_SEND_DEPTH / 4) {
+                if (drain_cq(c, h) != 0) {
+                    return -1;
+                }
+                // A peer that stopped acknowledging keeps the QP retrying for
+                // a long time; honour a stop request instead of blocking
+                // roce_stop (and so teardown) behind it.
+                if (!atomic_load_explicit(&c->running, memory_order_relaxed)) {
+                    snprintf(c->err, sizeof(c->err),
+                             "RoCE proxy stopped with %u writes outstanding to rank %d",
+                             hca->outstanding[p], p);
+                    return -1;
+                }
+            }
+            uint32_t stripe_packs = total_packs / (uint32_t)c->n_hca;
+            if ((uint32_t)h < total_packs % (uint32_t)c->n_hca) {
+                stripe_packs += 1;
+            }
+            uint32_t stripe_bytes = stripe_packs * 16;
+            uint64_t byte_offset = (uint64_t)pack_offset * 16;
+            uint64_t remote = c->peer_addr[p];
+            struct ibv_sge flag_sge = {
+                .addr = (uint64_t)(uintptr_t)&seq_copy,
+                .length = 4,
+                .lkey = 0,
+            };
+            struct ibv_send_wr flag_wr;
+            memset(&flag_wr, 0, sizeof(flag_wr));
+            flag_wr.wr_id = (uint64_t)p;
+            flag_wr.sg_list = &flag_sge;
+            flag_wr.num_sge = 1;
+            flag_wr.opcode = IBV_WR_RDMA_WRITE;
+            flag_wr.send_flags = IBV_SEND_SIGNALED | IBV_SEND_INLINE;
+            flag_wr.wr.rdma.remote_addr =
+                remote + c->flag_off +
+                (((uint64_t)c->rank * ROCE_SLOTS + slot) * (uint64_t)c->n_hca +
+                 (uint64_t)h) * ROCE_FLAG_STRIDE;
+            flag_wr.wr.rdma.rkey = c->peer_rkey[h][p];
+
+            struct ibv_send_wr data_wr;
+            struct ibv_sge data_sge;
+            struct ibv_send_wr *first_wr = &flag_wr;
+            if (stripe_bytes != 0) {
+                data_sge = (struct ibv_sge){
+                    .addr = (uint64_t)(uintptr_t)(send + byte_offset),
+                    .length = stripe_bytes,
+                    .lkey = hca->mr->lkey,
+                };
+                memset(&data_wr, 0, sizeof(data_wr));
+                data_wr.wr_id = (uint64_t)p;
+                data_wr.next = &flag_wr;
+                data_wr.sg_list = &data_sge;
+                data_wr.num_sge = 1;
+                data_wr.opcode = IBV_WR_RDMA_WRITE;
+                data_wr.wr.rdma.remote_addr =
+                    remote + c->recv_off +
+                    ((uint64_t)c->rank * ROCE_SLOTS + slot) * c->slot_bytes +
+                    byte_offset;
+                data_wr.wr.rdma.rkey = c->peer_rkey[h][p];
+                first_wr = &data_wr;
+            }
+            struct ibv_send_wr *bad = NULL;
+            int rc = ibv_post_send(hca->qp[p], first_wr, &bad);
+            if (rc != 0) {
+                set_err(c, "ibv_post_send", rc);
+                return -1;
+            }
+            hca->outstanding[p] += 1;
+            hca->bytes_posted += stripe_bytes;
+            pack_offset += stripe_packs;
+        }
+    }
+    c->ops_posted += 1;
+    for (int h = 0; h < c->n_hca; h++) {
+        if (drain_cq(c, h) != 0) {
+            return -1;
+        }
+    }
+    return 0;
+}
+
+static void *proxy_main(void *arg) {
+    roce_ctx_t *c = (roce_ctx_t *)arg;
+    volatile uint32_t *ctrl = (volatile uint32_t *)(c->region + c->ctrl_off);
+    // Spin while ops are flowing.  After ROCE_IDLE_SPINS polls without a
+    // doorbell, request a short nanosleep between polls (the OS decides the
+    // actual delay) so an idle runtime does not hold a core next to the
+    // serving process.  The missed-doorbell catch-up below keeps the protocol
+    // correct however long the thread is away.
+    uint64_t idle = 0;
+    const struct timespec nap = {0, 20000};
+    while (atomic_load_explicit(&c->running, memory_order_relaxed)) {
+        uint32_t seq = __atomic_load_n(&ctrl[0], __ATOMIC_ACQUIRE);
+        if (seq == c->last_seq) {
+            idle++;
+            if (idle % 64 == 0) {
+                for (int h = 0; h < c->n_hca; h++) {
+                    if (drain_cq(c, h) != 0) {
+                        atomic_store(&c->failed, 1);
+                        return NULL;
+                    }
+                }
+            }
+            if (idle >= ROCE_IDLE_SPINS) {
+                nanosleep(&nap, NULL);
+            }
+            continue;
+        }
+        idle = 0;
+        // The doorbell holds only the newest sequence.  Our kernel for op N
+        // completes on the peers' payloads alone, so op N+1 can ring before
+        // this thread has seen op N (it slept, or the scheduler moved it).
+        // Peers cannot get further than one op ahead of us, so at most
+        // ROCE_SLOTS doorbells are pending and every send slot is intact:
+        // post each missed sequence in order using its per-slot byte count.
+        uint32_t pending = seq - c->last_seq;
+        if (pending > ROCE_SLOTS) {
+            snprintf(c->err, sizeof(c->err),
+                     "doorbell skipped %u ops (last %u, now %u)", pending, c->last_seq, seq);
+            atomic_store(&c->failed, 1);
+            return NULL;
+        }
+        for (uint32_t s = c->last_seq + 1; pending > 0; s++, pending--) {
+            uint32_t nbytes = ctrl[4 + (s & 1u)];
+            if (post_op(c, s, nbytes) != 0) {
+                atomic_store(&c->failed, 1);
+                return NULL;
+            }
+            c->last_seq = s;
+        }
+    }
+    return NULL;
+}
+
+int roce_start(roce_ctx_t *c) {
+    if (atomic_load(&c->running)) {
+        return 0;
+    }
+    if (!c->started) {
+        // A restart continues from the last posted sequence so ops that rang
+        // the doorbell while the thread was stopped are still posted.
+        volatile uint32_t *ctrl = (volatile uint32_t *)(c->region + c->ctrl_off);
+        c->last_seq = ctrl[0];
+        c->started = 1;
+    }
+    atomic_store(&c->failed, 0);
+    atomic_store(&c->running, 1);
+    int rc = pthread_create(&c->thread, NULL, proxy_main, c);
+    if (rc != 0) {
+        atomic_store(&c->running, 0);
+        set_err(c, "pthread_create", rc);
+        return -1;
+    }
+    return 0;
+}
+
+void roce_stop(roce_ctx_t *c) {
+    if (atomic_exchange(&c->running, 0)) {
+        pthread_join(c->thread, NULL);
+    }
+}
+
+int roce_failed(roce_ctx_t *c) { return atomic_load(&c->failed); }
+
+const char *roce_error(roce_ctx_t *c) { return c->err; }
+
+uint64_t roce_stat(roce_ctx_t *c, int which) {
+    switch (which) {
+    case 0:
+        return c->ops_posted;
+    case 1:
+        return c->writes_completed;
+    case 2:
+        return c->last_seq;
+    default:
+        return 0;
+    }
+}
+
+uint64_t roce_hca_stat(roce_ctx_t *c, int hca, int which) {
+    if (hca < 0 || hca >= c->n_hca) {
+        return -1;
+    }
+    switch (which) {
+    case 0:
+        return c->hca[hca].writes_completed;
+    case 1:
+        return c->hca[hca].bytes_posted;
+    default:
+        return 0;
+    }
+}
+
+void roce_destroy(roce_ctx_t *c) {
+    if (c == NULL) {
+        return;
+    }
+    roce_stop(c);
+    for (int h = 0; h < ROCE_MAX_HCAS; h++) {
+        roce_hca_t *hca = &c->hca[h];
+        for (int p = 0; p < ROCE_MAX_PEERS; p++) {
+            if (hca->qp[p] != NULL) {
+                ibv_destroy_qp(hca->qp[p]);
+            }
+        }
+        if (hca->cq != NULL) {
+            ibv_destroy_cq(hca->cq);
+        }
+        if (hca->mr != NULL) {
+            ibv_dereg_mr(hca->mr);
+        }
+        if (hca->pd != NULL) {
+            ibv_dealloc_pd(hca->pd);
+        }
+        if (hca->ctx != NULL) {
+            ibv_close_device(hca->ctx);
+        }
+    }
+    free(c);
+}
diff --git tensorfold/families/glm5_next/cuda/engine.py tensorfold/families/glm5_next/cuda/engine.py
index 6492798..53ddda9 100644
--- tensorfold/families/glm5_next/cuda/engine.py
+++ tensorfold/families/glm5_next/cuda/engine.py
@@ -148,6 +148,15 @@ class GlmEngine:
         self.serial_only = serial_only
         self.comm = comm if comm is not None else NCCL(rank, 2, master, port)
         self.comm.barrier()
+        if comm is None and os.environ.get("TF_GLM_COMM", "nccl") == "roce":
+            # small all-gathers (a decode round's partials, the samplers) over b12x's one-shot RoCE transport
+            from tensorfold.cuda.roce import RoceComm
+
+            self.comm = RoceComm(self.comm, rank, 2)
+            if rank == 0:
+                print(f"[tensorfold] all-gathers up to {self.comm.roce.max_bytes >> 10} KiB over RoCE "
+                      f"({', '.join(self.comm.roce.hcas)}; b12x's RoCEnante transport), larger ones over NCCL",
+                      flush=True)
         cfg = Config.read(model_dir)
         # Without --context the window stays dense, attending every key without indexer work.
         explicit = context is not None if context_explicit is None else bool(context_explicit)
@@ -589,6 +598,8 @@ class GlmEngine:
             self._share(positions)
         stats = self._run(list(prompt), max_tokens, sampling, stop_eos, on_tokens, code, hit, draft, constraint, feed)
         stats.update(policy=spec, drafts=draft)
+        if hasattr(self.comm, "check"):                  # a RoCE wait that timed out inside a graph surfaces here
+            self.comm.check()
         if feed is not None:
             stats.update(image_rows=len(positions), encode_s=round(feed.encode_s, 3))
         return stats
@@ -621,6 +632,8 @@ class GlmEngine:
                     raise RuntimeError(f"rank 1 has no snapshot of the {cached} tokens rank 0 resumes from")
             self._run(prompt, max_tokens, sampling, bool(stop_eos), lambda new: None, code, hit, bool(draft),
                       constraint, feed)
+            if hasattr(self.comm, "check"):
+                self.comm.check()
 
 
 class VisionFeed: