libr4d: register form of the fused all-reduce writes with a wake store into the idle peer path

ar_hc_write / ar_gather_hc_write get a register form when every thread owns at most one
16-byte word (up to 12 rows of 2560, P2P instances): y, inj and h are loaded into registers
before the first atomic and not re-read after the handshake; LDS-only barriers instead of
__syncthreads; the flag poll is a relaxed system-scope load (the push check with retry behind
a system acquire stays). Before waiting on its chain turn each block stores one word into the
peer's memory: the P2P path between the cards goes idle after ~20 us, and the next store then
becomes visible ~4 us later; the wake store hides that. Wire format, flags, counters, check word
and arithmetic unchanged, mixable with the plain kernels on one instance; host-mailbox twins
keep the plain kernels. The chained wait the forms sit behind ends in r4d_chain_acquire (the
previous commit's s_dcache_inv). 63 new r4d_selftest cases: register form against plain form,
byte-identical, M = 1..8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Code000andClaude Opus 5.5 authored and StillDeadcode committed 2026-11-17 19:01:12 +01:00
1 parent cfec01ec8d
commit 304597970f
6 files changed
+474 -10

No files matched your search

+4
View File
@@ -322,6 +322,10 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla
// is the engine's link word, ended once the peer's push has landed (r4d_ar_link_landed); // is the engine's link word, ended once the peer's push has landed (r4d_ar_link_landed);
// `gate_ctr` is its block counter. The gather form below takes the same pair. A non-zero `chain` // `gate_ctr` is its block counter. The gather form below takes the same pair. A non-zero `chain`
// launches the chained form (r4d_chain.h), which the gather form has at decode heights. // launches the chained form (r4d_chain.h), which the gather form has at decode heights.
// At a message of one 16B word a thread on a P2P instance (`stage` 0) both take their register
// form (r4d_ar_hc_write_reg_kernel), which also stores into the peer's wake word: `peer_flags` is
// then 3 * r4d_ar_max_blocks() words (the flags and two slots' check words) and one more line of
// 64 bytes behind them, as r4d_ar_entry.hip allocates it.
void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n,
long hc, long irow, long hrow, long stream, long nblocks, long nthreads, long hc, long irow, long hrow, long stream, long nblocks, long nthreads,
+6 -2
View File
@@ -266,6 +266,10 @@ int ar8_settle(ArInst* in, int rank, int world) {
* counter, padded to a cache line. */ * counter, padded to a cache line. */
long kSeqWords(long nbw) { return 2L * nbw + 32; } long kSeqWords(long nbw) { return 2L * nbw + 32; }
/* Behind a flags allocation's flags and check words: a 2-rank instance's wake word
* (r4d_ar_link_wake, r4d_ar_seq.h), on a line of its own. */
constexpr long kWakeBytes = 64;
/* Build the world. `max_numel` is the largest message any launch on this instance carries. /* Build the world. `max_numel` is the largest message any launch on this instance carries.
* *
* One sizing rule for the whole family: a slot holds a full message. The one-shots need exactly * One sizing rule for the whole family: a slot holds a full message. The one-shots need exactly
@@ -367,10 +371,10 @@ int build(ArInst* in, long long group, int rank, int world, long long max_numel,
if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
if (host) { if (host) {
sc = r4d_ar_host_alloc((long)nslots * in->slot_bytes); sc = r4d_ar_host_alloc((long)nslots * in->slot_bytes);
fl = r4d_ar_host_alloc((flag_words + 2L * maxb) * 4); fl = r4d_ar_host_alloc((flag_words + 2L * maxb) * 4 + kWakeBytes);
} else { } else {
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen); sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
fl = r4d_ar_ipc_alloc((flag_words + 2L * maxb) * 4, 1, handle, &hlen); fl = r4d_ar_ipc_alloc((flag_words + 2L * maxb) * 4 + kWakeBytes, 1, handle, &hlen);
} }
sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen)); sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen));
+38
View File
@@ -109,3 +109,41 @@ __device__ __forceinline__ void r4d_ar_hc_write_word(const unsigned short* __res
*hp = hv; *hp = hv;
} }
} }
// The write's operands read ahead of the handshake, for a kernel whose threads each own one word
// (r4d_ar_hc_write_reg_kernel): a row's gains and the word's hc stream words depend on nothing the
// peer sends, so their loads ride under the push and the flag round trip instead of following the
// reduce. r4d_ar_hc_write_apply is r4d_ar_hc_write_word over those registers: the same values in
// the same arithmetic, so the same bytes.
#define R4D_ARHC_MAX 8
struct R4dArHcPre {
float g[R4D_ARHC_MAX];
int4 hv[R4D_ARHC_MAX];
};
__device__ __forceinline__ void r4d_ar_hc_write_load(const unsigned short* __restrict__ inj,
const unsigned short* __restrict__ h, int row,
int i0, int n, int hc, long irow, long hrow,
R4dArHcPre& p) {
#pragma unroll
for (int c = 0; c < R4D_ARHC_MAX; ++c) {
if (c >= hc) break;
p.g[c] = bf2f(inj[(long)row * irow + c]);
p.hv[c] = *reinterpret_cast<const int4*>(h + (long)row * hrow + (long)c * n + i0);
}
}
__device__ __forceinline__ void r4d_ar_hc_write_apply(unsigned short* __restrict__ h, int row,
int i0, int n, int hc, long hrow,
const unsigned short* yv, R4dArHcPre& p) {
float v[8];
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = bf2f(yv[j]);
#pragma unroll
for (int c = 0; c < R4D_ARHC_MAX; ++c) {
if (c >= hc) break;
int4 hv = p.hv[c];
unsigned short* he = reinterpret_cast<unsigned short*>(&hv);
#pragma unroll
for (int j = 0; j < 8; ++j) he[j] = f2bf(bf2f(he[j]) + p.g[c] * v[j]);
*reinterpret_cast<int4*>(h + (long)row * hrow + (long)c * n + i0) = hv;
}
}
+188 -6
View File
@@ -337,6 +337,169 @@ __global__ void r4d_ar_gather_hc_write_kernel(
if (CH::on) r4d_chain_done(); if (CH::on) r4d_chain_done();
} }
// ---- The register form of the two fused writes: every thread owns at most one word of its block
// (the launchers' rule: a decode or verify step's message, 320 words a block at four rows of 2560).
// The kernel is then a chain of dependent round trips, not a stream of bytes, and this form
// shortens the chain. The arithmetic, the wire, the flag values and the counters are the plain
// kernels', so the bytes are too, and the two forms follow one another on one instance.
//
// * The path to the peer is woken before the block waits for its turn (r4d_ar_link_wake).
// * The word of `y`, the row's gains and the word's stream words are loaded before the first
// atomic returns and stay in registers: the push does not wait for the slot parity and then a
// load, and nothing is read again behind the handshake.
// * The handshake is r4d_ar_word_handshake (r4d_ar_seq.h): LDS-only barriers, a relaxed poll.
//
// On 2x R9700, Qwen3.8-Flash-Next at tp 2 (96 of these a verify pass, chain 3 with coupling):
// -2.7% a step against the plain kernels, the wake about half of it. P2P instances only: a host
// mailbox keeps the plain kernels and their mirror. `acq` has no meaning here (nothing is read
// behind the check).
template <class CH>
__global__ void r4d_ar_hc_write_reg_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, unsigned int nbw, long long* gate, unsigned int* gate_ctr) {
r4d_ar_link_wake(peer_flags, nbw);
if (CH::on) r4d_chain_wait();
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x;
__shared__ unsigned int s_seq, s_slot;
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
const int w = (n16 + nb - 1) / nb; // 16B words per block, at most the block's threads
const int start = b * w;
int end = start + w; if (end > n16) end = n16;
const int k = start + tid;
const bool live = k < end;
const int kk = live ? k : 0; // a thread without a word reads word 0 and drops it
const int wpr = n >> 3; // 16B words a row
const int row = kk / wpr, i0 = (kk - row * wpr) * 8;
/* Everything that does not depend on the peer, issued before the first atomic returns. */
const int4 v = y4[kk];
R4dArHcPre pre;
r4d_ar_hc_write_load(inj, h, row, i0, n, hc, irow, hrow, pre);
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
const unsigned int s = s_seq;
const int slot = (int)s_slot;
int4* ps = peer_base + (size_t)slot * slot_stride16;
const int4* ms = my_base + (size_t)slot * slot_stride16;
int4 m = make_int4(0, 0, 0, 0);
r4d_ar_word_handshake(peer_flags, my_flags, nbw, (unsigned)slot, (unsigned)b, s, drain,
[&](unsigned int& hh) {
if (live) { ps[k] = v; hh = r4d_archk_u4(v, 4u * (unsigned)k); }
},
[&](unsigned int& hh) {
if (live) { m = ms[k]; hh += r4d_archk_u4(m, 4u * (unsigned)k); }
});
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
if (live) {
const int4 r = vadd<__hip_bfloat16, 8>(v, m);
y4[k] = r;
r4d_ar_hc_write_apply(h, row, i0, n, hc, hrow, reinterpret_cast<const unsigned short*>(&r),
pre);
}
if (CH::on) r4d_chain_done();
}
// The gather's write in the register form: the LDS slot table as r4d_ar_gather_hc_write_kernel
// builds it, then one word a thread, gathered, pushed and kept. Decode table only (no inverse).
template <class CH>
__global__ void r4d_ar_gather_hc_write_reg_kernel(
int4* __restrict__ y4, int4* peer_base, const int4* my_base, unsigned int* peer_flags,
unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj,
unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow,
int slot_stride16, int drain, unsigned int nbw, R4dArGather G, long long* gate,
unsigned int* gate_ctr) {
r4d_ar_link_wake(peer_flags, nbw);
if (CH::on) r4d_chain_wait();
const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x;
__shared__ unsigned int s_seq, s_slot;
__shared__ int s_i[R4D_ARG_ROWS * R4D_ARG_SLOTS];
__shared__ float s_w[R4D_ARG_ROWS * R4D_ARG_SLOTS];
__shared__ float s_g[R4D_ARG_ROWS];
const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid);
const int w = (n16 + nb - 1) / nb; // 16B words per block, at most the block's threads
const int start = b * w;
int end = start + w; if (end > n16) end = n16;
const int wpr = n >> 3; // 16B words a row
const int row_lo = start / wpr;
const int nrow = end > start ? (end - 1) / wpr - row_lo + 1 : 0;
const int K = G.top_k;
const int k = start + tid;
const bool live = k < end;
const int kk = live ? k : (end > start ? start : 0); // a thread without a word drops its loads
const int row = kk / wpr, i0 = (kk - row * wpr) * 8;
R4dArHcPre pre;
r4d_ar_hc_write_load(inj, h, row, i0, n, hc, irow, hrow, pre);
r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe
const unsigned int s = s_seq;
const int slot = (int)s_slot;
int4* ps = peer_base + (size_t)slot * slot_stride16;
const int4* ms = my_base + (size_t)slot * slot_stride16;
/* Slot table, as r4d_ar_gather_hc_write_kernel's. */
for (int x = tid; x < nrow * K; x += nt) s_i[x] = -1;
__syncthreads();
{
const int lo = row_lo * K, hi = (row_lo + nrow) * K;
for (int i = tid; i < G.T; i += nt) {
const int f = G.sorted[i];
if (f >= lo && f < hi) s_i[f - lo] = i;
}
}
for (int x = tid; x < nrow * K; x += nt)
s_w[x] = bf2f(G.ew[(long)(row_lo + x / K) * G.ew_ld + x % K]);
if (G.sh)
for (int r = tid; r < nrow; r += nt) {
const float v0 = bf2f(G.sg[(long)(row_lo + r) * G.sg_ld]);
s_g[r] = G.sig ? (1.0f / (1.0f + __expf(-v0))) : v0;
}
__syncthreads();
int4 v = make_int4(0, 0, 0, 0);
if (live) v = r4d_ar_gather_word<false>(G, nullptr, s_i, s_w, s_g, row, row - row_lo, i0);
int4 m = make_int4(0, 0, 0, 0);
r4d_ar_word_handshake(peer_flags, my_flags, nbw, (unsigned)slot, (unsigned)b, s, drain,
[&](unsigned int& hh) {
if (live) { ps[k] = v; hh = r4d_archk_u4(v, 4u * (unsigned)k); }
},
[&](unsigned int& hh) {
if (live) { m = ms[k]; hh += r4d_archk_u4(m, 4u * (unsigned)k); }
});
r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid);
if (live) {
const int4 r = vadd<__hip_bfloat16, 8>(v, m);
y4[k] = r;
r4d_ar_hc_write_apply(h, row, i0, n, hc, hrow, reinterpret_cast<const unsigned short*>(&r),
pre);
}
if (CH::on) r4d_chain_done();
}
/* r4d_ar_form_pin: the form of the fused writes at a message of one word a thread. -1 is the
* launchers' rule (the register form on a P2P instance), 0 the plain kernels, 1 the rule again.
* A test hook (r4d_selftest compares the two forms byte for byte); nothing else sets it. */
static int g_ar_form = -1;
extern "C" void r4d_ar_form_pin(int form) { g_ar_form = form; }
/* r4d_ar_late_push_pin: 1 makes every 2-rank exact all-reduce, and the register form of the fused
* writes, send its flags before its pushes (drain 4). A test hook (r4d_selftest); nothing else
* sets it. */
static int g_ar_late_push = 0;
extern "C" void r4d_ar_late_push_pin(int on) { g_ar_late_push = on; }
/* Whether a fused write takes the register form: one word a thread, the streams within the
* registers' bound, and the slots in the peer's VRAM (`stage` 0: a host mailbox, read over the
* link, keeps the plain kernels and their mirror). Both ranks decide from the same M, n and grid. */
static bool ar_reg_form(int n16, int nb, int nt, long hc, long stage) {
return g_ar_form != 0 && (n16 + nb - 1) / nb <= nt && hc <= R4D_ARHC_MAX && !stage;
}
// The IPC handle goes into a caller-owned buffer of R4D_AR_HANDLE_BYTES so this stays a C ABI. // The IPC handle goes into a caller-owned buffer of R4D_AR_HANDLE_BYTES so this stays a C ABI.
static_assert(sizeof(hipIpcMemHandle_t) <= R4D_AR_HANDLE_BYTES, "ipc handle larger than the ABI buffer"); static_assert(sizeof(hipIpcMemHandle_t) <= R4D_AR_HANDLE_BYTES, "ipc handle larger than the ABI buffer");
@@ -447,6 +610,19 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m
if (nt < 64) nt = 64; if (nt < 64) nt = 64;
if (nt > 1024) nt = 1024; if (nt > 1024) nt = 1024;
nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes nt &= ~31; // whole waves: the push check's wave sum reads all 32 lanes
if (ar_reg_form(n16, nb, nt, hc, stage)) {
/* Tests only: every push lands after its flag (drain 4). */
const int dr = g_ar_late_push ? 4 : (int)drain;
#define R4D_ARHWR(CH_) \
r4d_ar_hc_write_reg_kernel<CH_><<<nb, nt, 0, st>>>( \
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, \
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, \
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, dr, nbw, (long long*)gate, \
(unsigned int*)gate_ctr)
if (chain) R4D_ARHWR(r4dchain); else R4D_ARHWR(R4dUnchained);
#undef R4D_ARHWR
return;
}
#define R4D_ARHW(CH_) \ #define R4D_ARHW(CH_) \
r4d_ar_hc_write_kernel<CH_><<<nb, nt, 0, st>>>( \ r4d_ar_hc_write_kernel<CH_><<<nb, nt, 0, st>>>( \
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, \ (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, \
@@ -508,7 +684,18 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags,
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, \ (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, \
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, \ n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, \
inv_, (long long*)gate, (unsigned int*)gate_ctr, stage) inv_, (long long*)gate, (unsigned int*)gate_ctr, stage)
if (by_inv) { if (!by_inv && ar_reg_form(n16, nb, nt, hc, stage)) {
/* Tests only: every push lands after its flag (drain 4). */
const int dr = g_ar_late_push ? 4 : (int)drain;
#define R4D_ARGHWR(CH_) \
r4d_ar_gather_hc_write_reg_kernel<CH_><<<nb, nt, 0, st>>>( \
(int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, \
(unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, \
n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, dr, nbw, G, (long long*)gate, \
(unsigned int*)gate_ctr)
if (chain) R4D_ARGHWR(r4dchain); else R4D_ARGHWR(R4dUnchained);
#undef R4D_ARGHWR
} else if (by_inv) {
r4d_ar_gather_inv_kernel<<<1, 1024, 0, st>>>((int*)inv, (const int*)sorted, G.T); r4d_ar_gather_inv_kernel<<<1, 1024, 0, st>>>((int*)inv, (const int*)sorted, G.T);
R4D_ARGHW(true, R4dUnchained, (const int*)inv); R4D_ARGHW(true, R4dUnchained, (const int*)inv);
} else if (chain) { } else if (chain) {
@@ -561,11 +748,6 @@ void r4d_ar_ipc_enable_peer(long peer) {
throw std::runtime_error(std::string("enable_peer: ") + hipGetErrorString(e)); throw std::runtime_error(std::string("enable_peer: ") + hipGetErrorString(e));
} }
/* r4d_ar_late_push_pin: 1 makes every 2-rank exact all-reduce send its flags before its pushes
* (drain 4). A test hook (r4d_selftest); nothing else sets it. */
static int g_ar_late_push = 0;
extern "C" void r4d_ar_late_push_pin(int on) { g_ar_late_push = on; }
void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags, void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags,
long my_flags, long seq_ctrs, long slot_stride16, long my_flags, long seq_ctrs, long slot_stride16,
long inp, long out, long n_elem, long dtype, long inp, long out, long n_elem, long dtype,
+118
View File
@@ -198,6 +198,124 @@ __device__ __forceinline__ void r4d_archk_wait(unsigned int* my_flags, unsigned
} }
} }
// ---- The handshake of a kernel whose threads each own at most one word of the block's message
// (a decode or verify step: r4d_ar_hc_write_reg_kernel, r4d_ar_oneshot_2rank_exact.hip). Such a
// kernel is a chain of dependent round trips, and this is the plain kernels' protocol -- the same
// check word, the same flag value, a pass only behind the peer's flag and on an agreeing sum --
// with the chain shortened:
//
// * Barriers order LDS only (r4d_lds_barrier). A __syncthreads also waits for every outstanding
// load and store and invalidates the vector caches: 0.26 us against 0.03 on this part, five
// times a launch in the plain kernels.
// * The flag poll is a relaxed system-scope load. As an acquire load every poll is followed by a
// system-scope cache invalidate (0.35 us, and whatever the card had cached for the kernels
// behind goes with it), for as long as the peer is late. The slot is fine-grained memory, read
// past the caches, and the push check re-reads behind a system-scope acquire whenever the
// bytes do not agree, exactly as r4d_archk_wait does.
// * `push` stores the thread's word and `rehash` loads the peer's into the caller's registers, so
// the reduce reads nothing again.
//
// drain 4 is the plain kernels' test mode (r4d_ar_late_push_pin): the flag ahead of the push and
// the push ~20 us behind it.
#define R4D_ARW_SPIN_MAX 4000000000ULL
// A barrier that orders LDS only.
__device__ __forceinline__ void r4d_lds_barrier() {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
__builtin_amdgcn_s_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
}
// The wake word of a 2-rank instance: the word behind the flags and the two slots' check words
// (r4d_ar_entry.hip sizes the allocation). Nothing reads it.
//
// The path between two cards idles when nothing crosses it. On 2x R9700 behind an EPYC's two root
// complexes, with each card's own link busy all the while: a store into the peer's memory more
// than ~20 us after the last one becomes visible there ~4 us later than one behind recent traffic,
// and the path is back at full speed ~2-4 us after that first store. A step's all-reduces are
// ~100 us apart, and a handshake's last store is its flag, so the whole of that wait lands on the
// flag: both ranks sit in their polls for it (5.9 us a mixer all-reduce of Qwen3.8-Flash-Next
// where neither rank was late, against 2.4 behind a store 2-20 us earlier). A block's first lane
// stores into the wake word before it waits for its turn, which is as early as the kernel knows it
// is about to push: the path wakes while the block waits, takes its counters and pushes.
__device__ __forceinline__ void r4d_ar_link_wake(unsigned int* peer_flags, unsigned int nbw) {
if (threadIdx.x == 0)
__hip_atomic_store(&peer_flags[3u * nbw], blockIdx.x, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
}
template <typename P, typename F>
__device__ __forceinline__ void r4d_ar_word_handshake(unsigned int* peer_flags,
unsigned int* my_flags, unsigned int nbw,
unsigned int slot, unsigned int b,
unsigned int seq, int drain, const P& push,
const F& rehash) {
__shared__ unsigned int s_wput[32];
__shared__ unsigned int s_wchk[32];
__shared__ unsigned int s_wok;
const unsigned int tid = threadIdx.x, nt = blockDim.x, nw = (nt + 31u) / 32u;
const bool late = drain == 4;
if (late) {
if (tid == 0)
__hip_atomic_store(&peer_flags[b], seq, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
const unsigned long long t0 = wall_clock64();
while (wall_clock64() - t0 < 2000ull) __builtin_amdgcn_s_sleep(8); // 100 MHz: 20 us
}
unsigned int hck = 0u;
push(hck);
hck = r4d_archk_wave_sum(hck);
if ((tid & 31u) == 0u) s_wput[tid >> 5] = hck;
/* Every wave's pushes are out before the one barrier in front of the flag (the drain modes of
* the plain kernels; 2 is thread 0's fence below). */
if (drain == 1) __threadfence_system();
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
r4d_lds_barrier();
if (tid == 0) {
unsigned int t = 0u;
for (unsigned int w = 0; w < nw; ++w) t += s_wput[w];
unsigned int* const cw = r4d_archk_word(peer_flags, nbw, slot, b);
if (late) {
/* Nothing else writes the pushes back before the kernel ends: a release (r4d_archk_put). */
__hip_atomic_store(cw, t + seq * R4D_ARCHK_SALT, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
} else {
/* The flag's release writes the pushes back, so the check word itself can be relaxed. */
__hip_atomic_store(cw, t + seq * R4D_ARCHK_SALT, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM);
if (drain == 2) __threadfence_system();
__hip_atomic_store(&peer_flags[b], seq, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM);
}
unsigned long long z = 0;
/* A handshake that cannot complete is a lockstep violation; trap rather than sum stale bytes. */
while (r4d_ar_seq_behind(__hip_atomic_load(&my_flags[b], __ATOMIC_RELAXED,
__HIP_MEMORY_SCOPE_SYSTEM), seq))
if (++z > R4D_ARW_SPIN_MAX) __builtin_trap();
}
r4d_lds_barrier();
const unsigned long long t0 = tid == 0 ? wall_clock64() : 0ull;
for (;;) {
/* The check word first, so its round trip overlaps the re-hash's loads (r4d_archk_wait). */
const unsigned int want = tid == 0 ? __hip_atomic_load(r4d_archk_word(my_flags, nbw, slot, b),
__ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM)
: 0u;
unsigned int h = 0u;
rehash(h);
h = r4d_archk_wave_sum(h);
if ((tid & 31u) == 0u) s_wchk[tid >> 5] = h;
r4d_lds_barrier();
if (tid == 0) {
unsigned int t = 0u;
for (unsigned int w = 0; w < nw; ++w) t += s_wchk[w];
const bool ok = t + seq * R4D_ARCHK_SALT == want;
if (!ok && wall_clock64() - t0 > R4D_ARCHK_DEADLINE) __builtin_trap();
s_wok = ok ? 1u : 0u;
}
r4d_lds_barrier();
if (s_wok) return;
r4d_lds_barrier(); // s_wchk and s_wok are rewritten by the next try
/* Drop the vector caches, so the next try reads the bytes from where the push lands. */
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
__builtin_amdgcn_s_sleep(2);
}
}
// ---- The host mailbox's one read. A host twin's slots are pinned host memory (r4d_ar_entry.hip), // ---- The host mailbox's one read. A host twin's slots are pinned host memory (r4d_ar_entry.hip),
// which the card reads past every cache over its own link, so reading the slot for the check and // which the card reads past every cache over its own link, so reading the slot for the check and
// again for the reduce crosses the link twice: at --p2p off a prefill all-reduce's reads doubled // again for the reduce crosses the link twice: at --p2p off a prefill all-reduce's reads doubled
+120 -2
View File
@@ -154,6 +154,7 @@ struct Plugin {
void (*mla_stats)(unsigned long long*) = nullptr; void (*mla_stats)(unsigned long long*) = nullptr;
void (*pin_mla_rows)(int) = nullptr; void (*pin_mla_rows)(int) = nullptr;
void (*pin_late_push)(int) = nullptr; void (*pin_late_push)(int) = nullptr;
void (*pin_ar_form)(int) = nullptr;
int (*record)(const void**, int) = nullptr; int (*record)(const void**, int) = nullptr;
void (*ar8_settings)(const R4DAr8Settings*) = nullptr; void (*ar8_settings)(const R4DAr8Settings*) = nullptr;
}; };
@@ -226,6 +227,7 @@ static bool load(Plugin* pl, const char* path) {
okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats); okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats);
okall &= sym(pl->h, "r4d_mla_rows_pin_form", &pl->pin_mla_rows); okall &= sym(pl->h, "r4d_mla_rows_pin_form", &pl->pin_mla_rows);
okall &= sym(pl->h, "r4d_ar_late_push_pin", &pl->pin_late_push); okall &= sym(pl->h, "r4d_ar_late_push_pin", &pl->pin_late_push);
okall &= sym(pl->h, "r4d_ar_form_pin", &pl->pin_ar_form);
okall &= sym(pl->h, "r4d_record_dispatches", &pl->record); okall &= sym(pl->h, "r4d_record_dispatches", &pl->record);
okall &= sym(pl->h, "r4d_ar8_test_settings", &pl->ar8_settings); okall &= sym(pl->h, "r4d_ar8_test_settings", &pl->ar8_settings);
ScopedAr8::apply = pl->ar8_settings; ScopedAr8::apply = pl->ar8_settings;
@@ -29209,6 +29211,7 @@ struct ArHc {
const char* act = nullptr; /* gather's shared arm: null operand, "none", "sigmoid" */ const char* act = nullptr; /* gather's shared arm: null operand, "none", "sigmoid" */
bool use_scratch = false; /* hand the inverse table's scratch to the gather */ bool use_scratch = false; /* hand the inverse table's scratch to the gather */
void* inst = nullptr; void* inst = nullptr;
int rounds = 1; /* launches on the one instance, y handed in again */
int rc_init = RAD_E_STATE, rc_launch = RAD_OK; int rc_init = RAD_E_STATE, rc_launch = RAD_OK;
std::vector<uint16_t> y_in, inj, h0; /* what we hand the kernel */ std::vector<uint16_t> y_in, inj, h0; /* what we hand the kernel */
std::vector<uint16_t> ye, ew, sh, sg; /* the gather's inputs */ std::vector<uint16_t> ye, ew, sh, sg; /* the gather's inputs */
@@ -29284,8 +29287,11 @@ static void ar_hc_worker(ArHc* t) {
} }
} }
if (t->rc_launch == RAD_OK) { if (t->rc_launch == RAD_OK) {
t->rc_launch = t->row->launch(&a, nullptr); for (int round = 0; round < t->rounds && t->rc_launch == RAD_OK; ++round) {
st_stream_sync(nullptr); if (round) st_memcpy(y, t->y_in.data(), yb, hipMemcpyHostToDevice);
t->rc_launch = t->row->launch(&a, nullptr);
st_stream_sync(nullptr);
}
t->y_out.resize((size_t)(t->M * t->n)); t->y_out.resize((size_t)(t->M * t->n));
t->h_out.resize((size_t)(t->M * t->hc * t->n)); t->h_out.resize((size_t)(t->M * t->hc * t->n));
st_memcpy(t->y_out.data(), y, yb, hipMemcpyDeviceToHost); st_memcpy(t->y_out.data(), y, yb, hipMemcpyDeviceToHost);
@@ -29491,6 +29497,115 @@ static void ar_hc_write_case(const Plugin& pl, const std::vector<int>& devs, con
} }
} }
/* The register form of the two fused writes (r4d_ar_hc_write_reg_kernel and its gather twin: one
* word a thread, the write's operands read ahead, the handshake of r4d_ar_seq.h's
* r4d_ar_word_handshake) against the plain kernels, through r4d_ar_form_pin, at the decode and
* verify heights of Qwen3.8-Flash-Next's residual (n 2560, four streams): five launches back to
* back on one instance, so both slot parities and the counters' carry-over are walked, and every
* rank's y and h after the last compared byte for byte. The register form runs a second time with
* every push held ~20 us behind its flag (r4d_ar_late_push_pin), which is the path its push check
* re-reads on. The forms must agree bit for bit: the plain kernels are the ones ar_hc_write_case
* holds against the host oracle. */
static void ar_hc_forms_case(const Plugin& pl, const std::vector<int>& devs, const char* name,
bool want_gather) {
const RadKernelInfo* row = find(pl, name);
const std::string nm = std::string(name) + " register form";
if (!row) { ok(nm.c_str(), false, "row absent"); return; }
if (devs.size() < 2) { skip(nm.c_str(), "needs 2 gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, 2)) { skip(nm.c_str(), "no peer path between the cards (device.p2p)"); return; }
if (!pl.pin_ar_form || !pl.pin_late_push) { skip(nm.c_str(), "no r4d_ar_form_pin"); return; }
struct Arm { const char* act; };
const std::vector<Arm> arms = want_gather ? std::vector<Arm>{ { nullptr }, { "none" } }
: std::vector<Arm>{ { nullptr } };
for (const Arm& arm : arms)
for (int64_t M : { 1, 2, 3, 4, 5, 6, 8 }) {
const int64_t n = 2560, hc = 4, k = want_gather ? 8 : 0, T = M * k;
std::vector<int32_t> sorted((size_t)T, -1);
if (want_gather) {
std::vector<int32_t> ex((size_t)T);
uint64_t rs = 0x9E3779B97F4A7C15ull ^ ((uint64_t)M * 1315423911ull);
auto rnd = [&]() { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; };
for (int64_t i = 0; i < T; ++i) {
const uint64_t v = rnd();
ex[(size_t)i] = (v % 31 == 0) ? -1 : (int32_t)((v >> 8) % 64);
}
int64_t pos = 0;
for (int32_t e = 0; e < 64; ++e)
for (int64_t i = 0; i < T; ++i)
if (ex[(size_t)i] == e) sorted[(size_t)pos++] = (int32_t)i;
}
/* form 0: the plain kernels; 1: the register form; 2: the register form, late pushes. */
std::vector<std::vector<ArHc>> runs;
bool up = true, ran = true;
for (int form = 0; form < 3 && up && ran; ++form) {
pl.pin_ar_form(form == 0 ? 0 : 1);
pl.pin_late_push(form == 2 ? 1 : 0);
std::vector<ArHc> t(2);
std::vector<std::thread> th;
for (int r = 0; r < 2; ++r) {
ArHc& x = t[(size_t)r];
x.row = row; x.rank = r; x.dev = devs[(size_t)r]; x.world = 2;
x.M = M; x.n = n; x.hc = hc; x.top_k = k; x.act = arm.act; x.rounds = 5;
x.y_in.resize((size_t)(M * n));
x.inj.resize((size_t)(M * hc));
x.h0.resize((size_t)(M * hc * n));
uint64_t rs = 0x9E3779B97F4A7C15ull ^ ((uint64_t)(r + 1) * 0x9E3779B97F4A7C15ull) ^
((uint64_t)M * 1315423911ull);
auto rnd = [&]() { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; };
for (auto& v : x.y_in) v = h_to_bf16(((int64_t)(rnd() % 4001) - 2000) / 512.0f);
/* The gains and the streams are replicated across ranks, as the engine holds them. */
uint64_t rc = 0x2545F4914F6CDD1Dull ^ (uint64_t)M;
auto rndc = [&]() { rc ^= rc << 13; rc ^= rc >> 7; rc ^= rc << 17; return rc; };
for (auto& v : x.inj) v = h_to_bf16(((int64_t)(rndc() % 2001) - 1000) / 4000.0f);
for (auto& v : x.h0) v = h_to_bf16(((int64_t)(rndc() % 4001) - 2000) / 512.0f);
if (want_gather) {
x.sorted = sorted;
x.ye.resize((size_t)(T * n));
x.ew.resize((size_t)T);
for (auto& v : x.ye) v = h_to_bf16(((int64_t)(rnd() % 4001) - 2000) / 512.0f);
for (auto& v : x.ew) v = h_to_bf16((float)(rndc() % 1000 + 1) / 1024.0f);
if (arm.act) {
x.sh.resize((size_t)(M * n));
x.sg.resize((size_t)M);
for (auto& v : x.sh) v = h_to_bf16(((int64_t)(rnd() % 4001) - 2000) / 256.0f);
for (auto& v : x.sg) v = h_to_bf16(((int64_t)(rndc() % 801) - 400) / 100.0f);
}
}
th.emplace_back(ar_hc_worker, &x);
}
for (std::thread& x : th) x.join();
for (const ArHc& x : t) { up = up && x.rc_init == RAD_OK; ran = ran && x.rc_launch == RAD_OK; }
if (row->fini) for (ArHc& x : t) if (x.inst) row->fini(x.inst);
runs.push_back(std::move(t));
}
pl.pin_ar_form(-1);
pl.pin_late_push(0);
const std::string at = fmt(" M=%lld n=%lld hc=%lld%s", (long long)M, (long long)n,
(long long)hc, want_gather ? (arm.act ? ", top_k 8, shared arm"
: ", top_k 8") : "");
ok((nm + at + ": every form launches").c_str(), up && ran && runs.size() == 3);
if (!up || !ran || runs.size() != 3) continue;
static const char* const kWhat[] = { "", "byte-identical to the plain kernels after five launches",
"with every push ~20 us behind its flag: byte-identical too" };
for (size_t f = 1; f < 3; ++f) {
int64_t bad = 0, nz = 0;
for (int r = 0; r < 2; ++r) {
const ArHc& a = runs[0][(size_t)r];
const ArHc& b = runs[f][(size_t)r];
for (size_t i = 0; i < a.y_out.size(); ++i) bad += a.y_out[i] != b.y_out[i];
for (size_t i = 0; i < a.h_out.size(); ++i) { bad += a.h_out[i] != b.h_out[i]; nz += b.h_out[i] != 0; }
}
/* The two ranks' y agree as well (the fold is symmetric), and something was written. */
int64_t skew = 0;
for (size_t i = 0; i < runs[f][0].y_out.size(); ++i)
skew += runs[f][0].y_out[i] != runs[f][1].y_out[i];
ok((nm + at + ", " + kWhat[f]).c_str(), bad == 0 && skew == 0 && nz > M * hc * n,
fmt("%lld bytes differ from the plain kernels, %lld between the ranks", (long long)bad,
(long long)skew));
}
}
}
/* ------------------------------------------------------------------ the fused junction (ar_rmsnorm_quant_i8) */ /* ------------------------------------------------------------------ the fused junction (ar_rmsnorm_quant_i8) */
/* The all-reduce with the sandwich-norm junction as its epilogue, at two ranks /* The all-reduce with the sandwich-norm junction as its epilogue, at two ranks
* (ar_rmsnorm_quant_i8) and at four (ar_rmsnorm_quant_i8_4rank), against the chain it replaces: * (ar_rmsnorm_quant_i8) and at four (ar_rmsnorm_quant_i8_4rank), against the chain it replaces:
@@ -33704,6 +33819,9 @@ static void device_phase(const Plugin& pl) {
std::printf(" %s\n", n.c_str()); std::printf(" %s\n", n.c_str());
ar_hc_write_case(pl, devs, n.c_str(), std::strstr(base, "4rank") ? 4 : 2, ar_hc_write_case(pl, devs, n.c_str(), std::strstr(base, "4rank") ? 4 : 2,
std::strstr(base, "gather") != nullptr); std::strstr(base, "gather") != nullptr);
/* The host twins keep the plain kernels: their mailbox is read over the link. */
if (!std::strstr(base, "4rank") && n == base)
ar_hc_forms_case(pl, devs, n.c_str(), std::strstr(base, "gather") != nullptr);
} }
} }
/* The wide rows at every width are dispatched above and skip themselves, naming the width /* The wide rows at every width are dispatched above and skip themselves, naming the width