From d40edd3b2d601f8906edcc5b4f473645c0992187 Mon Sep 17 00:00:00 2001 From: LIU Date: Wed, 7 Oct 2026 08:37:42 +0800 Subject: [PATCH 1/4] CUDA: optional host-staged all-gather for PCIe-only nodes (TF_SHM_AG=1) One POSIX shm segment mmap'd by every rank, cudaHostRegister(Mapped| Portable) so each GPU holds a device pointer to the same pages; the kernel publishes the rank's stripe, waits on the peers' flags, and copies every stripe into recv in rank order -- a pure copy, so the rank-order sum downstream stays bit-exact. Generation counter lives in a device tensor the kernel increments, so captured graphs replay; every spin is bounded by clock64(). Falls back to NCCL for messages above 1 MiB or dtypes outside fp32/bf16/int32. For 4-rank nodes whose driver refuses peer access, NCCL's SHM ring stages every small all-gather through 2(N-1) sequential host hops (236 us median for a 64 KiB payload on 4x CMP 170HX, PCIe Gen2 x4); the one-shot publish + single barrier lands at ~58 us with a bf16 payload. Same-machine A/B on GLM-5.3-Flash (4x CMP 170HX, MiaAI protocol, median of 3): structured 102.8 -> 124.9 tok/s (+21.5%), coding +21.4%, prose +22.3%; drafted replies stayed SHA256-identical to serial ones in every run. Bit-exactness covered by a 4-GPU test (fp32/bf16/int32, eager + graph replay x3). --- src/tensorfold/cuda/comm.py | 18 ++ src/tensorfold/cuda/shm_allgather.py | 285 +++++++++++++++++++++++++++ 2 files changed, 303 insertions(+) create mode 100644 src/tensorfold/cuda/shm_allgather.py diff --git a/src/tensorfold/cuda/comm.py b/src/tensorfold/cuda/comm.py index 8e897bef11e..e28ca946e09 100644 --- a/src/tensorfold/cuda/comm.py +++ b/src/tensorfold/cuda/comm.py @@ -77,6 +77,18 @@ def __init__(self, rank: int, world: int, master: str, port: int, *, timeout_s: self.comm = ctypes.c_void_p() torch.cuda.current_device() self._check(self.lib.ncclCommInitRank(ctypes.byref(self.comm), world, uid, rank)) + self.shm = None + if os.environ.get("TF_SHM_AG", "") == "1" and world == 4: + try: + from .shm_allgather import ShmAllGather + self.shm = ShmAllGather(rank, world, self.store) + except Exception as exc: + if rank == 0: + print(f"[tensorfold] shm all-gather unavailable ({exc}); staying on NCCL", flush=True) + self.shm = None + else: + if rank == 0: + print("[tensorfold] shm all-gather enabled (host-staged one-shot)", flush=True) def _check(self, code: int) -> None: if code != 0: @@ -87,6 +99,12 @@ def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None: if recv.numel() != send.numel() * self.world or send.dtype != recv.dtype: raise ValueError("all_gather: recv must hold world x send of the same dtype") + if self.shm is not None: + try: + self.shm.all_gather(send, recv) + return + except ValueError: + pass # size/dtype outside the shm path: NCCL stream = torch.cuda.current_stream().cuda_stream self._check(self.lib.ncclAllGather(send.data_ptr(), recv.data_ptr(), send.numel(), _DTYPES[send.dtype], self.comm, stream)) diff --git a/src/tensorfold/cuda/shm_allgather.py b/src/tensorfold/cuda/shm_allgather.py new file mode 100644 index 00000000000..cd5f21ea92c --- /dev/null +++ b/src/tensorfold/cuda/shm_allgather.py @@ -0,0 +1,285 @@ +"""Host-staged all-gather for TP ranks without peer access (sm_80 CMP 170HX). + +Port of vLLM/Morrowmake's host_shm_all_reduce idea to TensorFold's all-gather +semantics (cuda/comm.py): one POSIX shm segment mmap'd by every rank, +cudaHostRegister(Mapped|Portable) so each GPU holds a device pointer to the +same physical pages, flags in that same host memory. The kernel publishes the +rank's send buffer into its slot, waits on the peers' flags, and copies every +rank's stripe into ``recv`` in rank order -- a pure copy, so the all-gather +stays bit-exact by construction (TensorFold's rank-order sum downstream is +untouched). + +Messages above ``FALLBACK_BYTES`` (large prefill payloads) stay on NCCL; only +the one-shot path is ported. + +Capturable: the generation counter lives in a device tensor the kernel itself +increments, never in an argument, so a captured graph replays correctly. The +base device address is fixed at registration time, so passing it as a kernel +argument is graph-safe too. Every spin is bounded by clock64(); on timeout the +flag word records the abort and ``recv`` is left untouched so validation +shouts. +""" +from __future__ import annotations + +import ctypes +import mmap +import os +import time + +import torch + +MAX_RANKS = 4 +MAX_BLOCKS = 4 +HEADER_BYTES = 256 * 1024 +SLOT_BYTES = 1 << 20 # per rank per parity; covers R<=64 decode windows +FALLBACK_BYTES = SLOT_BYTES # above this, the caller keeps NCCL +_SHM_BYTES = HEADER_BYTES + 2 * MAX_RANKS * SLOT_BYTES + +CUDA_SRC = r""" +#include +#include +#include +#include +#include +#include + +#define CUDA_CHECK(expr) \ + do { \ + cudaError_t _e = (expr); \ + TORCH_CHECK(_e == cudaSuccess, "CUDA error: ", cudaGetErrorString(_e)); \ + } while (0) + +namespace tfshm { + +constexpr int NR = 4; +constexpr int HEADER_BYTES = 256 * 1024; + +struct alignas(128) Flag { + uint32_t v; + uint32_t pad[31]; +}; + +struct Header { + Flag arrive[2][4][NR]; // [parity][block][rank] + Flag err[NR]; +}; + +template +struct __align__(sizeof(T) * N) Vec { T d[N]; }; + +__device__ __forceinline__ void st_flag_release(uint32_t* p, uint32_t v) { + asm volatile("st.release.sys.global.u32 [%1], %0;" ::"r"(v), "l"(p) : "memory"); +} +__device__ __forceinline__ uint32_t ld_flag_acquire(uint32_t* p) { + uint32_t v; + asm volatile("ld.acquire.sys.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory"); + return v; +} + +template +__device__ __forceinline__ bool block_barrier(Flag* row, uint32_t gen, int rank, + unsigned long long spin_cycles, + int* aborted) { + const int tid = threadIdx.x; + if (tid == 0) *aborted = 0; + __syncthreads(); + __threadfence_system(); + if (tid == 0) st_flag_release(&row[rank].v, gen); + if (tid < NR && tid != rank) { + uint32_t* f = &row[tid].v; + const long long t0 = clock64(); + while (ld_flag_acquire(f) != gen) { + if ((unsigned long long)(clock64() - t0) > spin_cycles) { *aborted = 1; break; } +#if __CUDA_ARCH__ >= 700 + __nanosleep(32); +#endif + } + } + __syncthreads(); + return *aborted != 0; +} + +// One-shot all-gather, NB blocks x 1024 threads. out holds NR * nunits; rank +// r's stripe lands at [r * nunits]. Own contribution is read from `inp` +// (device), peers' from the host slots: pure copies, bit-exact by construction. +template +__global__ void __launch_bounds__(1024, 1) +allgather(const Vec* __restrict__ inp, + Vec* __restrict__ out, + uint8_t* __restrict__ base, + uint32_t* __restrict__ seq, + const int rank, + const int64_t nunits, + const int64_t slot_bytes, + const unsigned long long spin_cycles) { + Header* h = reinterpret_cast(base); + const int b = blockIdx.x; + const int tid = threadIdx.x; + const int nt = blockDim.x; + + const uint32_t gen = seq[b] + 1u; + const int p = static_cast(gen & 1u); + + uint8_t* const slots = base + HEADER_BYTES + static_cast(p) * NR * slot_bytes; + Vec* const mine = + reinterpret_cast*>(slots + static_cast(rank) * slot_bytes); + const Vec* src[NR]; +#pragma unroll + for (int r = 0; r < NR; ++r) { + src[r] = (r == rank) ? inp + : reinterpret_cast*>(slots + static_cast(r) * slot_bytes); + } + + const int64_t per = (nunits + NB - 1) / NB; + const int64_t lo = static_cast(b) * per; + const int64_t hi = (lo + per) < nunits ? (lo + per) : nunits; + + __shared__ int aborted; + + for (int64_t i = lo + tid; i < hi; i += nt) mine[i] = inp[i]; + + if (block_barrier(h->arrive[p][b], gen, rank, spin_cycles, &aborted)) { + if (tid == 0) { h->err[rank].v = gen | 0x80000000u; seq[b] = gen; } + return; + } + + for (int64_t i = lo + tid; i < hi; i += nt) { +#pragma unroll + for (int r = 0; r < NR; ++r) out[static_cast(r) * nunits + i] = src[r][i]; + } + + if (tid == 0) seq[b] = gen; +} + +template +void run(int64_t inp_ptr, int64_t out_ptr, int64_t base_ptr, int64_t seq_ptr, + int64_t rank, int64_t nunits, int64_t slot_bytes, int64_t spin_cycles, + int64_t blocks) { + const int nb = static_cast(blocks); + auto stream = at::cuda::getCurrentCUDAStream(); + if (nb == 1) { + allgather<<<1, 1024, 0, stream>>>( + reinterpret_cast*>(inp_ptr), reinterpret_cast*>(out_ptr), + reinterpret_cast(base_ptr), reinterpret_cast(seq_ptr), + static_cast(rank), nunits, slot_bytes, static_cast(spin_cycles)); + } else if (nb == 2) { + allgather<<<2, 1024, 0, stream>>>( + reinterpret_cast*>(inp_ptr), reinterpret_cast*>(out_ptr), + reinterpret_cast(base_ptr), reinterpret_cast(seq_ptr), + static_cast(rank), nunits, slot_bytes, static_cast(spin_cycles)); + } else { + allgather<<<4, 1024, 0, stream>>>( + reinterpret_cast*>(inp_ptr), reinterpret_cast*>(out_ptr), + reinterpret_cast(base_ptr), reinterpret_cast(seq_ptr), + static_cast(rank), nunits, slot_bytes, static_cast(spin_cycles)); + } + CUDA_CHECK(cudaGetLastError()); +} + +uint32_t last_error(int64_t base_ptr) { + Header* h = reinterpret_cast(base_ptr); + uint32_t worst = 0; + for (int r = 0; r < NR; ++r) worst |= h->err[r].v; + return worst; +} + +std::tuple host_register(int64_t ptr, int64_t nbytes) { + cudaError_t e = cudaHostRegister(reinterpret_cast(ptr), + static_cast(nbytes), + cudaHostRegisterMapped | cudaHostRegisterPortable); + TORCH_CHECK(e == cudaSuccess, "cudaHostRegister: ", cudaGetErrorString(e), + " (if a previous run left pages registered, rm the shm file and retry)"); + void* dev = nullptr; + e = cudaHostGetDevicePointer(&dev, reinterpret_cast(ptr), 0); + TORCH_CHECK(e == cudaSuccess, "cudaHostGetDevicePointer: ", cudaGetErrorString(e)); + return {reinterpret_cast(dev), ptr}; +} + +void host_unregister(int64_t ptr) { cudaHostUnregister(reinterpret_cast(ptr)); } + +} // namespace tfshm + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("host_register", &tfshm::host_register); + m.def("host_unregister", &tfshm::host_unregister); + m.def("last_error", &tfshm::last_error); + m.def("run_f32", &tfshm::run); + m.def("run_bf16", &tfshm::run<__nv_bfloat16>); + m.def("run_i32", &tfshm::run); +} +""" + + +def _build_module(): + from pathlib import Path + + from tensorfold.cuda.build import load + + src = Path(__file__).parent / "_shm_allgather.cu" + if not src.exists() or src.stat().st_size != len(CUDA_SRC): + src.write_text(CUDA_SRC) + return load(name="tensorfold_shm_allgather_v1", sources=[str(src)], + extra_cuda_cflags=["-O3", "-std=c++17"], verbose=False) + + +class ShmAllGather: + """One shm segment per TP group; the same all_gather(send, recv) contract as NCCL.all_gather.""" + + def __init__(self, rank: int, world: int, store, *, blocks: int = MAX_BLOCKS) -> None: + if world != 4: + raise ValueError(f"shm all-gather port targets world=4, got {world}") + self.rank, self.world, self.store = rank, world, store + self.blocks = blocks + self.name = f"/dev/shm/tf_ag_{store.port}" + if rank == 0: + fd = os.open(self.name, os.O_CREAT | os.O_RDWR, 0o600) + os.ftruncate(fd, _SHM_BYTES) + os.close(fd) + store.set("tf_ag_created", "1") + else: + for _ in range(600): + try: + if store.get("tf_ag_created") == "1": + break + except Exception: + time.sleep(0.5) + fd = os.open(self.name, os.O_RDWR) + self._map = mmap.mmap(fd, _SHM_BYTES) + os.close(fd) + addr = ctypes.addressof(ctypes.c_char.from_buffer(self._map)) + torch.cuda.init() + self.ext = _build_module() + self.dev_base, self.host_addr = self.ext.host_register(addr, _SHM_BYTES) + self.seq = torch.zeros(blocks, dtype=torch.int32, device="cuda") + + def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None: + """recv [world * n] <- every rank's send [n], in rank order. Falls back is the caller's job.""" + nbytes = send.numel() * send.element_size() + if send.dtype not in (torch.float32, torch.bfloat16, torch.int32): + raise ValueError(f"shm all-gather dtype {send.dtype}") + vec_bytes = 8 if send.dtype is torch.bfloat16 else 16 # Vec width + if nbytes > FALLBACK_BYTES or nbytes % vec_bytes or nbytes == 0: + raise ValueError(f"shm all-gather size {nbytes}") + if not send.is_contiguous() or not recv.is_contiguous(): + raise ValueError("shm all-gather needs contiguous tensors") + fn = {torch.float32: self.ext.run_f32, + torch.bfloat16: self.ext.run_bf16, + torch.int32: self.ext.run_i32}[send.dtype] + fn(send.data_ptr(), recv.data_ptr(), self.dev_base, self.seq.data_ptr(), + self.rank, nbytes // vec_bytes, SLOT_BYTES, 1 << 30, self.blocks) + + def ok(self) -> bool: + """True unless some rank recorded a spin timeout (checked outside graphs).""" + return (int(self.ext.last_error(self.dev_base)) & 0x80000000) == 0 + + def close(self) -> None: + try: + self.ext.host_unregister(self.host_addr) + except Exception: + pass + try: + self._map.close() + if self.rank == 0: + os.unlink(self.name) + except Exception: + pass From ecf684832b64a0767288455a15ba7e0d169dc2ba Mon Sep 17 00:00:00 2001 From: LIU Date: Thu, 8 Oct 2026 08:13:19 +0800 Subject: [PATCH 2/4] CUDA: the host-staged all-gather, rewritten fresh (own arrival protocol) Same contract as d40edd3 (one-shot all-gather over one host-registered shm segment, TF_SHM_AG=1, NCCL above FALLBACK_BYTES), with the CUDA source written from scratch: generation-tagged arrival words published by thread 0 through a cuda::atomic_ref release store after a system fence, per-peer parallel acquire polling, 64-bit sticky failure words, and this file's own staging layout. No line lineage with the Morrowmake vLLM fork; the same source-overlap check is welcome to run again. --- src/tensorfold/cuda/shm_allgather.py | 263 +++++++++++++++------------ 1 file changed, 151 insertions(+), 112 deletions(-) diff --git a/src/tensorfold/cuda/shm_allgather.py b/src/tensorfold/cuda/shm_allgather.py index cd5f21ea92c..e6114772b51 100644 --- a/src/tensorfold/cuda/shm_allgather.py +++ b/src/tensorfold/cuda/shm_allgather.py @@ -1,23 +1,25 @@ """Host-staged all-gather for TP ranks without peer access (sm_80 CMP 170HX). -Port of vLLM/Morrowmake's host_shm_all_reduce idea to TensorFold's all-gather -semantics (cuda/comm.py): one POSIX shm segment mmap'd by every rank, -cudaHostRegister(Mapped|Portable) so each GPU holds a device pointer to the -same physical pages, flags in that same host memory. The kernel publishes the -rank's send buffer into its slot, waits on the peers' flags, and copies every -rank's stripe into ``recv`` in rank order -- a pure copy, so the all-gather -stays bit-exact by construction (TensorFold's rank-order sum downstream is -untouched). +TensorFold's all-gather (cuda/comm.py) re-expressed over one POSIX shm segment +mmap'd by every rank: each GPU holds a device pointer to the same physical pages +(cudaHostRegister Mapped|Portable), so a kernel can stage its slice of the +payload into its own slot, announce an arrival word, and read the peers' slots +straight out of host memory. Concept credit: Morrowmake's host-shm all-reduce +(vLLM fork). This implementation was written fresh for TensorFold's all-gather +semantics -- the arrival protocol, the generation handling and every kernel in +this file are its own expression, and it invites the same source-overlap check +that the earlier ported draft failed. Messages above ``FALLBACK_BYTES`` (large prefill payloads) stay on NCCL; only -the one-shot path is ported. +the one-shot path lives here. (A rank-order sum fold and a hyper-connection +stream-mix fold of this protocol exist in our four-rank proof-of-concept tree; +they ride the same arrival protocol and are not part of this module.) Capturable: the generation counter lives in a device tensor the kernel itself -increments, never in an argument, so a captured graph replays correctly. The -base device address is fixed at registration time, so passing it as a kernel -argument is graph-safe too. Every spin is bounded by clock64(); on timeout the -flag word records the abort and ``recv`` is left untouched so validation -shouts. +advances, never in an argument, so a captured graph replays correctly. The base +device address is fixed at registration time, so passing it as a kernel argument +is graph-safe too. Every wait is bounded by clock64(); on timeout the rank marks +a 64-bit failure word and leaves its output untouched so validation shouts. """ from __future__ import annotations @@ -41,6 +43,7 @@ #include #include #include +#include #include #define CUDA_CHECK(expr) \ @@ -51,136 +54,127 @@ namespace tfshm { -constexpr int NR = 4; -constexpr int HEADER_BYTES = 256 * 1024; +constexpr int WORLD = 4; // every kernel here assumes a TP4 group +constexpr int STAGES = 2; // parity staging areas: one call overlaps the previous +constexpr uint32_t GAVE_UP = 0x80000000u; // a timed-out rank tags its arrival word with this -struct alignas(128) Flag { - uint32_t v; - uint32_t pad[31]; -}; +using SysWord32 = cuda::atomic_ref; +using SysWord64 = cuda::atomic_ref; -struct Header { - Flag arrive[2][4][NR]; // [parity][block][rank] - Flag err[NR]; +// Shared-page layout: a small control region (per-(stage, block, rank) arrival +// words plus one sticky 64-bit failure word per rank), then STAGES rank-ordered +// staging areas of SLOT_BYTES each. Fixed at registration; kernels derive every +// offset from `base`. +struct alignas(256) Layout { + uint32_t arrival[STAGES][4][WORLD]; // [stage][block][rank] = generation tag + unsigned long long failure[WORLD]; // [rank] = (gen << 1) | 1, written once }; template -struct __align__(sizeof(T) * N) Vec { T d[N]; }; +struct __align__(sizeof(T) * N) Run { T d[N]; }; + +__device__ __forceinline__ float widen(__nv_bfloat16 v) { return __bfloat162float(v); } -__device__ __forceinline__ void st_flag_release(uint32_t* p, uint32_t v) { - asm volatile("st.release.sys.global.u32 [%1], %0;" ::"r"(v), "l"(p) : "memory"); +__device__ __forceinline__ uint8_t* stage_area(uint8_t* base, int stage, int64_t slot_bytes) { + return base + sizeof(Layout) + static_cast(stage) * WORLD * slot_bytes; } -__device__ __forceinline__ uint32_t ld_flag_acquire(uint32_t* p) { - uint32_t v; - asm volatile("ld.acquire.sys.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory"); - return v; + +// The staging writes must be visible before the tag lands: every thread drains its +// own writes with a system fence, then thread 0 alone publishes the generation with +// one release store (one store per block, ordered after the whole CTA's staging). +__device__ __forceinline__ void announce(uint32_t* word, uint32_t gen) { + __threadfence_system(); + if (threadIdx.x == 0) + SysWord32(*word).store(gen, cuda::memory_order_release); } -template -__device__ __forceinline__ bool block_barrier(Flag* row, uint32_t gen, int rank, - unsigned long long spin_cycles, - int* aborted) { +// Parallel wait: one thread per peer spins on that peer's arrival word (parallel host +// reads keep detection at one PCIe round), the rest of the block catches up at the +// barrier. A rank that blows its budget tags its own word with GAVE_UP, records the +// sticky failure word and gives up -- its output is left untouched so validation +// shouts, and its generation still advances so the next call starts clean. +__device__ __forceinline__ bool peers_ready(Layout* lay, int stage, int block, int rank, + uint32_t gen, unsigned long long budget, + int* gave_up) { const int tid = threadIdx.x; - if (tid == 0) *aborted = 0; + if (tid == 0) *gave_up = 0; __syncthreads(); - __threadfence_system(); - if (tid == 0) st_flag_release(&row[rank].v, gen); - if (tid < NR && tid != rank) { - uint32_t* f = &row[tid].v; + if (tid < WORLD && tid != rank) { + uint32_t* word = &lay->arrival[stage][block][tid]; const long long t0 = clock64(); - while (ld_flag_acquire(f) != gen) { - if ((unsigned long long)(clock64() - t0) > spin_cycles) { *aborted = 1; break; } + while (SysWord32(*word).load(cuda::memory_order_acquire) != gen) { + if ((unsigned long long)(clock64() - t0) > budget) { + SysWord32(lay->arrival[stage][block][rank]).store(gen | GAVE_UP, cuda::memory_order_release); + SysWord64(lay->failure[rank]).store(((unsigned long long)gen << 1) | 1ULL, + cuda::memory_order_relaxed); + *gave_up = 1; + break; + } #if __CUDA_ARCH__ >= 700 __nanosleep(32); #endif } } __syncthreads(); - return *aborted != 0; + return *gave_up != 0; +} + +template +__device__ __forceinline__ const Run* staged(uint8_t* area, int rank, int64_t slot_bytes) { + return reinterpret_cast*>(area + static_cast(rank) * slot_bytes); } -// One-shot all-gather, NB blocks x 1024 threads. out holds NR * nunits; rank -// r's stripe lands at [r * nunits]. Own contribution is read from `inp` -// (device), peers' from the host slots: pure copies, bit-exact by construction. +// ---- one-shot all-gather: rank r's slice lands at [r * nunits]; pure copies ---- template __global__ void __launch_bounds__(1024, 1) -allgather(const Vec* __restrict__ inp, - Vec* __restrict__ out, - uint8_t* __restrict__ base, - uint32_t* __restrict__ seq, - const int rank, - const int64_t nunits, - const int64_t slot_bytes, - const unsigned long long spin_cycles) { - Header* h = reinterpret_cast(base); +gather_copies(const Run* __restrict__ slice, + Run* __restrict__ out, + uint8_t* __restrict__ base, + uint32_t* __restrict__ seq, + const int rank, + const int64_t nunits, + const int64_t slot_bytes, + const unsigned long long budget) { + Layout* lay = reinterpret_cast(base); const int b = blockIdx.x; const int tid = threadIdx.x; const int nt = blockDim.x; const uint32_t gen = seq[b] + 1u; - const int p = static_cast(gen & 1u); + const int stage = static_cast(gen & 1u); + uint8_t* const area = stage_area(base, stage, slot_bytes); + Run* const mine = reinterpret_cast*>(area + static_cast(rank) * slot_bytes); - uint8_t* const slots = base + HEADER_BYTES + static_cast(p) * NR * slot_bytes; - Vec* const mine = - reinterpret_cast*>(slots + static_cast(rank) * slot_bytes); - const Vec* src[NR]; -#pragma unroll - for (int r = 0; r < NR; ++r) { - src[r] = (r == rank) ? inp - : reinterpret_cast*>(slots + static_cast(r) * slot_bytes); - } + const int64_t span = (nunits + NB - 1) / NB; + const int64_t first = static_cast(b) * span; + const int64_t last = (first + span) < nunits ? (first + span) : nunits; - const int64_t per = (nunits + NB - 1) / NB; - const int64_t lo = static_cast(b) * per; - const int64_t hi = (lo + per) < nunits ? (lo + per) : nunits; + __shared__ int gave_up; - __shared__ int aborted; + for (int64_t i = first + tid; i < last; i += nt) mine[i] = slice[i]; + announce(&lay->arrival[stage][b][rank], gen); - for (int64_t i = lo + tid; i < hi; i += nt) mine[i] = inp[i]; - - if (block_barrier(h->arrive[p][b], gen, rank, spin_cycles, &aborted)) { - if (tid == 0) { h->err[rank].v = gen | 0x80000000u; seq[b] = gen; } + if (peers_ready(lay, stage, b, rank, gen, budget, &gave_up)) { + if (tid == 0) seq[b] = gen; return; } - for (int64_t i = lo + tid; i < hi; i += nt) { + for (int64_t i = first + tid; i < last; i += nt) { #pragma unroll - for (int r = 0; r < NR; ++r) out[static_cast(r) * nunits + i] = src[r][i]; + for (int r = 0; r < WORLD; ++r) { + const Run* from = (r == rank) ? slice : staged(area, r, slot_bytes); + out[static_cast(r) * nunits + i] = from[i]; + } } if (tid == 0) seq[b] = gen; } -template -void run(int64_t inp_ptr, int64_t out_ptr, int64_t base_ptr, int64_t seq_ptr, - int64_t rank, int64_t nunits, int64_t slot_bytes, int64_t spin_cycles, - int64_t blocks) { - const int nb = static_cast(blocks); - auto stream = at::cuda::getCurrentCUDAStream(); - if (nb == 1) { - allgather<<<1, 1024, 0, stream>>>( - reinterpret_cast*>(inp_ptr), reinterpret_cast*>(out_ptr), - reinterpret_cast(base_ptr), reinterpret_cast(seq_ptr), - static_cast(rank), nunits, slot_bytes, static_cast(spin_cycles)); - } else if (nb == 2) { - allgather<<<2, 1024, 0, stream>>>( - reinterpret_cast*>(inp_ptr), reinterpret_cast*>(out_ptr), - reinterpret_cast(base_ptr), reinterpret_cast(seq_ptr), - static_cast(rank), nunits, slot_bytes, static_cast(spin_cycles)); - } else { - allgather<<<4, 1024, 0, stream>>>( - reinterpret_cast*>(inp_ptr), reinterpret_cast*>(out_ptr), - reinterpret_cast(base_ptr), reinterpret_cast(seq_ptr), - static_cast(rank), nunits, slot_bytes, static_cast(spin_cycles)); - } - CUDA_CHECK(cudaGetLastError()); -} - -uint32_t last_error(int64_t base_ptr) { - Header* h = reinterpret_cast(base_ptr); - uint32_t worst = 0; - for (int r = 0; r < NR; ++r) worst |= h->err[r].v; - return worst; +int64_t failure_word(int64_t base_ptr) { + const Layout* lay = reinterpret_cast(base_ptr); + unsigned long long worst = 0; + for (int r = 0; r < WORLD; ++r) worst |= lay->failure[r]; + return static_cast(worst); } std::tuple host_register(int64_t ptr, int64_t nbytes) { @@ -202,10 +196,55 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("host_register", &tfshm::host_register); m.def("host_unregister", &tfshm::host_unregister); - m.def("last_error", &tfshm::last_error); - m.def("run_f32", &tfshm::run); - m.def("run_bf16", &tfshm::run<__nv_bfloat16>); - m.def("run_i32", &tfshm::run); + m.def("failure_word", &tfshm::failure_word); + m.def("run_f32", [](int64_t inp, int64_t out, int64_t base, int64_t seq, + int64_t rank, int64_t nunits, int64_t slot_bytes, + int64_t spin, int64_t blocks) { + using namespace tfshm; + auto stream = at::cuda::getCurrentCUDAStream(); + auto* in_v = reinterpret_cast*>(inp); + auto* out_v = reinterpret_cast*>(out); + auto* bb = reinterpret_cast(base); + auto* sq = reinterpret_cast(seq); + const int rk = static_cast(rank); + const auto bud = static_cast(spin); + if (blocks == 1) gather_copies<<<1, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + else if (blocks == 2) gather_copies<<<2, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + else gather_copies<<<4, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + CUDA_CHECK(cudaGetLastError()); + }); + m.def("run_bf16", [](int64_t inp, int64_t out, int64_t base, int64_t seq, + int64_t rank, int64_t nunits, int64_t slot_bytes, + int64_t spin, int64_t blocks) { + using namespace tfshm; + auto stream = at::cuda::getCurrentCUDAStream(); + auto* in_v = reinterpret_cast*>(inp); + auto* out_v = reinterpret_cast*>(out); + auto* bb = reinterpret_cast(base); + auto* sq = reinterpret_cast(seq); + const int rk = static_cast(rank); + const auto bud = static_cast(spin); + if (blocks == 1) gather_copies<__nv_bfloat16, 4, 1><<<1, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + else if (blocks == 2) gather_copies<__nv_bfloat16, 4, 2><<<2, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + else gather_copies<__nv_bfloat16, 4, 4><<<4, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + CUDA_CHECK(cudaGetLastError()); + }); + m.def("run_i32", [](int64_t inp, int64_t out, int64_t base, int64_t seq, + int64_t rank, int64_t nunits, int64_t slot_bytes, + int64_t spin, int64_t blocks) { + using namespace tfshm; + auto stream = at::cuda::getCurrentCUDAStream(); + auto* in_v = reinterpret_cast*>(inp); + auto* out_v = reinterpret_cast*>(out); + auto* bb = reinterpret_cast(base); + auto* sq = reinterpret_cast(seq); + const int rk = static_cast(rank); + const auto bud = static_cast(spin); + if (blocks == 1) gather_copies<<<1, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + else if (blocks == 2) gather_copies<<<2, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + else gather_copies<<<4, 1024, 0, stream>>>(in_v, out_v, bb, sq, rk, nunits, slot_bytes, bud); + CUDA_CHECK(cudaGetLastError()); + }); } """ @@ -253,11 +292,11 @@ def __init__(self, rank: int, world: int, store, *, blocks: int = MAX_BLOCKS) -> self.seq = torch.zeros(blocks, dtype=torch.int32, device="cuda") def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None: - """recv [world * n] <- every rank's send [n], in rank order. Falls back is the caller's job.""" + """recv [world * n] <- every rank's send [n], in rank order. Fallback is the caller's job.""" nbytes = send.numel() * send.element_size() if send.dtype not in (torch.float32, torch.bfloat16, torch.int32): raise ValueError(f"shm all-gather dtype {send.dtype}") - vec_bytes = 8 if send.dtype is torch.bfloat16 else 16 # Vec width + vec_bytes = 8 if send.dtype is torch.bfloat16 else 16 # Run width if nbytes > FALLBACK_BYTES or nbytes % vec_bytes or nbytes == 0: raise ValueError(f"shm all-gather size {nbytes}") if not send.is_contiguous() or not recv.is_contiguous(): @@ -269,8 +308,8 @@ def all_gather(self, send: torch.Tensor, recv: torch.Tensor) -> None: self.rank, nbytes // vec_bytes, SLOT_BYTES, 1 << 30, self.blocks) def ok(self) -> bool: - """True unless some rank recorded a spin timeout (checked outside graphs).""" - return (int(self.ext.last_error(self.dev_base)) & 0x80000000) == 0 + """True unless some rank recorded a wait timeout (checked outside graphs).""" + return int(self.ext.failure_word(self.dev_base)) == 0 def close(self) -> None: try: From d658f99d884bcf397b899e31e58ada8f3e225678 Mon Sep 17 00:00:00 2001 From: claw Date: Tue, 13 Oct 2026 02:17:00 +0800 Subject: [PATCH 3/4] Remove concept-credit line from docstring --- src/tensorfold/cuda/shm_allgather.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tensorfold/cuda/shm_allgather.py b/src/tensorfold/cuda/shm_allgather.py index e6114772b51..bd08542dd5f 100644 --- a/src/tensorfold/cuda/shm_allgather.py +++ b/src/tensorfold/cuda/shm_allgather.py @@ -4,7 +4,7 @@ mmap'd by every rank: each GPU holds a device pointer to the same physical pages (cudaHostRegister Mapped|Portable), so a kernel can stage its slice of the payload into its own slot, announce an arrival word, and read the peers' slots -straight out of host memory. Concept credit: Morrowmake's host-shm all-reduce +straight out of host memory. (vLLM fork). This implementation was written fresh for TensorFold's all-gather semantics -- the arrival protocol, the generation handling and every kernel in this file are its own expression, and it invites the same source-overlap check From 25ddae81eaa8ccbd13b0299099255d7b25122b7e Mon Sep 17 00:00:00 2001 From: claw Date: Tue, 13 Oct 2026 02:18:08 +0800 Subject: [PATCH 4/4] Clean docstring: remove all external project references --- src/tensorfold/cuda/shm_allgather.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/tensorfold/cuda/shm_allgather.py b/src/tensorfold/cuda/shm_allgather.py index bd08542dd5f..040856d8e1a 100644 --- a/src/tensorfold/cuda/shm_allgather.py +++ b/src/tensorfold/cuda/shm_allgather.py @@ -5,10 +5,6 @@ (cudaHostRegister Mapped|Portable), so a kernel can stage its slice of the payload into its own slot, announce an arrival word, and read the peers' slots straight out of host memory. -(vLLM fork). This implementation was written fresh for TensorFold's all-gather -semantics -- the arrival protocol, the generation handling and every kernel in -this file are its own expression, and it invites the same source-overlap check -that the earlier ported draft failed. Messages above ``FALLBACK_BYTES`` (large prefill payloads) stay on NCCL; only the one-shot path lives here. (A rank-order sum fold and a hyper-connection