From 496d19d8e92b6dfcf985447aeb85f282b7f4119f Mon Sep 17 00:00:00 2001 From: Shogo Okada <33060490+okada-shogo@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:37:57 +0900 Subject: [PATCH 1/2] poly: the doorbell on AMD (HIP): a decode token with experts outside VRAM routes on the card, with no host round trip a layer Until now HIP had no doorbell, so an Inkling 2 token with some routed experts outside VRAM waited for the host at every layer (the router's scores to the host, an event wait, the picks back): 48 host round trips a token, 30-90 us each under WSL2 (dxg). With the doorbell the card routes, rings the host for the experts it lacks and goes on; the host's CPU workers answer through pinned memory, and the whole token is one recording. - bell.cuh: the card's side of the bell. On HIP: system-scope atomic loads and a release store for the bell's words, an acquire fence after the wait, s_sleep between looks. CUDA keeps its volatile accesses and __nanosleep(500) (the same code as before). - Engine::hmalloc(..., live): the bell, the token's input (h_x_) and the host's answer (h_cpu_) are hipHostMallocCoherent on HIP (hipHostMalloc's default memory is not coherent). CUDA unchanged. - bell_serve(): on HIP one hipStreamQuery after the token's launches. Under dxg a launch followed only by a look at host memory was not submitted within 2 s in 32 of 40 tries on an RX 9070 XT; one query fixed it. - bell_serve() gives up after 60 s with neither a ring nor the card's end (the card's waits end, the call throws), and run()/step() end the card's waits when a throw comes after a ring was launched (bell_unwind()). - poly_bell_test: ring and answer while the card waits, a whole pass in one recording, a token-sized pass (1,536 kernels in two recordings), an answer 3 s late, an abort. Routing on the card is the doorbell's own (route_rows(), as on CUDA and as HIP already routes with every expert in VRAM). It rounds the router's sigmoid differently from the host's route_by(), so the result is not bit-identical to HIP main's host-routed path (on CUDA main the doorbell differs from STRATA_POLY_BELL=0 in the same way). STRATA_POLY_BELL=0 gives main's bits. The doorbell is VecSzn's design (after Strata v0.2.19's Inkling hybrid mode); this ports it to HIP. Co-Authored-By: Claude Opus 5.5 --- docs/SETTINGS.md | 2 +- docs/models/inkling.md | 5 +- engine/cmake/strata_poly.cmake | 7 + engine/include/strata/poly/kernels.hpp | 2 +- engine/src/poly/bell.cuh | 54 ++++ engine/src/poly/bell_test.cu | 428 +++++++++++++++++++++++++ engine/src/poly/engine.cpp | 74 +++-- engine/src/poly/engine.hpp | 5 +- engine/src/poly/inkling2.hpp | 2 +- engine/src/poly/kernels.cu | 15 +- terminal/data/settings-register.json | 4 +- 11 files changed, 562 insertions(+), 36 deletions(-) create mode 100644 engine/src/poly/bell.cuh create mode 100644 engine/src/poly/bell_test.cu diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index bb8fe28061..b3cfc76681 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -443,7 +443,7 @@ version made it the default. | `STRATA_PF_XMX` | text | Intel Arc | v0.2.16 | [INTEL.md](INTEL.md), [release-notes-0.2.0.md](release-notes-0.2.0.md) | | `STRATA_PIPELINE_ADAPT_ASYNC` | number | NVIDIA and AMD | v0.2.16 | - | | `STRATA_PLE_AUTO_MMAP` | number | NVIDIA and AMD, Intel Arc | v0.2.16 | [DETAILS.md](DETAILS.md) | -| `STRATA_POLY_BELL` | on / off | NVIDIA | - | - | +| `STRATA_POLY_BELL` | on / off | NVIDIA and AMD | - | [inkling.md](models/inkling.md) | | `STRATA_POLY_EXPERT_TILES` | on / off | NVIDIA and AMD | - | [inkling.md](models/inkling.md) | | `STRATA_POLY_HIP_GROUPED` | on / off | NVIDIA and AMD | - | - | | `STRATA_POLY_NV4_TILE` | on / off | NVIDIA and AMD | - | - | diff --git a/docs/models/inkling.md b/docs/models/inkling.md index 8157465201..692ba9b232 100644 --- a/docs/models/inkling.md +++ b/docs/models/inkling.md @@ -277,7 +277,10 @@ every expert on the CPU the answers match an RTX 2070 Super's: on the RX 7900 XT 64 of 64 steps after a 302-token prompt, and at 15 to 16 of 16 after 2,048 tokens. On RDNA4 the prompt's FP16 products go through hipBLASLt, which rounds them differently: after one 2,048-token prompt that is unusually sensitive, the RX 9070 XT's answers differed from CUDA's more than the RX 7900 XT's, and with `ROCBLAS_USE_HIPBLASLT=0` as much as the -RX 7900 XT's; after 302 and 8,192 tokens they match CUDA's. Use an NVIDIA card or a Mac for now. +RX 7900 XT's; after 302 and 8,192 tokens they match CUDA's. With some experts in RAM a decode token is routed on +the card, which hands the experts it lacks to the CPU through the doorbell, as on NVIDIA: no wait for the host at +each layer. The card's routing rounds a little differently from the host's; `STRATA_POLY_BELL=0` routes on the host +as before. Use an NVIDIA card or a Mac for now. Not run yet: an AMD card on native Linux or Windows, `--expert-gpu` on two cards (built but not run), `--layer-split` on two unequal cards (below; it has run on two RTX 2070 Super), UD-Q4_K_XL on the 8 GB card and UD-Q4_K_XL on a Mac. diff --git a/engine/cmake/strata_poly.cmake b/engine/cmake/strata_poly.cmake index 11a4ab043e..3d93a1b08a 100644 --- a/engine/cmake/strata_poly.cmake +++ b/engine/cmake/strata_poly.cmake @@ -266,6 +266,13 @@ if(STRATA_BUILD_POLY AND STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA target_include_directories(poly_route_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) target_link_libraries(poly_route_test PRIVATE ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) + # the doorbell between a running card and the host (bell_ring(), bell_add()); needs a card (77 without one) + add_executable(poly_bell_test src/poly/bell_test.cu src/poly/kernels.cu) + target_include_directories(poly_bell_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include + ${_strata_gpu_include_directories}) + target_link_libraries(poly_bell_test PRIVATE ${_strata_gpu_blas_target} ${_strata_gpu_runtime_target}) + add_test(NAME poly_bell_test COMMAND poly_bell_test) + set_tests_properties(poly_bell_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) # the fused residual sum, RMS norm and Q8_1 quantization against the three launches; needs a card, run by hand add_executable(poly_norm_q8_test src/poly/norm_q8_test.cu src/poly/kernels.cu) target_include_directories(poly_norm_q8_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include diff --git a/engine/include/strata/poly/kernels.hpp b/engine/include/strata/poly/kernels.hpp index a13246f3f4..e1672f9eae 100644 --- a/engine/include/strata/poly/kernels.hpp +++ b/engine/include/strata/poly/kernels.hpp @@ -299,7 +299,7 @@ struct ExpertBell { }; /// One token's picks ids[0..n_used) with weights w at layer `layer`: the ones whose slots[] entry is null, at a place /// under skip_from, go into the bell, x (n floats) into hx, and the bell rings (seq[0] counts the rings; seq[1] is -/// this one, or 0 when there is none). One block. CUDA only. +/// this one, or 0 when there is none). One block. CUDA and HIP. void bell_ring(const void* const* slots, const int32_t* ids, const float* w, int n_used, int skip_from, int layer, const float* x, float* hx, int n, ExpertBell* bell, uint32_t* seq, void* stream); /// Where seq[1] is a ring: wait until the bell's ack is that ring (or abort is set), then acc += hy (n floats). diff --git a/engine/src/poly/bell.cuh b/engine/src/poly/bell.cuh new file mode 100644 index 0000000000..32feb8c3ba --- /dev/null +++ b/engine/src/poly/bell.cuh @@ -0,0 +1,54 @@ +// src/poly/bell.cuh - the card's side of the doorbell (ExpertBell, kernels.hpp): its loads and stores of the words +// the host writes and reads while a kernel runs, and its wait between two looks. CUDA keeps its volatile accesses +// and __threadfence_system(), as before. On HIP the words are read and written with system-scope atomics (a +// kernel on an RX 9070 XT under WSL2 saw the host's writes to pinned memory live this way, and the host its writes: +// a round trip of 1.3 to 2.8 us), and the bell's memory is coherent (Engine::hmalloc(): hipHostMallocCoherent), so +// no cache between the card and the host holds a stale copy. +#pragma once + +#include "strata/poly/kernels.hpp" + +#include + +namespace strata::poly { + +/// The word *p as the host last wrote it. +__device__ __forceinline__ uint32_t bell_peek(const volatile uint32_t* p) { +#if defined(__HIP_DEVICE_COMPILE__) + return __hip_atomic_load(const_cast(p), __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_SYSTEM); +#else + return *p; +#endif +} + +/// *p = v for the host to see; what this thread wrote before (and fenced at system scope) is the host's first. +__device__ __forceinline__ void bell_poke(volatile uint32_t* p, uint32_t v) { +#if defined(__HIP_DEVICE_COMPILE__) + __hip_atomic_store(const_cast(p), v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM); +#else + *p = v; +#endif +} + +/// A pause between two looks at the bell, so that a waiting block does not keep the memory path busy (a spinning +/// card draws power that a laptop's CPU, computing the experts meanwhile, would rather have): 0.5 us on CUDA; on AMD +/// s_sleep 8, 8 x 64 clocks (~0.2 us at 2.5 GHz). +__device__ __forceinline__ void bell_pause() { +#if defined(__HIP_DEVICE_COMPILE__) + __builtin_amdgcn_s_sleep(8); +#elif defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 + __nanosleep(500); +#endif +} + +/// One thread: wait until the bell's ack is ring r or the host gave up (abort). The caller's block then meets at a +/// barrier and fences at system scope before it reads what the host wrote. +__device__ __forceinline__ void bell_wait(const ExpertBell* bell, uint32_t r) { + while (bell_peek(&bell->ack) != r && !bell_peek(&bell->abort)) bell_pause(); +#if defined(__HIP_DEVICE_COMPILE__) + // the acquire that pairs with the host's release before its ack: the host's sum is this thread's to share + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, ""); +#endif +} + +} // namespace strata::poly diff --git a/engine/src/poly/bell_test.cu b/engine/src/poly/bell_test.cu new file mode 100644 index 0000000000..2a80721697 --- /dev/null +++ b/engine/src/poly/bell_test.cu @@ -0,0 +1,428 @@ +// src/poly/bell_test.cu - the doorbell (bell_ring(), bell_add(), ExpertBell) between a running card and this host, +// as Engine::bell_serve() answers it: the picks the card lacks and the token's input reach the host while the card +// goes on, and the card adds the host's answer only once it is there. Cases: no miss (no ring); a ring answered +// while the card waits, many times over with new numbers each time (a stale read of the answer or of the input +// shows); 48 layers of rings in one recording, answered as they come, alone and between ~1,500 other kernels with +// large arguments in two recordings (a token's size: the host's launches must not wait for room behind a card that +// waits for the host); an answer 3 s late; an abort, which must end the card's wait. +// The memory is the engine's (pinned; on HIP coherent, as Engine::hmalloc() gives the doorbell). +// +// usage: poly_bell_test (exit 0: every check passed; 77: no card) +#include "strata/poly/kernels.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace strata::poly; +using Clock = std::chrono::steady_clock; + +constexpr int kExperts = 64, kUsed = 8, kEmbd = 2304, kLayers = 48; +int failed = 0, checks = 0; +int delay_us = 0; // serve(): the host waits this long before it answers a ring (a card that does not wait shows) + +void expect(bool ok, const char* what) { + ++checks; + if (!ok) { + ++failed; + std::printf("FAIL %s\n", what); + } +} + +void ck(cudaError_t e) { + if (e == cudaSuccess) return; + ++failed; + std::printf("FAIL CUDA: %s\n", cudaGetErrorString(e)); +} + +void* host_live(size_t bytes) { + void* p = nullptr; +#if defined(STRATA_USE_HIP) + if (hipHostMalloc(&p, bytes, hipHostMallocMapped | hipHostMallocCoherent) != hipSuccess) return nullptr; +#else + if (cudaMallocHost(&p, bytes) != cudaSuccess) return nullptr; +#endif + std::memset(p, 0, bytes); + return p; +} + +struct Rig { + ExpertBell* bell = nullptr; + float *hx = nullptr, *hy = nullptr; // pinned: the token's input, the host's answer + uint32_t* seq = nullptr; // the card's + void** slots = nullptr; // per layer: an expert's slot, null outside VRAM + int32_t* ids = nullptr; // per layer: the token's picks + float *w = nullptr, *x = nullptr, *acc = nullptr; + std::vector h_ids; // kLayers x kUsed + std::vector h_w; + std::vector missing; // kLayers x kExperts + cudaStream_t st = nullptr; + cudaEvent_t done = nullptr; + uint32_t seen = 0; +}; + +// Each layer's picks: distinct experts, about a third of them outside VRAM (skip: none outside). +void make_layers(Rig& g, std::mt19937& rng, bool none_missing) { + g.h_ids.assign((size_t) kLayers * kUsed, 0); + g.h_w.assign(g.h_ids.size(), 0.f); + g.missing.assign((size_t) kLayers * kExperts, 0); + std::vector slots((size_t) kLayers * kExperts); + std::uniform_real_distribution u(0.f, 1.f); + for (int il = 0; il < kLayers; ++il) { + for (int e = 0; e < kExperts; ++e) { + const bool miss = !none_missing && u(rng) < 0.33f; + g.missing[(size_t) il * kExperts + e] = miss; + slots[(size_t) il * kExperts + e] = miss ? nullptr : (void*) (uintptr_t) (0x1000 + e); // never read + } + std::vector pool(kExperts); + for (int e = 0; e < kExperts; ++e) pool[e] = e; + std::shuffle(pool.begin(), pool.end(), rng); + for (int k = 0; k < kUsed; ++k) { + g.h_ids[(size_t) il * kUsed + k] = pool[k]; + g.h_w[(size_t) il * kUsed + k] = u(rng); + } + } + ck(cudaMemcpy(g.slots, slots.data(), slots.size() * sizeof(void*), cudaMemcpyHostToDevice)); + ck(cudaMemcpy(g.ids, g.h_ids.data(), g.h_ids.size() * sizeof(int32_t), cudaMemcpyHostToDevice)); + ck(cudaMemcpy(g.w, g.h_w.data(), g.h_w.size() * sizeof(float), cudaMemcpyHostToDevice)); +} + +void launch_layer(Rig& g, int il) { + bell_ring(g.slots + (size_t) il * kExperts, g.ids + (size_t) il * kUsed, g.w + (size_t) il * kUsed, kUsed, kUsed, + il, g.x + (size_t) il * kEmbd, g.hx, kEmbd, g.bell, g.seq, g.st); + bell_add(g.bell, g.seq, g.hy, g.acc, kEmbd, g.st); +} + +// A stand-in for a layer's other kernels: an argument as large as the engine's larger ones, one write. +struct Big { + float* out; + int pad[60]; +}; +__global__ void filler_kernel(Big b) { + if (threadIdx.x == 0 && blockIdx.x == 0) b.out[0] = (float) b.pad[0]; +} + +// The host's answer to layer il's ring: its jobs checked against the picks, its input against x, and an answer +// that depends on the layer and the round (so a stale one shows). +float answer(int il, int round, int i) { return (float) ((il * 7 + round * 13 + i) % 97) * 0.25f - 3.f; } + +// Engine::bell_serve()'s loop: answer each ring until the card is past `done`. abort_after: rings answered before +// the host gives up instead (abort), -1 never. False: the card did not finish within 10 s. +bool serve(Rig& g, const std::vector& h_x, int round, int abort_after, int* answered, bool* jobs_ok) { + ck(cudaEventRecord(g.done, g.st)); + (void) cudaStreamQuery(g.st); // as bell_serve(): under WSL2 a launch may wait for the host's next HIP call + const Clock::time_point t0 = Clock::now(); + *answered = 0; + for (;;) { + const uint32_t r = g.bell->ring; + if (r != g.seen) { + std::atomic_thread_fence(std::memory_order_acquire); + g.seen = r; + if (abort_after >= 0 && *answered >= abort_after) { + g.bell->abort = 1; + ck(cudaStreamSynchronize(g.st)); + g.bell->abort = 0; + g.seen = g.bell->ring; + return true; + } + const int il = g.bell->layer, n = g.bell->n; + // the jobs: the picks outside VRAM, in pick order + std::vector want; + for (int k = 0; k < kUsed; ++k) { + const int e = g.h_ids[(size_t) il * kUsed + k]; + if (g.missing[(size_t) il * kExperts + e]) want.push_back(k); + } + bool ok = n == (int) want.size(); + for (int j = 0; ok && j < n; ++j) + ok = g.bell->e[j] == g.h_ids[(size_t) il * kUsed + want[j]] && + g.bell->w[j] == g.h_w[(size_t) il * kUsed + want[j]]; + for (int i = 0; ok && i < kEmbd; ++i) ok = g.hx[i] == h_x[(size_t) il * kEmbd + i]; + *jobs_ok = *jobs_ok && ok; + if (delay_us > 0) std::this_thread::sleep_for(std::chrono::microseconds(delay_us)); + for (int i = 0; i < kEmbd; ++i) g.hy[i] = answer(il, round, i); + std::atomic_thread_fence(std::memory_order_release); + g.bell->ack = r; + ++*answered; + continue; + } + const cudaError_t q = cudaEventQuery(g.done); + if (q == cudaSuccess) return true; + if (q != cudaErrorNotReady) { + std::printf("CUDA: %s\n", cudaGetErrorString(q)); + return false; + } + if (Clock::now() - t0 > std::chrono::seconds(10)) { + g.bell->abort = 1; // end the card's wait so that the test can go on + ck(cudaStreamSynchronize(g.st)); + g.bell->abort = 0; + g.seen = g.bell->ring; + return false; + } + } +} + +bool rings_at(const Rig& g, int il) { + for (int k = 0; k < kUsed; ++k) + if (g.missing[(size_t) il * kExperts + g.h_ids[(size_t) il * kUsed + k]]) return true; + return false; +} + +// acc after layers [0, layers) of a round: each ringing layer adds its answer +std::vector want_acc(const Rig& g, const std::vector& acc0, int layers, int round) { + std::vector a = acc0; + for (int il = 0; il < layers; ++il) { + if (!rings_at(g, il)) continue; + for (int i = 0; i < kEmbd; ++i) a[i] += answer(il, round, i); + } + return a; +} + +std::vector down(const float* d, size_t n) { + std::vector v(n); + ck(cudaMemcpy(v.data(), d, n * sizeof(float), cudaMemcpyDeviceToHost)); + return v; +} + +} // namespace + +int main() { + int devices = 0; + const cudaError_t de = cudaGetDeviceCount(&devices); +#if defined(STRATA_USE_HIP) + const bool none = de == hipErrorNoDevice; +#else + const bool none = de == cudaErrorNoDevice; +#endif + if (none || (de == cudaSuccess && devices == 0)) { + std::printf("no card\n"); + return 77; + } + if (de != cudaSuccess) { + std::printf("FAIL the runtime: %s\n", cudaGetErrorString(de)); + return 1; + } + Rig g; + g.bell = (ExpertBell*) host_live(sizeof(ExpertBell)); + g.hx = (float*) host_live(kEmbd * sizeof(float)); + g.hy = (float*) host_live(kEmbd * sizeof(float)); + if (!g.bell || !g.hx || !g.hy) { + std::printf("FAIL pinned memory\n"); + return 1; + } + ck(cudaMalloc(&g.seq, 2 * sizeof(uint32_t))); + ck(cudaMemset(g.seq, 0, 2 * sizeof(uint32_t))); + ck(cudaMalloc(&g.slots, (size_t) kLayers * kExperts * sizeof(void*))); + ck(cudaMalloc(&g.ids, (size_t) kLayers * kUsed * sizeof(int32_t))); + ck(cudaMalloc(&g.w, (size_t) kLayers * kUsed * sizeof(float))); + ck(cudaMalloc(&g.x, (size_t) kLayers * kEmbd * sizeof(float))); + ck(cudaMalloc(&g.acc, kEmbd * sizeof(float))); + ck(cudaStreamCreateWithFlags(&g.st, cudaStreamNonBlocking)); + ck(cudaEventCreateWithFlags(&g.done, cudaEventDisableTiming)); + std::mt19937 rng(5); + std::normal_distribution nd(0.f, 1.f); + std::vector h_x((size_t) kLayers * kEmbd), acc0(kEmbd); + const auto fresh = [&] { + for (float& v : h_x) v = nd(rng); + for (float& v : acc0) v = nd(rng); + ck(cudaMemcpy(g.x, h_x.data(), h_x.size() * sizeof(float), cudaMemcpyHostToDevice)); + ck(cudaMemcpy(g.acc, acc0.data(), acc0.size() * sizeof(float), cudaMemcpyHostToDevice)); + }; + + // 1. no expert outside VRAM: no ring, nothing added + { + make_layers(g, rng, true); + fresh(); + const uint32_t ring0 = g.bell->ring; + launch_layer(g, 0); + int answered = 0; + bool jobs_ok = true; + expect(serve(g, h_x, 0, -1, &answered, &jobs_ok), "no miss: the card finishes"); + expect(answered == 0 && g.bell->ring == ring0, "no miss: no ring"); + expect(down(g.acc, kEmbd) == acc0, "no miss: acc unchanged"); + } + + // 2. one layer a call, rung and answered while the card waits: 2,000 rounds with new numbers each + { + make_layers(g, rng, false); + int il = 0; + while (il + 1 < kLayers && !rings_at(g, il)) ++il; + expect(rings_at(g, il), "one layer: a layer with a miss"); + bool all_ok = true, jobs_ok = true; + double worst_us = 0, sum_us = 0; + const int rounds = 2000; + for (int round = 0; round < rounds; ++round) { + for (int i = 0; i < kEmbd; ++i) h_x[(size_t) il * kEmbd + i] = nd(rng); + for (float& v : acc0) v = nd(rng); + ck(cudaMemcpyAsync(g.x + (size_t) il * kEmbd, h_x.data() + (size_t) il * kEmbd, kEmbd * sizeof(float), + cudaMemcpyHostToDevice, g.st)); + ck(cudaMemcpyAsync(g.acc, acc0.data(), kEmbd * sizeof(float), cudaMemcpyHostToDevice, g.st)); + ck(cudaStreamSynchronize(g.st)); + const Clock::time_point t0 = Clock::now(); + launch_layer(g, il); + int answered = 0; + delay_us = round % 10 == 9 ? 200 + 200 * (round % 7) : 0; // some rounds answer late + const bool fin = serve(g, h_x, round, -1, &answered, &jobs_ok); + delay_us = 0; + const double us = std::chrono::duration(Clock::now() - t0).count(); + worst_us = std::max(worst_us, us), sum_us += us; + std::vector want = acc0; + for (int i = 0; i < kEmbd; ++i) want[i] += answer(il, round, i); + if (!fin || answered != 1 || down(g.acc, kEmbd) != want) { + if (all_ok) std::printf(" round %d: finished %d, answered %d\n", round, (int) fin, answered); + all_ok = false; + } + } + expect(jobs_ok, "one layer: the jobs and the input as the card had them"); + expect(all_ok, "one layer: acc + the host's answer, every round"); + std::printf(" one layer a call: %d rounds, %.1f us a call on average, worst %.0f us (launch, ring, answer, add, " + "the card done)\n", rounds, sum_us / rounds, worst_us); + } + + // 3. 48 layers in one recording, answered as they ring (bell_serve() after a whole pass), 20 rounds + { + make_layers(g, rng, false); + cudaGraph_t graph = nullptr; + cudaGraphExec_t exec = nullptr; + bool rec = cudaStreamBeginCapture(g.st, cudaStreamCaptureModeThreadLocal) == cudaSuccess; + for (int il = 0; il < kLayers && rec; ++il) launch_layer(g, il); + rec = rec && cudaStreamEndCapture(g.st, &graph) == cudaSuccess && + cudaGraphInstantiateWithFlags(&exec, graph, 0) == cudaSuccess; + expect(rec, "recording: 48 layers recorded"); + int rings = 0; + for (int il = 0; il < kLayers; ++il) rings += rings_at(g, il); + bool all_ok = rec, jobs_ok = true; + double sum_us = 0; + const int rounds = 20; + for (int round = 0; round < rounds && rec; ++round) { + fresh(); + const Clock::time_point t0 = Clock::now(); + ck(cudaGraphLaunch(exec, g.st)); + int answered = 0; + const bool fin = serve(g, h_x, round, -1, &answered, &jobs_ok); + sum_us += std::chrono::duration(Clock::now() - t0).count(); + if (!fin || answered != rings || down(g.acc, kEmbd) != want_acc(g, acc0, kLayers, round)) { + if (all_ok) std::printf(" round %d: finished %d, answered %d of %d\n", round, (int) fin, answered, rings); + all_ok = false; + } + } + expect(jobs_ok, "recording: the jobs and the inputs as the card had them"); + expect(all_ok, "recording: acc + every ringing layer's answer, every round"); + std::printf(" recording: %d of %d layers ring, %.0f us a pass on average\n", rings, kLayers, sum_us / rounds); + if (exec) cudaGraphExecDestroy(exec); + if (graph) cudaGraphDestroy(graph); + } + + // 3b. the token's size: per layer 15 kernels between the ring and the add and 15 after, in two recordings (4 + // layers, then 44), as Engine::run() launches a whole pass, then served + { + make_layers(g, rng, false); + float* sink = nullptr; + ck(cudaMalloc(&sink, sizeof(float))); + Big b{}; + b.out = sink; + cudaGraph_t graph[2] = {}; + cudaGraphExec_t exec[2] = {}; + bool rec = true; + for (int part = 0; part < 2 && rec; ++part) { + rec = cudaStreamBeginCapture(g.st, cudaStreamCaptureModeThreadLocal) == cudaSuccess; + for (int il = part ? 4 : 0; il < (part ? kLayers : 4) && rec; ++il) { + bell_ring(g.slots + (size_t) il * kExperts, g.ids + (size_t) il * kUsed, g.w + (size_t) il * kUsed, kUsed, + kUsed, il, g.x + (size_t) il * kEmbd, g.hx, kEmbd, g.bell, g.seq, g.st); + for (int k = 0; k < 15; ++k) filler_kernel<<<1, 64, 0, g.st>>>(b); + bell_add(g.bell, g.seq, g.hy, g.acc, kEmbd, g.st); + for (int k = 0; k < 15; ++k) filler_kernel<<<1, 64, 0, g.st>>>(b); + } + rec = rec && cudaStreamEndCapture(g.st, &graph[part]) == cudaSuccess && + cudaGraphInstantiateWithFlags(&exec[part], graph[part], 0) == cudaSuccess; + } + expect(rec, "token size: 48 layers x 32 kernels recorded"); + int rings = 0; + for (int il = 0; il < kLayers; ++il) rings += rings_at(g, il); + bool all_ok = rec, jobs_ok = true; + double sum_us = 0; + const int rounds = 20; + for (int round = 0; round < rounds && rec; ++round) { + fresh(); + const Clock::time_point t0 = Clock::now(); + ck(cudaGraphLaunch(exec[0], g.st)); + ck(cudaGraphLaunch(exec[1], g.st)); + int answered = 0; + delay_us = round % 2 ? 300 : 0; + const bool fin = serve(g, h_x, round, -1, &answered, &jobs_ok); + delay_us = 0; + sum_us += std::chrono::duration(Clock::now() - t0).count(); + if (!fin || answered != rings || down(g.acc, kEmbd) != want_acc(g, acc0, kLayers, round)) { + if (all_ok) std::printf(" round %d: finished %d, answered %d of %d\n", round, (int) fin, answered, rings); + all_ok = false; + } + } + expect(jobs_ok && all_ok, "token size: every ring answered, acc right, every round"); + std::printf(" token size: %d kernels a pass, %d rings, %.0f us a pass on average\n", kLayers * 32, rings, + sum_us / rounds); + for (int part = 0; part < 2; ++part) { + if (exec[part]) cudaGraphExecDestroy(exec[part]); + if (graph[part]) cudaGraphDestroy(graph[part]); + } + cudaFree(sink); + } + + // 3c. an answer 3 s late (the card waits in one kernel that long: a cold first token's experts from the disk) + { + make_layers(g, rng, false); + fresh(); + int il = 0; + while (il + 1 < kLayers && !rings_at(g, il)) ++il; + launch_layer(g, il); + int answered = 0; + bool jobs_ok = true; + delay_us = 3000000; + const bool fin = serve(g, h_x, 7, -1, &answered, &jobs_ok); + delay_us = 0; + std::vector want = acc0; + for (int i = 0; i < kEmbd; ++i) want[i] += answer(il, 7, i); + expect(fin && answered == 1 && jobs_ok && down(g.acc, kEmbd) == want, "a 3 s wait: the card waits, then adds"); + // and the card still works after it + fresh(); + launch_layer(g, il); + expect(serve(g, h_x, 8, -1, &answered, &jobs_ok) && answered == 1, "after the 3 s wait: a ring answered"); + } + + // 4. an abort after 3 answers: the card's waits end at once and the stream finishes + { + make_layers(g, rng, false); + fresh(); + for (int il = 0; il < kLayers; ++il) launch_layer(g, il); + int answered = 0; + bool jobs_ok = true; + const Clock::time_point t0 = Clock::now(); + const bool fin = serve(g, h_x, 0, 3, &answered, &jobs_ok); + const double ms = std::chrono::duration(Clock::now() - t0).count(); + expect(fin && answered == 3 && cudaStreamQuery(g.st) == cudaSuccess, "abort: the stream ends"); + expect(ms < 5000, "abort: within 5 s"); + // the bell works again after an abort + make_layers(g, rng, false); + fresh(); + for (int il = 0; il < kLayers; ++il) launch_layer(g, il); + jobs_ok = true; + expect(serve(g, h_x, 1, -1, &answered, &jobs_ok) && jobs_ok && + down(g.acc, kEmbd) == want_acc(g, acc0, kLayers, 1), + "after an abort: 48 layers answered again"); + } + + if (const cudaError_t e = cudaGetLastError(); e != cudaSuccess && e != cudaErrorNotReady) { + std::printf("CUDA: %s\n", cudaGetErrorString(e)); + ++failed; + } + std::printf("%d checks, %d failed\n", checks, failed); + return failed ? 1 : 0; +} diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 35005b37ed..c10cdd712a 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -945,13 +945,19 @@ void* Engine::dmalloc(size_t bytes, const char* what) { return p; } -void* Engine::hmalloc(size_t bytes, const char* what) { +void* Engine::hmalloc(size_t bytes, const char* what, [[maybe_unused]] bool live) { void* p = nullptr; const std::string why = std::string(what) + " (" + std::to_string(bytes) + " bytes)"; // A container at its memory limit refused pinned memory with "invalid argument" five times in five minutes // while a download filled its page cache; a moment later the kernel has reclaimed some. cudaError_t e = cudaSuccess; for (int tries = 0; tries < 4; ++tries) { +#if defined(STRATA_USE_HIP) + // hipHostMalloc's default memory is not coherent (HIP_HOST_COHERENT=0): a kernel may read it from a cache + // and see the host's writes only at its next launch + if (live) e = hipHostMalloc(&p, std::max(bytes, 256), hipHostMallocMapped | hipHostMallocCoherent); + else +#endif e = cudaMallocHost(&p, std::max(bytes, 256)); if (e == cudaSuccess) break; cudaGetLastError(); @@ -3892,8 +3898,9 @@ void Engine::alloc() { at_ = (long long*) dmalloc(at_rows * 2 * sizeof(long long), "scratch"); h_at_ = (long long*) hmalloc(at_rows * 2 * sizeof(long long), "pinned memory"); h_rl_ = (float*) hmalloc(n * n_expert_ * sizeof(float), "pinned memory"); - h_x_ = (float*) hmalloc(n * n_embd_ * sizeof(float), "pinned memory"); - h_cpu_ = (float*) hmalloc(n * n_embd_ * sizeof(float), "pinned memory"); + // the doorbell's input and answer (bells()): the card writes h_x_ and reads h_cpu_ while the host works on them + h_x_ = (float*) hmalloc(n * n_embd_ * sizeof(float), "pinned memory", bells()); + h_cpu_ = (float*) hmalloc(n * n_embd_ * sizeof(float), "pinned memory", bells()); h_logits_ = (float*) hmalloc((size_t) n_vocab_ * sizeof(float), "pinned memory"); if (mmq_) { @@ -3994,7 +4001,6 @@ void Engine::alloc() { d_nfetch_ = (int*) dmalloc(sizeof(int), "scratch"); d_use_ = (int32_t*) dmalloc(layers_.size() * (size_t) n_expert_ * sizeof(int32_t), "scratch"); ck(cudaMemset(d_use_, 0, layers_.size() * (size_t) n_expert_ * sizeof(int32_t)), "expert uses"); -#if !defined(STRATA_USE_HIP) // the doorbell (bell_on()): every layer's experts by picks on the card, or none of them; STRATA_POLY_BELL=0: none const char* bell_env = std::getenv("STRATA_POLY_BELL"); bool bell = bells() && !split_ && !(bell_env && bell_env[0] == '0'); @@ -4007,7 +4013,7 @@ void Engine::alloc() { most = std::max(most, L.gu2() + L.d_bytes); // (slot_bytes is not known before fill_expert_cache()) } if (bell && most > 0) { - h_bell_ = (ExpertBell*) hmalloc(sizeof(ExpertBell), "pinned memory"); + h_bell_ = (ExpertBell*) hmalloc(sizeof(ExpertBell), "pinned memory", true); std::memset((void*) h_bell_, 0, sizeof(ExpertBell)); d_bell_seq_ = (uint32_t*) dmalloc(2 * sizeof(uint32_t), "scratch"); ck(cudaMemset(d_bell_seq_, 0, 2 * sizeof(uint32_t)), "the doorbell"); @@ -4019,7 +4025,6 @@ void Engine::alloc() { ck(cudaEventCreateWithFlags(&ev, cudaEventDisableTiming), "cudaEventCreate"); ev_bell_ = ev; } -#endif #endif tab_ = (int32_t*) dmalloc(tab, "scratch"); h_tab_ = (int32_t*) hmalloc(tab, "pinned memory"); @@ -5634,7 +5639,7 @@ bool Engine::moe_card(Layer& L, int il, int n) { } bool Engine::bell_on(int n) const { -#if defined(STRATA_GPU_METAL) || defined(STRATA_USE_HIP) +#if defined(STRATA_GPU_METAL) (void) n; return false; #else @@ -5647,9 +5652,18 @@ bool Engine::bell_on(int n) const { // the card is past the token's last launch. Here, not on threads of its own: the token's launches are all handed // over by then, and this thread would wait for the card anyway. void Engine::bell_serve() { -#if !defined(STRATA_GPU_METAL) && !defined(STRATA_USE_HIP) +#if !defined(STRATA_GPU_METAL) ck(cudaEventRecord((cudaEvent_t) ev_bell_, cs(st_)), "the doorbell"); - for (;;) { +#if defined(STRATA_USE_HIP) + // Under WSL2 (dxg) HIP may hold launches back until the host makes another HIP call: a launch followed only by + // a look at host memory was not submitted within 2 s in 32 of 40 tries on an RX 9070 XT, and one hipStreamQuery + // after it was enough. This query is that call; the loop's queries go on making them. + (void) cudaStreamQuery(cs(st_)); +#endif + // A minute with neither a ring nor the card's end (a ring this thread never sees, a launch never submitted): the + // card's waits end as on a failed job, and the call throws, where the process hung before. + Clock::time_point moved = Clock::now(); + for (unsigned spins = 0;; ++spins) { const uint32_t r = h_bell_->ring; if (r != bell_seen_) { std::atomic_thread_fence(std::memory_order_acquire); @@ -5657,24 +5671,36 @@ void Engine::bell_serve() { try { bell_job(); } catch (...) { - h_bell_->abort = 1; // the card's waits end; what it adds is spoiled, and the call throws - cudaStreamSynchronize(cs(st_)); - h_bell_->abort = 0; - bell_seen_ = h_bell_->ring; + bell_unwind(); // the card's waits end; what it adds is spoiled, and the call throws throw; } std::atomic_thread_fence(std::memory_order_release); h_bell_->ack = r; + moved = Clock::now(); continue; } const cudaError_t q = cudaEventQuery((cudaEvent_t) ev_bell_); if (q == cudaSuccess) return; if (q != cudaErrorNotReady) ck(q, "the doorbell"); + if (spins % 4096 == 0 && Clock::now() - moved > std::chrono::seconds(60)) { + bell_unwind(); + throw std::runtime_error("the doorbell: no ring and no end from the card in 60 s"); + } _mm_pause(); } #endif } +// The card's waits on the bell end at once (abort): what it adds is spoiled. Then the bell as the card left it. +void Engine::bell_unwind() { +#if !defined(STRATA_GPU_METAL) + h_bell_->abort = 1; + cudaStreamSynchronize(cs(st_)); + h_bell_->abort = 0; + bell_seen_ = h_bell_->ring; +#endif +} + void Engine::bell_job() { const int il = h_bell_->layer, n = std::min(h_bell_->n, kBellJobs); const Layer& L = layers_[(size_t) il]; @@ -7110,10 +7136,15 @@ void Engine::run(const int32_t* tokens, int n) { // workers from inside the launches, which bell_serve() answers once they are all handed to the card. bell_ = bell_on(n); bell_counts_ |= bell_; + // a throw after a ring was launched and before bell_serve() answers it: the card's waits end (bell_unwind()) struct BellOff { - bool& on; - ~BellOff() { on = false; } - } bell_off{bell_}; + Engine& e; + const int unwinding = std::uncaught_exceptions(); + ~BellOff() { + if (e.bell_ && std::uncaught_exceptions() > unwinding) e.bell_unwind(); + e.bell_ = false; + } + } bell_off{*this}; const bool card = n < kStageRows && card_moe(n); const auto on_card = [&](int il, int m, size_t rec) { Layer& L = layers_[(size_t) il]; @@ -7306,10 +7337,15 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* // did not fill for it. bell_ = bell_on(R); bell_counts_ |= bell_; + // a throw after a ring was launched and before bell_serve() answers it: the card's waits end (bell_unwind()) struct BellOff { - bool& on; - ~BellOff() { on = false; } - } bell_off{bell_}; + Engine& e; + const int unwinding = std::uncaught_exceptions(); + ~BellOff() { + if (e.bell_ && std::uncaught_exceptions() > unwinding) e.bell_unwind(); + e.bell_ = false; + } + } bell_off{*this}; const bool card = R < kStageRows && card_moe(R); // a token alone is routed on the card (the doorbell, bell_on()), so the rows the host takes are too (below) // (card_moe(1)'s test without its side effects: the doorbell, the card's slot table, no --expert-gpu; a layer that diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index ab0e274541..a31a20b62b 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -782,7 +782,9 @@ class Engine { int room(int n) const; int room_key(int n) const; void* dmalloc(size_t bytes, const char* what); - void* hmalloc(size_t bytes, const char* what); + /// `live`: memory that the card and the host read and write while a kernel runs (the doorbell): on HIP + /// coherent (hipHostMallocCoherent), so the card never reads it from a cache; on CUDA all pinned memory is. + void* hmalloc(size_t bytes, const char* what, bool live = false); void hfree(void* p); std::vector ram_keep(const std::vector* lately = nullptr) const; bool read_file(uint8_t* dst, const uint8_t* src, size_t n, bool copy = false) const; @@ -1206,6 +1208,7 @@ class Engine { bool bell_on(int n) const; void bell_serve(); void bell_job(); + void bell_unwind(); uint8_t* stage_ = nullptr; ///< experts that are not cached, on their way through VRAM uint8_t* h_stage_[2] = {}; ///< pinned; filled in turn void* ev_stage_[2] = {}; ///< marks the upload out of each diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 9b3b442939..45db3328d8 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -146,7 +146,7 @@ class Inkling2 final : public Engine { bool bells() const override { return true; } #if defined(STRATA_USE_HIP) // the shared expert is one memset (moe_shared()), and a graph launch a layer for it cost an RX 9070 XT's host - // more than the memset: with experts on the CPU (no doorbell on HIP) a token's layers are launched one by one + // more than the memset: with experts on the CPU and no doorbell a token's layers are launched one by one bool shared_recorded() const override { return false; } #endif // routed on the card in that recording: the host reads neither diff --git a/engine/src/poly/kernels.cu b/engine/src/poly/kernels.cu index 256f269c10..ff5d1b03cf 100644 --- a/engine/src/poly/kernels.cu +++ b/engine/src/poly/kernels.cu @@ -1,6 +1,7 @@ // src/poly/kernels.cu - see the header. The reference for every formula is llama.cpp's graph of the model and the // ggml ops it builds. Where a kernel takes several tokens, blockIdx.y is the token unless it says otherwise. #include "strata/poly/kernels.hpp" +#include "bell.cuh" #include "strata/kernels/dp4a.hpp" #ifdef STRATA_POLY_GDN_MMA #include "gdn_mma.hpp" @@ -3989,31 +3990,25 @@ __global__ void bell_ring_kernel(const void* const* __restrict__ slots, const in return; } for (int i = threadIdx.x; i < n; i += blockDim.x) hx[i] = x[i]; - __threadfence_system(); // the input and the jobs are the host's before the ring + __threadfence_system(); // the input and the jobs are the host's before the ring (bell_poke()) __syncthreads(); if (threadIdx.x == 0) { bell->layer = layer; bell->n = jobs; __threadfence_system(); const uint32_t s = ++seq[0]; - bell->ring = s; + bell_poke(&bell->ring, s); __threadfence_system(); seq[1] = s; } } -// One block: one thread asks the bell every half microsecond or so, the others sleep at the barrier (a spinning card -// draws power that a laptop's CPU, computing the experts meanwhile, would rather have). +// One block: one thread asks the bell every half microsecond or so (bell_wait()), the others sleep at the barrier. __global__ void bell_add_kernel(const ExpertBell* bell, const uint32_t* __restrict__ seq, const float* hy, float* __restrict__ acc, int n) { const uint32_t s = seq[1]; if (s == 0) return; - if (threadIdx.x == 0) - while (bell->ack != s && !bell->abort) { -#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700 - __nanosleep(500); -#endif - } + if (threadIdx.x == 0) bell_wait(bell, s); __syncthreads(); __threadfence_system(); for (int i = threadIdx.x; i < n; i += blockDim.x) acc[i] += *(volatile const float*) (hy + i); diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 1b115a1705..b305c0b192 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -34086,13 +34086,13 @@ { "name": "STRATA_POLY_BELL", "backends": [ - "cuda" + "cuda-hip" ], "reads": [ { "file": "engine/src/poly/engine.cpp", "line": 3731, - "backend": "cuda", + "backend": "cuda-hip", "fn": "getenv" } ], From fa92ae5651fde0fac4d29695c162ab148a4cc2b3 Mon Sep 17 00:00:00 2001 From: Shogo Okada <33060490+okada-shogo@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:46:35 +0900 Subject: [PATCH 2/2] poly: a window's tokens take the card's picks where a token alone does With the doorbell (bell_on(): Inkling 2 with experts outside VRAM, now on HIP as well) a token alone is routed on the card: route_card(), whose gate sigmoid uses the card's expf. A window of several tokens (--window N lookup guesses, the drafter's verify) went to moe(), which routed each row on the host: route(), the same formula with the host's std::exp. The two need not round alike in the last bit, so a guessed token's expert weights (and, at a near tie, an expert) could differ from the ones it got alone, and greedy answers with guesses parted from the answers without them. run() now does for a window what step() does for its rows since 1d4d9e25c: where a token alone routes on the card, up() routes the window's rows there before the router's event, with the picks and weights written straight to pinned memory (h_ids_, h_wts_, now also allocated for bells() with a window over 1), and moe() takes them (step_ids_). step()'s tests move into picks_like_alone() and picks_like_alone(L), shared by both; step() behaves as before. Not in a window's halves (they need reads_by_layer(), which no family with the doorbell has), not with --cache-bias, and not on Metal (no doorbell there). Class: same bits as one token at a time. RX 9070 XT, IQ4_NL, frozen experts at equal placement, STRATA_SPEC_FIXED=1, 128 tokens of code 2048 and chat/prose 8192: --window 4 and the DSpark drafter differed from no guesses in 6 of 6 before, 0 of 6 after. Co-Authored-By: Claude Opus 5.5 --- engine/src/poly/engine.cpp | 58 +++++++++++++++++++++++++++----------- engine/src/poly/engine.hpp | 9 ++++-- 2 files changed, 48 insertions(+), 19 deletions(-) diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index c10cdd712a..70ec94596e 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -3991,8 +3991,9 @@ void Engine::alloc() { d_ids_ = (int32_t*) dmalloc(rr * sizeof(int32_t), "scratch"); d_wts_ = (float*) dmalloc(rr * sizeof(float), "scratch"); h_ids_ = (int32_t*) hmalloc(rr * sizeof(int32_t), "pinned memory"); - // the weights of step()'s rows, back from the card where a token alone routes there (the doorbell) - if (bells() && opt_.batch > 0) h_wts_ = (float*) hmalloc(rr * sizeof(float), "pinned memory"); + // the weights of step()'s rows and a window's, back from the card where a token alone routes there (doorbell) + if (bells() && (opt_.batch > 0 || opt_.window > 1)) + h_wts_ = (float*) hmalloc(rr * sizeof(float), "pinned memory"); d_slots_ = (void**) dmalloc((size_t) n_layer_ * n_expert_ * sizeof(void*), "scratch"); #if !defined(STRATA_GPU_METAL) d_far_ = (void**) dmalloc((size_t) n_layer_ * n_expert_ * sizeof(void*), "scratch"); @@ -5229,7 +5230,7 @@ bool Engine::moe(Layer& L, int il, int n, const std::function* first) { const auto route_row = [&](int t) { int* ids = ids_of[t]; float* w = w_of[t]; - if (step_ids_) { // step()'s rows: the card's picks and weights (step_ids_) + if (step_ids_) { // step()'s rows or a window's: the card's picks and weights (step_ids_) const size_t from = (size_t) (at + t) * n_used_; std::copy(step_ids_ + from, step_ids_ + from + n_used_, ids); std::copy(h_wts_ + from, h_wts_ + from + n_used_, w); @@ -5647,6 +5648,24 @@ bool Engine::bell_on(int n) const { #endif } +// card_moe(1)'s test without its side effects: the doorbell, the card's slot table, no --expert-gpu. Not with +// --cache-bias, whose host route() biases the picks. +bool Engine::picks_like_alone() const { + bool on = h_wts_ && bell_on(1) && d_slots_ && n_used_ <= card_rows() && !opt_.dump && opt_.cache_bias <= 0.f; +#if !defined(STRATA_GPU_METAL) + on = on && !ecard_; +#endif + return on; +} + +// A layer that card_moe() found it cannot route (L.card == 0) is routed on the host alone too. One it has not tried +// yet (L.card == -1) counts as the card's only where its types have the card's pick kernels, as moe_card() would find. +bool Engine::picks_like_alone(const Layer& L) const { + return L.card == 1 || (L.card == -1 && kernels::native_mmvq_ids_supported((int) L.gu_type) && + kernels::native_mmvq_ids_supported((int) L.u_type) && + kernels::native_mmvq_ids_supported((int) L.d_type)); +} + // The doorbell's host side, after a token's launches: each ring is a layer's experts that the card lacks, computed by // the workers as moe() computes its CPU experts (the token's input in h_x_, their sum into h_cpu_) and answered, until // the card is past the token's last launch. Here, not on threads of its own: the token's launches are all handed @@ -7030,13 +7049,24 @@ void Engine::run(const int32_t* tokens, int n) { // call's tokens together are [0, window) by their number, and a half of a window comes after those, by the // window's tokens and which half it is. Which tokens leave their state is the window's, so its halves' too. const size_t wn = (size_t) opt_.window, recs = 3 * wn + (size_t) opt_.batch + 1; // step()'s rows after + // A window's tokens together, where a token alone is routed on the card (the doorbell): moe() takes the card's + // picks for them, as step() does for its rows, so each token gets the weights and experts it gets alone. + // (picks_like_alone() implies the window is not on the card: card_moe(n) has neither the doorbell nor + // card_routes() for it. Not in halves, whose two halves would share h_ids_: they need reads_by_layer(), which + // no family with the doorbell has.) + const bool halves = n > 1 && windowed_ && !card_routes() && halves_; + const bool like_alone = n > 1 && windowed_ && !halves && picks_like_alone(); + bool card_picks = false; // the layer up() took last is routed on the card for moe() const auto up = [&](int il, int m, size_t rec) { Layer& L = layers_[(size_t) il]; prefetch_layer(il, m); const size_t head = (size_t) head_key(il, m) * recs + rec; if (replay && L.fixed) replayed(L.heads, head, [&] { layer_head(L, il, m); }); else layer_head(L, il, m); + card_picks = false; if (!L.moe || batched(L, m)) return; + // the picks straight into the pinned memory moe() reads: a launch less than d_ids_ and copy2() + card_picks = like_alone && picks_like_alone(L) && route_card(il, m, h_ids_, h_wts_); ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); if (replay && shared_recorded()) replayed(L.shared, rec, [&] { moe_shared(L, il, m); }); else moe_shared(L, il, m); @@ -7062,7 +7092,7 @@ void Engine::run(const int32_t* tokens, int n) { // // A half's launches are the ones its tokens have in a call of their own, at their rows of the buffers // (shift_rows()), so each token comes out as it would alone. - if (n > 1 && windowed_ && !card_routes() && halves_) { + if (halves) { const int first[3] = {0, (n + 1) / 2, n}; // half k is the tokens [first[k], first[k + 1]) const unsigned bits = snap_bits_; // the window's tokens that leave the recurrent state int at = 0; @@ -7236,6 +7266,11 @@ void Engine::run(const int32_t* tokens, int n) { if (batched(L, n)) { moe_rows(L, il, n); } else if (!on_card(il, n, (size_t) n - 1)) { + struct Picks { + const int32_t*& ids; + ~Picks() { ids = nullptr; } + } picks_off{step_ids_}; + step_ids_ = card_picks ? h_ids_ : nullptr; if (moe(L, il, n)) moe_add(n); } else if (bell_) { // Layer by layer (the first tokens, before the whole pass is recorded): the ring is answered here, since @@ -7348,13 +7383,7 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* } bell_off{*this}; const bool card = R < kStageRows && card_moe(R); // a token alone is routed on the card (the doorbell, bell_on()), so the rows the host takes are too (below) - // (card_moe(1)'s test without its side effects: the doorbell, the card's slot table, no --expert-gpu; a layer that - // card_moe() found it cannot route, L.card == 0, is routed on the host alone too: below) - bool picks_like_alone = h_wts_ && bell_on(1) && d_slots_ && n_used_ <= card_rows() && !opt_.dump && R > 1 && - !guesses && opt_.cache_bias <= 0.f; -#if !defined(STRATA_GPU_METAL) - picks_like_alone = picks_like_alone && !ecard_; -#endif + const bool like_alone = R > 1 && !guesses && picks_like_alone(); // an architecture that takes the rows in one head: their sequences and positions while it does std::vector rows; if (batch_heads()) @@ -7594,12 +7623,7 @@ void Engine::step(const int* seqs, const int32_t* tokens, int n, const int32_t* // the card's picks too (moe(), step_ids_). The host's route() computes the gates' sigmoid with its own // exp, which can differ from the card's in the last bit, and a row would not get the weights, or now // and then the experts, it gets alone. - // (a layer card_moe() has not tried yet, L.card == -1, counts as the card's only where its types have the - // card's pick kernels, as moe_card() would find: else a token alone would be routed on the host) - const bool layer_card = L.card == 1 || (L.card == -1 && kernels::native_mmvq_ids_supported((int) L.gu_type) && - kernels::native_mmvq_ids_supported((int) L.u_type) && - kernels::native_mmvq_ids_supported((int) L.d_type)); - const bool card_picks = !card && picks_like_alone && layer_card && route_card(il, R, d_ids_, d_wts_); + const bool card_picks = !card && like_alone && picks_like_alone(L) && route_card(il, R, d_ids_, d_wts_); if (card_picks) copy2(d_ids_, h_ids_, R * n_used_, d_wts_, h_wts_, R * n_used_, st_); ck(cudaEventRecord((cudaEvent_t) ev_, cs(st_)), "router"); if (replay && shared_recorded()) replayed(L.shared, rec, [&] { moe_shared(L, il, R); }); diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index a31a20b62b..f0fab8b03d 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -1177,8 +1177,8 @@ class Engine { int32_t* d_ids_ = nullptr; ///< a batch's experts and weights when it routes on the card float* d_wts_ = nullptr; int32_t* h_ids_ = nullptr; ///< pinned: the experts, back from the card - float* h_wts_ = nullptr; ///< pinned: their weights, for step()'s rows (bells(), --batch) - /// While moe() takes step()'s rows: their picks from the card (h_ids_, h_wts_), as a token alone routes there + float* h_wts_ = nullptr; ///< pinned: their weights, for step()'s and window()'s rows (bells()) + /// While moe() takes several rows: their picks from the card (h_ids_, h_wts_), as a token alone routes there const int32_t* step_ids_ = nullptr; void** d_slots_ = nullptr; ///< every layer's L.slot on the card, n_expert_ a layer (moe_card()) std::vector h_slots_; ///< what d_slots_ holds @@ -1206,6 +1206,11 @@ class Engine { bool bell_ = false; ///< this call rings (run()) bool bell_counts_ = false; ///< a call since follow() last read d_use_ rang: picks to read bool bell_on(int n) const; + // Where a token alone routes on the card (the doorbell), rows the host takes are routed there too (route_card(), + // step_ids_): the host's route() need not round the gates like the card's. The first: whether a token alone is + // routed on the card at all; the second: whether layer L is (moe_card() would find its kernels). + bool picks_like_alone() const; + bool picks_like_alone(const Layer& L) const; void bell_serve(); void bell_job(); void bell_unwind();