Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
STRATA_HC_PERSIST=1 (opt-in, HIP): the verifier's hyper-connection read as one persistent kernel
Vop3p6cbc15a81ad8
diff --git a/bench/results/2026-10-12-hc-persist-gfx1030/README.md b/bench/results/2026-10-12-hc-persist-gfx1030/README.mdnew file mode 100644index 000000000..061c9b33f--- /dev/null+++ b/bench/results/2026-10-12-hc-persist-gfx1030/README.md@@ -0,0 +1,146 @@+# STRATA_HC_PERSIST=1: the verifier's hyper-connection read as one persistent kernel (gfx1030)++2x RX 6900 XT (gfx1030, 16 GB, PCIe 4.0 x8 each), Ryzen 5 5600X, 128 GB DDR4-3200, Ubuntu 26.04, kernel 7.0.0-38,+ROCm 10.0. Qwen3.8-Flash-Next IQ3_S (and Unsloth UD-Q4_K_XL), two-card layer split.++## Result++- The read itself: **1.35-2.10x faster** at 1-8 tokens on 40 WGPs (38.9 us against 55.1 us at 2 tokens).+- End to end, ms per verify window (`STRATA_DECODE_TIMING`, the configuration below, this branch, one binary with+ the variable unset / set, 6 alternating rounds): **-4.2 % at 4K and -2.8 % at 32K, every round the same way**.+ Tokens per window and prompt speed unchanged.+- Not bitwise (another summation order). Against a double-accumulation reference it is as close as the default read.+- Off by default; with the variable unset the engine's output is bitwise the same as without the change (checked below).++## What the read does and why it was slow here++Every layer the verifier reads the hyper-connection twice: RMS norm over 4 x 2560, a 320-row down projection (plus 4+inject rows) and a 320 -> 10240 up projection. At 1-8 tokens this is three small launches with two global dependencies+between them; on gfx1030 the down kernel runs 41 blocks on 40 WGPs and the card idles between launches.++The persistent kernel runs 80 blocks (two per WGP) and two grid barriers on an atomic counter:++1. each block takes 128 columns of the 10240 (norm sum of squares + partial dots of the 324 down/inject rows),+2. barrier, each block reduces 4-5 of the 324 rows,+3. barrier, the up projection (a thread pair per row) and the same epilogue as `gr_up_kernel`.++An ablation found only two parts that matter: the down projection split by columns over all 80 blocks, and one launch+instead of three. Prefetching the up weights (into registers, or touching them into L2 / Infinity Cache across the+barrier) and prefetching the epilogue inputs measured 0 and were removed - the 13 MB are read from VRAM once either way.++| tokens | default read, us | persistent, us | |+|---|---|---|---|+| 1 | 51.6 | 38.1 | 1.35x |+| 2 | 55.1 | 38.9 | 1.41x |+| 3 | 60.0 | 40.5 | 1.48x |+| 4 | 63.9 | 43.6 | 1.46x |+| 5 | 67.6 | 43.1 | 1.57x |+| 6 | 71.5 | 46.1 | 1.55x |+| 7 | 96.4 | 46.3 | 2.08x |+| 8 | 104.4 | 49.7 | 2.10x |++(`hc_persist_bench.cpp`, one card, a graph of 48 reads over 40 weight sets so the weights are cold, best of 3.)++## Safety: what happens on a card it was not written for++- `warpSize != 32` (wave64): off, the default read runs.+- Residency is decided by **running** every token count once at start-up with a 50 ms barrier timeout and comparing+ the result with the default read; a timeout means "not resident" and that token count and larger ones keep the+ default read. In a read the barrier gives up after 2 s (never seen in a working run).+- No occupancy API in front of the run: on 30 WGPs (HSA_CU_MASK) it promised more blocks than the card holds (a hang+ before the timeout existed), and with the HIP 7.1 runtime (Ubuntu's `libamdhip64.so.7.1.52801`) it promised fewer+ (1 per WGP on 40 WGPs), which turned the read off although it runs resident there.+- One line per card says what was decided:++```+strata hc: CUDA0: STRATA_HC_PERSIST=1: the verifier's hyper-connection read runs as one persistent kernel (80 blocks on+40 multiprocessors, up to 8 tokens; 0 token counts timed out in the check; checked against the default read, max+relative difference 1.8e-07)+```++Smaller cards, simulated on one 6900 XT with `HSA_CU_MASK` (`ROCR_VISIBLE_DEVICES=1`), both with ROCm 10.0 and with+the HIP 7.1 runtime (the same numbers within 0.2 us):++| WGPs (CU mask) | like | tokens | persistent vs default |+|---|---|---|---|+| 40 | 6900 XT | 1-8 | 1.35-2.10x |+| 30 (`0:0-59`) | 6800 | 1-8 | 1.36-1.84x |+| 20 (`0:0-39`) | 6700 XT's CU count | 1-8 | 1.38-2.07x |+| 5 (`0:0-9`), 1 (`0:0-1`) | - | - | check timed out, default read, no hang |++The mask keeps Navi 21's 256-bit bus and 128 MB Infinity Cache; a real 6700 XT / 6600 (narrower bus, smaller cache)+is not simulated by it.++## End to end++`strata-split.json`: `--layer-split`, IQ3_S, `--kv int8 --kv-resident 32768`, speculation 3 with min-p 0.7,+`--pipeline-windows 2`, `STRATA_SH_STREAM=1`, `STRATA_SPLIT_MTP_BATCH=1`. Main (a0116b27) with this change, one+binary, cold server per arm, the variable unset (default) and set alternating, 6 rounds, two 4K and two 32K requests+per arm (256 tokens out), ms per verify window from `STRATA_DECODE_TIMING`:++| | default read | `STRATA_HC_PERSIST=1` | | rounds |+|---|---|---|---|---|+| 4K, ms per window | 25.81 | 24.73 | **-4.2 %** | -4.3 / -2.6 / -3.6 / -3.4 / -5.8 / -5.2 |+| 32K, ms per window | 24.40 | 23.72 | **-2.8 %** | -2.8 / -2.1 / -5.6 / -2.7 / -1.3 / -2.1 |+| tokens per window | 1.93 / 1.94 | 1.92 / 1.94 | | |+| prompt, tok/s (4K / 32K) | 848 / 1,636 | 850 / 1,632 | | |++Run-to-run noise in ms per window is about +-3 % per round here, which is why the rounds alternate. An earlier version+of the kernel (the up weights prefetched into registers, since removed) measured -2.8 % / -2.0 % against the default read (two builds, 6 rounds) on+Unsloth UD-Q4_K_XL (`STRATA_MMQ_KQUANTS=ON`, 0.1.42); this version was not re-measured on it.++## Quality++`STRATA_LOGPOS` over three chats (9.4K, 34.7K, 105.8K tokens; ~500 scored positions each, top-256), pipeline windows+off, on **this PR's code on main (a0116b27)**. Only the 106K chat is reproducible run to run on this machine (the+first two differ in all positions between two runs of the same binary), so it is the one compared.+`STRATA_HC_PERSIST=3` is a reference that accumulates the same kernel in double.++| 106K chat, against the double reference | KL mean | argmax same |+|---|---|---|+| default read | 0.0136 | 95.0 % |+| `STRATA_HC_PERSIST=1` | 0.0131 | 96.3 % |++On 0.1.42 the same comparison gave 0.047 (default) and 0.038 (the earlier version of the kernel).++Default path unchanged: main (a0116b27) built without and with this change, the same options, the variable unset:+the 106K chat's 481 scored positions are bitwise identical. With the variable unset `fused_gr_persist_init` and+`fused_gr_read_persist` return in their first line.++0 stalls in every engine run with it (more than 30); three Strata slots on this machine use it daily since 2026-10-12.++## Tried and dropped++- Cooperative launch (`hipLaunchCooperativeKernel` + `grid.sync`): works and can be captured in a graph, but each+ launch costs ~12 us more than a plain one here - more than the whole gain.+- `__builtin_amdgcn_global_load_lds` to stage the up weights: slower (4x the instructions, dword only on gfx1030), and+ AMD clang 23 (ROCm 10.0) folds a constant address offset into the instruction offset, which the hardware also adds+ to the LDS destination - the data lands shifted unless the pointer is laundered through an empty `asm`.+- Non-temporal loads for the weights: no effect.+- `STRATA_GR_V3=1` as a comparison: on gfx1030 it needs the two-half split, which fails its check (#375), so it falls+ back to the default read.++## Not tested++- Any other card for real: RDNA 2 Navi 22/23 (6700 XT, 6600), RDNA 3 (7900), RDNA 4 (9070), NVIDIA. The kernel is+ inside `#if defined(__HIPCC__)`; CUDA and SYCL get two empty stubs (`fused_gr_persist_init` does nothing,+ `fused_gr_read_persist` returns false). CUDA and SYCL were not built here (no toolkit on this machine).+- Windows HIP.+- The drafter's reads (they run on their own stream and keep the default kernels) and the prompt path.++## Help wanted++On any RDNA card, with `STRATA_HC_PERSIST=1` in the engine's environment:++1. the `strata hc:` line from the engine log (does it run, up to how many tokens, any timeouts?), and+2. two runs of the same prompt with `STRATA_DECODE_TIMING=1`, with and without the variable (ms per window).++To time the read alone (from the repository root, after a HIP build in `build/`):++```+hipcc -O3 --offload-arch=<your gfx> -I include -c bench/results/2026-10-12-hc-persist-gfx1030/hc_persist_bench.cpp -o hcpb.o+hipcc --offload-arch=<your gfx> hcpb.o build/libstrata_kernels.a build/libstrata_core.a -lrocblas -o hc_persist_bench+STRATA_HC_PERSIST=1 ./hc_persist_bench+```++Developed with an AI coding assistant; every number above was measured on 2x RX 6900 XT (gfx1030, PCIe 4.0 x8 each) / Ryzen 5 5600X, ROCm 10.0.diff --git a/bench/results/2026-10-12-hc-persist-gfx1030/hc_persist_bench.cpp b/bench/results/2026-10-12-hc-persist-gfx1030/hc_persist_bench.cppnew file mode 100644index 000000000..e7b20f8f8--- /dev/null+++ b/bench/results/2026-10-12-hc-persist-gfx1030/hc_persist_bench.cpp@@ -0,0 +1,73 @@+// The engine's STRATA_HC_PERSIST read (public API) against the default read, per token count: the largest relative+// difference from the default read, and the time per read in a graph of 48 cold reads. Run with STRATA_HC_PERSIST=1+#include <hip/hip_runtime.h>+#include "strata/kernels/fused_gr.hpp"+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <vector>+namespace K = strata::kernels;+#define CK(x) do { hipError_t e_ = (x); if (e_ != hipSuccess) { std::fprintf(stderr, "%s:%d %s\n", __FILE__, __LINE__, hipGetErrorString(e_)); std::exit(1); } } while (0)+constexpr int N = 2560, HC = 4, D = N * HC, LR = 320, TM = 8;+static uint16_t bf16(float x) { uint32_t u; std::memcpy(&u, &x, 4); return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16); }+int main(int argc, char** argv) {+ setvbuf(stdout, nullptr, _IONBF, 0);+ const int W = argc > 1 ? std::atoi(argv[1]) : 40;+ K::fused_gr_check();+ K::fused_gr_persist_init();+ std::mt19937 rng(5); std::normal_distribution<float> nd(0.f, 1.f);+ std::vector<float> R((size_t) TM * D), bo((size_t) TM * N), inj((size_t) TM * HC), wn(D);+ for (auto& x : R) x = nd(rng); for (auto& x : bo) x = 0.5f * nd(rng); for (auto& x : inj) x = nd(rng); for (auto& x : wn) x = 1.f + 0.3f * nd(rng);+ const size_t WD = (size_t) LR * D, WU = WD, WI = (size_t) HC * D;+ uint16_t *dwd, *dwu, *dwi; CK(hipMalloc(&dwd, WD * 2 * W)); CK(hipMalloc(&dwu, WU * 2 * W)); CK(hipMalloc(&dwi, WI * 2 * W));+ { std::vector<uint16_t> b(WD); for (int s = 0; s < W; ++s) {+ for (auto& x : b) x = bf16(0.02f * nd(rng)); CK(hipMemcpy(dwd + WD * s, b.data(), WD * 2, hipMemcpyHostToDevice));+ for (auto& x : b) x = bf16(0.05f * nd(rng)); CK(hipMemcpy(dwu + WU * s, b.data(), WU * 2, hipMemcpyHostToDevice));+ for (size_t i = 0; i < WI; ++i) b[i] = bf16(0.02f * nd(rng)); CK(hipMemcpy(dwi + WI * s, b.data(), WI * 2, hipMemcpyHostToDevice)); } }+ float *dR, *dbo, *dinj, *dwn, *dxn, *dlo, *drs, *dio, *dmix;+ CK(hipMalloc(&dR, R.size() * 4)); CK(hipMalloc(&dbo, bo.size() * 4)); CK(hipMalloc(&dinj, inj.size() * 4)); CK(hipMalloc(&dwn, D * 4));+ CK(hipMalloc(&dxn, (size_t) TM * D * 4)); CK(hipMalloc(&dlo, (size_t) TM * LR * 4)); CK(hipMalloc(&drs, TM * HC * 4));+ CK(hipMalloc(&dio, TM * HC * 4)); CK(hipMalloc(&dmix, (size_t) TM * N * 4));+ CK(hipMemcpy(dbo, bo.data(), bo.size() * 4, hipMemcpyHostToDevice)); CK(hipMemcpy(dinj, inj.data(), inj.size() * 4, hipMemcpyHostToDevice));+ CK(hipMemcpy(dwn, wn.data(), D * 4, hipMemcpyHostToDevice));+ hipStream_t st; CK(hipStreamCreateWithFlags(&st, hipStreamNonBlocking));+ hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);+ auto args = [&](K::FusedGrArgs* a, int T, int set) {+ for (int t = 0; t < T; ++t) { a[t] = K::FusedGrArgs{}; a[t].R = dR + (size_t) t * D; a[t].R_out = dR + (size_t) t * D; a[t].apply = true;+ a[t].bo_prev = dbo + (size_t) t * N; a[t].inj_prev = dinj + t * HC; a[t].w_norm = dwn; a[t].w_down = dwd + WD * set;+ a[t].w_up = dwu + WU * set; a[t].w_inject = dwi + WI * set; a[t].eps = 1e-6f; a[t].lo = dlo + t * LR; a[t].rs = drs + t * HC;+ a[t].inject_out = dio + t * HC; a[t].mixed = dmix + (size_t) t * N; } };+ for (int T = 1; T <= TM; ++T) {+ K::FusedGrArgs a[TM]; args(a, T, 0);+ std::vector<float> out[2];+ bool ran = true;+ for (int w = 0; w < 2; ++w) {+ CK(hipMemcpy(dR, R.data(), R.size() * 4, hipMemcpyHostToDevice)); CK(hipMemset(dmix, 0xff, (size_t) TM * N * 4)); CK(hipDeviceSynchronize());+ if (w == 0) K::fused_gr_read_multi(a, T, dxn, st); else ran = K::fused_gr_read_persist(a, T, st);+ CK(hipStreamSynchronize(st));+ out[w].resize((size_t) T * N); CK(hipMemcpy(out[w].data(), dmix, out[w].size() * 4, hipMemcpyDeviceToHost));+ }+ if (!ran) { std::printf("T %d: persistent read not used here (falls back)\n", T); continue; }+ double mr = 0, md = 0; bool fin = true;+ for (size_t i = 0; i < out[0].size(); ++i) { fin = fin && std::isfinite(out[1][i]); mr = std::fmax(mr, std::fabs(out[0][i])); md = std::fmax(md, std::fabs(out[1][i] - out[0][i])); }+ double us[2];+ for (int w = 0; w < 2; ++w) {+ double best = 1e30;+ for (int r = 0; r < 3; ++r) {+ hipGraph_t g; hipGraphExec_t ge;+ CK(hipStreamBeginCapture(st, hipStreamCaptureModeGlobal));+ for (int i = 0; i < 48; ++i) { args(a, T, (i * 7) % W); if (w == 0) K::fused_gr_read_multi(a, T, dxn, st); else K::fused_gr_read_persist(a, T, st); }+ CK(hipStreamEndCapture(st, &g)); CK(hipGraphInstantiate(&ge, g, nullptr, nullptr, 0));+ for (int i = 0; i < 2; ++i) CK(hipGraphLaunch(ge, st));+ CK(hipEventRecord(e0, st)); for (int i = 0; i < 10; ++i) CK(hipGraphLaunch(ge, st)); CK(hipEventRecord(e1, st)); CK(hipEventSynchronize(e1));+ float ms; hipEventElapsedTime(&ms, e0, e1); best = std::fmin(best, 1e3 * ms / 480);+ hipGraphExecDestroy(ge); hipGraphDestroy(g);+ }+ us[w] = best;+ }+ std::printf("T %d: default %6.1f us persistent %6.1f us (%.2fx) max rel diff %.2e%s\n", T, us[0], us[1], us[0] / us[1], md / mr, fin ? "" : " NON-FINITE");+ }+ return 0;+}diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.mdindex d0038683e..d5b5147fb 100644--- a/docs/AMD_HIP.md+++ b/docs/AMD_HIP.md@@ -517,6 +517,13 @@ run it; the report below is from a community machine: an RX 6900 XT 16 GB (gfx10matrix cores; `hip_prefill_hipblaslt_gemm`, no hipBLASLt table) and 3 that fail for reasons outside the engine(`ple_parity` needs a Q2_0 PLE file that is not on that machine, `expert_multi_test` refuses the CPU without AVX-512,`platform_memory_test` cannot `mlock` at the shell's default `ulimit -l`).+- **The verifier's hyper-connection read as one persistent kernel:** `STRATA_HC_PERSIST=1` (opt-in, HIP, 32-lane+ waves) runs the read of 1-8 tokens as one kernel of 80 blocks with two grid barriers instead of three launches; a+ start-up run per token count with a barrier timeout decides where it is resident, and one `strata hc:` line per card+ says so. On 2x RX 6900 XT (ROCm 10.0, layer split): the read 1.35-2.10x, ms per verify window -4.2 % / -2.8 % at+ 4K / 32K (6 rounds), not bit-identical (as close to a double-accumulation reference as the default read):+ [bench/results/2026-10-12-hc-persist-gfx1030](../bench/results/2026-10-12-hc-persist-gfx1030/README.md). Other+ RDNA cards are untested; the `strata hc:` line and a `STRATA_DECODE_TIMING` run from one are welcome.- **gfx1031** (RX 6700 XT, #524): setup knows it (the `gfx103X-all` wheels, unvalidated); its reporter runs it dailyon one card. More reports: an RX 6700 XT 12 GB run as gfx1030 on ROCm 7.2.4 (#1027: IQ2_XS, decode 30-32 tok/s, prompt about 300 tok/s, 6 of 6needles), and an RX 6800M 12 GB on Windows with a self-built engine (#915, #1078: Q2_0, decode 9-27 tok/s, prompt 50-114 tok/s; thediff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hppindex 003242473..76af88cd9 100644--- a/include/strata/kernels/fused_gr.hpp+++ b/include/strata/kernels/fused_gr.hpp@@ -79,4 +79,12 @@ void fused_gr_set_fast(int on);void fused_gr_check();int fused_gr_variant();+/// Opt-in STRATA_HC_PERSIST=1 (HIP): the multi read as one persistent kernel (80 resident blocks, the down projection+/// split by column slices, two grid barriers). Another summation order (not bitwise).+/// `fused_gr_persist_init` checks residency and the result against the default read once per card (Verifier::init);+/// `fused_gr_read_persist` returns false when it did not run (off, too many tokens, a Q8 / QFUSE read) - then the caller+/// runs `fused_gr_read_multi`. Only for reads on a stream no other persistent read runs on concurrently (the verifier's).+void fused_gr_persist_init();+bool fused_gr_read_persist(const FusedGrArgs* a, int n_tok, void* stream);+} // namespace strata::kernelsdiff --git a/src/core/verify.cpp b/src/core/verify.cppindex a8791cc67..36f62804d 100644--- a/src/core/verify.cpp+++ b/src/core/verify.cpp@@ -566,6 +566,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live thererr_stats_ = route_resident_cfg().stats_on(device_); // STRATA_ROUTE_RESIDENT: this GPU's counters, outside graph capturestrata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there+ strata::kernels::fused_gr_persist_init(); // opt-in STRATA_HC_PERSIST=1 (HIP)wt_ = &wt;g_ = &g;ss_ = &ss;@@ -1103,6 +1104,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {else if (strata::kernels::cpu::expert_layout().native) a.q8_mixed = nat_xq_ + (size_t) t * (N / 32) * 36;}}+ if (strata::kernels::fused_gr_read_persist(fa, n, cs)) return false; // STRATA_HC_PERSIST=1; q8_mixed is never set therereturn fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr,(int) (l * kProfPer + (half == 0 ? 27 : 30)));};diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cuindex c3c2fc8d9..2653a92b6 100644--- a/src/kernels/cuda/fused_gr.cu+++ b/src/kernels/cuda/fused_gr.cu@@ -12,6 +12,8 @@#include <cuda_runtime.h>#include <atomic>+#include <type_traits>+#include <cmath>#include <cstdio>#include <cstdlib>#include <cstring>@@ -2330,4 +2332,433 @@ void fused_gr_check() {}+// ===================================== the read as ONE persistent kernel (opt-in STRATA_HC_PERSIST=1, HIP) ==============+// 80 blocks that must all be resident (a start-up run per T decides; larger T keep the default read) and two grid+// barriers on an atomic counter. Block b: (A) stages R' * w_norm for columns [128 b, 128 b + 128) (one stream) and writes+// that slice's sum of squares and the UNSCALED partial dots of the 320 down + 4 inject rows (the v3 identity+// w . xn = sum_c rs[c] (w[:, c] . x'[c])); barrier; (B) rs per stream, then rows (k, r) = b + 80 j reduced to lo / inject;+// barrier; (C) the up projection read straight from VRAM, a thread pair per row, the epilogue as gr_up_kernel.+// ANOTHER SUMMATION ORDER than the default read (not bitwise; the init check bounds the difference). Only the verifier's hyper-connection reads use it: they run on one stream per card (both pipeline+// verifiers share it), so two of these kernels never wait on each other; the drafter's reads keep the default kernels.+#if defined(__HIPCC__)+namespace {+namespace hcp {+// Measured on gfx1030 (bench/results/2026-10-12-hc-persist-gfx1030): the gain over the three-kernel read is (1) the down+// projection split by column slices over all 80 blocks (the default read runs 41 blocks staging the activations through+// LDS) and (2) one launch with two grid barriers instead of three launches and the gaps between them. Prefetching the+// up weights (into registers or by touching them into L2 / Infinity Cache) and the epilogue inputs measured no gain on+// gfx1030 and is gone: the 13 MB are read once from VRAM whichever way.+constexpr int NB = 80, SL = D / NB, SPS = N / SL, UPC = N / NB, NR = LR + HC;+static_assert(UPC * HC * 2 == THREADS, "a thread pair per up row");+struct PArgs {+ FusedGrArgs a[kFusedGrMaxT];+ float* part; // [T][NR][NB]+ float* ssp; // [T][NB]+ unsigned* bar; // [0] count, [32] generation, [48] abort (a barrier that timed out)+ unsigned long long timeout_ticks; // s_memrealtime ticks (100 MHz) a barrier waits before it aborts the read+ double* partd; // STRATA_HC_PERSIST=3 (a reference only): the partial dots and sums of squares in double+ double* sspd;+};+// Returns false when the read was aborted: a block waited longer than `ticks` (the 80 blocks were not all resident - the+// start-up check finds that out by running every T with a short timeout) or another block aborted. Then every block+// leaves the kernel; the outputs are not written completely and bar[48] stays set until the host clears the words.+__device__ __forceinline__ bool grid_sync(unsigned* bar, unsigned long long ticks) {+ __shared__ int s_abort;+ __syncthreads();+ if (threadIdx.x == 0) {+ int ab = 0;+ const unsigned gen = __hip_atomic_load(&bar[32], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ __threadfence();+ const unsigned arrived = __hip_atomic_fetch_add(&bar[0], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT);+ if (arrived == NB - 1) {+ __hip_atomic_store(&bar[0], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ __hip_atomic_fetch_add(&bar[32], 1u, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);+ } else {+ const unsigned long long t0 = __builtin_amdgcn_s_memrealtime();+ while (__hip_atomic_load(&bar[32], __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_AGENT) == gen) {+ if (__hip_atomic_load(&bar[48], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) != 0u) { ab = 1; break; }+ if (__builtin_amdgcn_s_memrealtime() - t0 > ticks) {+ __hip_atomic_store(&bar[48], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);+ ab = 1;+ break;+ }+ __builtin_amdgcn_s_sleep(1);+ }+ }+ if (__hip_atomic_load(&bar[48], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) != 0u) ab = 1;+ s_abort = ab;+ }+ __syncthreads();+ __threadfence();+ return s_abort == 0;+}+// STRATA_HC_PERSIST=3 (a reference only, slow): every dot and sum accumulated in double+__device__ __forceinline__ double dot8d(const uint4 w, const float* x) {+ double acc = 0.0;+ const unsigned u[4] = {w.x, w.y, w.z, w.w};+#pragma unroll+ for (int q = 0; q < 4; ++q) {+ acc += (double) __uint_as_float(u[q] << 16) * (double) x[2 * q];+ acc += (double) __uint_as_float(u[q] & 0xffff0000u) * (double) x[2 * q + 1];+ }+ return acc;+}+template <int T, bool DP = false>+__global__ void __launch_bounds__(THREADS) persist_kernel(PArgs f) {+ using A = typename std::conditional<DP, double, float>::type;+ __shared__ __align__(16) float xs[T][SL];+ __shared__ __align__(16) float lo[T][LR];+ __shared__ float s_rs[T][HC];+ __shared__ float g[T][HC][UPC];+ const int tid = threadIdx.x, lane = tid & 31, b = blockIdx.x;+ const FusedGrArgs& a0 = f.a[0];+ // (A) block b: columns [128 b, 128 b + 128) of D (one stream): R' * w_norm into LDS, the slice's sum of squares, and+ // the UNSCALED partial dots of the 320 down + 4 inject rows (w . xn = sum_c rs[c] (w[:, c] . x'[c]))+ const int c_b = b / SPS, col0 = b * SL;+ if (tid < T * (SL / 4)) {+ const int k = tid / (SL / 4), o4 = tid - k * (SL / 4);+ const FusedGrArgs& a = f.a[k];+ const int i = col0 + o4 * 4, d = i - c_b * N;+ float4 r = *reinterpret_cast<const float4*>(a.R + i);+ if (a.apply) {+ const float gw = 2.0f * sigmoidf_(a.inj_prev[c_b] / (float) HC);+ const float4 bo = *reinterpret_cast<const float4*>(a.bo_prev + d);+ r.x = fmaf(bo.x, gw, r.x); r.y = fmaf(bo.y, gw, r.y); r.z = fmaf(bo.z, gw, r.z); r.w = fmaf(bo.w, gw, r.w);+ }+ const float4 gn = *reinterpret_cast<const float4*>(a.w_norm + i);+ if constexpr (DP) {+ double ss = (double) r.x * r.x + (double) r.y * r.y + (double) r.z * r.z + (double) r.w * r.w;+#pragma unroll+ for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor(ss, o);+ if (lane == 0) f.sspd[k * NB + b] = ss;+ } else {+ const float ss = warp_sum(r.x * r.x + r.y * r.y + r.z * r.z + r.w * r.w); // warp k = token k+ if (lane == 0) f.ssp[k * NB + b] = ss;+ }+ *reinterpret_cast<float4*>(&xs[k][o4 * 4]) = make_float4(r.x * gn.x, r.y * gn.y, r.z * gn.z, r.w * gn.w);+ }+ __syncthreads();+ const int hw = tid >> 4, hl = tid & 15;+ const bool inj = a0.w_inject != nullptr;+ const int nrows = inj ? NR : LR;+#pragma unroll 3+ for (int r = hw; r < nrows; r += 16) {+ const uint16_t* wrow = r < LR ? a0.w_down + (size_t) r * D : a0.w_inject + (size_t) (r - LR) * D;+ const uint4 w = __ldg(reinterpret_cast<const uint4*>(wrow + col0) + hl);+ A acc[T];+#pragma unroll+ for (int k = 0; k < T; ++k) {+ A v;+ if constexpr (DP) v = dot8d(w, &xs[k][hl * 8]); else v = dot8(w, &xs[k][hl * 8]);+#pragma unroll+ for (int o = 8; o > 0; o >>= 1) v += __shfl_xor(v, o);+ acc[k] = v;+ }+#pragma unroll+ for (int k = 0; k < T; ++k)+ if (hl == k) {+ if constexpr (DP) f.partd[((size_t) k * NR + r) * NB + b] = acc[k];+ else f.part[((size_t) k * NR + r) * NB + b] = (float) acc[k];+ }+ }+ if (!grid_sync(f.bar, f.timeout_ticks)) return;+ // (B) rs per stream (every block), then rows (k, r) = b + 80 j reduced to lo / inject by the blocks in turn+ if (tid < T * HC) {+ const int k = tid / HC, c = tid - k * HC;+ float rr;+ if constexpr (DP) {+ double sd = 0.0;+ for (int j = 0; j < SPS; ++j) sd += f.sspd[k * NB + c * SPS + j];+ rr = (float) (1.0 / sqrt(sd / (double) N + (double) f.a[k].eps));+ } else {+ float s = 0.0f;+ for (int j = 0; j < SPS; ++j) s += f.ssp[k * NB + c * SPS + j];+ rr = rsqrtf(s / (float) N + f.a[k].eps);+ }+ s_rs[k][c] = rr;+ if (b == 0) f.a[k].rs[c] = rr;+ }+ __syncthreads();+ for (int idx = b + NB * tid; idx < T * nrows; idx += NB * THREADS) {+ const int k = idx / nrows, r = idx - k * nrows;+ A sum = 0;+ if constexpr (DP) {+ const double* p1 = f.partd + ((size_t) k * NR + r) * NB;+ for (int c = 0; c < HC; ++c) {+ double p = 0.0;+ for (int j = 0; j < SPS; ++j) p += p1[c * SPS + j];+ sum += (double) s_rs[k][c] * p;+ }+ } else {+ const float4* p4 = reinterpret_cast<const float4*>(f.part + ((size_t) k * NR + r) * NB);+#pragma unroll+ for (int c = 0; c < HC; ++c) {+ float p = 0.0f;+#pragma unroll+ for (int j = 0; j < SPS / 4; ++j) {+ const float4 v = p4[c * (SPS / 4) + j];+ p += (v.x + v.y) + (v.z + v.w);+ }+ sum = fmaf(s_rs[k][c], p, sum);+ }+ }+ if (r < LR) {+ const A x = sum / (A) HC;+ f.a[k].lo[r] = (float) (x / ((A) 1 + (DP ? (A) exp((double) -x) : (A) __expf((float) -x))));+ } else {+ f.a[k].inject_out[r - LR] = (float) sum;+ }+ }+ if (!grid_sync(f.bar, f.timeout_ticks)) return;+ for (int idx = tid; idx < T * LR; idx += THREADS) {+ const int k = idx / LR, r = idx - k * LR;+ lo[k][r] = f.a[k].lo[r];+ }+ __syncthreads();+ // (C) the up projection, a thread pair per row (block b: columns 32 b .. 32 b + 31 of all four streams), then the+ // epilogue as gr_up_kernel+ {+ const int d0 = b * UPC;+ const int ur = tid >> 1, uh = tid & 1, uc = ur / UPC, udd = ur - uc * UPC, ui = uc * N + d0 + udd;+ const uint4* w4u = reinterpret_cast<const uint4*>(a0.w_up + (size_t) ui * LR) + uh * 20;+ A v[T];+#pragma unroll+ for (int k = 0; k < T; ++k) v[k] = 0;+#pragma unroll 1+ for (int j0 = 0; j0 < 20; j0 += 5) { // five chunks a batch (all twenty at once costs registers)+ uint4 w[5];+#pragma unroll+ for (int q = 0; q < 5; ++q) w[q] = __ldg(w4u + j0 + q);+#pragma unroll+ for (int q = 0; q < 5; ++q)+#pragma unroll+ for (int k = 0; k < T; ++k) {+ if constexpr (DP) v[k] += dot8d(w[q], &lo[k][uh * 160] + (j0 + q) * 8);+ else v[k] += dot8(w[q], &lo[k][uh * 160] + (j0 + q) * 8);+ }+ }+ float acc[T];+#pragma unroll+ for (int k = 0; k < T; ++k) acc[k] = (float) (v[k] + __shfl_xor(v[k], 1));+ if (uh == 0) {+ const float wn = a0.w_norm[ui];+#pragma unroll+ for (int k = 0; k < T; ++k) {+ const FusedGrArgs& a = f.a[k];+ float rv = a.R[ui];+ if (a.apply) {+ rv = fmaf(a.bo_prev[d0 + udd], 2.0f * sigmoidf_(a.inj_prev[uc] / (float) HC), rv);+ a.R_out[ui] = rv;+ }+ g[k][uc][udd] = rv * wn * s_rs[k][uc] * sigmoidf_(acc[k]);+ }+ }+ }+ __syncthreads();+ for (int idx = tid; idx < T * UPC; idx += THREADS) {+ const int k = idx / UPC, col = idx - k * UPC;+ float s = 0.0f;+#pragma unroll+ for (int c = 0; c < HC; ++c) s += g[k][c][col];+ f.a[k].mixed[b * UPC + col] = s / (float) HC;+ }+}+struct DevState {+ float* part = nullptr;+ float* ssp = nullptr;+ double* partd = nullptr;+ double* sspd = nullptr;+ unsigned* bar = nullptr;+ int max_t = 0; // 0: off on this card+ bool tried = false;+};+DevState g_dev[64];+using KFn = void (*)(PArgs);+template <bool DP>+KFn kernel_t(int T) {+ switch (T) {+ case 1: return persist_kernel<1, DP>;+ case 2: return persist_kernel<2, DP>;+ case 3: return persist_kernel<3, DP>;+ case 4: return persist_kernel<4, DP>;+ case 5: return persist_kernel<5, DP>;+ case 6: return persist_kernel<6, DP>;+ case 7: return persist_kernel<7, DP>;+ case 8: return persist_kernel<8, DP>;+ }+ return nullptr;+}+bool dp_on() {+ static const bool dp = [] { const char* v = std::getenv("STRATA_HC_PERSIST"); return v != nullptr && std::atoi(v) == 3; }();+ return dp;+}+KFn kernel_for(int T) { return dp_on() ? kernel_t<true>(T) : kernel_t<false>(T); }+// s_memrealtime runs at 100 MHz on RDNA: a barrier gives up after 2 s in a read (never in a working run; it only turns a+// hang into a wrong read) and after 50 ms in the start-up check (where a timeout means "not resident here")+constexpr unsigned long long kTicksRun = 200000000ULL, kTicksCheck = 5000000ULL;+void launch(const FusedGrArgs* a, int n_tok, const DevState& st, cudaStream_t s, unsigned long long ticks) {+ PArgs f;+ for (int t = 0; t < n_tok; ++t) f.a[t] = a[t];+ f.part = st.part; f.ssp = st.ssp; f.bar = st.bar; f.partd = st.partd; f.sspd = st.sspd; f.timeout_ticks = ticks;+ kernel_for(n_tok)<<<NB, THREADS, 0, s>>>(f);+}+bool env_on() {+ static const bool on = [] { const char* v = std::getenv("STRATA_HC_PERSIST"); return v != nullptr && std::atoi(v) != 0; }();+ return on;+}+} // namespace hcp+} // namespace++void fused_gr_persist_init() {+ if (!hcp::env_on()) return;+ int dev = 0;+ cudaGetDevice(&dev);+ if (dev < 0 || dev >= 64 || hcp::g_dev[dev].tried) return;+ hcp::DevState& st = hcp::g_dev[dev];+ st.tried = true;+ cudaDeviceProp prop{};+ cudaGetDeviceProperties(&prop, dev);+ if (prop.warpSize != 32) {+ std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: the kernel is written for 32-lane waves "+ "(this card runs %d)\n", dev, prop.warpSize);+ return;+ }+ const int mp = prop.multiProcessorCount; // only for the confirmation line (WGPs on RDNA)+ bool ok = cudaMalloc((void**) &st.part, (size_t) kFusedGrMaxT * hcp::NR * hcp::NB * sizeof(float)) == cudaSuccess &&+ cudaMalloc((void**) &st.ssp, (size_t) kFusedGrMaxT * hcp::NB * sizeof(float)) == cudaSuccess &&+ cudaMalloc((void**) &st.bar, 64 * sizeof(unsigned)) == cudaSuccess &&+ cudaMalloc((void**) &st.partd, (size_t) kFusedGrMaxT * hcp::NR * hcp::NB * sizeof(double)) == cudaSuccess &&+ cudaMalloc((void**) &st.sspd, (size_t) kFusedGrMaxT * hcp::NB * sizeof(double)) == cudaSuccess &&+ cudaMemset(st.bar, 0, 64 * sizeof(unsigned)) == cudaSuccess;+ if (!ok) {+ cudaGetLastError();+ std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: workspace allocation failed\n", dev);+ return;+ }+ // the check: random weights and inputs with the pending write and the inject rows, against the default read; the+ // persistent read sums in another order, so it is bounded, not bitwise. Every T is RUN with a 50 ms barrier timeout; a+ // timeout means "not resident here" and larger T keep the default read. No occupancy API in front of it: it promised+ // more than the card holds on 30 WGPs under HSA_CU_MASK (a hang without the timeout) and less than it holds with+ // the HIP 7.1 runtime (1 block per WGP on 40 WGPs, which turned the read off although it runs resident).+ std::mt19937 rng(11);+ std::normal_distribution<float> nd(0.f, 1.f);+ auto bf = [](float x) { uint32_t u; std::memcpy(&u, &x, 4); return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16); };+ const int TM = kFusedGrMaxT;+ std::vector<float> R((size_t) TM * D), bo((size_t) TM * N), inj((size_t) TM * HC), wn(D);+ for (auto& x : R) x = nd(rng);+ for (auto& x : bo) x = 0.5f * nd(rng);+ for (auto& x : inj) x = nd(rng);+ for (auto& x : wn) x = 1.0f + 0.3f * nd(rng);+ std::vector<uint16_t> wd((size_t) LR * D), wu((size_t) D * LR), wi((size_t) HC * D);+ for (auto& x : wd) x = bf(0.02f * nd(rng));+ for (auto& x : wu) x = bf(0.05f * nd(rng));+ for (auto& x : wi) x = bf(0.02f * nd(rng));+ float *dR, *dbo, *dinj, *dwn, *dxn, *dlo, *drs, *dio, *dmix;+ uint16_t *dwd, *dwu, *dwi;+ cudaMalloc((void**) &dR, R.size() * 4); cudaMalloc((void**) &dbo, bo.size() * 4);+ cudaMalloc((void**) &dinj, inj.size() * 4); cudaMalloc((void**) &dwn, wn.size() * 4);+ cudaMalloc((void**) &dxn, (size_t) TM * D * 4); cudaMalloc((void**) &dlo, (size_t) TM * LR * 4);+ cudaMalloc((void**) &drs, (size_t) TM * HC * 4); cudaMalloc((void**) &dio, (size_t) TM * HC * 4);+ cudaMalloc((void**) &dmix, (size_t) TM * N * 4);+ cudaMalloc((void**) &dwd, wd.size() * 2); cudaMalloc((void**) &dwu, wu.size() * 2); cudaMalloc((void**) &dwi, wi.size() * 2);+ cudaMemcpy(dbo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice);+ cudaMemcpy(dinj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice);+ cudaMemcpy(dwn, wn.data(), wn.size() * 4, cudaMemcpyHostToDevice);+ cudaMemcpy(dwd, wd.data(), wd.size() * 2, cudaMemcpyHostToDevice);+ cudaMemcpy(dwu, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice);+ cudaMemcpy(dwi, wi.data(), wi.size() * 2, cudaMemcpyHostToDevice);+ double worst = 0.0;+ int bad_t = 0, timeouts = 0;+ // 0: the read agrees with the default read; 1: a barrier timed out (not resident); 2: wrong or a device error+ auto check = [&](int T) -> int {+ FusedGrArgs a[kFusedGrMaxT];+ for (int t = 0; t < T; ++t) {+ a[t] = FusedGrArgs{};+ a[t].R = dR + (size_t) t * D; a[t].R_out = dR + (size_t) t * D; a[t].apply = true;+ a[t].bo_prev = dbo + (size_t) t * N; a[t].inj_prev = dinj + (size_t) t * HC;+ a[t].w_norm = dwn; a[t].w_down = dwd; a[t].w_up = dwu; a[t].w_inject = dwi; a[t].eps = 1e-6f;+ a[t].lo = dlo + (size_t) t * LR; a[t].rs = drs + (size_t) t * HC;+ a[t].inject_out = dio + (size_t) t * HC; a[t].mixed = dmix + (size_t) t * N;+ }+ std::vector<float> out[2];+ for (int which = 0; which < 2; ++which) {+ cudaMemcpy(dR, R.data(), R.size() * 4, cudaMemcpyHostToDevice);+ cudaMemset(dmix, 0xff, (size_t) TM * N * 4);+ cudaMemset(dio, 0xff, (size_t) TM * HC * 4);+ cudaDeviceSynchronize();+ if (which == 0) fused_gr_read_multi(a, T, dxn, nullptr);+ else hcp::launch(a, T, st, nullptr, hcp::kTicksCheck);+ if (cudaDeviceSynchronize() != cudaSuccess) { cudaGetLastError(); return 2; }+ if (which == 1) {+ unsigned abort_word = 0;+ cudaMemcpy(&abort_word, st.bar + 48, sizeof abort_word, cudaMemcpyDeviceToHost);+ if (abort_word != 0u) {+ cudaMemset(st.bar, 0, 64 * sizeof(unsigned));+ cudaDeviceSynchronize();+ return 1;+ }+ }+ out[which].resize((size_t) T * (N + HC + D));+ cudaMemcpy(out[which].data(), dmix, (size_t) T * N * 4, cudaMemcpyDeviceToHost);+ cudaMemcpy(out[which].data() + (size_t) T * N, dio, (size_t) T * HC * 4, cudaMemcpyDeviceToHost);+ cudaMemcpy(out[which].data() + (size_t) T * (N + HC), dR, (size_t) T * D * 4, cudaMemcpyDeviceToHost);+ }+ double mref = 0.0, md = 0.0;+ bool finite = true;+ for (size_t i = 0; i < out[0].size(); ++i) {+ finite = finite && std::isfinite(out[1][i]);+ mref = std::fmax(mref, std::fabs((double) out[0][i]));+ md = std::fmax(md, std::fabs((double) out[1][i] - out[0][i]));+ }+ const double rel = md / (mref > 0 ? mref : 1.0);+ worst = std::fmax(worst, rel);+ return finite && rel < 1e-4 ? 0 : 2;+ };+ int max_t = 0;+ for (int T = 1; T <= kFusedGrMaxT && ok; ++T) {+ const int r = check(T);+ if (r == 1) ++timeouts; else if (r == 2) { bad_t = T; ok = false; }+ if (r != 0) break;+ max_t = T;+ }+ cudaFree(dR); cudaFree(dbo); cudaFree(dinj); cudaFree(dwn); cudaFree(dxn); cudaFree(dlo); cudaFree(drs);+ cudaFree(dio); cudaFree(dmix); cudaFree(dwd); cudaFree(dwu); cudaFree(dwi);+ cudaMemset(st.bar, 0, 64 * sizeof(unsigned));+ cudaDeviceSynchronize();+ cudaGetLastError();+ if (!ok) {+ std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: the check failed at %d tokens "+ "(max relative difference %.3g)\n", dev, bad_t, worst);+ return;+ }+ if (max_t == 0) {+ std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1 is off here: 80 blocks are not resident at once on %d "+ "multiprocessors (the check timed out)\n", dev, mp);+ return;+ }+ st.max_t = max_t;+ std::fprintf(stderr, "strata hc: CUDA%d: STRATA_HC_PERSIST=1: the verifier's hyper-connection read runs as one "+ "persistent kernel (80 blocks on %d multiprocessors, up to %d tokens; %d token counts timed out in "+ "the check; checked against the default read, max relative difference %.2g)\n", dev, mp, max_t,+ timeouts, worst);+}++bool fused_gr_read_persist(const FusedGrArgs* a, int n_tok, void* stream) {+ if (!hcp::env_on() || n_tok < 1) return false;+ int dev = 0;+ cudaGetDevice(&dev);+ if (dev < 0 || dev >= 64) return false;+ const hcp::DevState& st = hcp::g_dev[dev];+ if (n_tok > st.max_t) return false;+ if (a[0].q8_down != nullptr || a[0].q8_up != nullptr) return false; // STRATA_HC_Q8: the default read+ for (int t = 0; t < n_tok; ++t)+ if (a[t].q8_mixed != nullptr) return false; // STRATA_QFUSE: the default read+ hcp::launch(a, n_tok, st, (cudaStream_t) stream, hcp::kTicksRun);+ return true;+}+#else+void fused_gr_persist_init() {}+bool fused_gr_read_persist(const FusedGrArgs*, int, void*) { return false; }+#endif+} // namespace strata::kernels