diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index f7a058c1..34cc5f66 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -88,6 +88,27 @@ void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int /// bo[t, :] = shared[t, :] * sigmoid(sg[t]) + sum_k w[t, k] * D[slot[t, k], :] void moe_combine(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, int64_t T, void* stream); +/// --peer-device's prompt share as sums: bo[t, :] = (sum over the k with slot[t, k] < rows_local of w[t, k] * +/// D[slot[t, k], :], in k order) + peer[t, :] + shared[t, :] * sigmoid(sg[t]). `peer` (the peer's per-token sums) +/// may be mapped host memory. +void moe_combine_peer(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, + const float* peer, int64_t rows_local, float* bo, int64_t T, void* stream); +/// sum[t, :] += wk[p] * rows[r, :] with p = pair[r], t = p / 10 (the routed pair's token), for n rows of ONE expert +/// (no token twice: launches in a fixed expert order make the sums repeatable). After eddoursul/Strata's +/// moe_scatter_add (f8de703). +void peer_scatter_add(float* sum, const float* rows, const float* wk, const int32_t* pair, int64_t n, void* stream); +/// The same for a group of experts in one launch (a token may recur): token tok[b] adds its rows list[start[b] .. +/// start[b + 1]) in that order (the experts' order), row r at rows[r - r0]: bitwise the per-expert launches'. +/// eddoursul/Strata's moe_gather_add, with the weight looked up through the row's pair. +void peer_gather_add(float* sum, const float* rows, int64_t r0, const float* wk, const int32_t* pair, const int32_t* tok, + const int32_t* start, const int32_t* list, int64_t n_tok, void* stream); +/// moe_combine_peer with the peer's sums in FP16 (`peer16`, may be mapped host memory) +void moe_combine_peer16(const float* D, const int32_t* slot, const float* w, const float* shared, const float* sg, + const uint16_t* peer16, int64_t rows_local, float* bo, int64_t T, void* stream); +/// y = FP16 bits of x, saturated at +-65504 (the peer's sums on their way back; eddoursul/Strata 2acfac4) +void sums_to_f16(const float* x, uint16_t* y, int64_t n, void* stream); +/// dst[0, n) = FP32 of the FP16 src[0, n) (n a multiple of 8, 16-byte aligned; src may be mapped host memory) +void f16_to_f32_wide(float* dst, const uint16_t* src, int64_t n, void* stream); // ---- QSA helpers /// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`). diff --git a/serve/server.py b/serve/server.py index 80334e04..f93826fe 100644 --- a/serve/server.py +++ b/serve/server.py @@ -714,6 +714,11 @@ class StrataEngine: self.slot_order = [g * gs + t for t in range(gs) for g in range(groups)] self.slot_group = [b // gs if gs else 0 for b in range(self.batch)] # each slot's pipeline group self.slot_groups = groups + # pipelined groups (the engine says how many it runs: INFO batch_groups; older engines: the args). A pipelined + # group's window spans its slots up to its last busy one, and the engine keeps no pipelined slot as a + # conversation cache - see pick_slot + groups_run = int(self.info.get("batch_groups") or groups) + self.slot_gs = gs if groups > 1 and groups_run > 1 else 0 self.slot_q = [queue.Queue() for _ in range(self.batch)] self.slot_busy = [False] * self.batch # what each slot's sessions hold (prompt + every token a window fed), so a conversation's next turn goes to @@ -1420,6 +1425,16 @@ class StrataEngine: free = [b for b in self.slot_order if not self.slot_busy[b]] if not free: return None + gs = getattr(self, "slot_gs", 0) + if gs: + # pipelined groups: the engine keeps no pipelined slot as a conversation cache, so nothing is worth keeping + # free for a next turn. A group's window spans its slots up to its last busy one, so first fill a hole + # below a busy slot of the same group (it costs no extra row), then follow the spreading order + # (reported on #793: least-recently-used picks left leading holes, [_ B], that cost a whole row each) + def fills_hole(b): + g0 = b - b % gs + return any(self.slot_busy[x] for x in range(b + 1, g0 + gs)) + return min(free, key=lambda b: (not fills_hole(b), self.slot_order.index(b))) def held_prefix(b): h = self.slot_held[b] return len(h) if h and len(h) < len(prompt) and prompt[:len(h)] == h else 0 diff --git a/serve/test_slot_alloc.py b/serve/test_slot_alloc.py new file mode 100644 index 00000000..474b4f78 --- /dev/null +++ b/serve/test_slot_alloc.py @@ -0,0 +1,83 @@ +"""serve/test_slot_alloc.py - which batch slot a request gets (StrataEngine.pick_slot), no engine needed. + + python -m unittest serve.test_slot_alloc -v +""" +from __future__ import annotations + +import random +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from serve.server import StrataEngine # noqa: E402 + + +def engine(batch, groups, pipelined=True): + e = object.__new__(StrataEngine) # pick_slot reads only the slot tables + gs = batch // groups + e.batch = batch + e.slot_order = [g * gs + t for t in range(gs) for g in range(groups)] + e.slot_busy = [False] * batch + e.slot_held = [[] for _ in range(batch)] + e.slot_used = [0.0] * batch + e.slot_gs = gs if pipelined and groups > 1 else 0 + return e + + +class Pipelined(unittest.TestCase): + def test_spreads_over_the_groups_first(self): + e = engine(6, 3) + got = [] + for _ in range(6): + b = e.pick_slot([1, 2, 3]) + e.slot_busy[b] = True + got.append(b) + self.assertEqual(got, [0, 2, 4, 1, 3, 5]) + + def test_fills_a_leading_hole_first(self): + # #793's report: a group left as [_ B] costs a whole row; the next request goes into that hole + e = engine(6, 3) + e.slot_busy[3] = True # group 1 = [_ B] + e.slot_used[0] = 0.0 # least recently used: what the LRU fallback picked + e.slot_used[2] = 99.0 + self.assertEqual(e.pick_slot([1]), 2) + + def test_never_opens_a_hole_below_the_pick(self): + for batch, groups in ((6, 3), (8, 4), (8, 2), (4, 2)): + gs = batch // groups + e, rng = engine(batch, groups), random.Random(batch * 10 + groups) + for _ in range(2000): + busy = [b for b in range(batch) if e.slot_busy[b]] + if busy and (rng.random() < 0.45 or len(busy) == batch): + e.slot_busy[rng.choice(busy)] = False # a request ends, anywhere + continue + b = e.pick_slot([7]) + g0 = b - b % gs + with self.subTest(batch=batch, groups=groups): + self.assertTrue(all(e.slot_busy[x] for x in range(g0, b)), + f"slot {b} picked with a free slot below it in its group: {e.slot_busy}") + e.slot_busy[b] = True + + def test_held_tokens_are_ignored(self): + # the engine keeps no pipelined slot as a cache: a held prefix must not pull a request into a hole-making slot + e = engine(6, 3) + e.slot_held[5] = [1, 2] + self.assertEqual(e.pick_slot([1, 2, 3]), 0) + + +class OneGroup(unittest.TestCase): + def test_reuse_then_least_recently_used(self): + e = engine(4, 1, pipelined=False) + e.slot_held[2] = [1, 2] + self.assertEqual(e.pick_slot([1, 2, 3]), 2) # its conversation's next turn + e.slot_held[2] = [9] + e.slot_held = [[5], [], [9], [6]] + self.assertEqual(e.pick_slot([1, 2, 3]), 1) # an empty slot before evicting a held one + e.slot_held[1] = [8] + e.slot_used = [5.0, 3.0, 9.0, 1.0] + self.assertEqual(e.pick_slot([1, 2, 3]), 3) # else the least recently used + + +if __name__ == "__main__": + unittest.main() diff --git a/src/core/peer_experts.cpp b/src/core/peer_experts.cpp index ad88bda8..f68a2e0a 100644 --- a/src/core/peer_experts.cpp +++ b/src/core/peer_experts.cpp @@ -98,6 +98,7 @@ bool PeerExperts::open(int device, const std::vector int a = 0, b = 0; cudaDeviceCanAccessPeer(&a, 0, device); cudaDeviceCanAccessPeer(&b, device, 0); + if (const char* np = std::getenv("STRATA_PEER_NO_P2P"); np != nullptr && std::atoi(np) != 0) a = 0; // test knob: pretend the pair has no P2P p2p_ = a && b; if (p2p_) { On on0(0); diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 5314a5f1..18ec999a 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -2058,6 +2058,110 @@ void gather_rows16(const uint16_t* x16, const int32_t* src, uint16_t* dst16, int gather_rows16_kernel<<>>(x16, src, dst16, n, width); check("gather_rows16"); } +namespace { +__global__ void moe_combine_peer_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot, + const float* __restrict__ w, const float* __restrict__ shared, + const float* __restrict__ sg, const float* __restrict__ peer, int64_t rows_local, + float* __restrict__ bo, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * N) return; + const int64_t t = i / N, d = i % N; + float s = 0.0f; +#pragma unroll + for (int k = 0; k < 10; ++k) { + const int32_t r = slot[t * 10 + k]; + if (r < rows_local) s = fmaf(w[t * 10 + k], Dm[(int64_t) r * N + d], s); + } + bo[i] = (s + peer[i]) + shared[i] * sigm(sg[t]); +} +__global__ void peer_scatter_add_kernel(float* __restrict__ sum, const float* __restrict__ rows, + const float* __restrict__ wk, const int32_t* __restrict__ pair, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n * N) return; + const int64_t r = i / N, d = i % N; + const int32_t p = pair[r]; + float* o = sum + (int64_t) (p / 10) * N + d; + *o = fmaf(wk[p], rows[i], *o); +} +__global__ void moe_combine_peer16_kernel(const float* __restrict__ Dm, const int32_t* __restrict__ slot, + const float* __restrict__ w, const float* __restrict__ shared, + const float* __restrict__ sg, const uint16_t* __restrict__ peer16, + int64_t rows_local, float* __restrict__ bo, int64_t T) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= T * N) return; + const int64_t t = i / N, d = i % N; + float s = 0.0f; +#pragma unroll + for (int k = 0; k < 10; ++k) { + const int32_t r = slot[t * 10 + k]; + if (r < rows_local) s = fmaf(w[t * 10 + k], Dm[(int64_t) r * N + d], s); + } + bo[i] = (s + __half2float(__ushort_as_half(peer16[i]))) + shared[i] * sigm(sg[t]); +} +__global__ void peer_gather_add_kernel(float* __restrict__ sum, const float* __restrict__ rows, int64_t r0, + const float* __restrict__ wk, const int32_t* __restrict__ pair, + const int32_t* __restrict__ tok, const int32_t* __restrict__ start, + const int32_t* __restrict__ list) { + const int64_t d = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (d >= N) return; + const int b = blockIdx.y; + float* o = sum + (int64_t) tok[b] * N + d; + float s = *o; + for (int i = start[b]; i < start[b + 1]; ++i) { + const int r = list[i]; + s = fmaf(wk[pair[r]], rows[(r - r0) * N + d], s); + } + *o = s; +} +__global__ void sums_to_f16_kernel(const float* __restrict__ x, uint16_t* __restrict__ y, int64_t n) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = hf_sat(x[i]); +} +__global__ void f16_to_f32_wide_kernel(float4* __restrict__ dst, const uint4* __restrict__ src, int64_t n8) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; // eight values + if (i >= n8) return; + const uint4 v = src[i]; + const __half2* h = reinterpret_cast(&v); + const float2 a = __half22float2(h[0]), b = __half22float2(h[1]), c = __half22float2(h[2]), e = __half22float2(h[3]); + dst[2 * i] = make_float4(a.x, a.y, b.x, b.y); + dst[2 * i + 1] = make_float4(c.x, c.y, e.x, e.y); +} +} // namespace +void moe_combine_peer16(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, + const uint16_t* peer16, int64_t rows_local, float* bo, int64_t T, void* stream) { + moe_combine_peer16_kernel<<>>(Dm, slot, w, shared, sg, peer16, + rows_local, bo, T); + check("moe_combine_peer16"); +} +void peer_gather_add(float* sum, const float* rows, int64_t r0, const float* wk, const int32_t* pair, const int32_t* tok, + const int32_t* start, const int32_t* list, int64_t n_tok, void* stream) { + if (n_tok <= 0) return; + peer_gather_add_kernel<<>>( + sum, rows, r0, wk, pair, tok, start, list); + check("peer_gather_add"); +} +void sums_to_f16(const float* x, uint16_t* y, int64_t n, void* stream) { + if (n <= 0) return; + sums_to_f16_kernel<<>>(x, y, n); + check("sums_to_f16"); +} +void f16_to_f32_wide(float* dst, const uint16_t* src, int64_t n, void* stream) { + if (n <= 0) return; + f16_to_f32_wide_kernel<<>>(reinterpret_cast(dst), + reinterpret_cast(src), n / 8); + check("f16_to_f32_wide"); +} +void moe_combine_peer(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, + const float* peer, int64_t rows_local, float* bo, int64_t T, void* stream) { + moe_combine_peer_kernel<<>>(Dm, slot, w, shared, sg, peer, rows_local, + bo, T); + check("moe_combine_peer"); +} +void peer_scatter_add(float* sum, const float* rows, const float* wk, const int32_t* pair, int64_t n, void* stream) { + if (n <= 0) return; + peer_scatter_add_kernel<<>>(sum, rows, wk, pair, n); + check("peer_scatter_add"); +} void moe_combine(const float* Dm, const int32_t* slot, const float* w, const float* shared, const float* sg, float* bo, int64_t T, void* stream) { #ifndef STRATA_W_NO_COMB diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 48e7715f..465e6717 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -614,6 +614,26 @@ struct PeerPrefill { size_t host_x_cap = 0, host_rows_cap = 0, host_src_cap = 0; // elements static constexpr size_t kHostBounds = 2 * (NE + NE / 16 + 2) + 64; int64_t back_at = 0, back_rows = 0; + // SUMS (the host route's default, STRATA_PF_PEER_SUMS=0: rows): the peer adds its rows into one weighted sum per + // token (`sum`, from the routing weights `wk` and each row's routed pair `pair`) and sends that back (`host_sum`, + // T x N) instead of its rows (rows_peer x N, up to K times more over the primary's link); the primary's combine + // adds it to its own experts' rows (eddoursul/Strata's second-GPU prompt path, f8de703). + bool sums = false; + cudaStream_t x_stream = nullptr; // primary: the host route's copies beside its compute stream + cudaEvent_t ev_x = nullptr; + bool f16 = false; // the sums mode's transfers in FP16 (STRATA_PF_PEER_F16=0: FP32) + // the sums in one launch per group (STRATA_PF_PEER_GATHER=0: per expert): per group [tokens | starts | rows] at + // adds_at[g], built on the host from the rows' pairs, uploaded once per layer + bool gather = false; + int32_t *adds = nullptr, *host_adds = nullptr; + size_t adds_cap = 0; + std::vector adds_at; + std::vector ntok, tcur, touched; + uint16_t *sum16 = nullptr, *host_x16 = nullptr, *host_sum16 = nullptr; + float *sum = nullptr, *wk = nullptr; + int32_t* pair = nullptr; + float *host_w = nullptr, *host_sum = nullptr; + int32_t* host_pair = nullptr; std::vector bounds_host; std::vector owned; int64_t layers = 0, experts = 0, rows = 0, over_cap = 0; // stats @@ -637,10 +657,18 @@ struct PeerPrefill { if (s) cudaStreamDestroy(s); cudaSetDevice(prev); if (ev_in) cudaEventDestroy(ev_in); + if (x_stream) { cudaStreamSynchronize(x_stream); cudaStreamDestroy(x_stream); } + if (ev_x) cudaEventDestroy(ev_x); if (host_x) cudaFreeHost(host_x); if (host_rows) cudaFreeHost(host_rows); if (host_src) cudaFreeHost(host_src); if (host_bounds) cudaFreeHost(host_bounds); + if (host_w) cudaFreeHost(host_w); + if (host_sum) cudaFreeHost(host_sum); + if (host_pair) cudaFreeHost(host_pair); + if (host_x16) cudaFreeHost(host_x16); + if (host_sum16) cudaFreeHost(host_sum16); + if (host_adds) cudaFreeHost(host_adds); } }; @@ -1540,15 +1568,28 @@ bool Prefill::bind_stage_helper(int64_t T) { bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& err) { Impl& m = *impl_; if (peer == nullptr || !peer->valid()) { m.pp.reset(); return true; } - if (!peer->p2p()) { err = "prefill peer: the two GPUs cannot access each other (no P2P)"; return false; } + // Without P2P the activations and the result rows take the mapped host route of the layer split's helper + // (STRATA_PF_PEER_HOST=0: refuse as before, the prompt path then stays on the primary) + const bool host_route_ok = [] { const char* v = std::getenv("STRATA_PF_PEER_HOST"); return v == nullptr || std::atoi(v) != 0; }(); + if (!peer->p2p() && !host_route_ok) { err = "prefill peer: the two GPUs cannot access each other (no P2P)"; return false; } if (!mmq_plan().any) { err = "prefill peer: needs the MMQ prompt path"; return false; } auto pp = std::make_unique(); pp->peer = peer; + pp->p2p = peer->p2p(); pp->T_max = m.T_max; pp->cap_rows = std::max(1, std::min(cap_rows, m.T_max * K)); const int64_t R = pp->cap_rows; const MmqPlan& mp = mmq_plan(); if (cudaEventCreateWithFlags(&pp->ev_in, cudaEventDisableTiming) != cudaSuccess) { err = "prefill peer: event"; return false; } + if (!pp->p2p) { // the host route's copies on a stream of their own (STRATA_PF_PEER_XSTREAM=0: the compute stream) + const char* xv = std::getenv("STRATA_PF_PEER_XSTREAM"); + if ((xv == nullptr || std::atoi(xv) != 0) && + (cudaStreamCreateWithFlags(&pp->x_stream, cudaStreamNonBlocking) != cudaSuccess || + cudaEventCreateWithFlags(&pp->ev_x, cudaEventDisableTiming) != cudaSuccess)) { + err = "prefill peer: copy stream"; + return false; + } + } int prev = 0; cudaGetDevice(&prev); pp->dev = peer->device(); @@ -1573,7 +1614,7 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e pp->mixed = (float*) take((size_t) m.T_max * N * 4); { const char* v = std::getenv("STRATA_PF_PEER_COMPACT"); - pp->compact = v == nullptr || std::atoi(v) != 0; + pp->compact = (v == nullptr || std::atoi(v) != 0) || !pp->p2p; // the layer-sized path copies over P2P only } if (pp->compact) { pp->cap_rows = m.T_max * K; // no row cap: only the row tables grow with it @@ -1612,6 +1653,25 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e pp->Dm = (float*) take((size_t) R * N * 4); } const int64_t Rt = pp->cap_rows; + if (!pp->p2p && pp->compact) { + const char* v = std::getenv("STRATA_PF_PEER_SUMS"); + pp->sums = v == nullptr || std::atoi(v) != 0; + } + if (pp->sums) { + const char* v = std::getenv("STRATA_PF_PEER_F16"); + pp->f16 = (v == nullptr || std::atoi(v) != 0) && N % 8 == 0; + if (pp->f16) pp->sum16 = (uint16_t*) take((size_t) m.T_max * N * 2); + const char* gv = std::getenv("STRATA_PF_PEER_GATHER"); + pp->gather = gv == nullptr || std::atoi(gv) != 0; + if (pp->gather) { // tokens and starts (<= 2 rows + 1 per group) and rows: <= 3 x the rows + 2 per expert + pp->adds_cap = 3 * (size_t) Rt + 2 * NE + 64; + pp->adds = (int32_t*) take(pp->adds_cap * 4); + pp->tcur.assign((size_t) m.T_max, 0); + } + pp->sum = (float*) take((size_t) m.T_max * N * 4); + pp->wk = (float*) take((size_t) m.T_max * K * 4); + pp->pair = (int32_t*) take((size_t) Rt * 4); + } pp->src = (int32_t*) take((size_t) Rt * 4); pp->ident = (int32_t*) take((size_t) Rt * 4); pp->bounds = (int32_t*) take((size_t) (2 * (NE + NE / MMQ_GROUP + 2)) * 4); @@ -1623,12 +1683,48 @@ bool Prefill::set_peer(core::PeerExperts* peer, int64_t cap_rows, std::string& e mmq::iota(pp->ident, pp->cap_rows, pp->s); ok = cudaStreamSynchronize(pp->s) == cudaSuccess; } + if (ok && !pp->p2p) { // the host route's mapped buffers, sized for the largest chunk + auto host = [&](auto*& ptr, size_t& cap, size_t n) { + if (cudaHostAlloc((void**) &ptr, n * sizeof(*ptr), cudaHostAllocPortable | cudaHostAllocMapped) != cudaSuccess) { + cudaGetLastError(); + ptr = nullptr; + ok = false; + return; + } + cap = n; + }; + size_t bounds_cap = 0, w_cap = 0, sum_cap = 0, pair_cap = 0; + size_t x16_cap = 0, sum16_cap = 0; + if (pp->f16) host(pp->host_x16, x16_cap, (size_t) m.T_max * N); + else host(pp->host_x, pp->host_x_cap, (size_t) m.T_max * N); + if (ok && pp->sums) { + host(pp->host_w, w_cap, (size_t) m.T_max * K); + if (ok && pp->f16) host(pp->host_sum16, sum16_cap, (size_t) m.T_max * N); + else if (ok) host(pp->host_sum, sum_cap, (size_t) m.T_max * N); + if (ok) host(pp->host_pair, pair_cap, (size_t) pp->cap_rows); + size_t adds_cap = 0; + if (ok && pp->gather) host(pp->host_adds, adds_cap, pp->adds_cap); + } else if (ok) { + host(pp->host_rows, pp->host_rows_cap, (size_t) pp->cap_rows * N); + } + if (ok) host(pp->host_src, pp->host_src_cap, (size_t) pp->cap_rows); + if (ok) host(pp->host_bounds, bounds_cap, PeerPrefill::kHostBounds); + if (!ok) { + cudaSetDevice(prev); + err = "prefill peer: the host route's pinned buffers (" + + std::to_string(((size_t) pp->cap_rows * N * 4 + (size_t) m.T_max * N * 4) >> 20) + " MiB) do not fit in RAM"; + return false; + } + } size_t fb = 0, tb = 0; cudaMemGetInfo(&fb, &tb); cudaSetDevice(prev); if (!ok) { err = "prefill peer: the peer's buffers do not fit (raise --peer-reserve-mib or lower --peer-prefill-rows)"; return false; } std::fprintf(stderr, "strata prefill: peer GPU %d computes its experts' rows of each prompt chunk (up to %lld rows per " - "layer%s); %zu MiB left free on it\n", pp->dev, (long long) pp->cap_rows, + "layer%s%s); %zu MiB left free on it\n", pp->dev, (long long) pp->cap_rows, + pp->p2p ? "" : (pp->sums ? (pp->f16 ? ", no P2P: through mapped host memory in FP16, one weighted sum per token back" + : ", no P2P: through mapped host memory, one weighted sum per token back") + : ", no P2P: through mapped host memory"), pp->compact ? (pp->ps_frac > 0.0 ? (", compact group buffers, streams " + std::to_string((int) (pp->ps_frac * 100 + 0.5)) + "% of the primary's streamed experts through a " + std::to_string(pp->RP) + "-slot ring").c_str() : ", compact group buffers") : "", fb >> 20); @@ -3101,8 +3197,22 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri peer_now = use_mmq && !order_peer.empty(); if (peer_now) { PeerPrefill& P = *m.pp; - if (!P.p2p) cudaMemcpyAsync(P.host_x, m.mixed, (size_t) T * N * 4, cudaMemcpyDeviceToHost, m.cs); - cudaEventRecord(P.ev_in, m.cs); + // the host route's copies beside the compute stream: the primary's own experts start at once + // (mixed_h and w are rewritten only after this layer's combine, which waits for the peer) + cudaStream_t xs = m.cs; + if (P.x_stream != nullptr) { + cudaEventRecord(P.ev_x, m.cs); + cudaStreamWaitEvent(P.x_stream, P.ev_x, 0); + xs = P.x_stream; + } + if (!P.p2p && P.f16) cudaMemcpyAsync(P.host_x16, m.mixed_h, (size_t) T * N * 2, cudaMemcpyDeviceToHost, xs); + else if (!P.p2p) cudaMemcpyAsync(P.host_x, m.mixed, (size_t) T * N * 4, cudaMemcpyDeviceToHost, xs); + if (P.sums) { // the routing weights, and each peer row's routed pair (t * K + k) + cudaMemcpyAsync(P.host_w, m.w, (size_t) T * K * 4, cudaMemcpyDeviceToHost, xs); + for (int64_t i = 0; i < T * K; ++i) + if (const int32_t r = slot_h[(size_t) i]; r >= rows_local) P.host_pair[r - rows_local] = (int32_t) i; + } + cudaEventRecord(P.ev_in, xs); int prevd = 0; cudaGetDevice(&prevd); cudaSetDevice(P.dev); @@ -3111,6 +3221,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (P.out_pending) { cudaStreamWaitEvent(ps, P.ev_done, 0); P.out_pending = false; } pe.mark(kPeMoeIn, ps); if (P.p2p) cudaMemcpyPeerAsync(P.mixed, P.dev, m.mixed, prevd, (size_t) T * N * 4, ps); + else if (P.f16) f16_to_f32_wide(P.mixed, P.host_x16, T * N, ps); else copy_f32_wide(P.mixed, P.host_x, T * N, ps); P.back_at = rows_local; P.back_rows = rows_peer; @@ -3122,6 +3233,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri copy_i32(P.src, P.host_src, rows_peer, ps); } const size_t n = order_peer.size(); + if (P.sums) { + copy_f32_wide(P.wk, P.host_w, T * K, ps); + copy_i32(P.pair, P.host_pair, rows_peer, ps); + cudaMemsetAsync(P.sum, 0, (size_t) T * N * 4, ps); + } if (P.compact) { // groups of up to MMQ_GROUP experts and at most G rows, each computed from its own rows P.groups.clear(); @@ -3150,6 +3266,41 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri std::memcpy(P.host_bounds, P.bounds_host.data(), P.bounds_host.size() * 4); copy_i32(P.bounds, P.host_bounds, (int64_t) P.bounds_host.size(), ps); } + if (P.sums && P.gather) { // each group's tokens, their row lists in the experts' order + P.adds_at.resize(ng); + P.ntok.resize(ng); + size_t at = 0; + for (size_t g2 = 0; g2 < ng; ++g2) { + const int32_t r0 = P.bounds_host[P.groups[g2].first], r1 = P.bounds_host[P.groups[g2].second]; + P.touched.clear(); + for (int32_t r = r0; r < r1; ++r) { + const int32_t t = P.host_pair[r] / (int32_t) K; + if (P.tcur[(size_t) t]++ == 0) P.touched.push_back(t); + } + const size_t nt = P.touched.size(); + int32_t* a = P.host_adds + at; // [tokens nt | starts nt + 1 | rows] + a[nt] = 0; + for (size_t i = 0; i < nt; ++i) { + const int32_t t = P.touched[i]; + a[i] = t; + a[nt + 1 + i] = a[nt + i] + P.tcur[(size_t) t]; + P.tcur[(size_t) t] = a[nt + i]; // the fill cursor + } + int32_t* list = a + 2 * nt + 1; + for (int32_t r = r0; r < r1; ++r) + list[P.tcur[(size_t) (P.host_pair[r] / (int32_t) K)]++] = r; + for (int32_t t : P.touched) P.tcur[(size_t) t] = 0; + P.adds_at[g2] = at; + P.ntok[g2] = (int32_t) nt; + at += 2 * nt + 1 + (size_t) (r1 - r0); + } + if (at > P.adds_cap) { + err = "prefill: the peer's group tables overflow"; + cudaSetDevice(prevd); + return false; + } + copy_i32(P.adds, P.host_adds, (int64_t) at, ps); + } pe.mark(kPeMoeGemm, ps); const auto& f = lay.fmt[(size_t) l]; for (size_t g2 = 0; g2 < ng; ++g2) { @@ -3208,6 +3359,18 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri dn.ids = P.ident; dn.total_rows = nr; dn.max_rows = maxr; dn.dst = P.Dm_b[b]; dn.ld_dst = N; P.run_ctx->run(dn, ps); + if (P.sums && P.gather) { // into the per-token sums, one launch for the group + const int32_t* a = P.adds + P.adds_at[g2]; + const int64_t nt = P.ntok[g2]; + peer_gather_add(P.sum, P.Dm_b[b], r0, P.wk, P.pair, a, a + nt, a + 2 * nt + 1, nt, ps); + continue; + } + if (P.sums) { // into the per-token sums on this stream: Dm_b[b] is free after it + for (size_t j = j0; j < j1; ++j) + peer_scatter_add(P.sum, P.Dm_b[b] + (size_t) (P.bounds_host[j] - r0) * N, P.wk, + P.pair + P.bounds_host[j], P.bounds_host[j + 1] - P.bounds_host[j], ps); + continue; + } cudaEventRecord(P.ev_grp[g2 % PeerPrefill::kGrpEv], ps); cudaStreamWaitEvent(P.s_out, P.ev_grp[g2 % PeerPrefill::kGrpEv], 0); if (P.p2p) @@ -3276,7 +3439,16 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } } pe.mark(kPeMoeOut, ps); - if (P.out_pipe) { + if (P.sums) { // the sums go back: T x N + if (P.f16) { + sums_to_f16(P.sum, P.sum16, T * N, ps); + cudaMemcpyAsync(P.host_sum16, P.sum16, (size_t) T * N * 2, cudaMemcpyDeviceToHost, ps); + } else { + cudaMemcpyAsync(P.host_sum, P.sum, (size_t) T * N * 4, cudaMemcpyDeviceToHost, ps); + } + cudaEventRecord(P.ev_done, ps); + P.out_pending = true; + } else if (P.out_pipe) { cudaEventRecord(P.ev_done, P.s_out); P.out_pending = true; } else { @@ -3548,10 +3720,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } if (peer_now) { // multi-GPU: the peer's rows are in Dm (or, without P2P, in host memory) cudaStreamWaitEvent(m.cs, m.pp->ev_done, 0); - if (!m.pp->p2p) + if (!m.pp->p2p && !m.pp->sums) copy_f32_wide(m.Dm + (size_t) m.pp->back_at * N, m.pp->host_rows, m.pp->back_rows * N, m.cs); } - moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs); + if (peer_now && m.pp->sums && m.pp->f16) + moe_combine_peer16(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.pp->host_sum16, m.pp->back_at, m.bo, T, m.cs); + else if (peer_now && m.pp->sums) + moe_combine_peer(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.pp->host_sum, m.pp->back_at, m.bo, T, m.cs); + else + moe_combine(m.Dm, m.slot_dev, m.w, m.shared, m.sg, m.bo, T, m.cs); // debug: STRATA_DBG_NAN=1 reports the first layer of a chunk whose MoE produced non-finite values if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) { cudaStreamSynchronize(m.cs); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 4a5461a6..8c14a550 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -3176,6 +3176,12 @@ int main(int argc, char** argv) { // - an expert no cache holds costs ~190 ms per unit of routed mass: the CPU pool in decode and the PCIe stream // in prompts (fitted: the sweep's best K, 26-28, is where one more layer on the faster card stops paying // for the ~0.1% of the mass it pushes out of its cache); + // SCALED PER STAGE BY ITS PROBED LINK against the 20 GB/s x16 reference (pcie_frac_for_gbps' rule): the + // prompt path fetches a missed expert over ITS stage's link, so a stage on a narrow link pays + // proportionally more per missed unit. Without this the search is blind to asymmetric cards: + // 2026-10-04, 2x 4090 D with CUDA1 on a physical x1 link (1.6 GB/s), auto chose K=22 and read prompts + // at ~350 tok/s; with the scale (x12 on CUDA1) it chooses the fit-in-cache boundary K=38: ~1400 tok/s. + // With every scale 1.0 the objective is the formula the 190 ms was fitted with (unchanged). // - which experts a cache holds: its layers' profiled pairs, hottest first, until its free VRAM (less the // reserve, the prompt path's buffers and, on a later GPU, 1 GiB for its windows and the drafter) is used; // the routed mass a cache holds follows the COVERAGE CURVE below, not the (r+1)^-1.2 this used to use. @@ -3296,6 +3302,20 @@ int main(int argc, char** argv) { "%.2f GiB free before its session carve\n", dev, sms, khz / 1e6, layer_ms[(size_t) i], (double) cap[(size_t) i] / 1073741824.0); } + // The per-stage link, measured here (the stage-setup probes are skipped when --pcie-frac is given, and the + // search needs the reading either way). + std::vector link_scale((size_t) ns, 1.0); + for (int i = 0; i < ns; ++i) { + const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; + const strata::core::OnDevice on(dev); + std::string bursts; + const double bw = native_pack ? probe_pcie_h2d_gbps(&bursts) : -1.0; + // Never below 1.0: a link at or above the 20 GB/s reference keeps the fitted cost exactly (a x16 + // gen4/5 reads 26-28 and must not credit misses below the formula the sweep's K was fitted with). + if (bw > 0.0) link_scale[(size_t) i] = std::clamp(20.0 / bw, 1.0, 64.0); + std::fprintf(stderr, "strata generate: layer split auto: CUDA%d link %.1f GB/s -> miss cost x%.2f\n", + dev, bw, link_scale[(size_t) i]); + } const double miss_ms = std::getenv("STRATA_SPLIT_MISS_MS") ? std::atof(std::getenv("STRATA_SPLIT_MISS_MS")) : 190.0; // ---- THE COVERAGE CURVE: HOW MUCH ROUTED MASS A CACHE HOLDS, AND WHY IT IS NO LONGER A POWER LAW. // @@ -3362,20 +3382,27 @@ int main(int argc, char** argv) { std::fill(held_cnt.begin(), held_cnt.end(), 0); held_mass = 0; held = 0; + std::vector mass_i((size_t) ns, 0.0), held_i((size_t) ns, 0.0); std::vector full((size_t) ns, false); for (size_t r = 0; r < profile.size(); ++r) { const int64_t l = profile[r].first; int st = 0; while (st + 1 < ns && l >= at[(size_t) st]) ++st; + mass_i[(size_t) st] += mass[r]; if (full[(size_t) st]) continue; if (used[(size_t) st] + cost(l) > capr[(size_t) st]) { full[(size_t) st] = true; continue; } // as the fill used[(size_t) st] += cost(l); held_mass += mass[r]; + held_i[(size_t) st] += mass[r]; ++held; ++held_cnt[(size_t) st]; } held_mass /= std::max(total_mass, 1e-9); - double ms = miss_ms * (1.0 - held_mass); + // Each stage's misses on its own link (link_scale; 1.0 everywhere = the fitted single-constant formula). + double ms = 0.0; + for (int i = 0; i < ns; ++i) + ms += miss_ms * link_scale[(size_t) i] * std::max(0.0, mass_i[(size_t) i] - held_i[(size_t) i]) / + std::max(total_mass, 1e-9); for (int i = 0; i < ns; ++i) { const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1], le = i + 1 < ns ? at[(size_t) i] : g.n_layers; ms += (double) (le - lb) * layer_ms[(size_t) i]; @@ -8006,7 +8033,8 @@ int main(int argc, char** argv) { o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token, xcache.segmented() ? 1 : 0, o.batch > 0 ? (" batch_slots=" + std::to_string(o.batch) + - " slot_cache=" + std::to_string(o.prompt_cache > 0 ? 1 : 0)).c_str() : ""); + " slot_cache=" + std::to_string(o.prompt_cache > 0 ? 1 : 0) + + " batch_groups=" + std::to_string(o.batch_groups)).c_str() : ""); } // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the @@ -10631,6 +10659,20 @@ int main(int argc, char** argv) { std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str()); return 1; } + // Diagnostics (as in generate): STRATA_DUMP_FIRST_LOGITS= writes the logits of each request's first + // window to ., so the prompt paths (a peer card's share, a split) can be compared by KL + if (first_window) { + static const char* fl = std::getenv("STRATA_DUMP_FIRST_LOGITS"); + static int fl_n = 0; + if (fl != nullptr) { + std::vector row((size_t) ver.vocab()); + const std::string path = std::string(fl) + "." + std::to_string(fl_n++); + std::FILE* f = ver.copy_logits(0, row.data()) ? std::fopen(path.c_str(), "wb") : nullptr; + if (f == nullptr || std::fwrite(row.data(), sizeof(float), row.size(), f) != row.size()) + std::fprintf(stderr, "strata serve: STRATA_DUMP_FIRST_LOGITS: cannot write %s\n", path.c_str()); + if (f) std::fclose(f); + } + } int a = 0; while (a < T - 1 && window[(size_t) a + 1] == outv[(size_t) a]) ++a; if (from_sfx) { ++sfx_windows; sfx_drafts += T - 1; sfx_ok += a; }