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

F7: the draft pass's kernels in the main layer's forms (fork d3d48b1)

Niko12214a5713fbb448
diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp
index c1e014302..499792755 100644
--- a/include/strata/core/mtp.hpp
+++ b/include/strata/core/mtp.hpp
@@ -217,6 +217,8 @@ private:
cudaGraphExec_t prefill_dev_exec_[9] = {};
int32_t* pf_dev_ = nullptr; ///< E-4: a prompt's rows' token / step / position records, uploaded at once
int64_t pf_cap_ = 0; ///< its capacity in ints
+ cudaStream_t side_ = nullptr; // the shared expert's branch of the draft graphs (CUDA)
+ cudaEvent_t sh_fork_ = nullptr, sh_join_ = nullptr;
cudaGraphExec_t round_exec_[9] = {};
struct Tensor { std::string name, kind; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; };
diff --git a/include/strata/kernels/elementwise.hpp b/include/strata/kernels/elementwise.hpp
index ae0973c6d..39a2560a0 100644
--- a/include/strata/kernels/elementwise.hpp
+++ b/include/strata/kernels/elementwise.hpp
@@ -124,5 +124,13 @@ void doorbell_publish_res(const float* x, const int32_t* ids, const int32_t* d_r
/// Plan v0.3 P3: copy `n` int32 from mapped pinned host memory into device memory with a kernel (the QSA
/// per-token step and positions), instead of a host-to-device memcpy node in the middle of a layer.
void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream);
+/// Up to 8 copies from mapped host memory in one launch: `words` 4-byte words each (16 bytes a load where both
+/// ends are 16-byte aligned and the count a multiple of 4). Graph-capturable.
+struct MappedCopy {
+ void* dst = nullptr;
+ const void* src = nullptr;
+ int64_t words = 0;
+};
+void copy_from_mapped_multi(const MappedCopy* copies, int n, void* stream);
} // namespace strata::kernels
diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp
index 8f3111591..2784c0a3e 100644
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@ -133,6 +133,9 @@ MtpDrafter::~MtpDrafter() {
if (h_cparams_) cudaFreeHost(h_cparams_);
if (h_chist_) cudaFreeHost(h_chist_);
if (cs_) cudaStreamDestroy(cs_);
+ if (side_) cudaStreamDestroy(side_);
+ if (sh_fork_) cudaEventDestroy(sh_fork_);
+ if (sh_join_) cudaEventDestroy(sh_join_);
if (owns_weights_ && dense_) cudaFree(dense_);
if (owns_weights_ && experts_) cudaFree(experts_);
if (state_arena_) cudaFree(state_arena_);
@@ -411,6 +414,12 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
cudaGetLastError();
#endif
if (!prio && cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; }
+ if (cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking) != cudaSuccess ||
+ cudaEventCreateWithFlags(&sh_fork_, cudaEventDisableTiming) != cudaSuccess ||
+ cudaEventCreateWithFlags(&sh_join_, cudaEventDisableTiming) != cudaSuccess) {
+ err = "mtp: streams";
+ return false;
+ }
const double files_s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_files).count();
if (shared != nullptr) {
std::fprintf(stderr, "strata mtp: shared draft weights, %.0f MiB of private state and buffers\n",
@@ -774,34 +783,66 @@ bool MtpDrafter::record_rest(int step_row, cudaStream_t cs, std::string& err) {
}
fused_gr_read_multi(fa, T, xn_, cs);
}
- // ---- MoE: router, the 512 resident experts, the shared expert, the combine, the write
- for (int t = 0; t < T; ++t) {
- bf16_gemv_fp32_mmvf(mixed_ + t * N, bf16("mlp.gate.weight"), logits_ + t * g.n_expert, (int) N, (int) g.n_expert, cs);
- if (native_router_enabled()) native_router_top10(logits_ + t * g.n_expert, ids_ + t * K, w_ + t * K, cs);
- else router_top10(logits_ + t * g.n_expert, 1, (int) g.n_expert, (int) K, ids_ + t * K, w_ + t * K, cs);
- }
- moe_group_resident(ids_, (int) (T * K), (int) K, experts_, (int64_t) strata::kernels::cpu::BLOB, grp_ptr_,
- grp_start_, grp_counts_, hit_dst_, hit_slot_, cs);
- quantize_q8_0_scaled(mixed_, hit_xq_, hit_xs_, (int64_t) T * N, cs);
- moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_,
- hit_xs_, hit_scratch_, parts_, cs);
+ // ---- MoE: router, the 512 resident experts, the shared expert (on a branch beside them on CUDA), the
+ // combine, the write
NativeSharedWeights nsw;
nsw.gate_data = wq("mlp.shared_expert.gate_proj.weight", nsw.gate_type);
nsw.up_data = wq("mlp.shared_expert.up_proj.weight", nsw.up_type);
nsw.down_data = wq("mlp.shared_expert.down_proj.weight", nsw.down_type);
- nsw.q8_1 = xq_;
+ nsw.q8_1 = xq_; // the routed experts read hit_xq_
const SForm none{};
const bool need_bf16_x = !shared_expert_native_bf16_enabled();
static const bool fuse_head_gr = [] {
const char* v = std::getenv("STRATA_FUSE_HEAD_GR");
return v != nullptr && std::atoi(v) != 0;
}();
+ // the shared expert only reads mixed_ / xq_ and writes shared_: a branch beside the router and the routed
+ // experts, joined before the combine (CUDA; HIP keeps one stream: STRATA_MTP_SHARED_BRANCH=0 does too)
+ static const bool branch_on = [] {
+#if defined(STRATA_USE_HIP)
+ return false;
+#else
+ const char* v = std::getenv("STRATA_MTP_SHARED_BRANCH");
+ return v == nullptr || std::atoi(v) != 0;
+#endif
+ }();
+ cudaStream_t sh_cs = cs;
+ if (branch_on) {
+ if (cudaEventRecord(sh_fork_, cs) != cudaSuccess || cudaStreamWaitEvent(side_, sh_fork_, 0) != cudaSuccess) {
+ err = "mtp: the shared expert's branch";
+ return false;
+ }
+ sh_cs = side_;
+ }
+ auto shared_rows = [&]() {
+ for (int t = 0; t < T; ++t) {
+ if (need_bf16_x) f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, sh_cs);
+ shared_expert(nullptr, nullptr, x_bf16_, none, nullptr, nullptr, nullptr, none, nullptr, nullptr, nullptr,
+ none, nullptr, nullptr, nullptr, bf16("mlp.shared_expert_gate.weight"), sh_scratch_,
+ shared_ + t * N, N, g.n_ff, 32, sh_cs, mixed_ + t * N, &nsw);
+ }
+ };
+ if (branch_on) {
+ shared_rows();
+ if (cudaEventRecord(sh_join_, side_) != cudaSuccess) { err = "mtp: the shared expert's branch"; return false; }
+ }
for (int t = 0; t < T; ++t) {
- if (need_bf16_x) f32_to_bf16_bulk(mixed_ + t * N, x_bf16_, N, cs);
- shared_expert(nullptr, nullptr, x_bf16_, none, nullptr, nullptr, nullptr, none, nullptr, nullptr, nullptr, none,
- nullptr, nullptr, nullptr, bf16("mlp.shared_expert_gate.weight"), sh_scratch_, shared_ + t * N,
- N, g.n_ff, 32, cs, mixed_ + t * N, &nsw);
- if (native_moe_combine_enabled())
+ bf16_gemv_fp32_mmvf(mixed_ + t * N, bf16("mlp.gate.weight"), logits_ + t * g.n_expert, (int) N, (int) g.n_expert, cs);
+ if (native_router_enabled()) native_router_top10(logits_ + t * g.n_expert, ids_ + t * K, w_ + t * K, cs);
+ else router_top10(logits_ + t * g.n_expert, 1, (int) g.n_expert, (int) K, ids_ + t * K, w_ + t * K, cs);
+ }
+ moe_group_resident(ids_, (int) (T * K), (int) K, experts_, (int64_t) strata::kernels::cpu::BLOB, grp_ptr_,
+ grp_start_, grp_counts_, hit_dst_, hit_slot_, cs);
+ quantize_q8_0_scaled(mixed_, hit_xq_, hit_xs_, (int64_t) T * N, cs);
+ moe_grouped_s2(grp_ptr_, grp_start_, grp_counts_, hit_dst_, hit_slot_, (int64_t) T * K, (int64_t) T * K, hit_xq_,
+ hit_xs_, hit_scratch_, parts_, cs);
+ if (branch_on) {
+ if (cudaStreamWaitEvent(cs, sh_join_, 0) != cudaSuccess) { err = "mtp: the shared expert's join"; return false; }
+ } else {
+ shared_rows();
+ }
+ for (int t = 0; t < T; ++t) {
+ if (native_moe_combine_enabled())
native_moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);
else
moe_combine(parts_ + (size_t) t * K * N, w_ + t * K, shared_ + t * N, y_ + t * N, N, K, cs);
@@ -907,24 +948,31 @@ bool MtpDrafter::capture_round(int T, bool coupled, std::string& err) {
bool ok = true;
// coupled: the request's chain and the penalty history's base, for this round's drafts
if (coupled) coupled_draft_stage(m_cparams_, m_chist_, cparams_, cring_, kCoupledHistCap, cs_);
- copy_i32_from_mapped(tok_, m_tok_, T, cs_);
- copy_i32_from_mapped(step_, m_step_, (int64_t) 2 * T * 4, cs_);
- copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * g_->n_head, cs_);
- copy_i32_from_mapped(row_, m_row_, 2, cs_);
- copy_from_mapped(Rin_, window_R_, (int64_t) T * HCN, cs_);
// the catch-up: the layer's front for the window's T cells (their K/V), then its rest for row a only, on row
// a's intermediates copied to row 0, at the cell the host staged in step row 2*max_t - 1; the draft chain is
// one graph per step (`capture_step`) so the host can stop it when a draft is unlikely
const int ra = 2 * max_t_ - 1;
- const int64_t N = g_->n_embd;
+ const int64_t N = g_->n_embd, NH = g_->n_head;
+#if defined(STRATA_USE_HIP) // AMD keeps its separate copies
+ copy_i32_from_mapped(tok_, m_tok_, T, cs_);
+ copy_i32_from_mapped(step_, m_step_, (int64_t) 2 * T * 4, cs_);
+ copy_i32_from_mapped(pos_, m_pos_, (int64_t) 2 * T * NH, cs_);
+ copy_i32_from_mapped(row_, m_row_, 2, cs_);
+ copy_from_mapped(Rin_, window_R_, (int64_t) T * HCN, cs_);
+ copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_);
+ copy_i32_from_mapped(pos_ + ra * NH, m_pos_ + ra * NH, NH, cs_);
+#else // the draft round's seven inputs in one launch
+ const MappedCopy in[7] = {{tok_, m_tok_, T}, {step_, m_step_, (int64_t) 2 * T * 4}, {pos_, m_pos_, 2 * T * NH},
+ {row_, m_row_, 2}, {Rin_, window_R_, T * HCN}, {step_ + ra * 4, m_step_ + ra * 4, 4},
+ {pos_ + ra * NH, m_pos_ + ra * NH, NH}};
+ copy_from_mapped_multi(in, 7, cs_);
+#endif
ok = record_front(T, 0, cs_, err);
if (ok) {
if (T > 1) {
copy_row_to_first(row_, R_, HCN, inj_, g_->hc, mixed_, N, cs_);
native_quantize_q8_1(mixed_, xq_, (int) N, 1, cs_);
}
- copy_i32_from_mapped(step_ + ra * 4, m_step_ + ra * 4, 4, cs_);
- copy_i32_from_mapped(pos_ + ra * g_->n_head, m_pos_ + ra * g_->n_head, g_->n_head, cs_);
coupled_rec_ = coupled;
coupled_j_ = 0;
ok = record_rest(ra, cs_, err);
@@ -944,8 +992,14 @@ bool MtpDrafter::capture_step(int j, bool coupled, std::string& err) {
const int64_t HCN = g_->hc * g_->n_embd;
const int row = max_t_ + j - 1;
if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "mtp: begin capture"; return false; }
+#if defined(STRATA_USE_HIP)
copy_i32_from_mapped(step_ + row * 4, m_step_ + row * 4, 4, cs_);
copy_i32_from_mapped(pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head, cs_);
+#else
+ const MappedCopy in[2] = {{step_ + row * 4, m_step_ + row * 4, 4},
+ {pos_ + row * g_->n_head, m_pos_ + row * g_->n_head, g_->n_head}};
+ copy_from_mapped_multi(in, 2, cs_);
+#endif
coupled_rec_ = coupled;
coupled_j_ = j;
bool ok = record_forward(1, row, cs_, err);
diff --git a/src/kernels/cuda/elementwise.cu b/src/kernels/cuda/elementwise.cu
index ac78bc325..05ae76201 100644
--- a/src/kernels/cuda/elementwise.cu
+++ b/src/kernels/cuda/elementwise.cu
@@ -379,12 +379,52 @@ __global__ void copy_i32_from_mapped_kernel(int32_t* __restrict__ dst, const vol
for (int i = threadIdx.x; i < n; i += blockDim.x) dst[i] = src[i];
}
+#if !defined(__HIPCC__)
+struct MappedCopies {
+ MappedCopy c[8];
+};
+
+__global__ void copy_from_mapped_multi_kernel(MappedCopies a) {
+ const MappedCopy c = a.c[blockIdx.y];
+ const int64_t i0 = (int64_t) blockIdx.x * blockDim.x + threadIdx.x, st = (int64_t) gridDim.x * blockDim.x;
+ if ((c.words & 3) == 0 && ((uintptr_t) c.dst & 15) == 0 && ((uintptr_t) c.src & 15) == 0) {
+ const volatile float4* s = (const volatile float4*) c.src;
+ for (int64_t i = i0; i < c.words / 4; i += st) ((float4*) c.dst)[i] = const_cast<const float4*>(s)[i];
+ } else {
+ const volatile int32_t* s = (const volatile int32_t*) c.src;
+ for (int64_t i = i0; i < c.words; i += st) ((int32_t*) c.dst)[i] = s[i];
+ }
+}
+
+void copy_from_mapped_multi(const MappedCopy* copies, int n, void* stream) {
+ if (n <= 0) return;
+ if (n > 8) { std::fprintf(stderr, "copy_from_mapped_multi: at most 8 copies\n"); std::exit(1); }
+ MappedCopies a;
+ int64_t most = 0;
+ for (int i = 0; i < n; ++i) {
+ a.c[i] = copies[i];
+ most = copies[i].words > most ? copies[i].words : most;
+ }
+ const int64_t units = (most + 3) / 4;
+ const unsigned bx = (unsigned) ((units + 255) / 256 < 32 ? (units + 255) / 256 : 32);
+ copy_from_mapped_multi_kernel<<<dim3(bx < 1 ? 1 : bx, (unsigned) n), 256, 0, (cudaStream_t) stream>>>(a);
+ check_launch("copy_from_mapped_multi");
+}
+#endif
+
void copy_i32_from_mapped(int32_t* dst, const int32_t* src, int64_t n, void* stream) {
if (n <= 0) return;
copy_i32_from_mapped_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(dst, (const volatile int32_t*) src, (int) n);
check_launch("copy_i32_from_mapped");
}
+#if defined(__HIPCC__) // AMD keeps one copy a launch
+void copy_from_mapped_multi(const MappedCopy* copies, int n, void* stream) {
+ for (int i = 0; i < n; ++i)
+ copy_i32_from_mapped((int32_t*) copies[i].dst, (const int32_t*) copies[i].src, copies[i].words, stream);
+}
+#endif
+
void doorbell_ring(uint32_t* d_seq, void* stream) {
if (d_seq == nullptr) return;
doorbell_ring_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(d_seq);
diff --git a/src/kernels/cuda/quantize_act.cu b/src/kernels/cuda/quantize_act.cu
index ddd14dfbb..0e8e03a5a 100644
--- a/src/kernels/cuda/quantize_act.cu
+++ b/src/kernels/cuda/quantize_act.cu
@@ -97,6 +97,7 @@ __global__ void quantize_q8_0_kernel(const float* __restrict__ x, uint8_t* __res
/// `moe_hit_parity`. This function's job is different: it must match **this engine's own CPU reference**,
/// because a hit and a miss for the same expert on the same layer have to produce the same number. The CPU
/// path is the reference - C1 passes on it - so the hit path is brought to it, not the reverse.
+#if defined(__HIPCC__) // AMD keeps the thread-a-block kernel
__global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks,
float* __restrict__ scales, long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
@@ -126,6 +127,40 @@ __global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t
}
}
+#else
+// A warp a block, lane i on value i: the block's |max| is a max over the same values (0 for none above it, as the
+// serial scan from 0 through fmaxf), so every byte is the per-thread loop's.
+__global__ void quantize_q8_0_scaled_kernel(const float* __restrict__ x, uint8_t* __restrict__ blocks,
+ float* __restrict__ scales, long long n_blocks) {
+ const long long b = ((long long) blockIdx.x * blockDim.x + threadIdx.x) >> 5;
+ const int i = (int) (threadIdx.x & 31);
+ if (b >= n_blocks) return;
+ const float xi = x[b * QK8_0 + i];
+ uint8_t* out = blocks + b * 34;
+
+ float amax = fmaxf(0.0f, fabsf(xi));
+ for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
+ // VERBATIM from `cpu/expert.cpp:144-145`, including the `amax > 0` guard, so the fp32 value written here
+ // is bit-identical to the `s` the CPU path used.
+ const float s = amax > 0.f ? amax / 127.f : 0.f;
+ const float inv = s > 0.f ? 1.f / s : 0.f;
+ if (i == 0) {
+ scales[b] = s;
+ const uint16_t d16bits = f16_from_f32(s);
+ out[0] = (uint8_t) (d16bits & 0xFF);
+ out[1] = (uint8_t) (d16bits >> 8);
+ }
+ // VERBATIM from `cpu/expert.cpp:159-162`: reciprocal multiply, then `t + copysign(0.5, t)` truncated
+ // toward zero, which is `lround`'s rule - round half away from zero.
+ const float t = xi * inv;
+ const float r = t + (t >= 0.f ? 0.5f : -0.5f);
+ int v = (int) r;
+ v = v < -127 ? -127 : (v > 127 ? 127 : v);
+ out[2 + i] = (uint8_t) (int8_t) v;
+}
+
+#endif
+
__global__ void dequant_q8_0_kernel(const uint8_t* __restrict__ blocks, float* __restrict__ x,
long long n_blocks) {
const long long b = (long long) blockIdx.x * blockDim.x + threadIdx.x;
@@ -254,7 +289,11 @@ void quantize_q8_0_scaled(const float* x, uint8_t* blocks, float* scales, int64_
}
const long long nb = n / QK8_0;
const int threads = 128;
+#if defined(__HIPCC__)
const unsigned grid = (unsigned) ((nb + threads - 1) / threads);
+#else
+ const unsigned grid = (unsigned) ((nb + threads / 32 - 1) / (threads / 32)); // a warp a block
+#endif
quantize_q8_0_scaled_kernel<<<grid, threads, 0, (cudaStream_t) stream>>>(x, blocks, scales, nb);
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) {