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

decode: batch the verify window's per-token kernels (bit-identical); skip the PCIe path with --pcie-frac 0; decode timing/profile switches

Andy4a50d4ce8f44
diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp
index bf48b5b80..3d32fc15d 100644
--- a/include/strata/core/verify.hpp
+++ b/include/strata/core/verify.hpp
@@ -32,6 +32,7 @@
#include <cstdint>
#include <string>
+#include <vector>
namespace strata::core {
@@ -104,9 +105,14 @@ public:
/// arena directly, 2 = a copy kernel stages it inside the graph (no API calls on the pool's thread; best when
/// the CPU is RAM-bound, Q2_0). Set before the first `run`.
void set_pcie_mode(int mode) { sink_.pcie_mode = mode; }
+ /// the pool never plans a PCIe share (--pcie-frac 0): the window skips that path. Before the first run.
+ void set_pcie_off(bool off) { pcie_off_ = off; }
double ms_wait = 0, ms_pool = 0, ms_host = 0, ms_commit = 0;
int64_t windows = 0;
+ /// STRATA_VERIFY_PROFILE=1 - GPU stage times of the windows since the last call (ms per
+ /// window), as one line; empty when off.
+ std::string profile_report();
private:
bool capture(int T, std::string& err);
@@ -121,6 +127,12 @@ private:
bool head_sampling_ = true; ///< set_head_sampling
bool capture_commit(std::string& err);
bool record_window(int T, cudaStream_t cs, std::string& err);
+ static constexpr int kProfPer = 32; // stamps per layer
+ bool prof_on_ = false;
+ unsigned long long* prof_ = nullptr; // device: n_layers * kProfPer + 4 stamps
+ std::vector<unsigned long long> prof_h_;
+ double prof_sum_[2][kProfPer] = {}; // [GDN / QSA layers][stage]
+ int64_t prof_windows_ = 0;
const WeightTable* wt_ = nullptr;
const ModelGeometry* g_ = nullptr;
@@ -150,6 +162,7 @@ private:
uint32_t* h_flag_ = nullptr; uint32_t* m_flag_ = nullptr;
uint32_t* h_flagA_ = nullptr; uint32_t* m_flagA_ = nullptr; // the GPU plan is in place
uint32_t* h_flagB_ = nullptr; uint32_t* m_flagB_ = nullptr; // the PCIe share's DMA copies have landed
+ bool pcie_off_ = false; // no PCIe share (--pcie-frac 0)
cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts)
struct FlagSet { uint32_t* flag; uint32_t value; };
FlagSet flag_sets_[2 * 64 * 2] = {}; // host-function arguments, one per (layer, group)
diff --git a/include/strata/kernels/bf16_gemv.hpp b/include/strata/kernels/bf16_gemv.hpp
index 6f3619d98..906a8f0b1 100644
--- a/include/strata/kernels/bf16_gemv.hpp
+++ b/include/strata/kernels/bf16_gemv.hpp
@@ -44,5 +44,9 @@ void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_i
/// No allocations or synchronization, including when stream is null (the CUDA default stream).
void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
int64_t n_in, int64_t n_out, void* stream);
+/// bf16_gemv_fp32_mmvf for n_tok (1..8) activation rows x[t * ldx], outputs y[t * ldy + j]; one launch,
+/// the weight read once, every output bit-identical to its own single-row call.
+void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
+ int64_t n_in, int64_t n_out, int n_tok, void* stream);
} // namespace strata::kernels
diff --git a/include/strata/kernels/elementwise.hpp b/include/strata/kernels/elementwise.hpp
index 65b9022cb..0136176c4 100644
--- a/include/strata/kernels/elementwise.hpp
+++ b/include/strata/kernels/elementwise.hpp
@@ -102,6 +102,10 @@ void doorbell_wait(const uint32_t* d_flag, const uint32_t* d_seq, void* stream);
/// device memory with a kernel, so the handoff stays on the compute queue (a memcpy node is a copy-engine
/// operation, which WDDM submits separately and which measured 67 flushes per token).
void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream);
+/// `rows` rows of `width` floats from mapped memory, except the rows listed in hit_rows[0, *count) (device),
+/// which are written +0.0 instead (a verify window's GPU-computed entries: the pool leaves zeros there).
+void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows,
+ const int32_t* count, void* stream);
/// Plan v0.3 P3: the doorbell's payload and its ring in ONE kernel. Copies `x` (n floats), `ids` and `weights`
/// (k each) into the mapped host regions, fences, and increments the mapped sequence number - replacing three
diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp
index e3136a8fb..ba4e7c9d9 100644
--- a/include/strata/kernels/fused_gr.hpp
+++ b/include/strata/kernels/fused_gr.hpp
@@ -46,6 +46,7 @@ void fused_gr_read(const FusedGrArgs& a, void* stream);
/// weight pointers and eps must be the same for every t); `xn_scratch` is n_tok * hc * n_embd floats. Every
/// token's outputs are bitwise `fused_gr_read(a[t])`.
constexpr int kFusedGrMaxT = 8;
-void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream);
+void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream,
+ unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0);
} // namespace strata::kernels
diff --git a/include/strata/kernels/native_moe.hpp b/include/strata/kernels/native_moe.hpp
index 0c48d6ae8..34760efe6 100644
--- a/include/strata/kernels/native_moe.hpp
+++ b/include/strata/kernels/native_moe.hpp
@@ -15,4 +15,7 @@ bool native_moe_combine_enabled();
// Requires a nonnull ordered stream and disjoint output. No allocation or sync.
void native_moe_combine(const float* parts, const float* weights, const float* shared,
float* output, int64_t n_embd, int64_t k, void* stream);
+/// n_tok rows (parts [n,k,N], weights [n,k], shared/output [n,N]) in one launch, each as the single call.
+void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output,
+ int64_t n_embd, int64_t k, int n_tok, void* stream);
}
diff --git a/include/strata/kernels/native_router.hpp b/include/strata/kernels/native_router.hpp
index 4b3dccdab..0511b0b01 100644
--- a/include/strata/kernels/native_router.hpp
+++ b/include/strata/kernels/native_router.hpp
@@ -14,4 +14,6 @@ bool native_router_enabled();
// four-byte aligned and outputs disjoint from each other and the input.
// Requires a nonnull ordered CUDA stream. No allocation or synchronization.
void native_router_top10(const float* logits, int32_t* ids, float* weights, void* stream);
+/// n_tok rows at once (logits [n,512], ids/weights [n,10]); each row exactly as the single call.
+void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream);
}
diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp
index d66093221..1ce71cd31 100644
--- a/include/strata/kernels/verify_kernels.hpp
+++ b/include/strata/kernels/verify_kernels.hpp
@@ -38,6 +38,8 @@ void gdn_step_norm_multi(float* state, const float* h, int conv_channels, const
/// Spin until *flag >= value (a mapped host flag). The value is fixed at capture, so several rings can be
/// outstanding at once (the split verify window keeps two).
void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream);
+/// the GPU's %globaltimer (ns) into buf[i] (a one-thread kernel: the verify window's stage profiler).
+void gpu_stamp(unsigned long long* buf, int i, void* stream);
/// Rows of the S2/S4/S8 embedding for T token ids read from DEVICE memory; out (T, n). Bitwise `embedding_gather`.
void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens,
diff --git a/src/core/verify.cpp b/src/core/verify.cpp
index 72fccd5e3..8896731da 100644
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@ -8,6 +8,8 @@
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/bf16_gemv.hpp"
+#include "strata/kernels/native_router.hpp"
+#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/fused_gr.hpp"
@@ -32,7 +34,11 @@
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/verify_kernels.hpp"
+#include <algorithm>
#include <atomic>
+#include <map>
+#include <string>
+#include <vector>
#include <chrono>
#include <cmath>
#include <cstdio>
@@ -174,7 +180,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
// ---- mapped staging
bool ok = mapped(T * 4, (void**) &h_tok_, (void**) &m_tok_) &&
mapped(T * strata::kernels::kStepCount * 4, (void**) &h_step_, (void**) &m_step_) &&
- mapped(T * NH * 4, (void**) &h_pos_, (void**) &m_pos_) &&
+ mapped(T * (NH + NKV + IQ) * 4, (void**) &h_pos_, (void**) &m_pos_) &&
mapped((2 + T) * 4 + 16, (void**) &h_commit_, (void**) &m_commit_) &&
mapped(T * N * 4, (void**) &h_ple_, (void**) &m_ple_) &&
mapped(T * 4 + 16, (void**) &h_out_, (void**) &m_out_) &&
@@ -213,7 +219,7 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
// ---- the device arena: the same sequence counted, then carved
auto carve = [&](Bump& b) {
tok_ = b.take<int32_t>(T); step_ = b.take<int32_t>(T * strata::kernels::kStepCount);
- pos_ = b.take<int32_t>(T * NH); commit_ = b.take<int32_t>(2 + T);
+ pos_ = b.take<int32_t>(T * (NH + NKV + IQ)); commit_ = b.take<int32_t>(2 + T);
ple_ = b.take<float>(T * N); emb_ = b.take<float>(T * N); R_ = b.take<float>(T * HC * N);
mixed_ = b.take<float>(T * N); bo_ = b.take<float>(T * N);
inj_ = b.take<float>(T * HC); inj2_ = b.take<float>(T * HC);
@@ -252,6 +258,12 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
return false;
}
cudaMemset(arena_, 0, count.used);
+ prof_on_ = std::getenv("STRATA_VERIFY_PROFILE") != nullptr;
+ if (prof_on_) {
+ const size_t np = (size_t) g.n_layers * kProfPer + 4;
+ if (cudaMalloc((void**) &prof_, np * 8) != cudaSuccess) { prof_on_ = false; prof_ = nullptr; cudaGetLastError(); }
+ else { cudaMemset(prof_, 0, np * 8); prof_h_.assign(np, 0); }
+ }
Bump real;
real.base = (uint8_t*) arena_;
carve(real);
@@ -300,13 +312,18 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
const bool ple_on = ss.ple.ready();
auto Rt = [&](int t) { return R_ + (size_t) t * HC * N; };
const int G = (split_ && T >= 2) ? 2 : 1;
+ static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
+ auto stamp = [&](int64_t l, int i, int grp) { if (prof_on_ && grp == 0) gpu_stamp(prof_, (int) (l * kProfPer + i), cs); };
const int tb_[2] = {0, (T + 1) / 2}, te_[2] = {G == 2 ? (T + 1) / 2 : T, T};
groups_[T] = G;
// ---- the window's inputs, from mapped staging
copy_i32_from_mapped(tok_, m_tok_, T, cs);
copy_i32_from_mapped(step_, m_step_, (int64_t) T * kStepCount, cs);
- copy_i32_from_mapped(pos_, m_pos_, (int64_t) T * NH, cs);
+ copy_i32_from_mapped(pos_, m_pos_, (int64_t) MT * (NH + NKV + IQ), cs);
+ // per-ROW positions of the K rows [t][NKV] and the indexer query rows [t][IQ] (for batched RoPE)
+ const int32_t* pos_k = pos_ + MT * NH;
+ const int32_t* pos_i = pos_ + MT * (NH + NKV);
if (ple_on) copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs);
// ---- the embeddings, broadcast to the hc streams
@@ -342,6 +359,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// ---------------------------------------------------------------- pre(l, group): up to the ring
auto pre = [&](int64_t l, int grp) -> bool {
const int tb = tb_[grp], te = te_[grp], n = te - tb;
+ stamp(l, 0, grp);
const LayerView v(wt, l);
const char* pfx[2] = {"hc_attn_", "hc_ffn_"};
const WeightRef *wn[2], *wd[2], *wu[2], *wi[2];
@@ -384,9 +402,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
a.eps = EPS; a.lo = lo_ + t * g.hc_lr; a.rs = rs_ + t * HC;
a.inject_out = inj_out + t * HC; a.mixed = mixed_ + t * N;
}
- fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs);
+ fused_gr_read_multi(fa, n, xn_ + (size_t) tb * HC * N, cs, (prof_on_ && grp == 0) ? prof_ : nullptr,
+ (int) (l * kProfPer + (half == 0 ? 27 : 30)));
};
gr_read_group(0, pending, inj2_, inj_);
+ stamp(l, 1, grp);
float* xm = mixed_ + tb * N;
try {
if (!is_qsa_layer(g, l)) {
@@ -409,14 +429,19 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
float* beta = beta_L_ + (size_t) gi * MT * HV;
native_quantize_q8_1(xm, xq_, (int) N, n, cs);
native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs);
+ stamp(l, 2, grp);
gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb);
+ stamp(l, 3, grp);
gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
(const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV,
n, cs);
+ stamp(l, 4, grp);
native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs);
+ stamp(l, 5, grp);
// the recurrence from the untouched state over tokens [0, te); outputs only for this group's
gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK,
(int) HV, te, nullptr, cs, tb);
+ stamp(l, 6, grp);
native_quantize_q8_1(y_ + (size_t) tb * ZV, xq_, (int) ZV, n, cs);
native_mmvq(wout->native_type, wout->native_data, xq_, bo_ + tb * N, (int) ZV, (int) N, n, cs);
} else {
@@ -439,16 +464,23 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs);
};
float* idx_raw = idx_raw_L_ + (size_t) qi * MT * ID;
+ // the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the
+ // window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token)
+ const bool qb = dec_batch && n > 1 && native_qsa_enabled() && native_rope_enabled() && !st.kv_q4;
native_quantize_q8_1(xm, xq_, (int) N, n, cs);
- for (int t = tb; t < te; ++t)
+ if (qb) bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wik->data, idx_raw + tb * ID, ID, N, ID, n, cs);
+ else for (int t = tb; t < te; ++t)
bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs);
+ stamp(l, 7, grp);
native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);
native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs);
- for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);
+ if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV);
+ else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);
if (st.kv_q4) { // Q4_0 KV (kv_q4.hpp): K and V rotated before they are stored
fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs);
}
+ stamp(l, 8, grp);
if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs);
for (int t = tb; t < te; ++t) {
const int32_t* step_t = step_ + t * kStepCount;
@@ -467,8 +499,20 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0,
(const float*) wikn->data, EPS, ib, s, st.max_cells,
(float) qsa_freq_base(), cs);
+ stamp(l, 9, grp);
native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD),
n, cs);
+ if (qb) {
+ if (cudaMemcpy2DAsync(qcur_ + tb * NH * HD, (size_t) HD * 4, qfull_ + tb * NH * 2 * HD, (size_t) HD * 2 * 4,
+ (size_t) HD * 4, (size_t) (n * NH), cudaMemcpyDeviceToDevice, cs) != cudaSuccess) {
+ err = "verify: the q/gate split failed";
+ return false;
+ }
+ norm_rope(qcur_ + tb * NH * HD, wqn, (int) (n * NH), (int) HD, pos_ + tb * NH);
+ bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) wiq->data, qidx_ + tb * IQ * ID, IQ * ID,
+ N, IQ * ID, n, cs);
+ norm_rope(qidx_ + tb * IQ * ID, wiqn, (int) (n * IQ), (int) ID, pos_i + tb * IQ);
+ } else {
for (int t = tb; t < te; ++t) {
float* qc = qcur_ + t * NH * HD;
if (cudaMemcpy2DAsync(qc, (size_t) HD * 4, qfull_ + t * NH * 2 * HD, (size_t) HD * 2 * 4,
@@ -484,16 +528,24 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wiq->data, qx, (int) N, (int) (IQ * ID), cs);
norm_rope(qx, wiqn, (int) IQ, (int) ID, pos_ + t * NH);
}
+ }
+ stamp(l, 10, grp);
qsa_block_scores(st.idx_pooled, st.idx_dead, qidx_ + tb * IQ * ID, step_ + tb * kStepCount, n, max_blocks_,
s, scores_ + (size_t) tb * max_blocks_, cs);
qsa_block_topk(scores_ + (size_t) tb * max_blocks_, step_ + tb * kStepCount, n, max_blocks_, cap_, s,
sel_ + (size_t) tb * cap_, cs);
+ stamp(l, 11, grp);
// KV streaming: the n selections' blocks resident (device-side, inside the graph)
qsa_kv_resolve(st, *g_, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, n, cap_, cs);
+ stamp(l, 12, grp);
const QsaAttnPools pools = qsa_attn_pools(st);
qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_,
s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs);
+ stamp(l, 13, grp);
if (st.kv_q4) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H
+ if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD,
+ (int) (n * NH), (int) HD, cs);
+ else
for (int t = tb; t < te; ++t) {
if (native_qsa_enabled())
native_qsa_gate_apply(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, attn32_ + t * NH * HD,
@@ -501,6 +553,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
else
qsa_gate_apply_f32(attn_ + t * NH * HD, qfull_ + t * NH * 2 * HD, s, attn32_ + t * NH * HD, cs);
}
+ stamp(l, 14, grp);
native_quantize_q8_1(attn32_ + tb * NH * HD, xq_, (int) (NH * HD), n, cs);
native_mmvq(wo->native_type, wo->native_data, xq_, bo_ + tb * N, (int) (NH * HD), (int) N, n, cs);
}
@@ -508,7 +561,18 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
err = "verify layer " + std::to_string(l) + ": " + e.what();
return false;
}
+ stamp(l, 16, grp);
gr_read_group(1, true, inj_, inj2_);
+ // the window's rows routed in 2 launches (one router GEMV reading the weight once, one
+ // top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old)
+ const WeightRef* w_router = v.get("ffn_gate_inp.weight");
+ if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10) {
+ try {
+ bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N,
+ NE, n, cs);
+ native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs);
+ } catch (const std::exception& e) { err = "verify router: " + std::string(e.what()); return false; }
+ } else
for (int t = tb; t < te; ++t) {
MoEBuffers mb = ss.moe;
mb.logits = logits_ + t * NE; mb.ids = ids_ + t * K; mb.weights = w_ + t * K;
@@ -516,6 +580,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
}
doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs);
+ stamp(l, 17, grp);
{
const WeightRef *wgi = need(v, "ffn_gate_inp_shexp.weight", err), *wsg = need(v, "ffn_gate_shexp.weight", err),
*wsu = need(v, "ffn_up_shexp.weight", err), *wsd = need(v, "ffn_down_shexp.weight", err);
@@ -528,7 +593,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
nsw.up_type = wsu->native_type; nsw.up_data = wsu->native_data;
nsw.down_type = wsd->native_type; nsw.down_data = wsd->native_data;
nsw.q8_1 = xq_;
- for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, cs);
+ if (dec_batch) f32_to_bf16_bulk(mixed_ + tb * N, sh_bf16_ + tb * N, (int64_t) n * N, cs); // contiguous rows
+ else for (int t = tb; t < te; ++t) f32_to_bf16_bulk(mixed_ + t * N, sh_bf16_ + t * N, N, cs);
try {
shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff,
sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, cs);
@@ -541,6 +607,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
quantize_q8_1_rows(xm, n, N, nat_xq_ + (size_t) tb * (N / 32) * 36, cs);
else
quantize_q8_0_scaled(xm, hit_xq_ + (size_t) tb * (N / 32) * 34, hit_xs_ + (size_t) tb * (N / 32), (int64_t) n * N, cs);
+ stamp(l, 18, grp);
return true;
};
@@ -552,6 +619,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K;
int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16);
copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
+ stamp(l, 19, grp);
const int32_t* p_counts = pl;
const int32_t* p_start = pl + 4;
const int32_t* p_dst = p_start + capx + 1;
@@ -576,6 +644,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
}
};
grouped(p_ptr, p_start, p_counts);
+ stamp(l, 20, grp);
+ if (!pcie_off_) { // with --pcie-frac 0 there is never a PCIe share: no wait, no empty launch
wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped
if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging
const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;
@@ -583,15 +653,29 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
fetch_blobs(p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), (int) per, cs);
rebase_ptrs((unsigned long long*) p_ptr2, p_counts + 2, stage, (int64_t) lay.blob_bytes(l), cs);
}
+ stamp(l, 21, grp);
grouped(p_ptr2, p_start2, p_counts + 2);
+ }
+ stamp(l, 22, grp);
wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows
- copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);
+ stamp(l, 23, grp);
+ if (dec_batch) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows)
+ copy_rows_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K, N, p_dst,
+ p_counts + 1, cs);
+ else
+ copy_from_mapped(parts_ + (size_t) tb * K * N, m_ymiss_ + (size_t) tb * K * N, (int64_t) n * K * N, cs);
moe_hit_add(parts_ + (size_t) tb * K * N, hit_out, p_dst, p_counts + 1, cap, N, cs);
+ if (dec_batch && n > 1 && native_moe_combine_enabled()) { // one launch for the window's rows
+ try {
+ native_moe_combine_multi(parts_ + (size_t) tb * K * N, w_ + tb * K, shared_ + tb * N, bo_ + tb * N, N, K, n, cs);
+ } catch (const std::exception& e) { err = "verify combine: " + std::string(e.what()); return false; }
+ } else
for (int t = tb; t < te; ++t) {
MoEBuffers mb = ss.moe;
mb.weights = w_ + t * K; mb.shared = shared_ + t * N;
if (!moe_combine_parts(g, l, K, mb, parts_ + (size_t) t * K * N, bo_ + t * N, cs, err)) return false;
}
+ stamp(l, 24, grp);
if (l == g.n_layers - 1) {
for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);
@@ -610,6 +694,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
}
// ---- the head, T columns, and the argmax of each
+ stamp(g.n_layers, 0, 0);
{
const WeightRef *hn = wt.find("output_hc_norm.weight"), *hd = wt.find("output_hc_down.weight"),
*hu = wt.find("output_hc_up.weight");
@@ -641,9 +726,36 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
sp.temperature = 0.0f;
sample_tokens(head_logits_, T, (int) n_vocab_, nullptr, 0, sp, m_out_, cs);
}
+ stamp(g.n_layers, 1, 0);
return true;
}
+std::string Verifier::profile_report() {
+ if (!prof_on_ || prof_windows_ == 0) return std::string();
+ static const char* names[kProfPer] = {"-", "hc-read0", "q8+qkv/q-idx gemv", "conv", "ab", "z", "rec", "q8+kv-idx",
+ "k/v+norm-rope", "kv+idx append", "q+q-idx", "scores+topk", "kv-resolve",
+ "attention", "gate", "", "out-proj", "hc-read1+router", "shared+quant",
+ "waitA", "VRAM hits", "waitB", "PCIe grp", "waitCPU", "copy+combine",
+ "(gap)", "head", " hc0 norm", " hc0 down", " hc0 up", "", ""};
+ std::string out;
+ char b[80];
+ double total = 0;
+ for (int k = 0; k < 2; ++k) {
+ out += k == 0 ? " GDN layers:" : " | QSA layers:";
+ for (int i = 0; i < kProfPer; ++i) {
+ if (prof_sum_[k][i] <= 0) continue;
+ total += prof_sum_[k][i];
+ std::snprintf(b, sizeof b, " %s %.2f", names[i], prof_sum_[k][i] / 1e6 / (double) prof_windows_);
+ out += b;
+ }
+ }
+ std::snprintf(b, sizeof b, " | total %.2f ms/window over %lld windows", total / 1e6 / (double) prof_windows_, (long long) prof_windows_);
+ out += b;
+ for (auto& r : prof_sum_) for (double& d : r) d = 0;
+ prof_windows_ = 0;
+ return out;
+}
+
bool Verifier::capture(int T, std::string& err) {
if (exec_[T] != nullptr) return true;
if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) {
@@ -663,6 +775,33 @@ bool Verifier::capture(int T, std::string& err) {
err = std::string("verify: end capture: ") + cudaGetErrorString(ce);
return false;
}
+ if (std::getenv("STRATA_VERIFY_NODES") != nullptr) { // what the window graph holds
+ size_t nn = 0;
+ cudaGraphGetNodes(graph, nullptr, &nn);
+ std::vector<cudaGraphNode_t> nodes(nn);
+ cudaGraphGetNodes(graph, nodes.data(), &nn);
+ std::map<std::string, int> kinds;
+ for (cudaGraphNode_t nd : nodes) {
+ cudaGraphNodeType ty;
+ cudaGraphNodeGetType(nd, &ty);
+ std::string name = "type" + std::to_string((int) ty);
+ if (ty == cudaGraphNodeTypeKernel) {
+ cudaKernelNodeParams kp{};
+ if (cudaGraphKernelNodeGetParams(nd, &kp) == cudaSuccess) {
+ const char* fn = nullptr;
+ if (cudaFuncGetName(&fn, kp.func) == cudaSuccess && fn) name = fn;
+ }
+ } else if (ty == cudaGraphNodeTypeMemcpy) name = "memcpy";
+ else if (ty == cudaGraphNodeTypeMemset) name = "memset";
+ ++kinds[name];
+ }
+ std::vector<std::pair<int, std::string>> v;
+ for (auto& [k2, c] : kinds) v.push_back({c, k2});
+ std::sort(v.rbegin(), v.rend());
+ std::fprintf(stderr, "strata verify: the %d-token window graph has %zu nodes:", T, nn);
+ for (size_t i = 0; i < v.size() && i < 40; ++i) std::fprintf(stderr, " %d x %.60s;", v[i].first, v[i].second.c_str());
+ std::fprintf(stderr, "\n");
+ }
const cudaError_t ie = cudaGraphInstantiate(&exec_[T], graph, 0);
cudaGraphDestroy(graph);
if (ie != cudaSuccess) {
@@ -756,6 +895,10 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
h_tok_[t] = tokens[t];
qsa_step_fill(h_step_ + t * kStepCount, pos0 + t, s);
for (int64_t h = 0; h < g.n_head; ++h) h_pos_[t * g.n_head + h] = (int32_t) (pos0 + t);
+ int32_t* pk = h_pos_ + (size_t) max_t_ * g.n_head;
+ int32_t* pi = pk + (size_t) max_t_ * g.n_head_kv;
+ for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = (int32_t) (pos0 + t);
+ for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = (int32_t) (pos0 + t);
}
if (ss.ple.ready()) {
uint32_t rows[kVerifyMaxT * PLE_N_HEADS];
@@ -840,6 +983,28 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; }
progress_at("verify window: waiting for the expert copies", (int64_t) T);
cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one
+ if (prof_on_ && G == 1) { // the window's GPU stage stamps
+ cudaMemcpy(prof_h_.data(), prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost);
+ const int64_t L = g.n_layers;
+ auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; };
+ for (int64_t l = 0; l < L; ++l) {
+ const int kind = is_qsa_layer(g, l) ? 1 : 0;
+ unsigned long long prev = at(l, 0);
+ for (int i = 1; i <= 24; ++i) {
+ const unsigned long long x = at(l, i);
+ if (x == 0 || x < prev) continue;
+ prof_sum_[kind][i] += (double) (x - prev);
+ prev = x;
+ }
+ if (l + 1 < L) prof_sum_[kind][25] += (double) (at(l + 1, 0) - at(l, 24));
+ prof_sum_[kind][27] += (double) (at(l, 27) - at(l, 0)); // hc-read0: norm
+ prof_sum_[kind][28] += (double) (at(l, 28) - at(l, 27)); // down
+ prof_sum_[kind][29] += (double) (at(l, 1) - at(l, 28)); // up
+ prof_sum_[kind][1] -= (double) (at(l, 1) - at(l, 0)); // (hc-read0 shown split)
+ }
+ prof_sum_[0][26] += (double) (at(L, 1) - at(L, 0));
+ ++prof_windows_;
+ }
// ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's
// own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to
// the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever
diff --git a/src/kernels/cuda/elementwise.cu b/src/kernels/cuda/elementwise.cu
index 420db2aad..a2e9e53b5 100644
--- a/src/kernels/cuda/elementwise.cu
+++ b/src/kernels/cuda/elementwise.cu
@@ -225,6 +225,37 @@ __global__ void copy_from_mapped_kernel(float4* __restrict__ dst, const volatile
}
}
+// the CPU rows of a verify window, skipping the rows the GPU plan computes itself (the
+// pool writes +0.0 into those, so this writes +0.0 too): block = row, the plan's hit rows `dst[0, *count)`.
+__global__ void copy_rows_from_mapped_kernel(float4* __restrict__ dst, const volatile float4* src, int64_t row4,
+ const int32_t* __restrict__ hit_rows, const int32_t* __restrict__ count) {
+ const int row = blockIdx.x;
+ __shared__ int hit;
+ if (threadIdx.x == 0) {
+ int h = 0;
+ const int c = *count;
+ for (int i = 0; i < c; ++i) h |= hit_rows[i] == row;
+ hit = h;
+ }
+ __syncthreads();
+ float4* d = dst + (int64_t) row * row4;
+ if (hit) {
+ for (int64_t i = threadIdx.x; i < row4; i += blockDim.x) d[i] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
+ } else {
+ const volatile float4* sr = src + (int64_t) row * row4;
+ for (int64_t i = threadIdx.x; i < row4; i += blockDim.x) d[i] = const_cast<const float4*>(sr)[i];
+ }
+}
+void copy_rows_from_mapped(float* dst, const float* src, int64_t rows, int64_t width, const int32_t* hit_rows,
+ const int32_t* count, void* stream) {
+ if (rows <= 0) return;
+ if ((width & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) {
+ std::fprintf(stderr, "copy_rows_from_mapped: width must be a multiple of 4 and both pointers 16-byte aligned\n");
+ std::exit(1);
+ }
+ copy_rows_from_mapped_kernel<<<(unsigned) rows, 128, 0, (cudaStream_t) stream>>>((float4*) dst, (const volatile float4*) src,
+ width / 4, hit_rows, count);
+}
void copy_from_mapped(float* dst, const float* src, int64_t n, void* stream) {
if (n <= 0) return;
if ((n & 3) != 0 || ((uintptr_t) dst & 15) != 0 || ((uintptr_t) src & 15) != 0) {
diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu
index c439ee48c..b95e5cfdb 100644
--- a/src/kernels/cuda/fused_gr.cu
+++ b/src/kernels/cuda/fused_gr.cu
@@ -1,6 +1,7 @@
// src/kernels/cuda/fused_gr.cu - see include/strata/kernels/fused_gr.hpp.
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/bf16_bits.hpp"
+#include "strata/kernels/verify_kernels.hpp"
#include <cuda_runtime.h>
@@ -295,7 +296,8 @@ __global__ void __launch_bounds__(THREADS) gr_up_multi_kernel(GrMulti m) {
} // namespace
-void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream) {
+void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf,
+ int stamp_i0) {
if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) {
std::fprintf(stderr, "fused_gr_read_multi: invalid arguments\n");
std::exit(1);
@@ -315,6 +317,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
m.T = n_tok;
cudaStream_t st = (cudaStream_t) stream;
gr_norm_multi_kernel<<<n_tok, THREADS, 0, st>>>(m);
+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream);
static bool attr = false;
if (!attr) {
cudaFuncSetAttribute(gr_down_multi_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize,
@@ -322,6 +325,7 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi
attr = true;
}
gr_down_multi_kernel<<<DOWN_BLOCKS + 1, THREADS, (size_t) n_tok * TILE * sizeof(float), st>>>(m);
+ if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream);
gr_up_multi_kernel<<<UPM_BLOCKS, THREADS, 0, st>>>(m);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {
diff --git a/src/kernels/cuda/native_bf16.cu b/src/kernels/cuda/native_bf16.cu
index 5131b20b9..1390a6abe 100644
--- a/src/kernels/cuda/native_bf16.cu
+++ b/src/kernels/cuda/native_bf16.cu
@@ -70,6 +70,54 @@ __global__ void bf16_f32_mmvf_kernel(const float* __restrict__ x, const uint16_t
if (t == 0) y[blockIdx.x] = acc;
}
+// the same kernel for up to 8 activation rows - the weight row is read ONCE and every
+// token keeps its own accumulator with exactly the single-row kernel's order (pairs, two ordered FMAs, the same warp
+// and block reductions), so each output is bit-identical to a bf16_f32_mmvf_kernel launch of its own.
+template <int BLOCK_SIZE, int NT>
+__global__ void bf16_f32_mmvf_multi_kernel(const float* __restrict__ x, int64_t ldx, const uint16_t* __restrict__ w,
+ float* __restrict__ y, int64_t ldy, int n_in, int n_tok) {
+ const int t = threadIdx.x;
+ const uint16_t* row = w + (size_t) blockIdx.x * n_in;
+ const uint32_t* weights2 = reinterpret_cast<const uint32_t*>(row);
+ __shared__ float partials[NT][32];
+ if constexpr (BLOCK_SIZE > 32) {
+ if (t < 32)
+#pragma unroll
+ for (int k = 0; k < NT; ++k) partials[k][t] = 0.0f;
+ __syncthreads();
+ }
+ float acc[NT];
+#pragma unroll
+ for (int k = 0; k < NT; ++k) acc[k] = 0.0f;
+ for (int pair = t; pair < n_in / 2; pair += BLOCK_SIZE) {
+ const uint32_t weight = weights2[pair];
+ const float w0 = f32_from_bf16((uint16_t) weight), w1 = f32_from_bf16((uint16_t) (weight >> 16));
+#pragma unroll
+ for (int k = 0; k < NT; ++k) {
+ if (k < n_tok) {
+ const float2 input = reinterpret_cast<const float2*>(x + (size_t) k * ldx)[pair];
+ acc[k] = __fmaf_rn(w0, input.x, acc[k]);
+ acc[k] = __fmaf_rn(w1, input.y, acc[k]);
+ }
+ }
+ }
+#pragma unroll
+ for (int k = 0; k < NT; ++k) acc[k] = mmvf_warp_sum(acc[k]);
+ if constexpr (BLOCK_SIZE > 32) {
+ if ((t & 31) == 0)
+#pragma unroll
+ for (int k = 0; k < NT; ++k) partials[k][t / 32] = acc[k];
+ __syncthreads();
+ if (t < 32)
+#pragma unroll
+ for (int k = 0; k < NT; ++k) acc[k] = mmvf_warp_sum(partials[k][t]);
+ }
+ if (t == 0)
+#pragma unroll
+ for (int k = 0; k < NT; ++k)
+ if (k < n_tok) y[(size_t) k * ldy + blockIdx.x] = acc[k];
+}
+
int mmvf_block_size(int64_t n_in) {
int best = 32;
int64_t best_iterations = (n_in + 63) / 64;
@@ -85,6 +133,26 @@ int mmvf_block_size(int64_t n_in) {
} // namespace
+void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
+ int64_t n_in, int64_t n_out, int n_tok, void* stream) {
+ if (n_tok == 1 && ldy >= n_out) { bf16_gemv_fp32_mmvf(x, w, y, n_in, n_out, stream); return; }
+ if (n_tok < 1 || n_tok > 8 || n_in <= 0 || (n_in & 1) != 0 || n_out <= 0 || (ldx & 1) != 0 || x == nullptr ||
+ w == nullptr || y == nullptr || (reinterpret_cast<uintptr_t>(x) & 7u) != 0)
+ throw std::invalid_argument("bf16_gemv_fp32_mmvf_multi: 1..8 rows, even n_in/ldx, aligned pointers");
+ const cudaStream_t st = (cudaStream_t) stream;
+#define STRATA_MMVF_M(N) case N: \
+ if (n_tok <= 4) bf16_f32_mmvf_multi_kernel<N, 4><<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); \
+ else bf16_f32_mmvf_multi_kernel<N, 8><<<(unsigned) n_out, N, 0, st>>>(x, ldx, w, y, ldy, (int) n_in, n_tok); break
+ switch (mmvf_block_size(n_in)) {
+ STRATA_MMVF_M(32); STRATA_MMVF_M(64); STRATA_MMVF_M(96); STRATA_MMVF_M(128);
+ STRATA_MMVF_M(160); STRATA_MMVF_M(192); STRATA_MMVF_M(224); STRATA_MMVF_M(256);
+ }
+#undef STRATA_MMVF_M
+ const cudaError_t result = cudaGetLastError();
+ if (result != cudaSuccess)
+ throw std::runtime_error(std::string("bf16_gemv_fp32_mmvf_multi launch: ") + cudaGetErrorString(result));
+}
+
void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
int64_t n_in, int64_t n_out, void* stream) {
if (n_in <= 0 || (n_in & 1) != 0 || n_in > std::numeric_limits<int>::max() ||
diff --git a/src/kernels/cuda/native_moe.cu b/src/kernels/cuda/native_moe.cu
index 42b57ca0f..7f1f91ce6 100644
--- a/src/kernels/cuda/native_moe.cu
+++ b/src/kernels/cuda/native_moe.cu
@@ -34,6 +34,9 @@ std::atomic<bool> enabled{false};
__global__ void combine(const float* __restrict__ parts, const float* __restrict__ weights,
const float* __restrict__ shared, float* __restrict__ output,
int64_t n_embd, int k) {
+ // blockIdx.y = the token of a multi-token launch (0 for the single one)
+ const int64_t tk = blockIdx.y;
+ parts += tk * k * n_embd; weights += tk * k; if (shared) shared += tk * n_embd; output += tk * n_embd;
const int64_t col = int64_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (col >= n_embd) return;
float sum = parts[col] * weights[0];
@@ -71,4 +74,13 @@ void native_moe_combine(const float* parts, const float* weights, const float* s
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
+void native_moe_combine_multi(const float* parts, const float* weights, const float* shared, float* output,
+ int64_t n_embd, int64_t k, int n_tok, void* stream) {
+ if (!stream || n_embd <= 0 || k < 1 || k > 15 || n_tok < 1)
+ throw std::invalid_argument("native MoE combine (multi) requires a stream, width, 1..15 experts, tokens");
+ combine<<<dim3(unsigned((n_embd + 255) / 256), (unsigned) n_tok), 256, 0, static_cast<cudaStream_t>(stream)>>>(
+ parts, weights, shared, output, n_embd, int(k));
+ const auto error = cudaGetLastError();
+ if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
+}
}
diff --git a/src/kernels/cuda/native_router.cu b/src/kernels/cuda/native_router.cu
index 124563712..3f8b69ce2 100644
--- a/src/kernels/cuda/native_router.cu
+++ b/src/kernels/cuda/native_router.cu
@@ -45,6 +45,8 @@ __launch_bounds__(256, 1)
__global__ void route(const float* __restrict__ logits, int32_t* __restrict__ ids,
float* __restrict__ weights) {
// Preserve the pinned 32x8 block geometry; only row zero is active here.
+ // blockIdx.x = the token (a multi-token launch; 0 for the single one)
+ logits += (size_t) blockIdx.x * 512; ids += (size_t) blockIdx.x * 10; weights += (size_t) blockIdx.x * 10;
if (threadIdx.y != 0) return;
const int lane = threadIdx.x;
float values[16];
@@ -114,4 +116,12 @@ void native_router_top10(const float* logits, int32_t* ids, float* weights, void
const auto error = cudaGetLastError();
if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
}
+void native_router_top10_multi(const float* logits, int32_t* ids, float* weights, int n_tok, void* stream) {
+ if (!stream || n_tok < 1 || !valid(logits, (size_t) n_tok * 512 * 4) || !valid(ids, (size_t) n_tok * 10 * 4) ||
+ !valid(weights, (size_t) n_tok * 10 * 4))
+ throw std::invalid_argument("native router (multi) requires a stream and aligned [n,512]/[n,10] buffers");
+ route<<<(unsigned) n_tok, dim3(32, 8), 0, static_cast<cudaStream_t>(stream)>>>(logits, ids, weights);
+ const auto error = cudaGetLastError();
+ if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error));
+}
}
diff --git a/src/kernels/cuda/shared_expert.cu b/src/kernels/cuda/shared_expert.cu
index 81402a9fd..d795bf840 100644
--- a/src/kernels/cuda/shared_expert.cu
+++ b/src/kernels/cuda/shared_expert.cu
@@ -135,6 +135,9 @@ __global__ void native_scalar_sigmoid_kernel(float* gate) {
// compilation flags. The dot product was already reduced by the pinned native MMVF implementation.
gate[0] = __fdividef(1.0f, 1.0f + __expf(-gate[0]));
}
+__global__ void native_scalar_sigmoid_multi_kernel(float* gate) { // thread t = token t, same expression
+ gate[threadIdx.x] = __fdividef(1.0f, 1.0f + __expf(-gate[threadIdx.x]));
+}
/// The MoE block's final combination. See the header for the two readings it exists to pin.
__global__ void moe_combine_kernel(const float* __restrict__ parts, const float* __restrict__ weights,
@@ -176,6 +179,11 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, cons
native_swiglu_kernel<<<(unsigned) ((n + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate, up, gate, n);
native_quantize_q8_1(gate, nw.q8_1, (int) n_ff, n_tok, stream);
native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream);
+ static const bool batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
+ if (native_bf16 && batch && n_tok > 1) { // one gemv for all rows (outputs identical), one sigmoid launch
+ bf16_gemv_fp32_mmvf_multi(x, n_embd, gate_inp_bf16, g, 1, n_embd, 1, n_tok, stream);
+ native_scalar_sigmoid_multi_kernel<<<1, n_tok, 0, cs>>>(g);
+ } else
for (int t = 0; t < n_tok; ++t) {
if (native_bf16) {
bf16_gemv_fp32_mmvf(x + (size_t) t * n_embd, gate_inp_bf16, g + t, n_embd, 1, stream);
diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu
index 6dde0cbf2..a84ba9584 100644
--- a/src/kernels/cuda/verify_kernels.cu
+++ b/src/kernels/cuda/verify_kernels.cu
@@ -454,4 +454,14 @@ void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* i
check("copy_indexed");
}
+// a GPU timestamp (ns, %globaltimer) into buf[i] - the verify window's stage profiler
+namespace { __global__ void gpu_stamp_kernel(unsigned long long* buf, int i) {
+ unsigned long long t;
+ asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t));
+ buf[i] = t;
+} }
+void gpu_stamp(unsigned long long* buf, int i, void* stream) {
+ gpu_stamp_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(buf, i);
+}
+
} // namespace strata::kernels
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 6e979d6a4..035e956ad 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -2478,6 +2478,7 @@ int main(int argc, char** argv) {
// issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy
// kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests).
ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);
+ ver.set_pcie_off(o.pcie_frac <= 0.0); // no PCIe share at all: the window skips that path
std::vector<int64_t> cur;
// ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens
// it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the
@@ -3166,6 +3167,20 @@ int main(int argc, char** argv) {
for (int64_t i = 0; i < n - 1; ++i) consumed.push_back((int32_t) ids[(size_t) i]);
const char* finish = "length";
const Clock::time_point d0 = Clock::now();
+ // STRATA_DECODE_TIMING=1: where a request's decode time goes (one line per request)
+ static const bool dec_timing = std::getenv("STRATA_DECODE_TIMING") != nullptr;
+ struct DecSnap {
+ double wait, pool, host, plan, actq, jobs, run;
+ int64_t misses, entries, hits, pcie;
+ };
+ auto dec_snap = [&]() {
+ return DecSnap{ver.ms_wait, ver.ms_pool, ver.ms_host, drive.d.ms_plan, drive.d.ms_actq, drive.d.ms_jobs,
+ drive.d.ms_run, drive.d.multi_misses, drive.d.multi_entries, drive.d.cache_hits,
+ drive.d.pcie_experts};
+ };
+ const DecSnap ds0 = dec_snap();
+ double dt_run = 0, dt_commit = 0, dt_draft = 0;
+ int64_t dec_windows = 0, dec_T = 0;
const int64_t decode_hits0 = drive.d.cache_hits;
const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused;
if (cancelled) finish = "cancel";
@@ -3208,6 +3223,7 @@ int main(int argc, char** argv) {
cudaMemcpyHostToDevice);
}
tr("window", p, T);
+ const Clock::time_point tw0 = Clock::now();
if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err) || drive.d.failed) {
std::printf("ERR %s\n", drive.d.failed && drive.d.fail ? drive.d.fail : err.c_str());
return 1;
@@ -3215,6 +3231,7 @@ int main(int argc, char** argv) {
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; }
+ const Clock::time_point tw1 = Clock::now();
std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate)
bool adapt_ok = true;
if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0)
@@ -3239,8 +3256,15 @@ int main(int argc, char** argv) {
}
std::fflush(stdout);
++rounds;
+ const Clock::time_point tw2 = Clock::now();
const bool drafted = eos || produced_n >= max_new ||
mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p);
+ {
+ const Clock::time_point tw3 = Clock::now();
+ auto msd = [](Clock::time_point a0, Clock::time_point b0) { return std::chrono::duration<double, std::milli>(b0 - a0).count(); };
+ dt_run += msd(tw0, tw1); dt_commit += msd(tw1, tw2); dt_draft += msd(tw2, tw3);
+ ++dec_windows; dec_T += T;
+ }
if (adapt_thr.joinable()) adapt_thr.join();
if (!adapt_ok) {
std::printf("ERR an adaptive refill failed\n");
@@ -3259,6 +3283,21 @@ int main(int argc, char** argv) {
p += a + 1;
}
const double decode_ms = std::chrono::duration<double, std::milli>(Clock::now() - d0).count();
+ if (dec_timing && dec_windows > 0) {
+ const DecSnap d1 = dec_snap();
+ const double w = (double) dec_windows, L = (double) g.n_layers;
+ std::fprintf(stderr, "strata decode timing: %lld windows, avg T %.2f, %.2f tokens/window, %.2f ms/window = "
+ "verify %.2f (GPU-reach wait %.2f + per-layer host %.2f [plan %.2f actq %.2f jobs %.2f "
+ "CPU %.2f] + stage %.2f) + commit/emit %.2f + draft %.2f; per layer-window: CPU experts "
+ "%.2f (%.2f entries), VRAM hits %.2f, PCIe %.2f\n",
+ (long long) dec_windows, dec_T / w, produced_n / w, decode_ms / w, dt_run / w,
+ (d1.wait - ds0.wait) / w, (d1.pool - ds0.pool) / w, (d1.plan - ds0.plan) / w,
+ (d1.actq - ds0.actq) / w, (d1.jobs - ds0.jobs) / w, (d1.run - ds0.run) / w,
+ (d1.host - ds0.host) / w, dt_commit / w, dt_draft / w, (d1.misses - ds0.misses) / (w * L),
+ (d1.entries - ds0.entries) / (w * L), (d1.hits - ds0.hits) / (w * L), (d1.pcie - ds0.pcie) / (w * L));
+ const std::string pr = ver.profile_report();
+ if (!pr.empty()) std::fprintf(stderr, "strata decode GPU stages (ms/window):%s\n", pr.c_str());
+ }
if (!cancelled) {
// a prompt stopped halfway leaves the session somewhere between two chunks: nothing to continue from
// (the checkpoints taken while reading it are still good)
@@ -3744,6 +3783,7 @@ int main(int argc, char** argv) {
// issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy
// kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests).
ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2);
+ ver.set_pcie_off(o.pcie_frac <= 0.0); // no PCIe share at all: the window skips that path
drive.d.plan = ver.plan_sink();
drive.d.pcie_num = (int) (o.pcie_frac * 256.0 + 0.5);
if (drive.d.pcie_num < 0) drive.d.pcie_num = 0;