Skip to content

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++

Merge remote-tracking branch 'origin/main' into pruned-geometry-support

pete97ae3b24180d
diff --cc src/prefill/prefill.cpp
index 78b04c5f6,297b70aa8..a359a07b6
--- a/src/prefill/prefill.cpp
+++ b/src/prefill/prefill.cpp
@@@ -173,6 -351,79 +351,79 @@@ Prefill::~Prefill()
namespace {
constexpr int64_t GEMM_SCRATCH = 32ll << 20; // FP16 elements for the largest dequantized dense weight
constexpr size_t GEMM_WS = 32u << 20; // cuBLAS workspace
+
+ // THE ATTENTION HALF AND THE MoE HALF SHARE THEIR BUFFERS. A layer runs its attention (GDN or QSA), writes it back
+ // into the residual, and only then its MoE, so the three sets of scratch are never live at once: one region the size
+ // of the largest holds them all. That is ~260 KB of the ~680 KB a prompt token cost - which is what lets a chunk
+ // grow (every expert is streamed once per chunk, so a bigger chunk streams fewer bytes per token). The sizes are
+ // counted with the same `take` sequence `init` uses; a mismatch makes `init` fail with "do not fit", never overlap.
+ uint64_t gdn_set_bytes(size_t T) {
+ Alloc a; a.count_only = true; bool ok = true;
+ a.take<float>(T * C, ok); a.take<float>(T * ZV, ok); a.take<float>(T * 2 * HV, ok); a.take<float>(T * HV, ok);
+ a.take<float>(T * HV, ok); a.take<float>(T * C, ok); a.take<float>(T * ZV, ok); a.take<uint16_t>(T * ZV, ok);
+ return a.used;
+ }
+ uint64_t qsa_set_bytes(size_t T, int64_t cap, int64_t max_blocks, int64_t sel_batch, int64_t attn_batch,
+ const strata::kernels::QsaShapes& s) {
+ Alloc a; a.count_only = true; bool ok = true;
+ a.take<float>(T * 512, ok); a.take<float>(T * 512, ok); a.take<float>(T * 12288, ok); a.take<float>(T * ZV, ok);
+ a.take<float>(T * 128, ok); a.take<float>(T * 512, ok); a.take<float>(T * ZV, ok); a.take<uint16_t>(T * ZV, ok);
+ a.take<int32_t>(T * (size_t) cap, ok);
+ a.take<float>((size_t) sel_batch * (size_t) max_blocks, ok);
+ a.take<float>((size_t) attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(cap, s), ok);
+ return a.used;
+ }
+ // Step 2b: which layers' experts go through MMQ (both weight types covered; the Strata Q2_0 pack always - its blob
+ // is converted to GGUF Q2_0 blocks on the gather), whether any layer keeps the FP16 path (IQ1_M), and the largest
+ // gate/up and down matrices a group buffer slot holds. STRATA_PREFILL_MMQ=0: the FP16 path everywhere (the A/B).
+ constexpr int MMQ_GROUP = 16; // experts per MMQ launch (the gather is per expert, as blobs arrive)
+ // MMQ reads up to one 256-value tile past a matrix's last row when the row length is not a multiple of it (the down
+ // product: 640 values). Those bytes meet zero activations, which is harmless only if they decode to finite numbers -
+ // llama.cpp zero-pads after every tensor, and so does a group buffer: this many zeroed bytes follow its last expert.
+ constexpr size_t MMQ_TAIL = 4096;
+ struct MmqPlan {
+ bool any = false, fallback = true;
+ std::vector<char> layer; // per layer: MMQ
+ size_t gu_max = 0, d_max = 0;
+ };
+ const MmqPlan& mmq_plan() {
+ static const MmqPlan plan = [] {
+ MmqPlan p;
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ const char* env = std::getenv("STRATA_PREFILL_MMQ");
+ const bool on = mmq::built() && (env == nullptr || std::atoi(env) != 0);
+ const int64_t layers = lay.native ? (int64_t) lay.fmt.size() : lay.n_layers;
+ p.layer.assign((size_t) std::max<int64_t>(layers, 0), 0);
+ p.fallback = !on || layers <= 0;
+ for (int64_t l = 0; on && l < layers; ++l) {
+ const int gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42, dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
+ if (!mmq::supported(gt) || !mmq::supported(dt)) { p.fallback = true; continue; }
+ p.layer[(size_t) l] = 1;
+ p.any = true;
+ p.gu_max = std::max(p.gu_max, mmq::matrix_bytes(gt, 1280, N));
+ p.d_max = std::max(p.d_max, mmq::matrix_bytes(dt, N, 640));
+ }
+ return p;
+ }();
+ return plan;
+ }
-uint64_t moe_set_bytes(size_t T) {
++uint64_t moe_set_bytes(size_t T, int64_t n_expert) {
+ const MmqPlan& mp = mmq_plan();
+ Alloc a; a.count_only = true; bool ok = true;
- a.take<float>(T * NE, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
++ a.take<float>(T * n_expert, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
+ a.take<int32_t>(T * K, ok);
+ if (mp.fallback) a.take<uint16_t>(T * K * N, ok);
+ a.take<float>(T * K * 1280, ok);
+ if (mp.fallback) a.take<uint16_t>(T * K * 640, ok);
+ a.take<float>(T * K * N, ok); a.take<float>(T * 640, ok);
+ a.take<float>(T * 640, ok); a.take<uint16_t>(T * 640, ok); a.take<float>(T * N, ok); a.take<float>(T, ok);
+ if (mp.any) {
+ a.take<uint8_t>(mmq::q8_bytes((int64_t) (T * K), N), ok);
+ a.take<float>(T * K * 640, ok);
+ a.take<uint8_t>(mmq::q8_bytes((int64_t) (T * K), 640), ok);
+ }
+ return a.used;
+ }
}
bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, core::SessionState& ss,
@@@ -186,7 -437,43 +437,43 @@@
}
if (cudaStreamCreateWithFlags(&m.copy, cudaStreamNonBlocking) != cudaSuccess) { err = "prefill: copy stream"; return false; }
const size_t T = (size_t) chunk;
+ m.T_max = chunk;
+ m.borrowed = borrow != nullptr;
bool ok = true;
+ // one-time: events, the stager, the host buffers (for the largest chunk), the identity page table
+ for (int i = 0; i < RING_MAX; ++i) {
+ if (cudaEventCreateWithFlags(&m.copied[i], cudaEventDisableTiming) != cudaSuccess) ok = false;
+ if (cudaEventCreateWithFlags(&m.used[i], cudaEventDisableTiming) != cudaSuccess) ok = false;
+ }
+ if (!m.stager) {
+ m.stager = std::make_unique<Stager>();
+ const int hw = (int) std::thread::hardware_concurrency();
+ if (!m.stager->init((size_t) MAXBLOB(), std::max(2, std::min(4, hw / 4)))) ok = false;
+ }
+ m.steps_host.resize(T * strata::kernels::kStepCount);
- m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(NE); m.off.resize(NE + 1);
++ m.ids_host.resize(T * K); m.slot_host.resize(T * K); m.src_host.resize(T * K); m.cnt.resize(m.g->n_expert); m.off.resize(m.g->n_expert + 1);
+ for (int b = 0; b < 2; ++b) {
+ if (!m.ple_emb_host[b] &&
+ cudaHostAlloc((void**) &m.ple_emb_host[b], (size_t) T * N * 4, cudaHostAllocDefault) != cudaSuccess) {
+ cudaGetLastError();
+ m.ple_pageable[b].resize(T * N); // pageable: the upload is staged before it returns
+ m.ple_emb_host[b] = m.ple_pageable[b].data();
+ }
+ if (!m.ple_copied[b] && cudaEventCreateWithFlags(&m.ple_copied[b], cudaEventDisableTiming) != cudaSuccess)
+ ok = false;
+ m.ple_rows[b].resize(T * strata::kernels::PLE_N_HEADS);
+ }
+ if (ss.qsa_states[0].kv_mode == 1) { // KV streaming: the staging pool's identity page table
+ const int64_t pages = ss.qsa_states[0].n_pages;
+ std::vector<int32_t> ident((size_t) pages);
+ for (int64_t i = 0; i < pages; ++i) ident[(size_t) i] = (int32_t) i;
+ if (cudaMalloc((void**) &m.ident_table, ident.size() * 4) != cudaSuccess ||
+ cudaMemcpy(m.ident_table, ident.data(), ident.size() * 4, cudaMemcpyHostToDevice) != cudaSuccess)
+ ok = false;
+ else
+ m.owned.push_back(m.ident_table);
+ }
+ if (!ok) { err = "prefill: host buffers or events for a chunk of " + std::to_string(chunk) + " tokens"; return false; }
Alloc o;
o.base = (uint8_t*) borrow;
o.cap = borrow_bytes;
@@@ -214,22 -509,60 +509,60 @@@ bool Prefill::carve(size_t T, void* all
s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
s.idx_dim = g.idx_key_dim;
m.cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
- m.sel_ids = o.take<int32_t>(T * (size_t) m.cap, ok);
m.max_blocks = ss.qsa_states[0].max_cells / s.idx_block + 2;
- m.sel_scores = o.take<float>((size_t) m.sel_batch * (size_t) m.max_blocks, ok);
- m.attn_scratch = o.take<float>((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok);
- m.logits = o.take<float>(T * m.g->n_expert, ok); m.w = o.take<float>(T * K, ok); m.ids = o.take<int32_t>(T * K, ok);
- m.slot_dev = o.take<int32_t>(T * K, ok); m.src_dev = o.take<int32_t>(T * K, ok);
- m.Xs = o.take<uint16_t>(T * K * N, ok); m.GU = o.take<float>(T * K * 1280, ok);
- m.Hh = o.take<uint16_t>(T * K * 640, ok); m.Dm = o.take<float>(T * K * N, ok);
- m.sgate = o.take<float>(T * 640, ok); m.sup = o.take<float>(T * 640, ok); m.sh_h = o.take<uint16_t>(T * 640, ok);
- m.shared = o.take<float>(T * N, ok); m.sg = o.take<float>(T, ok);
+ {
+ // one region for the attention half's and the MoE half's scratch (see gdn_set_bytes)
+ const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch,
- m.attn_batch, s), moe_set_bytes(T)});
++ m.attn_batch, s), moe_set_bytes(T, m.g->n_expert)});
+ uint8_t* base = o.take<uint8_t>((size_t) region, ok);
+ m.region = base;
+ m.region_bytes = region;
+ Alloc a;
+ a.base = base; a.cap = region; a.owned = &m.owned;
+ m.qkv = a.take<float>(T * C, ok); m.z = a.take<float>(T * ZV, ok); m.ab = a.take<float>(T * 2 * HV, ok);
+ m.gate = a.take<float>(T * HV, ok); m.beta = a.take<float>(T * HV, ok); m.hbuf = a.take<float>(T * C, ok);
+ m.y = a.take<float>(T * ZV, ok); m.y_h = a.take<uint16_t>(T * ZV, ok);
+ Alloc b;
+ b.base = base; b.cap = region; b.owned = &m.owned;
+ m.Kc = b.take<float>(T * 512, ok); m.Vc = b.take<float>(T * 512, ok); m.Qf = b.take<float>(T * 12288, ok);
+ m.q = b.take<float>(T * ZV, ok); m.idx_raw = b.take<float>(T * 128, ok); m.q_idx = b.take<float>(T * 512, ok);
+ m.attn = b.take<float>(T * ZV, ok); m.attn_h = b.take<uint16_t>(T * ZV, ok);
+ m.sel_ids = b.take<int32_t>(T * (size_t) m.cap, ok);
+ m.sel_scores = b.take<float>((size_t) m.sel_batch * (size_t) m.max_blocks, ok);
+ m.attn_scratch = b.take<float>((size_t) m.attn_batch * strata::kernels::qsa_decode_attn_scratch_floats(m.cap, s), ok);
+ Alloc c;
+ c.base = base; c.cap = region; c.owned = &m.owned;
- m.logits = c.take<float>(T * NE, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
++ m.logits = c.take<float>(T * m.g->n_expert, ok); m.w = c.take<float>(T * K, ok); m.ids = c.take<int32_t>(T * K, ok);
+ m.slot_dev = c.take<int32_t>(T * K, ok); m.src_dev = c.take<int32_t>(T * K, ok);
+ const MmqPlan& mp = mmq_plan();
+ m.Xs = mp.fallback ? c.take<uint16_t>(T * K * N, ok) : nullptr;
+ m.GU = c.take<float>(T * K * 1280, ok);
+ m.Hh = mp.fallback ? c.take<uint16_t>(T * K * 640, ok) : nullptr;
+ m.Dm = c.take<float>(T * K * N, ok);
+ m.sgate = c.take<float>(T * 640, ok); m.sup = c.take<float>(T * 640, ok); m.sh_h = c.take<uint16_t>(T * 640, ok);
+ m.shared = c.take<float>(T * N, ok); m.sg = c.take<float>(T, ok);
+ if (mp.any) {
+ m.Xq = c.take<uint8_t>(mmq::q8_bytes((int64_t) (T * K), N), ok);
+ m.H = c.take<float>(T * K * 640, ok);
+ m.Hq = c.take<uint8_t>(mmq::q8_bytes((int64_t) (T * K), 640), ok);
+ }
+ if (base == nullptr) ok = false;
+ }
for (int i = 0; i < DQ; ++i) { m.dq_gu[i] = o.take<uint16_t>(1280 * 2560, ok); m.dq_d[i] = o.take<uint16_t>(2560 * 640, ok); }
- for (int i = 0; i < STAGE; ++i) {
+ if (mmq_plan().any) {
+ const MmqPlan& mp = mmq_plan();
+ m.ids_identity = o.take<int32_t>(T * K, ok);
- m.bounds_dev = o.take<int32_t>((size_t) (2 * (NE + NE / MMQ_GROUP + 2)), ok);
++ m.bounds_dev = o.take<int32_t>((size_t) (2 * (m.g->n_expert + m.g->n_expert / MMQ_GROUP + 2)), ok);
+ m.grp_gu = o.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok);
+ m.grp_d = o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok);
+ // (written at every run's start, not here: when serving, these are live expert-cache slots until a request
+ // lends them - a write now would corrupt a resident expert)
+ if (!m.mmq_ctx) m.mmq_ctx = std::make_unique<mmq::Context>();
+ }
+ m.ring = ring_slots(T);
+ for (int i = 0; i < m.ring; ++i) {
m.stage_dev[i] = o.take<uint8_t>((size_t) MAXBLOB(), ok);
- if (cudaHostAlloc((void**) &m.stage_host[i], (size_t) MAXBLOB(), cudaHostAllocDefault) != cudaSuccess) ok = false;
- if (cudaEventCreateWithFlags(&m.copied[i], cudaEventDisableTiming) != cudaSuccess) ok = false;
- if (cudaEventCreateWithFlags(&m.used[i], cudaEventDisableTiming) != cudaSuccess) ok = false;
+ m.stage_live[i] = false; // a new buffer: nothing of an earlier layout to wait for
}
m.ple_emb = o.take<float>(T * N, ok);
m.ple_norm = o.take<float>((size_t) strata::kernels::NG_HC_DIM, ok);
@@@ -261,20 -611,23 +611,23 @@@ uint64_t Prefill::bytes_needed(const co
auto f = [&](size_t n) { o.take<float>(n, ok); };
f(T * N); f(T * D); f(T * D); o.take<uint16_t>(T * D, ok); f(T * LR); o.take<uint16_t>(T * LR, ok);
f(T * D); f(T * HC); f(T * N); o.take<uint16_t>(T * N, ok); o.take<uint16_t>(T * N, ok); f(T * N);
- f(T * C); f(T * ZV); f(T * 2 * HV); f(T * HV); f(T * HV); f(T * C); f(T * ZV); o.take<uint16_t>(T * ZV, ok);
- f(T * 512); f(T * 512); f(T * 12288); f(T * ZV); f(T * 128); f(T * 512); f(T * ZV); o.take<uint16_t>(T * ZV, ok);
o.take<int32_t>(T * strata::kernels::kStepCount, ok);
strata::kernels::QsaShapes s = strata::kernels::qsa_real_shapes();
+ s.n_head = g.n_head; s.n_head_kv = g.n_head_kv; s.head_dim = g.head_dim; s.idx_n_head = g.idx_q_heads;
+ s.idx_dim = g.idx_key_dim;
const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
- o.take<int32_t>(T * (size_t) cap, ok);
const int64_t max_blocks = ss.qsa_states[0].max_cells / s.idx_block + 2;
- f(256 * (size_t) max_blocks);
- f(32 * strata::kernels::qsa_decode_attn_scratch_floats(cap, s));
- f(T * g.n_expert); f(T * K); o.take<int32_t>(T * K, ok); o.take<int32_t>(T * K, ok); o.take<int32_t>(T * K, ok);
- o.take<uint16_t>(T * K * N, ok); f(T * K * 1280); o.take<uint16_t>(T * K * 640, ok); f(T * K * N);
- f(T * 640); f(T * 640); o.take<uint16_t>(T * 640, ok); f(T * N); f(T);
+ o.take<uint8_t>((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s),
- moe_set_bytes(T)}), ok);
++ moe_set_bytes(T, g.n_expert)}), ok);
for (int i = 0; i < DQ; ++i) { o.take<uint16_t>(1280 * 2560, ok); o.take<uint16_t>(2560 * 640, ok); }
- for (int i = 0; i < STAGE; ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);
+ if (mmq_plan().any) {
+ const MmqPlan& mp = mmq_plan();
+ o.take<int32_t>(T * K, ok);
- o.take<int32_t>((size_t) (2 * (NE + NE / MMQ_GROUP + 2)), ok);
++ o.take<int32_t>((size_t) (2 * (g.n_expert + g.n_expert / MMQ_GROUP + 2)), ok);
+ o.take<uint8_t>(MMQ_GROUP * mp.gu_max + MMQ_TAIL, ok);
+ o.take<uint8_t>(MMQ_GROUP * mp.d_max + MMQ_TAIL, ok);
+ }
+ for (int i = 0; i < ring_slots(T); ++i) o.take<uint8_t>((size_t) MAXBLOB(), ok);
f(T * N);
f((size_t) strata::kernels::NG_HC_DIM);
strata::kernels::KvHostPools stage;
@@@ -356,10 -795,105 +795,105 @@@ bool Prefill::run(const int64_t* tokens
cudaMemcpyHostToDevice, m.cs);
int64_t qsa_index = 0, gdn_index = 0;
+ // step 3: this chunk's stream - every non-resident expert of every layer, layer by layer in id order (entry
+ // k lands in ring slot k % ring); a copy is issued once the entry `ring` before it is consumed (its slot's
+ // `used` event recorded), so the copy stream never waits on an event that is not queued yet
+ const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout();
+ const bool stream_all = m.ring > STAGE && T >= STREAM_ALL_MIN && m.src != nullptr;
+ struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; };
+ std::vector<StreamEntry> seq;
+ std::vector<size_t> seq_start;
+ size_t issued = 0, consumed = 0;
+ if (stream_all) {
+ seq_start.resize((size_t) g.n_layers + 1);
+ std::vector<Stager::Job> js;
+ for (int64_t l = 0; l < g.n_layers; ++l) {
+ seq_start[(size_t) l] = seq.size();
- for (int32_t e = 0; e < NE; ++e) {
- if (m.host_res && m.cache && m.host_res[(size_t) l * NE + e] >= 0) continue;
++ for (int32_t e = 0; e < m.g->n_expert; ++e) {
++ if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
+ const uint8_t* b = m.src->blob(l, e);
+ if (!b) { err = "prefill: expert source has no blob"; return false; }
+ int job = -1;
+ if (!m.src->pinned(l, e)) {
+ job = (int) js.size();
+ js.push_back({b, (size_t) lay0.blob_bytes(l)});
+ }
+ seq.push_back({(int32_t) l, e, b, job});
+ }
+ }
+ seq_start[(size_t) g.n_layers] = seq.size();
+ m.stager->start(std::move(js));
+ }
+ struct StagerDone {
+ Stager* st;
+ ~StagerDone() { if (st) st->finish(); }
+ } chunk_stager_done{stream_all ? m.stager.get() : nullptr};
+ auto issue_until = [&](size_t limit) {
+ limit = std::min(limit, seq.size());
+ while (issued < limit) {
+ const StreamEntry& en = seq[issued];
+ const int sl = (int) (issued % (size_t) m.ring);
+ const auto th = Clock::now();
+ const size_t bytes = (size_t) lay0.blob_bytes(en.l);
+ if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
+ if (en.job < 0) {
+ cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy);
+ ++stats_.experts_dma;
+ } else {
+ const uint8_t* hb = m.stager->wait(en.job);
+ cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy);
+ m.stager->issued_one(en.job, m.copy);
+ }
+ cudaEventRecord(m.copied[sl], m.copy);
+ m.stage_live[sl] = true;
+ stats_.ms_experts_host += ms_since(th);
+ ++stats_.experts_streamed;
+ ++issued;
+ }
+ };
+ if (stream_all) issue_until((size_t) m.ring); // layer 0's first experts, behind the embedding and the PLE
for (int64_t l = 0; l < g.n_layers; ++l) {
+ core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still moving
const core::LayerView v(*m.wt, l);
// ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows)
- if (l == 1 && ple_on) {
+ if (l == 1 && ple_on && ple_batch) {
+ // the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value
+ // projections as GEMMs (a token at a time they re-read ~52 MB of BF16 key per token on the IQ
+ // files), the rest with the per-token kernels' arithmetic (native_ple_postops_batch)
+ pt.mark(kPfPle, cs);
+ const auto tp = Clock::now();
+ const strata::kernels::PleWeights& pw = ss.ple.w;
+ constexpr int64_t HD = strata::kernels::NG_HC_DIM;
+ const uint64_t per_token = (uint64_t) (3 * HD + N + 4) * 4 + (uint64_t) N * 2 + 4096;
+ const int64_t SB = std::min<int64_t>(T, (int64_t) (m.region_bytes / per_token));
+ for (int64_t s0 = 0; s0 < T; s0 += SB) {
+ const int64_t nb = std::min(SB, T - s0);
+ uint8_t* q = m.region;
+ auto carve_f = [&](size_t n) { float* p = (float*) q; q += (n * 4 + 255) & ~(size_t) 255; return p; };
+ float* key = carve_f((size_t) nb * HD);
+ float* qn = carve_f((size_t) nb * HD);
+ float* gated = carve_f((size_t) nb * HD);
+ float* val = carve_f((size_t) nb * N);
+ float* gate = carve_f((size_t) nb * 4);
+ uint16_t* e16 = (uint16_t*) carve_f((size_t) nb * N / 2);
+ const float* emb = m.ple_emb + s0 * N;
+ if (pw.key_bf16 != nullptr) {
+ to_bf16(emb, e16, nb * N, m.cs);
+ m.gemm.bf16(e16, pw.key_bf16, key, nb, HD, N);
+ } else {
+ to_f16(emb, e16, nb * N, m.cs);
+ m.gemm.native(e16, pw.key_native_type, pw.key_native_data, key, nb, HD, N);
+ to_bf16(emb, e16, nb * N, m.cs);
+ }
+ m.gemm.bf16(e16, pw.value_bf16, val, nb, N, N);
+ try {
+ strata::kernels::native_ple_postops_batch(key, m.R + s0 * D, val, ss.ple.hist, pw, qn, gated,
+ gate, (int) nb, m.cs);
+ } catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; }
+ }
+ stats_.ms_ple += ms_since(tp);
+ } else if (l == 1 && ple_on) {
+ pt.mark(kPfPle, cs);
const auto tp = Clock::now();
for (int64_t t = 0; t < T; ++t) {
strata::kernels::PleOut po;
@@@ -552,8 -1093,9 +1093,9 @@@
*wsu = need(v, "ffn_up_shexp.weight", err),
*wsd = need(v, "ffn_down_shexp.weight", err);
if (!wr || !wgi || !wsg || !wsu || !wsd) return false;
+ pt.mark(kPfRouter, cs);
if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err)) return false;
- route(m.logits, m.ids, m.w, T, m.cs);
+ route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs);
// the shared expert and its scalar gate
if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false;
if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false;
@@@ -581,17 -1125,56 +1125,56 @@@
}
cudaMemcpyAsync(m.slot_dev, m.slot_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);
cudaMemcpyAsync(m.src_dev, m.src_host.data(), (size_t) T * K * 4, cudaMemcpyHostToDevice, m.cs);
- gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);
// the experts, in id order: resident ones from VRAM, the others through the staging ring
std::vector<int32_t> order;
- for (int32_t e = 0; e < NE; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e);
+ for (int32_t e = 0; e < m.g->n_expert; ++e) if (m.cnt[(size_t) e] > 0) order.push_back(e);
const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
+ const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l];
+ const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42;
+ const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42;
+ const size_t mmq_gub = use_mmq ? mmq::matrix_bytes(mmq_gt, 1280, N) : 0;
+ const size_t mmq_db = use_mmq ? mmq::matrix_bytes(mmq_dt, N, 640) : 0;
+ pt.mark(kPfGather, cs);
+ if (use_mmq) {
+ // step 2b: the layer's activations as q8_1 rows in expert order, straight from `mixed`
+ mmq::quantize(m.mixed, m.src_dev, m.Xq, mmq_gt, N, N, T * K, m.cs);
+ // each group's rows: absolute bounds (gate/up reads the layer's rows), relative ones (down
+ // reads the group's own quantized H)
+ const size_t n = order.size(), ng = (n + MMQ_GROUP - 1) / MMQ_GROUP;
+ m.bounds_host.resize(n + 1 + ng * (MMQ_GROUP + 1));
+ for (size_t j = 0; j < n; ++j) m.bounds_host[j] = m.off[(size_t) order[j]];
+ m.bounds_host[n] = (int32_t) (T * K);
+ for (size_t g = 0; g < ng; ++g)
+ for (size_t i = 0; i <= MMQ_GROUP; ++i)
+ m.bounds_host[n + 1 + g * (MMQ_GROUP + 1) + i] =
+ m.bounds_host[std::min(n, g * MMQ_GROUP + i)] - m.bounds_host[g * MMQ_GROUP];
+ cudaMemcpyAsync(m.bounds_dev, m.bounds_host.data(), m.bounds_host.size() * 4,
+ cudaMemcpyHostToDevice, m.cs);
+ } else {
+ gather_rows16(m.mixed_h, m.src_dev, m.Xs, T * K, N, m.cs);
+ }
// Stage ahead: the copy stream moves blobs host -> device while the compute stream works.
int stage_next = 0;
std::vector<int> stage_of(order.size(), -1);
+ // the unpinned ones are copied to pinned buffers by the stager's threads, in this order
+ std::vector<int> job_of(order.size(), -1);
+ if (!stream_all) {
+ std::vector<Stager::Job> js;
+ for (size_t j = 0; j < order.size(); ++j) {
+ const int32_t e = order[j];
- if (m.host_res && m.cache && m.host_res[(size_t) l * NE + e] >= 0) continue;
++ if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
+ if (m.src->pinned(l, e)) continue;
+ const uint8_t* b = m.src->blob(l, e);
+ if (!b) { err = "prefill: expert source has no blob"; return false; }
+ job_of[j] = (int) js.size();
+ js.push_back({b, (size_t) lay.blob_bytes(l)});
+ }
+ m.stager->start(std::move(js));
+ }
+ StagerDone stager_done{stream_all ? nullptr : m.stager.get()};
auto stage_one = [&](size_t j) -> bool {
const int32_t e = order[j];
- const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * NE + e] >= 0;
+ const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
if (resident) return true;
const int sl = stage_next;
stage_next = (stage_next + 1) % STAGE;
@@@ -641,13 -1253,85 +1253,85 @@@
} else {
blob_dequant_f16(blob_dev, m.dq_gu[q], m.dq_d[q], m.cs);
}
- if (stage_of[j] >= 0) cudaEventRecord(m.used[stage_of[j]], m.cs);
+ if (slot >= 0) cudaEventRecord(m.used[slot], m.cs);
const int64_t o0 = m.off[(size_t) e], ne = m.cnt[(size_t) e];
+ pt.mark(kPfGemmGU, cs);
m.gemm.f16(m.Xs + o0 * N, m.dq_gu[q], m.GU + o0 * 1280, ne, 1280, N);
swiglu_interleaved(m.GU + o0 * 1280, m.Hh + o0 * 640, ne, m.cs);
+ pt.mark(kPfGemmD, cs);
m.gemm.f16(m.Hh + o0 * 640, m.dq_d[q], m.Dm + o0 * N, ne, N, 640);
+ return true;
+ };
+ if (!stream_all) {
+ size_t staged = 0;
+ const size_t lookahead = STAGE - 1;
+ for (size_t j = 0; j < order.size(); ++j) {
+ while (staged < order.size() && staged <= j + lookahead) {
+ if (!stage_one(staged)) return false;
+ ++staged;
+ }
+ const int32_t e = order[j];
+ if (stage_of[j] < 0) {
+ ++stats_.experts_resident;
- if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * NE + e]), -1)) return false;
++ if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
+ } else {
+ pt.mark(kPfWaitCopy, cs);
+ cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0);
+ if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false;
+ }
+ }
+ } else {
+ // the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not
+ // pick only gives its slot back
+ size_t k = seq_start[(size_t) l];
+ const size_t kend = seq_start[(size_t) l + 1];
+ auto release_to = [&](int32_t e_stop) {
+ while (k < kend && seq[k].e < e_stop) {
+ cudaEventRecord(m.used[k % (size_t) m.ring], m.cs);
+ consumed = ++k;
+ issue_until(consumed + (size_t) m.ring);
+ }
+ };
+ for (size_t j = 0; j < order.size(); ++j) {
+ const int32_t e = order[j];
+ release_to(e);
+ if (k < kend && seq[k].e == e) {
+ const int sl = (int) (k % (size_t) m.ring);
+ pt.mark(kPfWaitCopy, cs);
+ cudaStreamWaitEvent(m.cs, m.copied[sl], 0);
+ if (!compute(j, m.stage_dev[sl], sl)) return false;
+ consumed = ++k;
+ issue_until(consumed + (size_t) m.ring);
+ } else {
+ ++stats_.experts_resident;
- if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * NE + e]), -1)) return false;
++ if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
+ }
+ }
- release_to(NE);
++ release_to(m.g->n_expert);
}
+ pt.mark(kPfCombine, cs);
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);
+ auto bad = [&](const float* d, int64_t n) {
+ std::vector<float> h((size_t) n);
+ cudaMemcpy(h.data(), d, (size_t) n * 4, cudaMemcpyDeviceToHost);
+ int64_t c = 0;
+ for (float v : h) c += !std::isfinite(v);
+ return c;
+ };
+ const int64_t bgu = bad(m.GU, T * K * 1280), bdm = bad(m.Dm, T * K * N), bbo = bad(m.bo, T * N);
+ const int64_t bh = m.H ? bad(m.H, T * K * 640) : -1;
+ static int64_t reported = -1;
+ if ((bgu || bdm || bbo || bh > 0) && reported != stats_.chunks) {
+ reported = stats_.chunks;
+ std::fprintf(stderr, "strata dbg: layer %lld (mmq %d, types %d/%d, %zu experts): non-finite GU %lld "
+ "H %lld Dm %lld bo %lld of T %lld\n", (long long) l, (int) use_mmq, mmq_gt, mmq_dt,
+ order.size(), (long long) bgu, (long long) bh, (long long) bdm, (long long) bbo,
+ (long long) T);
+ }
+ }
}
// ---- the hyper-connection write of this half
gr_write(m.R, m.bo, m.inj, HC, T, m.cs);
diff --cc src/program/generate.cpp
index f218d080a,b699ee193..88ad4a33a
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@@ -2111,11 -2208,69 +2224,70 @@@ int main(int argc, char** argv)
// from the live session or the longest conversation checkpoint its prompt starts with (see ConvCheckpoint),
// otherwise from an empty sequence (`session_zero`); the rest of the prompt goes through the batched prompt path
// and its last token through the first verify window - the path all three model files share. Decoding is greedy.
+ // The expert-cache slots (from the end of the cache) that hold the prompt path's buffers for a chunk, and the
+ // bytes from the first of them to the end.
+ // the share of expert bytes the arena could pin (sizes the prompt path's streamed ring and its lend cap)
+ if (srcp != nullptr && o.prefill_chunk > 0) {
+ uint64_t pinned = 0, total = 0;
+ const auto& lay = strata::kernels::cpu::expert_layout();
+ for (int64_t l = 0; l < g.n_layers; ++l)
+ for (int64_t e = 0; e < g.n_expert; ++e) {
+ const uint64_t b = lay.blob_bytes(l);
+ total += b;
+ if (srcp->pinned(l, e)) pinned += b;
+ }
+ strata::prefill::Prefill::set_pinned_share(total ? (double) pinned / (double) total : 1.0);
+ }
+ auto lend_slots = [&](int64_t c) -> int64_t {
+ const uint64_t need = strata::prefill::Prefill::bytes_needed(g, ss, c);
+ const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob;
+ int64_t k = (int64_t) ((need + (uint64_t) blob - 1) / (uint64_t) blob);
+ if (xcache.slot_offsets() != nullptr) { // sized slots: take slots from the end until they hold `need`
+ k = 0;
+ while (k < xcache.slots() &&
+ (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[xcache.slots() - k]) < need) ++k;
+ }
+ return k;
+ };
+ auto lend_bytes = [&](int32_t first) -> uint64_t {
+ return xcache.slot_offsets() ? (uint64_t) (xcache.bytes() - (int64_t) xcache.slot_offsets()[first])
+ : (uint64_t) (xcache.slots() - first) *
+ (uint64_t) strata::kernels::cpu::expert_layout().max_blob;
+ };
+ // The prompt path's chunk and the slots it borrows for its buffers: the requested chunk halved until it fits,
+ // or with --prefill auto the largest of kAutoChunks whose buffers take at most kAutoLendPct % of the slots (a
+ // lent slot's expert is streamed during the prompt and refilled after it; measured on a 12 GB card, 32K Q2_0
+ // prompt: 4096 791 tok/s, 6144 878, 8192 973 with 69% of the slots lent). A request lends only what its own
+ // prompt needs (Prefill::relayout), so a big chunk costs short prompts nothing. 0 = none fits.
+ auto plan_lend = [&](int64_t& chunk) -> int64_t {
+ static constexpr int64_t kAutoChunks[] = {8192, 6144, 4096, 3072, 2048, 1024, 512, 256};
+ // at 8192-token chunks nearly every expert streams anyway, so a lent slot costs little: 90% when the
+ // copies are DMA from pinned RAM (Q2_0 8192 + a 384-slot ring: 1283 tok/s), 85% when host copies are the
+ // limit (lending more only streams more through them). STRATA_PREFILL_LEND_PCT overrides (tuning).
+ const int64_t kAutoLendPct = [] {
+ const char* v = std::getenv("STRATA_PREFILL_LEND_PCT");
+ return v ? (int64_t) std::atoi(v)
+ : (int64_t) (strata::prefill::Prefill::pinned_share() >= 0.9 ? 90 : 85);
+ }();
+ auto slots_for = lend_slots;
+ if (o.prefill_auto) {
+ for (const int64_t c : kAutoChunks) {
+ const int64_t k = slots_for(c);
+ if (k + 128 <= xcache.slots() && k * 100 <= kAutoLendPct * xcache.slots()) { chunk = c; return k; }
+ }
+ return 0;
+ }
+ for (int64_t c = chunk; c >= 256; c /= 2) {
+ const int64_t k = slots_for(c);
+ if (k + 128 <= xcache.slots()) { chunk = c; return k; }
+ }
+ return 0;
+ };
if (o.serve) {
- if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 || thits.d_res == nullptr || host_res.empty()) {
- std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR, --prefill CHUNK, --expert-profile P and "
- "--expert-cache\n");
+ if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 ||
+ (graph_hits && (thits.d_res == nullptr || host_res.empty()))) {
+ std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR and --prefill CHUNK (and a fillable "
+ "--expert-cache; the graphed hit path additionally needs --expert-profile P)\n");
return 2;
}
strata::prefill::Prefill sp;