diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 62d488ed..81a08e1f 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -380,10 +380,12 @@ void r4d_ar_wide_dims(int* max_blocks, int* nb_design, int* max_peers); // rank s (fp32, ascending rank order), then gathered. Sends 2*(ws-1)/ws*N bytes per rank in two // hops, for sizes where the one-shot's (ws-1)*N send is too heavy. Shards are as even as the word // count allows (the first n16 % ws take one more word), so the message need not divide by the -// rank count. Regions A and B sit at 0 and the longest shard, so the slot stride must hold twice -// that. Above the bound below the caller falls back to the one-shot; it only guards the kernel's -// int word offsets (2^28 elements is 2^26 words at fp32). A lower bound would send large prefill -// chunks (e.g. 8192 tokens at Gemma 4's 2816 width, 23M-46M elements) to the one-shot. +// rank count. At 8 ranks `shard_weights` (8 ints, or null for the even split) sizes the shards per +// rank instead (r4d_ar_shards.h); every rank must pass the same weights. Regions A and B sit at 0 +// and the longest shard, so the slot stride must hold twice that. Above the bound below the +// caller falls back to the one-shot; it only guards the kernel's int word offsets (2^28 elements +// is 2^26 words at fp32). A lower bound would send large prefill chunks (e.g. 8192 tokens at +// Gemma 4's 2816 width, 23M-46M elements) to the one-shot. enum { R4D_AR_TWOSHOT_WIDE_MAX_ELEMS = 268435456 }; void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long peer_flags0, long peer_flags1, long my_scratch, long my_flags, long seq_ctrs, @@ -403,7 +405,8 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long peer_flags5, long peer_flags6, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, - long nblocks, long nthreads, long drain, long acq, long pub); + long nblocks, long nthreads, long drain, long acq, long pub, + const int* shard_weights); // The tiered int8 wire on both two-shot hops (r4d_ar_twoshot_Nrank_ti8.hip; codec in // r4d_ar_ti8.h), 3 or 4 ranks. Int8 groups of 32 with an fp16 scale and a per-group record // (T1 plain, T2 top-1-exact, T3 wht32), 38 bytes/group; tiering is deterministic and diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index c6ce62ad..36760cf2 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -20,6 +20,7 @@ #include "r4d_args.h" #include "r4d.h" +#include "r4d_ar_shards.h" #include #include @@ -68,6 +69,7 @@ struct Rendezvous { long flags [R4D_MAX_RANKS] = { 0 }; long seq [R4D_MAX_RANKS] = { 0 }; int dev [R4D_MAX_RANKS] = { 0 }; + int shard_w[R4D_MAX_RANKS][R4D_MAX_RANKS] = { { 0 } }; int failed = 0; }; @@ -111,6 +113,10 @@ struct ArInst { * each card reaches over its own link (see build). */ int host = 0; long gate_ctr = 0; /* the blocks that have seen their peer's bytes land (r4d_ar_seq.h) */ + /* The eight-rank two-shot's per-rank shard weights (r4d_ar_shards.h), fixed at build so the + * scratch was sized for them and a recorded launch keeps its table. */ + int shard_weighted = 0; + int shard_w[R4D_MAX_RANKS] = { 0 }; }; /* A parameter that may be declared as a range: init gets one band's frozen geometry, and buffers @@ -127,6 +133,29 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) { long align16(long v) { return (v + 15) & ~15L; } +/* RADIANCE_AR8_SHARD_WEIGHTS, read at every eight-rank build so a process can change it between + * instances; each rank reads it and build() checks that they agree. */ +bool ar8_shard_weights(int* w) { + const char* e = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); + if (!e || !*e) return false; + static std::once_flag said_bad, said_on; + int got[8]; + if (!r4d_ar_shard_weights_parse(e, 8, got)) { + std::call_once(said_bad, [e] { + std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs eight non-negative integers, " + "comma-separated, sum > 0); eight-rank two-shot shards stay even\n", + R4D_AR8_SHARD_WEIGHTS_ENV, e); + }); + return false; + } + std::memcpy(w, got, sizeof(got)); + std::call_once(said_on, [w] { + std::fprintf(stderr, "[r4d] eight-rank two-shot shards weighted %d,%d,%d,%d,%d,%d,%d,%d\n", + w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); + }); + return true; +} + /* Sequence counter allocation in words: 2 * nbw (r4d_ar_seq.h), then r4d_ar_link_landed's block * counter, padded to a cache line. */ long kSeqWords(long nbw) { return 2L * nbw + 32; } @@ -136,7 +165,9 @@ long kSeqWords(long nbw) { return 2L * nbw + 32; } * One sizing rule for the whole family: a slot holds a full message. The one-shots need exactly * that; the two-shot's two regions (2 * message / world_size) and the tiered-int8 wire's two * images (2 * ceil(shard/32) * 38 bytes) are smaller. RadInitFn is not told which row resolved, - * so sizing for the maximum avoids reconstructing which kernel this instance serves. + * so sizing for the maximum avoids reconstructing which kernel this instance serves. The one + * exception is a weighted eight-rank two-shot whose largest weight is over half the sum: its two + * regions of the longest shard outgrow a message, and the slot grows to hold them. * * Cost: at a 4096-token chunk on a 5120-wide residual, 40 MiB a slot and 80 MiB for the pair. One * set serves every op with the same (rank, world, dtype, bound); see the cache below. */ @@ -153,6 +184,15 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, in->max_numel = (long)max_numel; in->slot_bytes = align16((long)max_numel * in->esize); in->slot16 = in->slot_bytes / 16; + if (world == 8 && ar8_shard_weights(in->shard_w)) { + in->shard_weighted = 1; + const long need16 = + 2 * r4d_ar_shard_max_bound((long)max_numel * in->esize / 16, 8, in->shard_w); + if (need16 > in->slot16) { + in->slot16 = need16; + in->slot_bytes = need16 * 16; + } + } int maxb = 0, nb_design = 0, max_peers = 0; if (world == 2) { @@ -223,10 +263,21 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, g_rv.flags[rank] = fl; g_rv.seq[rank] = sq; g_rv.dev[rank] = dev; + for (int i = 0; i < R4D_MAX_RANKS; ++i) + g_rv.shard_w[rank][i] = in->shard_weighted ? in->shard_w[i] : -1; } int rc = rv_barrier(world); if (rc != RAD_OK) return rc; + /* Every rank must cut the message at the same words, or an owner reduces words its peers + * pushed elsewhere. All ranks compare the same table, so all refuse together. */ + for (int r = 0; r < world; ++r) + if (std::memcmp(g_rv.shard_w[r], g_rv.shard_w[rank], sizeof(g_rv.shard_w[rank]))) { + std::fprintf(stderr, "[r4d] ranks %d and %d read different %s\n", rank, r, + R4D_AR8_SHARD_WEIGHTS_ENV); + return RAD_E_STATE; + } + /* Peer access is per context, so each rank enables its own, after the publish barrier where * peer device ordinals are known. A host can expose more HIP devices than ranks (e.g. an * integrated GPU), so the ordinal comes from the peer rather than the rank. */ @@ -494,7 +545,11 @@ static int ar_setup(const RadArgs* a, ArCall* c, int shard_nb) { c->pub = cfgv.pub; const long words16 = (long)n * in->esize / 16; - const long basis = shard_nb ? words16 / in->world : words16; + long basis = shard_nb ? words16 / in->world : words16; + if (shard_nb && in->shard_weighted) { + long off[R4D_MAX_RANKS + 1]; + basis = r4d_ar_shard_table(words16, in->world, in->shard_w, off); + } /* The two-shots move shards, so they use the smaller basis and a tighter ceiling; the * full-message rule over-launches across the mid band. */ int cap = in->nb_cap; @@ -842,10 +897,14 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; if (c.in->world != 8) return RAD_E_SHAPE; if (c.numel > R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) return RAD_E_SHAPE; - const long words16 = c.numel * c.in->esize / 16; - if (words16 % c.in->world) return RAD_E_SHAPE; - if (2 * (c.numel * c.in->esize) / c.in->world > c.in->slot_bytes) return RAD_E_SCRATCH; const ArInst* in = c.in; + const int* weights = in->shard_weighted ? in->shard_w : nullptr; + /* Even shards keep the four-rank rule (whole words a rank); weighted ones are uneven anyway. */ + const long words16 = c.numel * in->esize / 16; + if (!weights && words16 % in->world) return RAD_E_SHAPE; + long off[R4D_MAX_RANKS + 1]; + const long sh_max = r4d_ar_shard_table(words16, in->world, weights, off); + if (2 * sh_max * 16 > in->slot_bytes) return RAD_E_SCRATCH; R4D_TRY("ar_twoshot_8rank_exact", r4d_ar_twoshot_8rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2], in->peer_scratch[3], in->peer_scratch[4], in->peer_scratch[5], @@ -856,7 +915,7 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) { in->my_scratch, in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, - c.pub)); + c.pub, weights)); return RAD_OK; } diff --git a/libr4d/r4d_ar_shards.h b/libr4d/r4d_ar_shards.h new file mode 100644 index 00000000..2cc2ec6d --- /dev/null +++ b/libr4d/r4d_ar_shards.h @@ -0,0 +1,76 @@ +#pragma once +// r4d_ar_shards.h: the exact two-shot's shard table. Shard s is the 16-byte words +// [off[s], off[s+1]) and is reduced by rank s. Host only and HIP-free: the launcher, the plugin +// shim (which sizes scratch and picks the block count from it) and the selftest (which prints it) +// must derive the same table from the same inputs. +// +// The even split is n16 / ws words a shard with the first n16 % ws shards one word longer. Weights +// split proportionally (floor(n16 * w_s / sum)) and hand the few remaining words, one each, to the +// weighted ranks in ascending order; equal weights therefore reproduce the even split exactly, and +// a zero weight always means an empty shard. Which rank owns a word changes only the link it +// crosses, not its fold (fp32, ascending rank), so every table gives the same bits. +#include + +#define R4D_AR8_SHARD_WEIGHTS_ENV "RADIANCE_AR8_SHARD_WEIGHTS" +enum { R4D_AR_SHARD_WEIGHT_MAX = 65535 }; + +// `ws` non-negative integers separated by commas, each at most R4D_AR_SHARD_WEIGHT_MAX, summing +// to more than zero; nothing else (no blanks, signs or trailing text). +inline bool r4d_ar_shard_weights_parse(const char* s, int ws, int* w) { + if (!s) return false; + long sum = 0; + for (int i = 0; i < ws; ++i) { + if (*s < '0' || *s > '9') return false; + long v = 0; + while (*s >= '0' && *s <= '9') { + v = v * 10 + (*s++ - '0'); + if (v > R4D_AR_SHARD_WEIGHT_MAX) return false; + } + w[i] = (int)v; + sum += v; + if (i + 1 < ws) { + if (*s != ',') return false; + ++s; + } + } + return *s == '\0' && sum > 0; +} + +// Fills off[0..ws] and returns the longest shard. `w` null: the even split. +inline long r4d_ar_shard_table(long n16, int ws, const int* w, long* off) { + long len[16]; + if (!w) { + const long base = n16 / ws, rem = n16 % ws; + for (int s = 0; s < ws; ++s) len[s] = base + (s < rem ? 1 : 0); + } else { + long sum = 0; + for (int s = 0; s < ws; ++s) sum += w[s]; + long left = n16; + for (int s = 0; s < ws; ++s) { + len[s] = n16 * w[s] / sum; + left -= len[s]; + } + for (int s = 0; s < ws && left > 0; ++s) + if (w[s] > 0) { ++len[s]; --left; } + } + long sh_max = 0; + off[0] = 0; + for (int s = 0; s < ws; ++s) { + off[s + 1] = off[s] + len[s]; + if (len[s] > sh_max) sh_max = len[s]; + } + return sh_max; +} + +// The longest shard any message of at most n16 words can get under `w` (null: even): what the +// scratch slot must hold twice. +inline long r4d_ar_shard_max_bound(long n16, int ws, const int* w) { + if (!w) return (n16 + ws - 1) / ws; + long sum = 0, wmax = 0; + for (int s = 0; s < ws; ++s) { + sum += w[s]; + if (w[s] > wmax) wmax = w[s]; + } + const long b = n16 * wmax / sum + 1; + return b < n16 ? b : n16; +} diff --git a/libr4d/r4d_ar_twoshot_Nrank_exact.hip b/libr4d/r4d_ar_twoshot_Nrank_exact.hip index a1f021cf..eedcd541 100644 --- a/libr4d/r4d_ar_twoshot_Nrank_exact.hip +++ b/libr4d/r4d_ar_twoshot_Nrank_exact.hip @@ -9,10 +9,14 @@ // to my out and every peer's slot[me] region B, flag 2s; assemble out from region B. Region A at // 0, B at sh_max; the slot stride must hold 2*sh_max. // -// Uneven shards: n16 words split into base = n16/ws words per shard, and the first n16 % ws shards -// take one more, so shard s starts at s*base + min(s, rem). At 4 and 8 ranks engine residuals -// divide evenly; at 3 they rarely do (a 2048-wide bf16 row is 256 words). Each word is the same -// fp32 fold in ascending rank order whoever owns it, so the bits match the one-shot's. +// The shard table (r4d_ar_shards.h) comes in as a kernel argument. By default it is the even +// split (the first n16 % ws shards one word longer); at 3 ranks engine residuals rarely divide (a +// 2048-wide bf16 row is 256 words). At 8 ranks it may be weighted per link +// (RADIANCE_AR8_SHARD_WEIGHTS); a rank with weight 0 owns nothing and only pushes, gathers and +// handshakes. Over both phases a rank moves N + (ws-2)*len_r each way, but phase 1 only sends +// N - len_r (receiving (ws-1)*len_r) and phase 2 the reverse, so a short shard on a slow link pays +// only as far as the phases overlap on that link (docs/GUIDE.md, 4.7). Each word is the same fp32 +// fold in ascending rank order whoever owns it, so the bits match the one-shot's. // // Shares the wide family's flag/seq/scratch set (r4d_ar_wide.h): it publishes in the 2*seq flag // space plus the 2s-1 half-step and advances the per-block counter once per AR, so one buffer set @@ -20,14 +24,21 @@ // requirement in the mix. #include "r4d.h" #include "r4d_ar_wide.h" +#include "r4d_ar_shards.h" #include #include +template +struct R4DArShardOff { + int off[WS + 1]; + int sh_max; +}; + template __global__ void r4d_ar_twoshot_wide_exact_kernel( const int4* __restrict__ in4, R4DArWidePeers peers, const int4* __restrict__ my_base, unsigned int* __restrict__ my_flags, - int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, int n16, + int4* __restrict__ out4, unsigned int* __restrict__ seq_ctrs, R4DArShardOff sh, int slot_stride16, int rank, int drain, int acq, int pub, long long* gate, unsigned int* gate_ctr) { constexpr int NPEERS = WS - 1; @@ -38,11 +49,9 @@ __global__ void r4d_ar_twoshot_wide_exact_kernel( const unsigned int s = s_seq; const int parity = (int)s_slot; - // shard s = words [s*base + min(s, rem), +base + (s < rem)); sh_max is the longest one - const int base = n16 / WS, rem = n16 % WS; - const int sh_max = base + (rem ? 1 : 0); -#define R4D_TS_OFF(s) ((s) * base + ((s) < rem ? (s) : rem)) -#define R4D_TS_LEN(s) (base + ((s) < rem ? 1 : 0)) + const int sh_max = sh.sh_max; +#define R4D_TS_OFF(s) (sh.off[s]) +#define R4D_TS_LEN(s) (sh.off[(s) + 1] - sh.off[s]) const int w = (sh_max + nb - 1) / nb; // block b owns words [w0,w1) of the SHARD space const int w0 = b * w; @@ -118,7 +127,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream_i, long nblocks, long nthreads, long drain, long acq, long pub, - long gate, long gate_ctr) { + long gate, long gate_ctr, const int* shard_weights) { constexpr int NPEERS = WS - 1; if (rank < 0 || rank >= WS) throw std::runtime_error("all_reduce: rank " + std::to_string(rank) + @@ -133,11 +142,25 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, std::to_string(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS) + " elems); use the fallback path"); const long n16 = nbytes / 16; - if (n16 < WS) + if (!shard_weights && n16 < WS) throw std::runtime_error("all_reduce: message (" + std::to_string(n16) + " 16B words) is shorter than one word a rank"); - // the longest shard (the kernel's uneven split); regions A and B each hold one - const long sh_max = (n16 + WS - 1) / WS; + if (n16 < 1) throw std::runtime_error("all_reduce: empty message"); + if (shard_weights) { + long wsum = 0; + for (int s = 0; s < WS; ++s) { + if (shard_weights[s] < 0 || shard_weights[s] > R4D_AR_SHARD_WEIGHT_MAX) + throw std::runtime_error("all_reduce: shard weight out of range"); + wsum += shard_weights[s]; + } + if (wsum <= 0) throw std::runtime_error("all_reduce: shard weights sum to zero"); + } + long off[WS + 1]; + const long sh_max = r4d_ar_shard_table(n16, WS, shard_weights, off); + R4DArShardOff sh{}; + for (int s = 0; s <= WS; ++s) sh.off[s] = (int)off[s]; + sh.sh_max = (int)sh_max; + // regions A and B each hold the longest shard if (2 * sh_max > (long)slot_stride16) throw std::runtime_error("all_reduce: shard (" + std::to_string(sh_max) + " 16B words) needs 2x inside the per-source slot stride (" + @@ -178,7 +201,7 @@ static void ar_twoshot_launch(const long* peer_scratch, const long* peer_flags, #define R4D_AR_TS_LAUNCH(T, LN) \ r4d_ar_twoshot_wide_exact_kernel<<>>( \ (const int4*)inp, peers, (const int4*)my_scratch, (unsigned int*)my_flags, \ - (int4*)out, (unsigned int*)seq_ctrs, (int)n16, (int)slot_stride16, \ + (int4*)out, (unsigned int*)seq_ctrs, sh, (int)slot_stride16, \ (int)rank, (int)drain, (int)acq, (int)pub, (long long*)gate, \ (unsigned int*)gate_ctr) if (dtype == 0) R4D_AR_TS_LAUNCH(__hip_bfloat16, 8); @@ -197,7 +220,7 @@ void r4d_ar_twoshot_3rank_exact(long peer_scratch0, long peer_scratch1, long pee const long pf[2] = {peer_flags0, peer_flags1}; /* No link gate at three ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<3>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, nullptr); } void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -209,7 +232,8 @@ void r4d_ar_twoshot_4rank_exact(long peer_scratch0, long peer_scratch1, long pee const long ps[3] = {peer_scratch0, peer_scratch1, peer_scratch2}; const long pf[3] = {peer_flags0, peer_flags1, peer_flags2}; ar_twoshot_launch<4>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, gate, gate_ctr, + nullptr); } void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long peer_scratch2, @@ -219,12 +243,14 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee long peer_flags5, long peer_flags6, long my_scratch, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long stream, - long nblocks, long nthreads, long drain, long acq, long pub) { + long nblocks, long nthreads, long drain, long acq, long pub, + const int* shard_weights) { const long ps[7] = {peer_scratch0, peer_scratch1, peer_scratch2, peer_scratch3, peer_scratch4, peer_scratch5, peer_scratch6}; const long pf[7] = {peer_flags0, peer_flags1, peer_flags2, peer_flags3, peer_flags4, peer_flags5, peer_flags6}; /* No link gate at eight ranks: the row answers 1, the engine releases by barrier. */ ar_twoshot_launch<8>(ps, pf, my_scratch, my_flags, seq_ctrs, slot_stride16, inp, out, n_elem, - dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L); + dtype, rank, stream, nblocks, nthreads, drain, acq, pub, 0L, 0L, + shard_weights); } diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index bce16403..0e9e2407 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -35,6 +35,7 @@ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_args.h" +#include "r4d_ar_shards.h" #include "r4d_hc_fp8.h" #include "r4d_fp8_frag.h" #include "r4d_fp8_lm.h" @@ -16239,6 +16240,82 @@ static void ar_pattern_worker(ArPattern* t) { st_free(out); } +/* An environment variable set (or, with a null value, cleared) for one scope and restored after + * it: the eight-rank two-shot reads its settings at every init. */ +struct ScopedEnv { + const char* name; + bool had; + std::string kept; + ScopedEnv(const char* n, const char* v) : name(n) { + const char* was = std::getenv(n); + had = was != nullptr; + if (was) kept = was; + if (v) setenv(n, v, 1); else unsetenv(n); + } + ~ScopedEnv() { if (had) setenv(name, kept.c_str(), 1); else unsetenv(name); } + ScopedEnv(const ScopedEnv&) = delete; + ScopedEnv& operator=(const ScopedEnv&) = delete; +}; + +struct ArPatternRun { const char* dtype; std::vector sizes; int oop; }; + +/* One run on a fresh instance per rank, every size checked against the fold. False when init + * failed, so the caller stops instead of reporting every later run as failed too. */ +static bool ar_pattern_check(const RadKernelInfo* row, const std::vector& devs, + const std::string& name, int world, const ArPatternRun& run) { + std::vector t((size_t)world); + std::vector th; + for (int r = 0; r < world; ++r) { + t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; + t[(size_t)r].world = world; + t[(size_t)r].dtype = run.dtype; t[(size_t)r].sizes = run.sizes; + t[(size_t)r].out_of_place = run.oop; + th.emplace_back(ar_pattern_worker, &t[(size_t)r]); + } + for (std::thread& x : th) x.join(); + const std::string what = name + " " + run.dtype; + bool up = true, ran = true; + std::string rcs; + for (const ArPattern& a : t) { + up = up && a.rc_init == RAD_OK; ran = ran && a.rc_launch == RAD_OK; + rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; + } + ok((what + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); + if (!up) return false; + ok((what + " launches").c_str(), ran, "init/launch rc " + rcs); + if (ran) { + const bool bf = !std::strcmp(run.dtype, "bf16"); + for (size_t k = 0; k < run.sizes.size(); ++k) { + const int64_t n = run.sizes[k]; + int64_t bad = 0, first = -1; + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int r = 0; r < world; ++r) { + const float v = ar_pattern_value(r, i); + acc += bf ? h_bf16(h_to_bf16(v)) : v; + } + const float want = bf ? h_bf16(h_to_bf16(acc)) : acc; + for (int r = 0; r < world; ++r) + if (t[(size_t)r].out.size() <= k || t[(size_t)r].out[k][(size_t)i] != want) { + if (first < 0) first = i; + ++bad; + } + } + const int64_t words = n * (bf ? 2 : 4) / 16; + const std::string label = + what + " numel " + std::to_string(n) + " (" + std::to_string(words) + + " words, % " + std::to_string(world) + " = " + + std::to_string(words % world) + + ((int)k == run.oop ? ", out of place" : ", in place") + + ") == fp32 ascending-rank fold on every rank, bit for bit"; + ok(label.c_str(), bad == 0, + std::to_string(bad) + " elements wrong, first at " + std::to_string(first)); + } + } + if (row->fini) for (ArPattern& a : t) if (a.inst) row->fini(a.inst); + return true; +} + static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, const char* name, int world) { const RadKernelInfo* row = find(pl, name); @@ -16247,12 +16324,13 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str()); return; } - struct Run { const char* dtype; std::vector sizes; int oop; }; + using Run = ArPatternRun; /* The three-rank list walks the UNEVEN split (words % 3 of 0, 1 and 2); the four- and * eight-rank rows cannot be given one -- cArTsExact4/cArTsExact8/cArTi8Ts4 constrain numel so * the words divide evenly (r4d_rows.cpp; every size below is a multiple of 64 elements, so - * the words divide by eight too), and the two-shot's own entry refuses any other message -- - * so their list keeps the whole-word sizes and the band edges instead. */ + * the words divide by eight too), and without shard weights the two-shot's own entry refuses + * any other message -- so their list keeps the whole-word sizes and the band edges instead + * (uneven eight-rank shards: ar_wide_weighted). */ std::vector runs; if (world == 3) { runs = { @@ -16279,64 +16357,16 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons { "fp32", { 8192, 8256, 1048576 }, 0 }, }; } - for (const Run& run : runs) { - std::vector t((size_t)world); - std::vector th; - for (int r = 0; r < world; ++r) { - t[(size_t)r].row = row; t[(size_t)r].rank = r; t[(size_t)r].dev = devs[(size_t)r]; - t[(size_t)r].world = world; - t[(size_t)r].dtype = run.dtype; t[(size_t)r].sizes = run.sizes; - t[(size_t)r].out_of_place = run.oop; - th.emplace_back(ar_pattern_worker, &t[(size_t)r]); - } - for (std::thread& x : th) x.join(); - const std::string what = std::string(name) + " " + run.dtype; - bool up = true, ran = true; - std::string rcs; - for (const ArPattern& a : t) { - up = up && a.rc_init == RAD_OK; ran = ran && a.rc_launch == RAD_OK; - rcs += std::to_string(a.rc_init) + "/" + std::to_string(a.rc_launch) + " "; - } - ok((what + " init (peer rendezvous)").c_str(), up, "init/launch rc " + rcs); - if (!up) return; - ok((what + " launches").c_str(), ran, "init/launch rc " + rcs); - if (ran) { - const bool bf = !std::strcmp(run.dtype, "bf16"); - for (size_t k = 0; k < run.sizes.size(); ++k) { - const int64_t n = run.sizes[k]; - int64_t bad = 0, first = -1; - for (int64_t i = 0; i < n; ++i) { - float acc = 0.0f; - for (int r = 0; r < world; ++r) { - const float v = ar_pattern_value(r, i); - acc += bf ? h_bf16(h_to_bf16(v)) : v; - } - const float want = bf ? h_bf16(h_to_bf16(acc)) : acc; - for (int r = 0; r < world; ++r) - if (t[(size_t)r].out.size() <= k || t[(size_t)r].out[k][(size_t)i] != want) { - if (first < 0) first = i; - ++bad; - } - } - const int64_t words = n * (bf ? 2 : 4) / 16; - const std::string label = - what + " numel " + std::to_string(n) + " (" + std::to_string(words) + - " words, % " + std::to_string(world) + " = " + - std::to_string(words % world) + - ((int)k == run.oop ? ", out of place" : ", in place") + - ") == fp32 ascending-rank fold on every rank, bit for bit"; - ok(label.c_str(), bad == 0, - std::to_string(bad) + " elements wrong, first at " + std::to_string(first)); - } - } - if (row->fini) for (ArPattern& a : t) if (a.inst) row->fini(a.inst); - } + for (const Run& run : runs) + if (!ar_pattern_check(row, devs, name, world, run)) return; /* The four- and eight-rank rows' even-shard rule, checked from the one place that can: a - * message whose 16-byte words do not divide by the world must be REFUSED - * (r4d_ar_twoshot_Nrank_exact.hip shards it evenly and the entry throws on any residual), not - * launched with a truncated tail. The three-rank row has no such rule -- it splits unevenly - * by design. 40 bf16 elements are 5 words (5 % 4 != 0), 72 are 9 (9 % 8 != 0). */ + * message whose 16-byte words do not divide by the world must be REFUSED, not launched with a + * truncated tail. The three-rank row has no such rule -- it splits unevenly by design -- and + * neither has a weighted eight-rank one (ar_wide_weighted), so the rule is checked without + * weights whatever the environment. 40 bf16 elements are 5 words (5 % 4 != 0), 72 are 9 + * (9 % 8 != 0). */ if (world >= 4 && std::strstr(name, "twoshot")) { + ScopedEnv even(R4D_AR8_SHARD_WEIGHTS_ENV, nullptr); const int64_t odd = world == 4 ? 40 : 72; const std::string w = std::to_string(world); std::vector t((size_t)world); @@ -16362,6 +16392,28 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& devs, cons } } +/* The eight-rank two-shot with per-rank shard weights (RADIANCE_AR8_SHARD_WEIGHTS): shards of + * unequal length, empty ones (weight 0: the rank only pushes, gathers and handshakes), a single + * owner (its two regions outgrow a message, so init must grow the slot), and messages shorter than + * one word a rank, which the even split refuses. The fold is the same whoever owns a word, so the + * oracle is unchanged. */ +static void ar_wide_weighted(const Plugin& pl, const std::vector& devs, const char* name) { + constexpr int W = 8; + const RadKernelInfo* row = find(pl, name); + if (!row) { ok(name, false, "row absent"); return; } + if ((int)devs.size() < W) { skip(name, "needs 8 gfx1201 cards"); return; } + /* bf16: 72 elements are 9 words, 8 are one; 8256 is 1032 words, 4196352 is 524544. */ + const std::vector runs = { + { "bf16", { 4194304, 72, 8, 128, 8256, 4196352, 4194304 }, 1 }, + { "fp32", { 36, 1048580 }, 0 }, + }; + for (const char* w : { "0,3,1,0,5,1,2,4", "1,0,0,0,0,0,0,0", "4,1,0,4,0,1,4,4" }) { + ScopedEnv env(R4D_AR8_SHARD_WEIGHTS_ENV, w); + for (const ArPatternRun& run : runs) + if (!ar_pattern_check(row, devs, std::string(name) + " weights " + w, W, run)) return; + } +} + /* The eight-rank exact all-reduce timed, one thread per card as the engine runs it: both rows * (one-shot, two-shot) at every message size given, each at the block rule and at fixed block * counts, out of place on the per-element pattern and checked bit for bit against the fp32 @@ -16568,6 +16620,17 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty g_cold > 0 ? fmt("cold (%lld MiB read before each; last arriver / with skew, " "medians)", (long long)(g_cold >> 20)).c_str() : "warm (back to back, period over the span, slowest rank)"); + /* The plugin reads the same variable through the same parser at init, so this is the table + * the two-shot runs. */ + int wts[W]; + const char* wenv = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV); + const bool weighted = wenv && *wenv && r4d_ar_shard_weights_parse(wenv, W, wts); + std::printf("two-shot shard weights: %s\n", + weighted ? fmt("%d,%d,%d,%d,%d,%d,%d,%d", wts[0], wts[1], wts[2], wts[3], wts[4], + wts[5], wts[6], wts[7]).c_str() + : wenv && *wenv ? fmt("even (%s=\"%s\" is invalid)", R4D_AR8_SHARD_WEIGHTS_ENV, + wenv).c_str() + : "even"); StBarrier bar(W); std::vector t((size_t)W); std::vector th; @@ -16591,16 +16654,22 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty size_t cfg = 0; for (int64_t n : sizes) { const double bytes = (double)n * esz; + const int64_t n16 = n * esz / 16; std::printf(" numel %lld (%.0f KiB, %lld 16-byte words)\n", (long long)n, bytes / 1024.0, - (long long)(n * esz / 16)); + (long long)n16); + long off[W + 1]; + const int64_t sh_max = r4d_ar_shard_table((long)n16, W, weighted ? wts : nullptr, off); + std::string shards; + for (int r = 0; r < W; ++r) shards += fmt(" %ld", off[r + 1] - off[r]); + std::printf(" two-shot shard words by rank:%s\n", shards.c_str()); for (size_t j = 0; j < rows.size(); ++j) { const bool two = j == 1; const double sent = two ? 2.0 * (W - 1) / W * bytes : (double)(W - 1) * bytes; for (int nb : nbs) { const Ar8Perf& r0 = t[0]; /* The entry's nb_for, to name the rule's count: 1400 words a block, floor 4, - * ceiling 16, the two-shot over its shard with ceiling 8 at eight ranks. */ - const int64_t basis = n * esz / 16 / (two ? W : 1); + * ceiling 16, the two-shot over its longest shard with ceiling 8 at eight ranks. */ + const int64_t basis = two ? (weighted ? sh_max : n16 / W) : n16; const int64_t rule = std::min(std::max(basis / 1400, 4), two ? 8 : 16); const std::string nbs_ = @@ -16614,6 +16683,11 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty int64_t bad = 0; for (const Ar8Perf& x : t) bad += x.bad[cfg]; double us = 0.0, us_hi = 0.0; + /* Warm: each rank's period; cold: each rank's median launch. */ + std::string per_rank; + for (const Ar8Perf& x : t) + per_rank += fmt(" %.1f", g_cold <= 0 ? (double)x.period[cfg] * 1000.0 + : (double)median(x.cold[cfg]) * 1000.0); if (g_cold <= 0) { for (const Ar8Perf& x : t) us = std::max(us, (double)x.period[cfg] * 1000.0); } else { @@ -16631,6 +16705,7 @@ static void ar8_perf(const Plugin& pl, int64_t numel, int iters, const char* dty us > 0 ? bytes / (us * 1e3) : 0.0, us > 0 ? sent / (us * 1e3) : 0.0, bad ? fmt("%lld elements differ from the fold", (long long)bad).c_str() : "= fold on every rank"); + std::printf(" us by rank:%s\n", per_rank.c_str()); ++cfg; } } @@ -19956,6 +20031,7 @@ static void device_phase(const Plugin& pl) { ar_wide_ti8(pl, devs, n.c_str(), world); } else if (std::strstr(base, "twoshot")) { ar_wide_pattern(pl, devs, n.c_str(), world); + if (world == 8) ar_wide_weighted(pl, devs, n.c_str()); } else { ar_wide_rank(pl, devs, n.c_str(), world); /* The one-shot through the same per-element oracle: both rows of the op agree