From d1dec64362e989a9aabd705365170cf507f9574b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 20:00:35 +0200 Subject: [PATCH 01/12] verify: STRATA_TAP_FILE, an env-gated dump of the hidden states at chosen layers per verified row (DFlash2 acceptance experiment; off by default, no new graph nodes without it) --- include/strata/core/verify.hpp | 12 +++++ include/strata/kernels/verify_kernels.hpp | 3 ++ src/core/verify.cpp | 57 +++++++++++++++++++++++ src/kernels/cuda/verify_kernels.cu | 13 ++++++ 4 files changed, 85 insertions(+) diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index 87e4ef9e..b2ea8192 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -547,6 +547,18 @@ private: int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}] float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids + // STRATA_TAP_FILE (off by default; nothing is allocated or captured without it): the DFlash2 experiment's hook. + // After each layer in STRATA_TAP_LAYERS (default 5,15,25,35,45) the window copies the layer's completed output + // (the residual with its pending FFN write applied, the mean of the hc streams) per row; run() appends + // (pos, token, taps) records to the file. + bool tap_on_ = false; + std::vector tap_layers_; ///< the tapped layer ids (zero-based, completed outputs) + std::vector tap_slot_; ///< layer -> slot in tap_layers_, or -1 + float* tap_dev_ = nullptr; ///< [max_t][n_taps][n_embd] + float* tap_scratch_ = nullptr; ///< one row's streams, [hc][n_embd] + float* h_tap_ = nullptr; float* m_tap_ = nullptr; ///< the mapped copy of tap_dev_ + std::FILE* tap_file_ = nullptr; + void tap_write(int T, const int32_t* tokens, int64_t pos0); uint32_t* h_nf_ = nullptr; uint32_t* m_nf_ = nullptr; // #879: kVerifyMaxT * kNonfiniteBlocks flags int nf_row_ = -1; ///< nonfinite_row() int64_t nf_pos_ = -1; ///< nonfinite_pos() diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 45bc70e1..e7dd1392 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -123,6 +123,9 @@ void embedding_gather_dev(const uint8_t* codes, const float* scales, const float uint64_t row_groups, float* out, void* stream); /// R[t][c][:] = x[t][:] for the hc streams. void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_tok, void* stream); +/// out[:n_embd] = the mean of the hc streams of ONE row R[hc][n_embd] (the DFlash2 drafter's target features; only the +/// STRATA_TAP_FILE hook calls it). +void hc_mean_streams(const float* R, float* out, int64_t n_embd, int hc, void* stream); /// dst[:n] = src[(*index) * stride + :n] (index read from device memory; a negative index copies nothing). void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index c90768ae..c9f48a74 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -627,6 +627,10 @@ Verifier::~Verifier() { if (h_commitb_) cudaFreeHost(h_commitb_); if (qcnt_) cudaFree(qcnt_); if (d_spec_) cudaFree(d_spec_); + if (tap_file_) std::fclose(tap_file_); + if (tap_dev_) cudaFree(tap_dev_); + if (tap_scratch_) cudaFree(tap_scratch_); + if (h_tap_) cudaFreeHost(h_tap_); if (logit_bias_device_) cudaFree(logit_bias_device_); if (cs_ && cs_ != ext_stream_) cudaStreamDestroy(cs_); // set_stream: the stage's stream, shared, not ours if (sh_cs_) cudaStreamDestroy(sh_cs_); @@ -654,6 +658,18 @@ Verifier::~Verifier() { if (h) cudaFreeHost(h); } +// STRATA_TAP_FILE: one record per row of the window: int32 position, int32 input token, then n_taps x n_embd floats +void Verifier::tap_write(int T, const int32_t* tokens, int64_t pos0) { + if (tap_file_ == nullptr) return; + const size_t per = tap_layers_.size() * (size_t) g_->n_embd; + for (int t = 0; t < T; ++t) { + const int32_t hdr[2] = {(int32_t) (pos0 + t), tokens[t]}; + std::fwrite(hdr, sizeof hdr, 1, tap_file_); + std::fwrite(h_tap_ + (size_t) t * per, sizeof(float), per, tap_file_); + } + std::fflush(tap_file_); +} + bool Verifier::set_logit_bias(const std::vector& bias, std::string& err) { if (next_ && !next_->set_logit_bias(bias, err)) return false; if (le_ < g_->n_layers) return true; @@ -763,6 +779,36 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) && mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_); if (!ok) { err = "verify: mapped staging allocation failed " + strata::core::pin_exhausted_hint(); return false; } + // STRATA_TAP_FILE: the DFlash2 experiment's hook (see verify.hpp); off unless the variable is set + if (const char* tap_path = std::getenv("STRATA_TAP_FILE"); tap_path != nullptr && tap_path[0] != '\0' && lb_ == 0 && + le_ == g.n_layers) { + tap_layers_.clear(); + const char* tl = std::getenv("STRATA_TAP_LAYERS"); + std::string list = tl != nullptr && tl[0] != '\0' ? tl : "5,15,25,35,45"; + for (size_t i = 0; i < list.size();) { + const size_t j = list.find(',', i); + const int l = std::atoi(list.substr(i, j == std::string::npos ? std::string::npos : j - i).c_str()); + if (l >= 0 && l < g.n_layers - 1) tap_layers_.push_back(l); + if (j == std::string::npos) break; + i = j + 1; + } + tap_slot_.assign((size_t) g.n_layers, -1); + for (size_t i = 0; i < tap_layers_.size(); ++i) tap_slot_[(size_t) tap_layers_[i]] = (int) i; + const size_t nt = tap_layers_.size(); + if (nt == 0 || cudaMalloc((void**) &tap_dev_, (size_t) T * nt * N * 4) != cudaSuccess || + cudaMalloc((void**) &tap_scratch_, (size_t) HC * N * 4) != cudaSuccess || + !mapped((size_t) T * nt * N * 4, (void**) &h_tap_, (void**) &m_tap_)) { + err = "verify: the STRATA_TAP_FILE buffers could not be allocated"; + return false; + } + tap_file_ = std::fopen(tap_path, "wb"); + if (tap_file_ == nullptr) { err = std::string("verify: cannot write STRATA_TAP_FILE ") + tap_path; return false; } + const int32_t hdr[4] = {0x50415453 /* 'STAP' */, 1, (int32_t) N, (int32_t) nt}; + std::fwrite(hdr, sizeof hdr, 1, tap_file_); + for (int l : tap_layers_) { const int32_t v = l; std::fwrite(&v, sizeof v, 1, tap_file_); } + tap_on_ = true; + std::fprintf(stderr, "strata: STRATA_TAP_FILE %s: %zu taps of %lld floats per row\n", tap_path, nt, (long long) N); + } if (bal_ != nullptr) { // set_pcie_balance: four stamp words per (layer, group) if (!mapped((size_t) g.n_layers * 2 * 4 * 8, (void**) &h_bal_, (void**) &m_bal_)) { err = "verify: mapped balance stamps allocation failed"; @@ -2132,6 +2178,15 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n, device_plan_ ? skip_ + grp : nullptr, ring, cs); stamp(l, 24, grp); + if (tap_on_ && !batch_rec_ && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0) { + // the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it) + const int64_t nt = (int64_t) tap_layers_.size(); + for (int t = tb; t < te; ++t) { + cudaMemcpyAsync(tap_scratch_, Rt(t), (size_t) HC * N * 4, cudaMemcpyDeviceToDevice, cs); + gr_write(tap_scratch_, bo_ + t * N, inj2_ + t * HC, gs, tap_scratch_, cs); + hc_mean_streams(tap_scratch_, tap_dev_ + ((size_t) t * nt + (size_t) tap_slot_[(size_t) l]) * N, N, (int) HC, cs); + } + } if (l == g.n_layers - 1) { if (!fuse_head_gr) { if (dec_batch && !g_no_multi_gr) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs); @@ -2259,6 +2314,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (nan_guard_on()) strata::kernels::logits_nonfinite_rows(head_logits_, T, (int) n_vocab_, m_nf_, cs); } stamp(g.n_layers, 1, 0); + if (tap_on_ && !batch_rec_) copy_from_mapped(m_tap_, tap_dev_, (int64_t) T * (int64_t) tap_layers_.size() * N, cs); return true; } @@ -3040,6 +3096,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } } for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t]; + if (tap_on_ && !batch_rec_) tap_write(T, tokens, pos0); note_nonfinite(T, nullptr); if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) { // debug: the first non-finite head static bool reported = false; diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index a451d9bd..dba0f101 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -580,6 +580,14 @@ __global__ void broadcast_streams_kernel(const float* __restrict__ x, float* __r R[(size_t) t * n * hc + i] = x[(size_t) t * n + i % n]; } +__global__ void hc_mean_streams_kernel(const float* __restrict__ R, float* __restrict__ out, int64_t n, int hc) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float s = 0.0f; + for (int c = 0; c < hc; ++c) s += R[(size_t) c * n + i]; + out[i] = s / (float) hc; +} + __global__ void copy_indexed_kernel(float* __restrict__ dst, const float* __restrict__ src, int64_t stride, const int32_t* __restrict__ index, int64_t n) { const int idx = *index; @@ -1514,6 +1522,11 @@ void broadcast_streams(const float* x, float* R, int64_t n_embd, int hc, int n_t check("broadcast_streams"); } +void hc_mean_streams(const float* R, float* out, int64_t n_embd, int hc, void* stream) { + hc_mean_streams_kernel<<<(unsigned) ((n_embd + 255) / 256), 256, 0, (cudaStream_t) stream>>>(R, out, n_embd, hc); + check("hc_mean_streams"); +} + void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* index, int64_t n, void* stream) { const unsigned blocks = (unsigned) ((n + 255) / 256 < 64 ? (n + 255) / 256 : 64); copy_indexed_kernel<<>>(dst, src, stride, index, n); From 17c9b92bc913976e2117d9e935b4cd155cf484d1 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 20:10:56 +0200 Subject: [PATCH 02/12] generate: STRATA_SPEC_T_CYCLE, a bench-only cycle of the verify window size with a per-width cost line (off by default) --- src/program/generate.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index dbc0cf83..d7116d2d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -16187,6 +16187,20 @@ int main(int argc, char** argv) { std::vector drafts((size_t) o.spec, 0); std::vector dprob((size_t) o.spec, 1.0f); std::vector window_hist((size_t) o.spec + 1, 0); + // STRATA_SPEC_T_CYCLE=1,2,3,4,5,6,7,8 (bench only, off by default): the window size cycles through the list, so one run + // measures the cost of each verify width (with --spec-oracle drafts every row is accepted); the first round of a + // width (its graph capture) is not counted + std::vector t_cycle; + if (const char* tc = std::getenv("STRATA_SPEC_T_CYCLE"); tc != nullptr && tc[0] != '\0') { + for (const char* q = tc; *q != '\0';) { + const int v = std::atoi(q); + if (v >= 1 && v <= o.spec) t_cycle.push_back(v); + while (*q != '\0' && *q != ',') ++q; + if (*q == ',') ++q; + } + } + std::vector t_cycle_ms((size_t) o.spec + 1, 0.0); + std::vector t_cycle_n((size_t) o.spec + 1, 0), t_cycle_seen((size_t) o.spec + 1, 0); // plan v0.3 P6: with a native pack the first window is the last prompt token alone (it produces the first // generated token and the MTP's first cell); otherwise the token loop already did that. bool first_window = native_pack; @@ -16258,6 +16272,7 @@ int main(int argc, char** argv) { while (T < S_mtp && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T; } if (first_window) T = 1; + if (!t_cycle.empty() && !first_window) T = t_cycle[(size_t) (rounds % (int64_t) t_cycle.size())]; bool from_sfx = false; int sfx_match = 0; if (o.suffix_draft > 0 && !first_window) { @@ -16400,6 +16415,10 @@ int main(int argc, char** argv) { p += a + 1; const double round_ms = std::chrono::duration(Clock::now() - t0).count(); total_ms += round_ms; + if (!t_cycle.empty() && timed_round && T <= o.spec && t_cycle_seen[(size_t) T]++ > 0) { + t_cycle_ms[(size_t) T] += round_ms; + ++t_cycle_n[(size_t) T]; + } if (timed_round && chain_n == 0) policy.observe(from_sfx, T, a, sfx_match, round_ms); else if (timed_round) policy.observe_chain(T_mtp, chain_n, a, cm, round_ms); if (rounds % 64 == 0) @@ -16430,6 +16449,12 @@ int main(int argc, char** argv) { if (o.lookup_chain > 0) std::printf("%-24s %lld windows, chained drafts accepted %lld of %lld\n", "lookup chain", (long long) chain_windows, (long long) chain_ok, (long long) chain_drafts); + if (!t_cycle.empty()) { + std::printf("%-24s", "window cost (ms/round)"); + for (size_t i = 1; i < t_cycle_ms.size(); ++i) + if (t_cycle_n[i] > 0) std::printf(" T%zu:%.2f(n=%lld)", i, t_cycle_ms[i] / (double) t_cycle_n[i], (long long) t_cycle_n[i]); + std::printf("\n"); + } std::printf("%-24s", "accepted per round"); for (size_t i = 0; i < accepted_hist.size(); ++i) std::printf(" %zu:%lld", i, (long long) accepted_hist[i]); std::printf("\n"); From 128223891e3a47b8daa0b66f00dd1645ddf6ac60 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 23:20:57 +0200 Subject: [PATCH 03/12] tools/dflash2: the torch port of the DFlash2 drafter and the scripts of the acceptance experiment (research tooling) --- tools/dflash2/README.md | 20 ++++ tools/dflash2/analyze2.py | 73 ++++++++++++ tools/dflash2/dflash2_ref.py | 201 ++++++++++++++++++++++++++++++++++ tools/dflash2/final_tables.py | 61 +++++++++++ tools/dflash2/mk_prompts.py | 40 +++++++ tools/dflash2/orch.py | 67 ++++++++++++ tools/dflash2/run_all2.py | 53 +++++++++ tools/dflash2/run_eval.py | 70 ++++++++++++ tools/dflash2/run_one.ps1 | 50 +++++++++ tools/dflash2/test_port.py | 45 ++++++++ 10 files changed, 680 insertions(+) create mode 100644 tools/dflash2/README.md create mode 100644 tools/dflash2/analyze2.py create mode 100644 tools/dflash2/dflash2_ref.py create mode 100644 tools/dflash2/final_tables.py create mode 100644 tools/dflash2/mk_prompts.py create mode 100644 tools/dflash2/orch.py create mode 100644 tools/dflash2/run_all2.py create mode 100644 tools/dflash2/run_eval.py create mode 100644 tools/dflash2/run_one.ps1 create mode 100644 tools/dflash2/test_port.py diff --git a/tools/dflash2/README.md b/tools/dflash2/README.md new file mode 100644 index 00000000..ff5c7155 --- /dev/null +++ b/tools/dflash2/README.md @@ -0,0 +1,20 @@ +# DFlash2 acceptance experiment (research tooling, not shipped) + +Measures how many tokens per round the incoai DFlash2 drafter for Qwen3.8-Flash-Next would get on OUR quantized target, offline, from the hidden states +the engine dumps. Results and method: phaseA-tests/notes-dflash2.md. All scripts keep the paths of the run (C:\dflash2-work on the owner PC, C:\strata-test\dflash2 +on the test box): edit them before reuse. + +Engine side (both off unless the variable is set): + +- `STRATA_TAP_FILE=` (+ `STRATA_TAP_LAYERS`, default `5,15,25,35,45`): `Verifier::record_window` copies each verified row's completed layer output (the mean of + the 4 hyper-connection streams, the quantity the drafter was trained on) and `Verifier::run` appends `pos, token, taps` records. +- `STRATA_SPEC_T_CYCLE=1,2,...,8` (CLI bench only): the verify window size cycles; the report line `window cost (ms/round)` gives the cost of each width. + +Scripts: + +- `mk_prompts.py` builds chat-template prompt ids with the server's own tokenizer and template. +- `orch.py [gen,genf,genfm,tap]` drives `run_one.ps1` on the test box: free generation (ids, MTP statistics), the same text with MTP only, and the + teacher-forced tap dump with oracle drafts (`--spec 8 --spec-oracle --spec-follow`, a 2-token prompt: a native pack never starts the speculative loop from a 1-token prompt). +- `dflash2_ref.py` is a plain-torch port of z-lab's `DFlash2DraftModel` (checked against it by `test_port.py`), with the target's embedding and head dequantized from the GGUF. +- `run_eval.py` (walk, a few block sizes), `run_all2.py` (every position, resumable: per-anchor correctness and the selector's confidences), `analyze2.py` and + `final_tables.py` (policies, speed estimates from the measured window costs). diff --git a/tools/dflash2/analyze2.py b/tools/dflash2/analyze2.py new file mode 100644 index 00000000..7db05068 --- /dev/null +++ b/tools/dflash2/analyze2.py @@ -0,0 +1,73 @@ +import json +import numpy as np + +TV = {1: 39.96, 2: 43.21, 3: 48.39, 4: 53.68, 5: 59.40, 6: 66.00, 7: 74.66, 8: 80.34} # ms per verify window, gfx1151 IQ3_S (STRATA_SPEC_T_CYCLE run) +HOST = 0.07 +PROD = {"chat_explain": (2.39, 43.33, 2.38, 43.97), "code_py": (2.27, 43.32, 2.22, 42.72), "code_cpp": (2.11, 40.60, 2.05, 39.93), + "math": (2.99, 52.38, 2.95, 52.29), "summarize": (2.81, 48.25, 2.75, 48.06), "json_extract": (3.25, 53.91, 3.22, 54.22), + "creative": (2.30, 42.77, 2.29, 42.65), "chat_advice": (1.94, 38.59, 1.92, 38.47)} # default tau, default tok/s, MTP-only tau, MTP-only tok/s +names = list(PROD) +A8 = json.load(open(r"C:\dflash2-work\anchors1_b8.json")) +A4 = json.load(open(r"C:\dflash2-work\anchors1_b4.json")) +SEQ = {n: json.load(open(r"C:\dflash2-work\p\%s.seq.json" % n)) for n in names} + + +def walk(rows, T_of, D, n): + by = {r["s"]: r for r in rows} + s = len(SEQ[n]["prompt"]) + tok = 0 + ms = 0.0 + rounds = 0 + hist = np.zeros(10) + while s in by: + r = by[s] + T = T_of(r) + a = 0 + while a < T - 1 and a < len(r["ok"]) and r["ok"][a]: + a += 1 + tok += a + 1 + ms += TV[T] + D + HOST + rounds += 1 + hist[T] += 1 + s += a + 1 + return tok / rounds, ms / rounds, 1000.0 * tok / ms, hist + + +def conf_T(theta, cap=8): + def f(r): + T = 1 + for p in r["p"][:cap - 1]: + if p >= theta: + T += 1 + else: + break + return T + return f + + +print("check, fixed b=8 walk tau vs the earlier walk: ", {n: round(walk(A8[n], lambda r: 8, 8, n)[0], 3) for n in names}) +print("check, fixed b=4 drafter walk tau: ", {n: round(walk(A4[n], lambda r: 4, 8, n)[0], 3) for n in names}) +out = {} +for D in (5.0, 8.0, 12.0): + print("\n=== drafter cost D = %.0f ms per round (verify cost + D + 0.07) ===" % D) + cfgs = [("fixed4 block-4 drafter", A4, lambda r: 4), ("fixed3 block-8 drafter", A8, lambda r: 3), + ("fixed4 block-8 drafter", A8, lambda r: 4), ("fixed5", A8, lambda r: 5), ("fixed6", A8, lambda r: 6), + ("fixed7", A8, lambda r: 7), ("fixed8", A8, lambda r: 8)] + for th in (0.3, 0.4, 0.5, 0.6, 0.7, 0.8): + for cap in (4, 5, 6, 8): + cfgs.append(("conf>=%.1f cap %d" % (th, cap), A8, conf_T(th, cap))) + print("%-26s" % "policy" + "".join("%15s" % n[:13] for n in names) + " mean-of-ratios") + best = None + for label, A, f in cfgs: + ratios, row = [], "%-26s" % label + for n in names: + tau, ms, tps, hist = walk(A[n], f, D, n) + ratios.append(tps / PROD[n][1]) + row += "%15s" % ("%.2f/%.1f(%+.0f%%)" % (tau, tps, 100 * (tps / PROD[n][1] - 1))) + m = 100 * (np.mean(ratios) - 1) + if D == 8.0 or label.startswith("fixed") or True: + print(row + " %+6.1f%%" % m) + if best is None or m > best[0]: + best = (m, label) + out[(D, label)] = m + print("best:", best) diff --git a/tools/dflash2/dflash2_ref.py b/tools/dflash2/dflash2_ref.py new file mode 100644 index 00000000..6702a8c6 --- /dev/null +++ b/tools/dflash2/dflash2_ref.py @@ -0,0 +1,201 @@ +"""A plain-torch port of the DFlash2 drafter (z-lab/dflash model.py, DFlash2DraftModel) for the offline acceptance experiment. + +Everything is fp32 on the CPU. The target's embedding table and LM head are the dequantized tensors of OUR GGUF (IQ4_XS embedding, +Q6_K head), the context features are the hidden states dumped by the engine's STRATA_TAP_FILE hook. +""" +import json, math, struct, sys +import numpy as np +import torch +import torch.nn.functional as F +from safetensors import safe_open + +sys.path.insert(0, r"C:\Users\AI-Server\Desktop\Strata\Public\Engine\third_party\llama.cpp\gguf-py") +import gguf +from gguf.quants import dequantize + + +def rms(x, w, eps=1e-6): + v = x.pow(2).mean(-1, keepdim=True) + return (x * torch.rsqrt(v + eps)) * w + + +def rotate_half(x): + h = x.shape[-1] // 2 + return torch.cat((-x[..., h:], x[..., :h]), dim=-1) + + +def load_dequant(path, rows, cols, qtype): + raw = np.fromfile(path, dtype=np.uint8) + bs, ts = gguf.GGML_QUANT_SIZES[qtype] + raw = raw.reshape(rows, cols // bs * ts) + return torch.from_numpy(dequantize(raw, qtype).astype(np.float32).reshape(rows, cols)) + + +class Drafter: + def __init__(self, st_path, cfg_path, embed, head, threads=6): + torch.set_num_threads(threads) + cfg = json.load(open(cfg_path)) + dc = cfg["dflash_config"] + self.H = cfg["hidden_size"] + self.L = cfg["num_hidden_layers"] + self.NH = cfg["num_attention_heads"] + self.NKV = cfg["num_key_value_heads"] + self.HD = cfg["head_dim"] + self.win = cfg["sliding_window"] + self.theta = cfg["rope_parameters"]["rope_theta"] + self.eps = cfg["rms_norm_eps"] + self.gs = dc["conv_group_size"] + self.ks = dc["conv_kernel_size"] + self.mask_id = dc["mask_token_id"] + self.top_k = dc["selector_top_k"] + self.taps = dc["target_layer_ids"] + self.embed = embed + self.head = head + self.w = {} + with safe_open(st_path, "pt") as f: + for k in f.keys(): + t = f.get_tensor(k) + # the two codebooks stay bf16 (only gathered rows are used); everything else fp32 + self.w[k] = t if "codebook" in k else t.float() + self.inv_freq = 1.0 / (self.theta ** (torch.arange(0, self.HD, 2, dtype=torch.float32) / self.HD)) + self.Kc = None + self.fast_head = False + self.head_bf16 = None + + def enable_fast_head(self): + self.head_bf16 = self.head.to(torch.bfloat16) + self.fast_head = True + + def cos_sin(self, pos): + fr = pos.float()[:, None] * self.inv_freq[None, :] + emb = torch.cat([fr, fr], dim=-1) + return emb.cos(), emb.sin() + + # ---- context: fc + hidden_norm over the tapped features, then every layer's K (norm + rope) and V + def set_context(self, feats): + """feats: [n, taps*H] float32, row j = the features of position j.""" + w = self.w + h = rms(feats @ w["fc.weight"].T, w["hidden_norm.weight"], self.eps) + n = h.shape[0] + cos, sin = self.cos_sin(torch.arange(n)) + self.Kc, self.Vc = [], [] + for l in range(self.L): + p = "layers.%d.self_attn." % l + k = (h @ w[p + "k_proj.weight"].T).view(n, self.NKV, self.HD) + v = (h @ w[p + "v_proj.weight"].T).view(n, self.NKV, self.HD) + k = rms(k, w[p + "k_norm.weight"], self.eps) + k = k * cos[:, None, :] + rotate_half(k) * sin[:, None, :] + self.Kc.append(k.permute(1, 0, 2).contiguous()) # [NKV, n, HD] + self.Vc.append(v.permute(1, 0, 2).contiguous()) + + def conv(self, x, dyn, base): + """_grouped_dynamic_convolve over a block x [b, H]; dyn [b, ks, groups]; base [ks, H].""" + b, H = x.shape + groups = H // self.gs + blocks = x.view(b, groups, self.gs) + out = torch.zeros_like(blocks) + for o in range(base.shape[0]): + vals = blocks if o == 0 else F.pad(blocks[:-o], (0, 0, 0, 0, o, 0)) + kern = base[o].float().view(1, groups, self.gs) + out = out + kern * vals + out = out + dyn[:, o, :, None] * vals + return out.view(b, H) + + def prepare(self, x, p): + w = self.w + groups = self.H // self.gs + dyn = (x @ w[p + "kernel_projection.weight"].T).view(x.shape[0], 2, self.ks, groups) + return self.conv(x, dyn[:, 0], w[p + "base_kernel"][0]), dyn[:, 1] + + def finish(self, x, dyn, p): + return self.conv(x, dyn, self.w[p + "base_kernel"][1]) + + # ---- one block: anchor token at position s (s >= 1), block size b; returns the drafted path (b-1 tokens), the candidate lists + def draft(self, s, anchor, b, greedy=True): + w = self.w + H, NH, NKV, HD = self.H, self.NH, self.NKV, self.HD + ids = torch.tensor([anchor] + [self.mask_id] * (b - 1)) + h = self.embed[ids] # [b, H] + pos = torch.arange(s, s + b) + cos, sin = self.cos_sin(pos) + # keys: context positions max(0, s-win+1) .. s-1 (a block row i sees ctx j when s+i-j < win), then the block + lo = max(0, s - self.win + 1) + for l in range(self.L): + p = "layers.%d." % l + r = h + x = rms(h, w[p + "input_layernorm.weight"], self.eps) + x, kdyn = self.prepare(x, p + "attention_conv.") + q = (x @ w[p + "self_attn.q_proj.weight"].T).view(b, NH, HD) + q = rms(q, w[p + "self_attn.q_norm.weight"], self.eps) + kn = rms((x @ w[p + "self_attn.k_proj.weight"].T).view(b, NKV, HD), w[p + "self_attn.k_norm.weight"], self.eps) + vn = (x @ w[p + "self_attn.v_proj.weight"].T).view(b, NKV, HD) + q = q * cos[:, None, :] + rotate_half(q) * sin[:, None, :] + kn = kn * cos[:, None, :] + rotate_half(kn) * sin[:, None, :] + Kc = self.Kc[l][:, lo:s, :] # [NKV, c, HD] + Vc = self.Vc[l][:, lo:s, :] + K = torch.cat([Kc, kn.permute(1, 0, 2)], dim=1) # [NKV, c+b, HD] + V = torch.cat([Vc, vn.permute(1, 0, 2)], dim=1) + c = Kc.shape[1] + kpos = torch.cat([torch.arange(lo, s), pos]) + vis = (pos[:, None] - kpos[None, :]).abs() < self.win # [b, c+b] + rep = NH // NKV + Kx = K.repeat_interleave(rep, dim=0) # [NH, c+b, HD] + Vx = V.repeat_interleave(rep, dim=0) + sc = torch.einsum("bhd,hkd->hbk", q, Kx) * (HD ** -0.5) + sc = sc.masked_fill(~vis[None], float("-inf")) + att = torch.softmax(sc, dim=-1) + o = torch.einsum("hbk,hkd->bhd", att, Vx).reshape(b, NH * HD) + o = o @ w[p + "self_attn.o_proj.weight"].T + o = self.finish(o, kdyn, p + "attention_conv.") + h = r + o + r = h + x = rms(h, w[p + "post_attention_layernorm.weight"], self.eps) + x, mdyn = self.prepare(x, p + "mlp_conv.") + m = (F.silu(x @ w[p + "mlp.gate_proj.weight"].T) * (x @ w[p + "mlp.up_proj.weight"].T)) @ w[p + "mlp.down_proj.weight"].T + m = self.finish(m, mdyn, p + "mlp_conv.") + h = r + m + self.last_all = rms(h, w["norm.weight"], self.eps) + out = self.last_all[1:] # rows 1..b-1 + if self.fast_head: + # candidates from a bf16 pass over the table (7x faster on this CPU), then the exact fp32 logits of the 32 best decide the top 16 + lb = (out.to(torch.bfloat16) @ self.head_bf16.T) + c32 = torch.topk(lb, 32, dim=-1, sorted=False).indices # [b-1, 32] + ex = torch.einsum("rkh,rh->rk", self.head[c32], out) # [b-1, 32] exact + unary, j16 = torch.topk(ex, self.top_k, dim=-1, sorted=False) + cand = c32.gather(-1, j16) + logits = None + else: + logits = out @ self.head.T # [b-1, V] + unary, cand = torch.topk(logits, self.top_k, dim=-1, sorted=False) + hp = out @ w["candidate_selector.hidden_projection.weight"].T # [b-1, rank] + A = w["candidate_selector.predecessor_codebook"] + B = w["candidate_selector.successor_codebook"] + pred = anchor + path, probs = [], [] + for i in range(b - 1): + sc = unary[i] + (B[cand[i]].float() @ (A[pred].float() * hp[i])) + j = int(torch.argmax(sc)) + probs.append(float(torch.softmax(sc, dim=-1)[j])) # the selector's own probability of the pick (a confidence) + pred = int(cand[i][j]) + path.append(pred) + top1 = (cand.gather(-1, unary.argmax(-1, keepdim=True))[:, 0] if logits is None else logits.argmax(-1)).tolist() + self.last_probs = probs + return path, top1 + + +def read_taps(path): + f = open(path, "rb") + magic, ver, N, nt = struct.unpack("<4i", f.read(16)) + assert magic == 0x50415453 and ver == 1, (hex(magic), ver) + layers = struct.unpack("<%di" % nt, f.read(4 * nt)) + rec = 8 + 4 * nt * N + data = f.read() + n = len(data) // rec + pos = np.empty(n, np.int32) + tok = np.empty(n, np.int32) + taps = np.empty((n, nt * N), np.float32) + for i in range(n): + o = i * rec + pos[i], tok[i] = struct.unpack_from("<2i", data, o) + taps[i] = np.frombuffer(data, np.float32, nt * N, o + 8) + return layers, pos, tok, taps diff --git a/tools/dflash2/final_tables.py b/tools/dflash2/final_tables.py new file mode 100644 index 00000000..9caa872b --- /dev/null +++ b/tools/dflash2/final_tables.py @@ -0,0 +1,61 @@ +import json +import numpy as np +import sys +sys.path.insert(0, r"C:\dflash2-work") +exec(open(r"C:\dflash2-work\analyze2.py").read().split("print(\"check")[0]) # TV, PROD, A8, A4, walk, conf_T, names + +fixed8 = {n: walk(A8[n], lambda r: 8, 8, n)[0] for n in names} +fixed4 = {n: walk(A4[n], lambda r: 4, 8, n)[0] for n in names} +fixed5 = {n: walk(A8[n], lambda r: 5, 8, n)[0] for n in names} +print("| prompt | MTP+lookup (default) tokens/round, tok/s | MTP only tokens/round, tok/s | DFlash2 block 4 | block 8 |") +print("| --- | --- | --- | --- | --- |") +for n in names: + p = PROD[n] + print("| %s | %.2f, %.1f | %.2f, %.1f | %.2f | %.2f |" % (n, p[0], p[1], p[2], p[3], fixed4[n], fixed8[n])) +print("| mean | %.2f, %.1f | %.2f, %.1f | %.2f | %.2f |" % (np.mean([PROD[n][0] for n in names]), np.mean([PROD[n][1] for n in names]), + np.mean([PROD[n][2] for n in names]), np.mean([PROD[n][3] for n in names]), np.mean(list(fixed4.values())), np.mean(list(fixed8.values())))) +print("gain of block-4 tokens/round over MTP default: mean of ratios %+.1f%%, per prompt %s" % ( + 100 * (np.mean([fixed4[n] / PROD[n][0] for n in names]) - 1), {n: round(100 * (fixed4[n] / PROD[n][0] - 1)) for n in names})) +print("gain of block-8 tokens/round over MTP default: mean of ratios %+.1f%%" % (100 * (np.mean([fixed8[n] / PROD[n][0] for n in names]) - 1))) + +# conditional acceptance by draft position (block 8, all anchors, conditional on all earlier correct) +cond = np.zeros(7); cn = np.zeros(7) +for n in names: + for r in A8[n]: + for i in range(7): + cn[i] += 1 + if r["ok"][i]: + cond[i] += 1 + else: + break +print("block-8 conditional acceptance by position (all prompts):", (cond / cn).round(3).tolist()) +cond4 = np.zeros(3); cn4 = np.zeros(3) +for n in names: + for r in A4[n]: + for i in range(3): + cn4[i] += 1 + if r["ok"][i]: + cond4[i] += 1 + else: + break +print("block-4 conditional acceptance by position (all prompts):", (cond4 / cn4).round(3).tolist()) + +print("\nspeed estimate table (tok/s), D = drafter cost per round") +pol = [("fixed 4 (block-4 drafter)", A4, lambda r: 4), ("fixed 5 (block-8 drafter)", A8, lambda r: 5), ("confidence>=0.5, up to 8", A8, conf_T(0.5, 8)), + ("confidence>=0.4, up to 6", A8, conf_T(0.4, 6))] +for label, A, f in pol: + for D in (5.0, 8.0, 12.0): + r_ = [] + tps_ = [] + for n in names: + tau, ms, tps, hist = walk(A[n], f, D, n) + r_.append(tps / PROD[n][1]) + tps_.append(tps) + print("%-28s D=%4.0f ms: mean %.1f tok/s (default %.1f): mean-of-ratios %+.1f%%, best %+.0f%% (%s), worst %+.0f%% (%s)" % ( + label, D, np.mean(tps_), np.mean([PROD[n][1] for n in names]), 100 * (np.mean(r_) - 1), + 100 * (max(r_) - 1), names[int(np.argmax(r_))], 100 * (min(r_) - 1), names[int(np.argmin(r_))])) +# window histogram of the confidence policy +print() +for n in names: + tau, ms, tps, hist = walk(A8[n], conf_T(0.5, 8), 8.0, n) + print(n, "conf>=0.5 cap 8: windows", {int(i): int(h) for i, h in enumerate(hist) if h}, "tau %.2f" % tau) diff --git a/tools/dflash2/mk_prompts.py b/tools/dflash2/mk_prompts.py new file mode 100644 index 00000000..78910f51 --- /dev/null +++ b/tools/dflash2/mk_prompts.py @@ -0,0 +1,40 @@ +"""Builds the chat-templated prompt ids for the DFlash2 acceptance experiment (same tokenizer and template the server uses).""" +import json, sys +from pathlib import Path + +REPO = Path(r"C:\Users\AI-Server\Desktop\Strata\GitHub\wt-022-dflash2") +sys.path.insert(0, str(REPO / "tools")) +sys.path.insert(0, str(REPO)) +import strata_tokenizer as ST +from serve.frontend import ChatTemplate + +tp = Path(r"C:\dflash2-work\tok") +vocab = json.loads((tp / "vocab.json").read_text(encoding="utf-8")) +tokens = [None] * len(vocab) +for t, i in vocab.items(): + tokens[i] = t +merges = (tp / "merges.txt").read_text(encoding="utf-8").split("\n") +types = json.loads((tp / "token_type.json").read_text()) +tok = ST.Tokenizer(tokens, merges, types) +tpl = ChatTemplate(tp / "chat_template.jinja") + +readme = (REPO / "README.md").read_text(encoding="utf-8")[:2600] + +PROMPTS = { + "chat_explain": "Explain how a hash map works and why lookups are O(1) on average. Then say when that guarantee breaks down. Keep it clear for a junior developer.", + "code_py": "Write a Python function that reads a web server log file, parses the timestamps (ISO-8601) and returns the five busiest one-minute windows with their request counts. Include a small test with pytest.", + "code_cpp": "Implement an LRU cache in C++17 with O(1) get and put using std::list and std::unordered_map. Show the class and a short main() that exercises it.", + "math": "A train leaves city A at 9:00 traveling at 80 km/h. A second train leaves city B, 450 km away, at 10:30 traveling toward A at 95 km/h. At what time do they meet, and how far from city A? Work it out step by step and check the result.", + "summarize": "Summarize the following text in exactly five bullet points, then give a one-sentence takeaway.\n\n" + readme, + "json_extract": "Extract the data below as JSON with the keys name, role, city, start_date (ISO format) and skills (a list). Output only the JSON.\n\nMaria Gonzalez joined the company on the 3rd of March 2021 as a senior data engineer. She works from the Lisbon office and her main tools are Spark, dbt, Airflow and a bit of Rust. Her colleague Tom Becker, a product designer from Vienna, started a year later, on 14 June 2022, and is good at Figma, user research and prototyping.", + "creative": "Write a short story (about 400 words) about a lighthouse keeper who discovers that the light has been answering messages from the sea. Give it a quiet, slightly eerie tone.", + "chat_advice": "I have a 12 GB graphics card and 64 GB of RAM. What are the trade-offs between running a large mixture-of-experts model with most of its experts in RAM versus a smaller dense model fully on the GPU? Give me a recommendation for daily coding help.", +} + +out = {} +for name, text in PROMPTS.items(): + s = tpl.render([{"role": "user", "content": text}]) + ids = tok.encode(s, parse_special=True) + out[name] = {"ids": ids, "text": s} + print(name, len(ids), repr(s[-60:])) +json.dump(out, open(r"C:\dflash2-work\prompts.json", "w")) diff --git a/tools/dflash2/orch.py b/tools/dflash2/orch.py new file mode 100644 index 00000000..fda18f59 --- /dev/null +++ b/tools/dflash2/orch.py @@ -0,0 +1,67 @@ +"""Runs the engine side of the DFlash2 experiment for one prompt on strix (foreground; one engine at a time).""" +import json, re, subprocess, sys, time +from pathlib import Path + +W = Path(r"C:\dflash2-work") +RW = "C:\\strata-test\\dflash2" + + +def ssh(cmd, timeout=1500): + r = subprocess.run(["ssh", "-o", "ServerAliveInterval=30", "strix", cmd], capture_output=True, text=True, timeout=timeout) + out = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if not l.startswith("**")) + return out + + +def scp_up(local, remote): + subprocess.run(["scp", "-q", str(local), "strix:" + remote.replace("\\", "/")], check=True, capture_output=True) + + +def scp_down(remote, local): + subprocess.run(["scp", "-q", "strix:" + remote.replace("\\", "/"), str(local)], check=True, capture_output=True) + + +def run_mode(mode, name, extra=""): + t = time.time() + out = ssh('powershell -NoProfile -ExecutionPolicy Bypass -File %s\\run_one.ps1 -Mode %s -Name %s %s' % (RW, mode, name, extra)) + print("[%s %s] %.0f s" % (mode, name, time.time() - t)) + print(out) + (W / "logs").mkdir(exist_ok=True) + (W / "logs" / ("%s_%s.log" % (mode, name))).write_text(out) + scp_down("%s\\out\\%s_%s.txt" % (RW, mode, name), W / "logs" / ("%s_%s.txt" % (mode, name))) + scp_down("%s\\out\\%s_%s.err" % (RW, mode, name), W / "logs" / ("%s_%s.err" % (mode, name))) + return out + + +def produced_ids(path): + txt = Path(path).read_text() + m = re.search(r"^output :(.*)$", txt, re.M) + return [int(x) for x in m.group(1).split()] if m else [] + + +def main(name, max_new, steps): + prompts = json.load(open(W / "prompts.json")) + pids = prompts[name]["ids"] + if "gen" in steps: + run_mode("gen", name, "-MaxNew %d" % max_new) + out = produced_ids(W / "logs" / ("gen_%s.txt" % name)) + print(name, "prompt", len(pids), "generated", len(out), "tail", out[-3:]) + seq = pids + out + (W / "p" / ("%s.out.ids" % name)).write_text(",".join(map(str, out))) + (W / "p" / ("%s.first.ids" % name)).write_text(",".join(map(str, seq[:2]))) + (W / "p" / ("%s.rest.ids" % name)).write_text(",".join(map(str, seq[2:]))) + json.dump({"prompt": pids, "out": out}, open(W / "p" / ("%s.seq.json" % name), "w")) + for k in ("out", "first", "rest"): + scp_up(W / "p" / ("%s.%s.ids" % (name, k)), "%s\\p\\%s.%s.ids" % (RW, name, k)) + for mode in ("genf", "genfm", "tap"): + if mode in steps: + run_mode(mode, name) + if "tap" in steps: + (W / "taps").mkdir(exist_ok=True) + scp_down("%s\\out\\tap_%s.bin" % (RW, name), W / "taps" / ("%s.bin" % name)) + + +if __name__ == "__main__": + name = sys.argv[1] + max_new = int(sys.argv[2]) + steps = sys.argv[3].split(",") if len(sys.argv) > 3 else ["gen", "genf", "genfm", "tap"] + main(name, max_new, steps) diff --git a/tools/dflash2/run_all2.py b/tools/dflash2/run_all2.py new file mode 100644 index 00000000..bc30dd72 --- /dev/null +++ b/tools/dflash2/run_all2.py @@ -0,0 +1,53 @@ +"""Per-anchor drafter results at EVERY generated position (stride 1), resumable: the exact path and the selector's confidences.""" +import json, sys, time +from pathlib import Path +import numpy as np +import torch +sys.path.insert(0, r"C:\dflash2-work") +import dflash2_ref as R + +W = Path(r"C:\dflash2-work") +names = sys.argv[1].split(",") +b = int(sys.argv[2]) +threads = int(sys.argv[3]) +budget = float(sys.argv[4]) # seconds this call may spend before it saves and stops +t_start = time.time() +embed = R.load_dequant(str(W / "embd_iq4xs.bin"), 248320, 2560, R.gguf.GGMLQuantizationType.IQ4_XS) +head = R.load_dequant(str(W / "head_q6k.bin"), 248320, 2560, R.gguf.GGMLQuantizationType.Q6_K) +d = R.Drafter(str(W / "drafter.safetensors"), str(W / "drafter_config.json"), embed, head, threads=threads) +d.enable_fast_head() +out_path = W / ("anchors1_b%d.json" % b) +res = json.load(open(out_path)) if out_path.exists() else {} +for name in names: + if res.get(name + "#done"): + continue + seqj = json.load(open(W / "p" / ("%s.seq.json" % name))) + seq = seqj["prompt"] + seqj["out"] + layers, pos, tok, taps = R.read_taps(str(W / "taps" / ("%s.bin" % name))) + keep = pos < len(seq) + pos, tok, taps = pos[keep], tok[keep], taps[keep] + n = int(pos.max()) + 1 + feats = np.zeros((n, taps.shape[1]), np.float32) + for i in range(len(pos)): + feats[pos[i]] = taps[i] + feats[0] = feats[1] + d.set_context(torch.from_numpy(feats)) + rows = res.get(name, []) + s0 = rows[-1]["s"] + 1 if rows else len(seqj["prompt"]) + t1 = time.time() + finished = True + with torch.no_grad(): + for s in range(s0, len(seq) - b): + path, top1 = d.draft(s, seq[s], b) + truth = seq[s + 1:s + b] + rows.append({"s": s, "ok": [int(path[i] == truth[i]) for i in range(b - 1)], "p": [round(x, 4) for x in d.last_probs]}) + if time.time() - t_start > budget: + finished = False + break + res[name] = rows + if finished: + res[name + "#done"] = True + json.dump(res, open(out_path, "w")) + print(name, b, len(rows), "anchors so far, %.0f s" % (time.time() - t1), "done" if finished else "PAUSED", flush=True) + if not finished: + break diff --git a/tools/dflash2/run_eval.py b/tools/dflash2/run_eval.py new file mode 100644 index 00000000..77056a02 --- /dev/null +++ b/tools/dflash2/run_eval.py @@ -0,0 +1,70 @@ +"""Offline DFlash2 acceptance on OUR quantized target: walks each prompt's dumped sequence the way the speculative loop would +(anchor, draft block, accept the leading matches of the drafted path against the engine's own greedy tokens, move on).""" +import json, sys, time +from pathlib import Path +import numpy as np +import torch +sys.path.insert(0, r"C:\dflash2-work") +import dflash2_ref as R + +W = Path(r"C:\dflash2-work") +names = sys.argv[1].split(",") +blocks = [int(x) for x in sys.argv[2].split(",")] if len(sys.argv) > 2 else [4, 8] +threads = int(sys.argv[3]) if len(sys.argv) > 3 else 6 + +t0 = time.time() +embed = R.load_dequant(str(W / "embd_iq4xs.bin"), 248320, 2560, R.gguf.GGMLQuantizationType.IQ4_XS) +head = R.load_dequant(str(W / "head_q6k.bin"), 248320, 2560, R.gguf.GGMLQuantizationType.Q6_K) +print("dequantized embed/head in %.0f s" % (time.time() - t0), flush=True) +d = R.Drafter(str(W / "drafter.safetensors"), str(W / "drafter_config.json"), embed, head, threads=threads) +res_path = W / "eval_results.json" +results = json.load(open(res_path)) if res_path.exists() else {} + +for name in names: + seqj = json.load(open(W / "p" / ("%s.seq.json" % name))) + prompt, out = seqj["prompt"], seqj["out"] + seq = prompt + out + layers, pos, tok, taps = R.read_taps(str(W / "taps" / ("%s.bin" % name))) + keep = pos < len(seq) # the tail of the last window is padding (zeros) past the sequence + pos, tok, taps = pos[keep], tok[keep], taps[keep] + n = int(pos.max()) + 1 + feats = np.zeros((n, taps.shape[1]), np.float32) + seen = np.zeros(n, bool) + for i in range(len(pos)): # the last record of a position wins + feats[pos[i]] = taps[i] + seen[pos[i]] = True + assert tok[i] == seq[pos[i]], ("token mismatch at", pos[i], tok[i], seq[pos[i]]) + if not seen[0] and seen[1]: # position 0 goes through the batched prefill (no tap): the next row stands in + feats[0] = feats[1] + seen[0] = True + assert seen.all(), "positions missing: %s" % np.where(~seen)[0][:5] + d.set_context(torch.from_numpy(feats)) + print("%s: prompt %d, generated %d, tap records %d, layers %s" % (name, len(prompt), len(out), len(pos), layers), flush=True) + results.setdefault(name, {}) + for b in blocks: + s = len(prompt) # the first generated token is the first anchor, as after a prefill + cyc, cond_ok, cond_n = [], np.zeros(b - 1), np.zeros(b - 1) + top1_ok = np.zeros(b - 1) + t1 = time.time() + with torch.no_grad(): + while s + b <= len(seq) - 0 and s < n: + path, top1 = d.draft(s, seq[s], b) + truth = seq[s + 1:s + b] + a = 0 + while a < b - 1 and path[a] == truth[a]: + a += 1 + for i in range(b - 1): # conditional on all earlier correct + if i <= a: + cond_n[i] += 1 + cond_ok[i] += (i < a) + if i <= a and top1[i] == truth[i]: + top1_ok[i] += 1 + cyc.append(a + 1) + s += a + 1 + tau = float(np.mean(cyc)) + results[name]["b%d" % b] = {"anchors": len(cyc), "tokens_per_round": tau, + "cond_accept": (cond_ok / np.maximum(cond_n, 1)).round(3).tolist(), + "hist": np.bincount(cyc, minlength=b + 1).tolist()} + print(" block %d: %d rounds, %.3f tokens per round, cond %s (%.0f s)" % + (b, len(cyc), tau, (cond_ok / np.maximum(cond_n, 1)).round(2).tolist(), time.time() - t1), flush=True) + json.dump(results, open(res_path, "w"), indent=1) diff --git a/tools/dflash2/run_one.ps1 b/tools/dflash2/run_one.ps1 new file mode 100644 index 00000000..dc0c38bc --- /dev/null +++ b/tools/dflash2/run_one.ps1 @@ -0,0 +1,50 @@ +# DFlash2 experiment runner on strix. One engine process at a time; reads ids from C:\strata-test\dflash2\p\.*.ids +# usage: run_one.ps1 -Mode gen|genf|genfm|tap|tcycle -Name [-MaxNew N] [-Cycle 1,2,...] +param([string]$Mode, [string]$Name, [int]$MaxNew = 900, [string]$Cycle = "", [string]$Exe = "strata-hook.exe", [string]$Tag = "", [string]$Extra = "") +$ErrorActionPreference = "Continue" +$W = "C:\strata-test\dflash2" +$D = "C:\Users\Administrator\Documents\Strata" +$OWN = "C:\Users\Administrator\AppData\Local\Strata\terminal\0.1.46.1" +$env:LOCALAPPDATA = "C:\strata-test\la" +$env:APPDATA = "C:\strata-test\la" +New-Item -ItemType Directory -Force -Path $env:LOCALAPPDATA | Out-Null +New-Item -ItemType Directory -Force -Path "$W\out" | Out-Null +$env:STRATA_ARENA_PIN_GIB = "none" +$env:PATH = "$W\eng\rocm\bin;" + $env:PATH +$mtp = $D + "\mtp\rt" +$base = @("--pack", "$D\packs\iq3_s", + "--native", "$D\models\IQ3_S\Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "--ple-gguf", "$D\models\IQ3_S\Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", + "--expert-profile", "$OWN\data\expert-profile.bin", + "--expert-cache", "auto", "--prefill", "auto", "--max-context", "4096", "--kv", "int8", "--vram-reserve-mib", "700", "--greedy") +$exe = "$W\eng\$Exe" +$out = "$W\out\${Mode}_${Name}${Tag}.txt" +$err = "$W\out\${Mode}_${Name}${Tag}.err" +Remove-Item $out, $err -ErrorAction SilentlyContinue +if ($Mode -eq "gen") { + $ids = (Get-Content "$W\p\$Name.prompt.ids" -Raw).Trim() + $a = $base + @("--spec", "4", "--spec-min-p", "0.5", "--mtp", $mtp, "--max-new", "$MaxNew", "--stop-eos", "--tokens", $ids) +} elseif ($Mode -eq "genf" -or $Mode -eq "genfm") { + # the production flags on a fixed text: the drafts are judged against the continuation in .out.ids + $ids = (Get-Content "$W\p\$Name.prompt.ids" -Raw).Trim() + $n = (Get-Content "$W\p\$Name.out.ids" -Raw).Split(",").Count + $a = $base + @("--spec", "4", "--spec-min-p", "0.5", "--mtp", $mtp, "--spec-follow", "$W\p\$Name.out.ids", "--max-new", "$n", "--tokens", $ids) + if ($Mode -eq "genfm") { $a += @("--suffix-draft", "0") } +} elseif ($Mode -eq "tap") { + $env:STRATA_TAP_FILE = "$W\out\tap_$Name.bin" + Remove-Item $env:STRATA_TAP_FILE -ErrorAction SilentlyContinue + $first = (Get-Content "$W\p\$Name.first.ids" -Raw).Trim() + $n = (Get-Content "$W\p\$Name.rest.ids" -Raw).Split(",").Count + $a = $base + @("--spec", "8", "--spec-oracle", "$W\p\$Name.rest.ids", "--spec-follow", "$W\p\$Name.rest.ids", "--max-new", "$n", "--tokens", $first) +} elseif ($Mode -eq "tcycle") { + $env:STRATA_SPEC_T_CYCLE = $Cycle + $first = (Get-Content "$W\p\$Name.first.ids" -Raw).Trim() + $a = $base + @("--spec", "8", "--spec-oracle", "$W\p\$Name.rest.ids", "--spec-follow", "$W\p\$Name.rest.ids", "--max-new", "$MaxNew", "--tokens", $first) +} else { "bad mode"; exit 2 } +if ($Extra -ne "") { $a += $Extra.Split("_") } +Set-Location $OWN +$t0 = Get-Date +$p = Start-Process -FilePath $exe -ArgumentList $a -RedirectStandardOutput $out -RedirectStandardError $err -NoNewWindow -PassThru +$p.WaitForExit() +"EXIT " + $p.ExitCode + " after " + [int]((Get-Date) - $t0).TotalSeconds + " s" +Get-Content $out | Select-String -Pattern "^decode|^speculation|^window|^accepted|^mtp|^suffix|^verify window" | ForEach-Object { $_.Line.Substring(0, [Math]::Min(300, $_.Line.Length)) } diff --git a/tools/dflash2/test_port.py b/tools/dflash2/test_port.py new file mode 100644 index 00000000..335363bd --- /dev/null +++ b/tools/dflash2/test_port.py @@ -0,0 +1,45 @@ +import sys, importlib.util, json, torch +sys.path.insert(0, r"C:\dflash2-work") +import dflash2_ref as R +torch.manual_seed(0) +# the reference (z-lab) model on transformers 4.57 +spec = importlib.util.spec_from_file_location("ghm", r"C:\Users\AI-Server\Desktop\Strata\phaseA-tests\ornith_tmp\gh_model.py") +ghm = importlib.util.module_from_spec(spec); spec.loader.exec_module(ghm) +from transformers.models.qwen3.modeling_qwen3 import Qwen3Config +cfgd = json.load(open(r"C:\dflash2-work\drafter_config.json")) +c = Qwen3Config(**{k: v for k, v in cfgd.items() if k in ("hidden_size","intermediate_size","num_hidden_layers","num_attention_heads","num_key_value_heads","head_dim","vocab_size","rms_norm_eps","max_position_embeddings","attention_bias","sliding_window","layer_types","use_sliding_window","max_window_layers")}) +c.rope_theta = cfgd["rope_parameters"]["rope_theta"] +c.dflash_config = cfgd["dflash_config"] +c.is_causal = False +c.num_target_layers = 48 +m = ghm.DFlash2DraftModel(c) +from safetensors.torch import load_file +sd = load_file(r"C:\dflash2-work\drafter.safetensors") +sd = {(k + ".weight" if k.startswith("candidate_selector.") and k.endswith("codebook") else k): v for k, v in sd.items()} +miss = m.load_state_dict(sd, strict=False); print("missing", miss.missing_keys[:5], "unexpected", miss.unexpected_keys[:5]) +m = m.float().eval() +# my port with a tiny random embed/head +V = 248320; H = 2560 +embed = torch.randn(V, H) * 0.02 +head = torch.randn(V, H) * 0.02 +d = R.Drafter(r"C:\dflash2-work\drafter.safetensors", r"C:\dflash2-work\drafter_config.json", embed, head) +n = 300; b = 8; s = 250 +feats = torch.randn(n, 5 * H) * 2.0 +d.set_context(feats) +anchor = 1234 +mine_path, _ = d.draft(s, anchor, b) +ids = torch.tensor([[anchor] + [d.mask_id] * (b - 1)]) +noise = embed[ids] +pos = torch.arange(0, s + b)[None] # context 0..s-1 then block +with torch.no_grad(): + out = m(position_ids=pos, noise_embedding=noise, target_hidden=feats[None, :s], past_key_values=None, use_cache=False) +print("shape", out.shape, "mine", d.last_all.shape) +err = (out[0] - d.last_all).abs().max().item() +print("max abs err all rows", err, "ref scale", out.abs().mean().item()) +# the selector path against the reference +logits = (out[:, 1:] @ head.T) +class Tgt: pass +with torch.no_grad(): + path, idx, q = m.candidate_selector.select(out[:, 1:], logits, torch.tensor([anchor]), 0.0) +print("ref path ", path[0].tolist()) +print("mine path", mine_path) From 5f426c38cb4bebc82d6f3a795ed601cadf98d54f Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 20 Oct 2026 23:32:05 +0200 Subject: [PATCH 04/12] tools/dflash2: q8test, the drafter with Q8_0 matrices keeps its acceptance --- tools/dflash2/q8test.py | 60 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 tools/dflash2/q8test.py diff --git a/tools/dflash2/q8test.py b/tools/dflash2/q8test.py new file mode 100644 index 00000000..30f2a154 --- /dev/null +++ b/tools/dflash2/q8test.py @@ -0,0 +1,60 @@ +"""Does a Q8_0 drafter (the matrices block-quantized like ggml Q8_0) keep the acceptance? Walk over two prompts, block 4 and 8.""" +import json, sys, time +from pathlib import Path +import numpy as np +import torch +sys.path.insert(0, r"C:\dflash2-work") +import dflash2_ref as R + +W = Path(r"C:\dflash2-work") +embed = R.load_dequant(str(W / "embd_iq4xs.bin"), 248320, 2560, R.gguf.GGMLQuantizationType.IQ4_XS) +head = R.load_dequant(str(W / "head_q6k.bin"), 248320, 2560, R.gguf.GGMLQuantizationType.Q6_K) +d = R.Drafter(str(W / "drafter.safetensors"), str(W / "drafter_config.json"), embed, head, threads=6) +d.enable_fast_head() + + +def q8_0(w): + """ggml Q8_0 along the last dimension: blocks of 32, scale = amax/127 stored as fp16, int8 codes""" + shp = w.shape + x = w.reshape(-1, 32) + amax = x.abs().amax(dim=1, keepdim=True) + sc = (amax / 127.0).to(torch.float16).float() + sc_safe = torch.where(sc == 0, torch.ones_like(sc), sc) + q = torch.round(x / sc_safe).clamp(-127, 127) + return (q * sc).reshape(shp) + + +def run(name, b, tag): + seqj = json.load(open(W / "p" / ("%s.seq.json" % name))) + seq = seqj["prompt"] + seqj["out"] + layers, pos, tok, taps = R.read_taps(str(W / "taps" / ("%s.bin" % name))) + keep = pos < len(seq) + pos, taps = pos[keep], taps[keep] + feats = np.zeros((int(pos.max()) + 1, taps.shape[1]), np.float32) + for i in range(len(pos)): + feats[pos[i]] = taps[i] + feats[0] = feats[1] + d.set_context(torch.from_numpy(feats)) + s = len(seqj["prompt"]) + cyc = [] + with torch.no_grad(): + while s + b <= len(seq): + path, _ = d.draft(s, seq[s], b) + truth = seq[s + 1:s + b] + a = 0 + while a < b - 1 and path[a] == truth[a]: + a += 1 + cyc.append(a + 1) + s += a + 1 + print("%s %s block %d: %.3f tokens per round (%d rounds)" % (tag, name, b, np.mean(cyc), len(cyc)), flush=True) + + +names = sys.argv[1].split(",") +orig = {k: v.clone() for k, v in d.w.items() if k.endswith("proj.weight") or k == "fc.weight" or k.endswith("kernel_projection.weight")} +for tag in ("fp32", "q8_0"): + if tag == "q8_0": + for k in orig: + d.w[k] = q8_0(orig[k]) + for n in names: + run(n, 4, tag) + run(n, 8, tag) From 7f97c35acaf39835b8587e1a73a90c76516b6d54 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 21 Oct 2026 14:04:15 +0200 Subject: [PATCH 05/12] DFlash2 drafter for Qwen3.8-Flash-Next: Q8_0 pack tool, GPU forward (conv, K/V ring, windowed attention, top-16 selector), permanent verify/prefill taps, --draft dflash2 --draft-model (opt-in, MTP stays the fallback) --- CMakeLists.txt | 9 +- include/strata/core/dflash2.hpp | 129 ++++++++ include/strata/core/verify.hpp | 7 + include/strata/kernels/dflash2.hpp | 66 ++++ include/strata/prefill/prefill.hpp | 10 + src/core/dflash2.cpp | 466 +++++++++++++++++++++++++++++ src/core/dflash2_parity.cpp | 95 ++++++ src/core/verify.cpp | 62 ++-- src/kernels/cuda/dflash2.cu | 412 +++++++++++++++++++++++++ src/prefill/prefill.cpp | 50 +++- src/program/generate.cpp | 83 ++++- tools/dflash2/mk_parity_case.py | 88 ++++++ tools/dflash2_pack.py | 127 ++++++++ 13 files changed, 1572 insertions(+), 32 deletions(-) create mode 100644 include/strata/core/dflash2.hpp create mode 100644 include/strata/kernels/dflash2.hpp create mode 100644 src/core/dflash2.cpp create mode 100644 src/core/dflash2_parity.cpp create mode 100644 src/kernels/cuda/dflash2.cu create mode 100644 tools/dflash2/mk_parity_case.py create mode 100644 tools/dflash2_pack.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7c686766..4ee0af93 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -336,6 +336,8 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_library(strata_core STATIC src/core/device.cu src/core/pinned.cu src/platform/memory.cpp src/core/graph.cpp src/core/weights.cpp src/core/layout.cpp) target_include_directories(strata_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + # the DFlash2 drafter (src/core/dflash2.cpp, src/kernels/cuda/dflash2.cu) exists in the CUDA and HIP builds; the Metal and SYCL builds compile without it + target_compile_definitions(strata_core PUBLIC STRATA_HAVE_DFLASH2=1) if(STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) # the runtime device check (src/core/device.cu) admits the cards this build was made for (#236) target_compile_definitions(strata_core PRIVATE STRATA_EXPERIMENTAL_SM60=1) @@ -418,6 +420,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/dequant_bf16.cu src/kernels/cuda/qsa_select.cu src/kernels/cuda/verify_kernels.cu + src/kernels/cuda/dflash2.cu src/kernels/cuda/iq_kernels.cu src/kernels/ngram.cpp src/ngram/ple_reader.cpp @@ -579,7 +582,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) # about arithmetic, and this one knows the ORDER the arithmetic happens in. add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp src/core/remote_expert_opt.cu - src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp + src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp src/core/dflash2.cpp src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp src/core/arch_defaults.cpp src/core/nv_defaults.cpp src/core/vmm.cpp src/core/conversation_file.cpp) target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) @@ -1081,6 +1084,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME verify_parity COMMAND verify_parity --selftest) endif() + # the DFlash2 drafter against the torch port on a synthetic case: needs the pack and a case file (tools/dflash2/mk_parity_case.py), so not a ctest + add_executable(dflash2_parity src/core/dflash2_parity.cpp) + target_include_directories(dflash2_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_parity PRIVATE strata_engine strata_kernels ${_strata_gpu_runtime_target}) add_executable(fused_gr_bench src/kernels/fused_gr_bench.cpp) target_include_directories(fused_gr_bench PRIVATE ${_strata_gpu_include_directories}) diff --git a/include/strata/core/dflash2.hpp b/include/strata/core/dflash2.hpp new file mode 100644 index 00000000..75aadb07 --- /dev/null +++ b/include/strata/core/dflash2.hpp @@ -0,0 +1,129 @@ +// include/strata/core/dflash2.hpp - the DFlash2 drafter for Qwen3.8-Flash-Next on the GPU (CUDA and HIP). +// +// incoai/Qwen3.8-Flash-Next-DFlash2 (Apache-2.0) is a block drafter: 5 transformer layers of hidden 2560 that read the target's hidden +// states (the mean of the 4 hyper-connection streams after layers 5, 15, 25, 35, 45) as context and, from the last accepted token plus +// 7 mask tokens, produce 7 draft tokens in one forward pass. A candidate selector (the head's top-16 per row, a rank-256 bilinear +// score between the previous pick and each candidate) picks the path left to right. tools/dflash2_pack.py packs it as Q8_0. +// +// context taps (5 x 2560 per accepted row) -> fc (12800 -> 2560) -> hidden_norm -> per layer K (norm + rope) and V -> ring slot pos % R +// block 8 rows: embed(anchor), embed(mask) x 7; per layer +// rms -> dynamic 2-tap conv (prepare) -> q, k, v -> q/k norm + rope -> attention over the ring + the block's own keys +// -> o -> conv (finish) + residual -> rms -> conv (prepare) -> gate/up -> silu*up -> down -> conv (finish) + residual +// selector final norm -> head over the draft vocabulary (rows 1..7) -> top-16 -> walk +// +// The ring holds only COMMITTED rows (an accepted window row's taps arrive after the verify window), and the block's keys stay outside +// it, so a rejected draft leaves nothing to roll back. One CUDA graph per context-row count n = 1..8 holds the context update and the +// block; the host stages the positions and the anchor and waits for the 7 drafts. +#pragma once + +#include "strata/core/session.hpp" + +#include + +#include +#include +#include +#include + +namespace strata::core { + +class NativeHead; + +class Dflash2Drafter { +public: + static constexpr int kRows = 8; ///< block rows: the anchor + 7 masks + static constexpr int kDrafts = kRows - 1; + static constexpr int kRing = 2064; ///< K/V slots per layer: the 2048 window + slack for rows written ahead of a rejection + + Dflash2Drafter() = default; + ~Dflash2Drafter(); + Dflash2Drafter(const Dflash2Drafter&) = delete; + Dflash2Drafter& operator=(const Dflash2Drafter&) = delete; + + /// Reads the pack (tools/dflash2_pack.py) to the GPU `device` and allocates the ring and the buffers (about 0.8 GB). + bool load(const std::string& pack_path, int device, std::string& err); + /// The target's embedding and head (and the draft vocabulary file, "" or missing: the whole head). + bool bind(const WeightTable& wt, const NativeHead* head, const std::string& vocab_file, std::string& err); + /// Tests: an embedding callback and a head given as raw rows of `head_type` (a native_mmvq type). + using EmbedFn = std::function; + bool bind_raw(EmbedFn embed, const void* head_w, int head_type, int64_t head_rows, const std::vector& vocab, std::string& err); + + /// A new request: the ring is empty again. + void reset() { have_ctx_ = 0; } + /// Context rows without a draft: `n` rows of taps (device, [n][5 * n_embd]) for positions pos0 ... pos0 + n - 1. + bool context(const float* taps_dev, int64_t n, int64_t pos0, std::string& err); + /// One round: the new context rows (n_new in 1..8: the committed window rows, taps device [n_new][5 * n_embd], positions pos0 ...), + /// then the block for `anchor` (the last committed token, at pos0 + n_new). `drafts` / `probs` get kDrafts entries (the + /// selector's pick and its probability). The taps pointer must be the same device buffer on every call (graphs are captured on it). + bool draft(const float* taps_dev, int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err); + + uint64_t vram_bytes() const { return vram_; } + int64_t n_draft_vocab() const { return n_dvocab_; } + int n_embd() const { return N_; } + const std::vector& tap_layers() const { return taps_; } + cudaStream_t stream() const { return cs_; } + /// Diagnostics (STRATA_DF2_DUMP): the final normalized block rows of the last draft(), host copy. + bool debug_rows(std::vector& rows, std::string& err); + + double ms_draft = 0, ms_gpu = 0, ms_ctx = 0; + int64_t rounds = 0; + +private: + struct Tensor { std::string name, dtype; int64_t rows = 0, cols = 0; uint64_t off = 0, bytes = 0; }; + const Tensor& find(const std::string& name) const; + const void* q8(const std::string& name) const { return blob_ + find(name).off; } + const float* f32(const std::string& name) const { return reinterpret_cast(blob_ + find(name).off); } + void mm(const std::string& name, const void* xq, float* y, int ncols); ///< Q8_0 matrix x ncols activation columns (quantized in xq) + void quant(const float* x, int n_in, int ncols); + bool record_context(const float* taps, int n, cudaStream_t cs, std::string& err); + bool record_block(cudaStream_t cs, std::string& err); + bool capture(int n, const float* taps, std::string& err); + bool alloc(std::string& err); + struct Prof; + Prof* prof_ = nullptr; + void stamp(const char* name); + void prof_collect(); + void prof_report() const; + + int device_ = -1; + cudaStream_t cs_ = nullptr; + std::vector tensors_; + uint8_t* blob_ = nullptr; + uint64_t vram_ = 0; + int N_ = 2560, L_ = 5, NH_ = 32, NKV_ = 8, HD_ = 128, I_ = 7680, window_ = 2048, group_ = 16, rank_ = 256, mask_token_ = 0; + float theta_ = 10000.0f, eps_ = 1e-6f; + std::vector taps_; + int64_t vocab_ = 0; + + // target pieces + EmbedFn embed_; + const void* head_w_ = nullptr; + int head_type_ = -1; + int64_t n_dvocab_ = 0; + int32_t* dvocab_ = nullptr; + uint8_t* dhead_ = nullptr; ///< the draft vocabulary's head rows (owned), or null with head_w_ the whole head + bool bound_ = false; + + // device buffers + int32_t* d_meta_ = nullptr; ///< [0..7] context positions, [8..15] block positions, [16] anchor token, [17] anchor position, [24..31] block tokens + int32_t* h_meta_ = nullptr; ///< host staging of d_meta_ (mapped; m_meta_ is its device alias) + int32_t* m_meta_ = nullptr; + int32_t* h_out_ = nullptr; ///< pinned: 7 draft tokens then 7 probabilities + float* hp_out_ = nullptr; + float *kring_[8] = {}, *vring_[8] = {}; + float *rt_ctx_ = nullptr, *rt_blk_ = nullptr; + uint8_t* xq_ = nullptr; + float *fcy_ = nullptr, *hctx_ = nullptr, *kc_ = nullptr, *vc_ = nullptr; + float *h_ = nullptr, *xn_ = nullptr, *xc_ = nullptr, *dyn_ = nullptr, *q_ = nullptr, *qn_ = nullptr, *k_ = nullptr, *v_ = nullptr, *kblk_ = nullptr; + float *ao_ = nullptr, *o_ = nullptr, *gate_ = nullptr, *up_ = nullptr, *mlp_ = nullptr, *part_ = nullptr, *fn_ = nullptr; + float *logits_ = nullptr, *topval_ = nullptr, *hsel_ = nullptr, *out_prob_ = nullptr; + int32_t *toptok_ = nullptr, *out_tok_ = nullptr; + uint32_t* topscratch_ = nullptr; + cudaGraphExec_t exec_[kRows + 1] = {}; + const float* graph_taps_ = nullptr; + int64_t have_ctx_ = 0; + cudaEvent_t ev_a_ = nullptr, ev_b_ = nullptr; + bool timing_ = false; +}; + +} // namespace strata::core diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index b2ea8192..db19db66 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -323,6 +323,12 @@ public: /// Token t's residual after the last layer, (hc, n_embd) on the device, valid until the next `run`. const float* final_R(int t) const; const float* final_R_all() const { return next_ ? next_->final_R_all() : R_; } + /// DFlash2 (before init): keep the completed outputs of these layers (zero-based; the mean of the hc streams) for every row of + /// each window in a device buffer, tap_dev() = [max_t][n_taps][n_embd] floats, valid until the next window. Single-stage + /// verifiers only; STRATA_TAP_FILE (research dump) turns the same buffer on without this call. + void set_taps(const std::vector& layers) { tap_req_ = layers; } + const float* tap_dev() const { return tap_dev_; } + bool tapping() const { return tap_on_; } /// The GPU plan the pool writes each layer (VRAM hits + the PCIe share of the misses); give it to the /// dispatch (`ExpertDispatch::plan`) before the first `run`. @@ -552,6 +558,7 @@ private: // (the residual with its pending FFN write applied, the mean of the hc streams) per row; run() appends // (pos, token, taps) records to the file. bool tap_on_ = false; + std::vector tap_req_; ///< set_taps std::vector tap_layers_; ///< the tapped layer ids (zero-based, completed outputs) std::vector tap_slot_; ///< layer -> slot in tap_layers_, or -1 float* tap_dev_ = nullptr; ///< [max_t][n_taps][n_embd] diff --git a/include/strata/kernels/dflash2.hpp b/include/strata/kernels/dflash2.hpp new file mode 100644 index 00000000..8a544f29 --- /dev/null +++ b/include/strata/kernels/dflash2.hpp @@ -0,0 +1,66 @@ +// include/strata/kernels/dflash2.hpp - the small kernels of the DFlash2 drafter (core/dflash2.hpp) for Qwen3.8-Flash-Next. +// +// The drafter's matrices run through the engine's multi-column MMVQ (native_q8_0_mmvq); what is here is everything between +// them: the grouped dynamic 2-tap convolution, the per-head RMS norm + rotary rotation, the windowed non-causal attention over a +// K/V ring, the top-16 selection over the head's logits and the selector's left-to-right walk. All launches are asynchronous on +// the given stream, allocate nothing and are graph-capturable. Layouts are row-major f32 unless noted. +#pragma once + +#include + +namespace strata::kernels { + +constexpr int kDf2Rows = 8; ///< block rows (the anchor + 7 masks) and the most context rows one update takes +constexpr int kDf2Kv = 8; ///< K/V heads +constexpr int kDf2Gqa = 4; ///< query heads per K/V head +constexpr int kDf2Hd = 128; ///< head dim +constexpr int kDf2Chunk = 256; ///< keys per attention block +constexpr int kDf2MaxChunks = 9; ///< ceil((2047 context keys + 8 block keys) / kDf2Chunk) +constexpr int kDf2TopK = 16; +constexpr int kDf2TopBlocks = 64; ///< partial top-k blocks per row (a block holds at most 4096 logits) + +/// out[b][c] = sum_{o < 2, b - o >= 0} (base[o][c] + dyn[b * dyn_stride + o * groups + c / group]) * x[(b - o) * H + c] (+ resid[b][c] when +/// resid != null; out may equal resid). x is [rows][H]; base is [2][H]; `dyn` points at this convolution's [2][groups] slice of row 0. +void df2_conv(const float* x, const float* dyn, int dyn_stride, const float* base, const float* resid, float* out, int rows, int H, + int group, void* stream); + +/// table[r][0][i], table[r][1][i] = cos, sin of pos[r] * theta^(-2 i / 128) for i < 64 (the angle reduced in double first, so a large +/// position keeps its precision under fast math). table: [rows][2][64]. +void df2_rope_table(const int32_t* pos, int rows, float theta, float* table, void* stream); + +/// Per (row, head): out = rope(rmsnorm(in) * gamma). `in` rows are `in_stride` floats apart (heads * 128 contiguous per row). The +/// rotation is the neox/rotate_half one over the whole head dim with row r's entry of `rope_table` (null: the norm only). The result of row r goes to +/// out + slot(r) * heads * 128 with slot(r) = (slot_mod > 0 ? pos[r] % slot_mod : r). `rope` false: the norm only. +void df2_norm_rope(const float* in, int in_stride, const float* gamma, const int32_t* pos, const float* rope_table, float* out, int slot_mod, + int rows, int heads, float eps, void* stream); + +/// out[slot(r)][c] = in[r][c], slot as above (the value half of the ring write). +void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod, int rows, int cols, void* stream); + +/// Attention of the block's 8 query rows (q: [8][32][128], already normed and rotated) over the context ring (kring, vring: +/// [ring_slots][8][128]) and the block's own keys (kblk, vblk: [8][8][128]). Row i at position s + i sees context position j when +/// s + i - j < window (j in [max(0, s - window + 1), s - 1], slot j % ring_slots) and every block key. `s` is read from *anchor_pos +/// on the device. Partials in `part` ([kDf2MaxChunks][8][32][130] floats) are combined into out [8][32*128]. +void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, + int ring_slots, int window, float* part, float* out, void* stream); + +/// Top-16 per row of logits [rows][n] (value-descending; ties to the lower index). idx_map (optional) maps a column to a token id. +/// scratch: rows * kDf2TopBlocks * 16 * 2 words. Outputs val[rows][16] and tok[rows][16]. n <= 4096 * kDf2TopBlocks. +void df2_topk(const float* logits, int n, const int32_t* idx_map, int rows, uint32_t* scratch, float* val, int32_t* tok, void* stream); + +/// The candidate selector's walk: for row i = 0..rows-1 the 16 candidates' scores are unary[i][j] + dot(succ[tok[i][j]], +/// pred[prev] * hp[i]) over `rank` values (codebooks are bf16 rows of `rank`), the pick is the argmax, prev = the pick. Writes +/// out_tok[i] and out_prob[i] (the softmax probability of the pick among the 16). `prev0` is read from *anchor_tok on the device. +void df2_select(const float* hp, const float* unary, const int32_t* tok, const uint16_t* pred_cb, const uint16_t* succ_cb, int rank, int rows, + const int32_t* anchor_tok, int32_t* out_tok, float* out_prob, void* stream); + +/// The verify window's tap: out[r][d] = mean over the hc streams c of (R[r][c][d] + bo[r][d] * 2 * sigmoid(inject[r][c] / hc)) - the layer output with +/// its pending FFN write (gr_write) applied, averaged over the streams. R rows are `R_stride` floats apart, bo rows `bo_stride`, inject rows +/// `inj_stride`, out rows `out_stride`. +void df2_tap_gr(const float* R, int64_t R_stride, const float* bo, int64_t bo_stride, const float* inject, int64_t inj_stride, float* out, int64_t out_stride, + int rows, int64_t n_embd, int hc, void* stream); + +/// out[r][:n_embd] = the mean of the hc streams of row r of R ([rows][hc][n_embd]) written to out + r * out_stride (a tap slot). +void df2_tap_rows(const float* R, float* out, int64_t out_stride, int64_t n_embd, int hc, int rows, void* stream); + +} // namespace strata::kernels diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index 7aadc072..f9bbca02 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -184,6 +184,13 @@ public: /// T x hc*n_embd, valid until the next chunk) and the chunk's first position; the MTP draft layer builds its /// K/V from them. The prefill stream is synchronized before the call. std::function on_chunk; + /// DFlash2 prompt taps (CUDA / HIP, single stage): before `run`, ask for the completed output of each layer in `layers` (zero-based; the + /// mean of the hc streams) for the prompt rows at positions >= `first_pos`, at most `cap_rows` rows per chunk (a staging buffer of + /// cap_rows x layers x n_embd floats is allocated at the first chunk). After each chunk that has such rows, on_taps(taps + /// [rows][layers][n_embd] device, rows, first position, err) runs with the stream synchronized. clear_taps frees the staging. + void set_taps(const std::vector& layers, int64_t first_pos, int64_t cap_rows) { tap_layers_ = layers; tap_first_ = first_pos; tap_cap_ = cap_rows; } + void clear_taps(); + std::function on_taps; /// Layer split: called by every stage when it has read a chunk, with the position reached, while its own state /// is still at that chunk's end (its stream synchronized; the last stage calls it just before `on_chunk`). An @@ -256,6 +263,9 @@ private: bool drain_pipeline(std::string& err); int64_t stage_lb_ = 0, stage_le_ = -1; + std::vector tap_layers_; + int64_t tap_first_ = 0, tap_cap_ = 0; + float* tap_dev_ = nullptr; Prefill* next_ = nullptr; Prefill* helper_ = nullptr; ///< set_stage_helper bool single_chunk_ = false; ///< a later stage: the prompt is one chunk (set by the stage before) diff --git a/src/core/dflash2.cpp b/src/core/dflash2.cpp new file mode 100644 index 00000000..80687d3f --- /dev/null +++ b/src/core/dflash2.cpp @@ -0,0 +1,466 @@ +// src/core/dflash2.cpp - see include/strata/core/dflash2.hpp. +#include "strata/core/dflash2.hpp" + +#include "strata/core/native_head.hpp" +#include "strata/core/on_device.hpp" +#include "strata/core/weights.hpp" +#include "strata/kernels/dflash2.hpp" +#include "strata/kernels/elementwise.hpp" +#include "strata/kernels/native_mmvq.hpp" +#include "strata/kernels/native_qsa.hpp" +#include "strata/kernels/verify_kernels.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core { +namespace { + +using Clock = std::chrono::steady_clock; +double ms_since(Clock::time_point t) { return std::chrono::duration(Clock::now() - t).count(); } + +bool mapped(size_t bytes, void** h, void** d) { + if (cudaHostAlloc(h, bytes, cudaHostAllocMapped) != cudaSuccess) return false; + std::memset(*h, 0, bytes); + return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess; +} + +constexpr int GGML_Q8_0 = 8; + +} // namespace + +Dflash2Drafter::~Dflash2Drafter() { + if (device_ < 0) return; + prof_report(); + delete prof_; + const OnDevice on_device(device_); + if (cs_) cudaStreamSynchronize(cs_); + for (cudaGraphExec_t& e : exec_) + if (e) cudaGraphExecDestroy(e); + auto fr = [](void* p) { if (p) cudaFree(p); }; + fr(blob_); fr(d_meta_); fr(xq_); fr(rt_ctx_); fr(rt_blk_); + for (int l = 0; l < 8; ++l) { fr(kring_[l]); fr(vring_[l]); } + fr(fcy_); fr(hctx_); fr(kc_); fr(vc_); fr(h_); fr(xn_); fr(xc_); fr(dyn_); fr(q_); fr(qn_); fr(k_); fr(v_); fr(kblk_); fr(ao_); fr(o_); + fr(gate_); fr(up_); fr(mlp_); fr(part_); fr(fn_); fr(logits_); fr(topval_); fr(hsel_); fr(toptok_); fr(topscratch_); + fr(dvocab_); fr(dhead_); + if (h_meta_) cudaFreeHost(h_meta_); + if (h_out_) cudaFreeHost(h_out_); + if (cs_) cudaStreamDestroy(cs_); + if (ev_a_) cudaEventDestroy(ev_a_); + if (ev_b_) cudaEventDestroy(ev_b_); +} + +// STRATA_DF2_PROFILE=1 (measurement only): the round runs without its graph and an event follows every stage; the per-stage averages print at exit +struct Dflash2Drafter::Prof { + std::vector ev; + std::vector name; + std::vector> total; + int64_t rounds = 0; +}; + +void Dflash2Drafter::stamp(const char* name) { + if (!prof_) return; + cudaEvent_t e; + cudaEventCreate(&e); + cudaEventRecord(e, cs_); + prof_->ev.push_back(e); + prof_->name.push_back(name); +} + +void Dflash2Drafter::prof_collect() { + if (!prof_ || prof_->ev.size() < 2) return; + cudaStreamSynchronize(cs_); + for (size_t i = 1; i < prof_->ev.size(); ++i) { + float ms = 0; + cudaEventElapsedTime(&ms, prof_->ev[i - 1], prof_->ev[i]); + auto it = std::find_if(prof_->total.begin(), prof_->total.end(), [&](const auto& t) { return t.first == prof_->name[i]; }); + if (it == prof_->total.end()) prof_->total.emplace_back(prof_->name[i], ms); else it->second += ms; + } + for (cudaEvent_t e : prof_->ev) cudaEventDestroy(e); + prof_->ev.clear(); + prof_->name.clear(); + ++prof_->rounds; +} + +void Dflash2Drafter::prof_report() const { + if (!prof_ || prof_->rounds == 0) return; + double sum = 0; + for (const auto& t : prof_->total) sum += t.second; + std::fprintf(stderr, "strata dflash2 profile (%lld rounds, ms per round, total %.3f):", (long long) prof_->rounds, sum / (double) prof_->rounds); + for (const auto& t : prof_->total) std::fprintf(stderr, " %s %.3f", t.first.c_str(), t.second / (double) prof_->rounds); + std::fputc(10, stderr); +} + +const Dflash2Drafter::Tensor& Dflash2Drafter::find(const std::string& name) const { + for (const Tensor& t : tensors_) + if (t.name == name) return t; + throw std::runtime_error("dflash2: tensor " + name + " is missing from the pack"); +} + +bool Dflash2Drafter::load(const std::string& path, int device, std::string& err) { + device_ = device; + const OnDevice on_device(device_); + std::FILE* f = std::fopen(path.c_str(), "rb"); + if (f == nullptr) { err = "dflash2: cannot open " + path; return false; } + struct Closer { std::FILE* f; ~Closer() { std::fclose(f); } } closer{f}; + uint32_t hdr[3]; + if (std::fread(hdr, 4, 3, f) != 3 || std::memcmp(hdr, "DF2P", 4) != 0 || hdr[1] != 1) { err = "dflash2: " + path + " is not a DF2P v1 pack"; return false; } + std::string index(hdr[2], ' '); + if (std::fread(index.data(), 1, hdr[2], f) != hdr[2]) { err = "dflash2: the pack's index is cut short"; return false; } + const long data_off = 12 + (long) hdr[2]; + uint64_t total = 0; + for (size_t i = 0; i < index.size();) { + const size_t j = index.find('\n', i); + if (j == std::string::npos) break; + const std::string line = index.substr(i, j - i); + i = j + 1; + char a[256], b[64], c[256]; + long long v1, v2, v3, v4; + if (std::sscanf(line.c_str(), "cfg %63s %255s", b, c) == 2) { + const std::string key = b; + if (key == "hidden") N_ = std::atoi(c); + else if (key == "layers") L_ = std::atoi(c); + else if (key == "heads") NH_ = std::atoi(c); + else if (key == "kv_heads") NKV_ = std::atoi(c); + else if (key == "head_dim") HD_ = std::atoi(c); + else if (key == "inter") I_ = std::atoi(c); + else if (key == "window") window_ = std::atoi(c); + else if (key == "rope_theta") theta_ = (float) std::atof(c); + else if (key == "eps") eps_ = (float) std::atof(c); + else if (key == "conv_group") group_ = std::atoi(c); + else if (key == "rank") rank_ = std::atoi(c); + else if (key == "mask_token") mask_token_ = std::atoi(c); + else if (key == "vocab") vocab_ = std::atoll(c); + else if (key == "taps") { + taps_.clear(); + for (const char* q = c; *q;) { taps_.push_back(std::atoi(q)); while (*q && *q != ',') ++q; if (*q == ',') ++q; } + } + } else if (std::sscanf(line.c_str(), "t %255s %63s %lld %lld %lld %lld", a, b, &v1, &v2, &v3, &v4) == 6) { + Tensor t; + t.name = a; t.dtype = b; t.rows = v1; t.cols = v2; t.off = (uint64_t) v3; t.bytes = (uint64_t) v4; + tensors_.push_back(t); + total = std::max(total, t.off + t.bytes); + } + } + if (tensors_.empty() || NH_ != 32 || NKV_ != 8 || HD_ != 128 || rank_ != 256 || N_ != 2560 || L_ > 8 || window_ + 16 > kRing) { + err = "dflash2: the pack's shape is not the Flash-Next drafter this engine was written for"; + return false; + } + if (cudaMalloc((void**) &blob_, total) != cudaSuccess) { err = "dflash2: the pack does not fit in VRAM (" + std::to_string(total >> 20) + " MiB)"; return false; } + vram_ += total; + std::vector stage(64u << 20); +#if defined(_WIN32) + _fseeki64(f, data_off, SEEK_SET); +#else + fseeko(f, data_off, SEEK_SET); +#endif + for (uint64_t o = 0; o < total;) { + const size_t n = (size_t) std::min(stage.size(), total - o); + if (std::fread(stage.data(), 1, n, f) != n) { err = "dflash2: the pack is shorter than its index"; return false; } + if (cudaMemcpy(blob_ + o, stage.data(), n, cudaMemcpyHostToDevice) != cudaSuccess) { err = "dflash2: weight upload failed"; return false; } + o += n; + } + if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "dflash2: stream"; return false; } + if (const char* e = std::getenv("STRATA_DF2_PROFILE"); e && e[0] == '1') prof_ = new Prof(); + if (const char* e = std::getenv("STRATA_DF2_TIMING"); e && e[0] == '1') { + timing_ = true; + cudaEventCreate(&ev_a_); + cudaEventCreate(&ev_b_); + } + return alloc(err); +} + +bool Dflash2Drafter::alloc(std::string& err) { + auto dev = [&](auto** p, size_t n) { + using T = std::remove_pointer_t>; + if (cudaMalloc((void**) p, n * sizeof(T)) != cudaSuccess) return false; + vram_ += n * sizeof(T); + return true; + }; + const size_t B = kRows; + bool ok = dev(&d_meta_, 32) && dev(&xq_, kernels::native_q8_1_bytes(std::max(N_ * 5, I_), kRows) + 4096) && dev(&rt_ctx_, B * 128) && dev(&rt_blk_, B * 128) && + dev(&fcy_, B * N_) && dev(&hctx_, B * N_) && dev(&kc_, B * NKV_ * HD_) && dev(&vc_, B * NKV_ * HD_) && dev(&h_, B * N_) && dev(&xn_, B * N_) && + dev(&xc_, B * N_) && dev(&dyn_, B * 640) && dev(&q_, B * NH_ * HD_) && dev(&qn_, B * NH_ * HD_) && dev(&k_, B * NKV_ * HD_) && dev(&v_, B * NKV_ * HD_) && + dev(&kblk_, B * NKV_ * HD_) && dev(&ao_, B * NH_ * HD_) && dev(&o_, B * N_) && dev(&gate_, B * I_) && dev(&up_, B * I_) && dev(&mlp_, B * N_) && + dev(&part_, (size_t) kernels::kDf2MaxChunks * 8 * 32 * 130) && dev(&fn_, B * N_) && dev(&topval_, kDrafts * 16) && dev(&toptok_, kDrafts * 16) && + dev(&hsel_, kDrafts * rank_) && dev(&topscratch_, (size_t) kDrafts * kernels::kDf2TopBlocks * kernels::kDf2TopK * 2); + for (int l = 0; ok && l < L_; ++l) ok = dev(&kring_[l], (size_t) kRing * NKV_ * HD_) && dev(&vring_[l], (size_t) kRing * NKV_ * HD_); + if (!ok) { err = "dflash2: the drafter's buffers do not fit in VRAM"; return false; } + void* hd = nullptr; + void* dd = nullptr; + if (!mapped(32 * 4, (void**) &hd, &dd)) { err = "dflash2: mapped staging"; return false; } + h_meta_ = (int32_t*) hd; + m_meta_ = (int32_t*) dd; + if (!mapped(64 * 4, &hd, &dd)) { err = "dflash2: mapped output"; return false; } + h_out_ = (int32_t*) hd; + out_tok_ = (int32_t*) dd; // the select kernel writes the 7 picks here (host-visible) ... + out_prob_ = (float*) dd + 16; // ... and their probabilities at +16 ints + cudaMemset(rt_ctx_, 0, B * 128 * 4); + for (int l = 0; l < L_; ++l) { cudaMemset(kring_[l], 0, (size_t) kRing * NKV_ * HD_ * 4); cudaMemset(vring_[l], 0, (size_t) kRing * NKV_ * HD_ * 4); } + return cudaDeviceSynchronize() == cudaSuccess; +} + +bool Dflash2Drafter::bind_raw(EmbedFn embed, const void* head_w, int head_type, int64_t head_rows, const std::vector& vocab, std::string& err) { + const OnDevice on_device(device_); + embed_ = std::move(embed); + head_w_ = head_w; + head_type_ = head_type; + n_dvocab_ = head_rows; + if (!vocab.empty()) { + n_dvocab_ = (int64_t) vocab.size(); + if (cudaMalloc((void**) &dvocab_, vocab.size() * 4) != cudaSuccess) { err = "dflash2: draft vocabulary"; return false; } + vram_ += vocab.size() * 4; + cudaMemcpy(dvocab_, vocab.data(), vocab.size() * 4, cudaMemcpyHostToDevice); + } + if ((n_dvocab_ + kernels::kDf2TopBlocks - 1) / kernels::kDf2TopBlocks > 4096) { err = "dflash2: the head has too many rows for the top-k"; return false; } + if (!logits_ && cudaMalloc((void**) &logits_, (size_t) kDrafts * (size_t) n_dvocab_ * 4) != cudaSuccess) { err = "dflash2: the draft logits do not fit"; return false; } + vram_ += (uint64_t) kDrafts * (uint64_t) n_dvocab_ * 4; + bound_ = true; + return true; +} + +bool Dflash2Drafter::bind(const WeightTable& wt, const NativeHead* head, const std::string& vocab_file, std::string& err) { + const OnDevice on_device(device_); + if (head == nullptr || !head->loaded()) { err = "dflash2: the drafter needs the native head (--native)"; return false; } + const WeightRef* we = wt.find("token_embd.weight"); + if (we == nullptr) { err = "dflash2: token_embd.weight is missing"; return false; } + EmbedFn embed = [we](const int32_t* tok, int n, float* out, cudaStream_t cs) { + if (const NativeEmbed* ne = native_embed()) { + ne->gather_dev(tok, n, out, cs); + } else { + const auto* codes = (const uint8_t*) we->data; + const auto* scales = (const float*) (codes + we->codes_bytes); + const auto* offsets = we->has_offset ? (const float*) (codes + we->codes_bytes + we->scales_bytes) : nullptr; + kernels::embedding_gather_dev(codes, scales, offsets, tok, n, we->ne0, we->code_bits, we->code_bias, we->group_elems, + (uint64_t) (we->ne0 / (8 / we->code_bits)), (uint64_t) (we->ne0 / we->group_elems), out, cs); + } + }; + std::vector vocab; + if (!vocab_file.empty()) { + if (std::FILE* vf = std::fopen(vocab_file.c_str(), "rb")) { + std::fseek(vf, 0, SEEK_END); + const long size = std::ftell(vf); + std::fseek(vf, 0, SEEK_SET); + if (size >= 4 && size % 4 == 0) { + vocab.resize((size_t) size / 4); + if (std::fread(vocab.data(), 4, vocab.size(), vf) != vocab.size()) vocab.clear(); + } + std::fclose(vf); + } + } + const void* hw = head->weights(); + const int64_t row_bytes = (int64_t) head->row_bytes(); + int64_t head_rows = row_bytes > 0 ? (int64_t) (head->weight_bytes() / (uint64_t) row_bytes) : 0; + if (!vocab.empty()) { + int32_t* dv = nullptr; + if (cudaMalloc((void**) &dv, vocab.size() * 4) != cudaSuccess || cudaMalloc((void**) &dhead_, (size_t) ((int64_t) vocab.size() * row_bytes)) != cudaSuccess) { + if (dv) cudaFree(dv); + err = "dflash2: the draft vocabulary's head rows do not fit"; + return false; + } + cudaMemcpy(dv, vocab.data(), vocab.size() * 4, cudaMemcpyHostToDevice); + kernels::gather_rows((const uint8_t*) hw, row_bytes, dv, (int64_t) vocab.size(), dhead_, nullptr); + cudaDeviceSynchronize(); + cudaFree(dv); + vram_ += (uint64_t) ((int64_t) vocab.size() * row_bytes); + hw = dhead_; + head_rows = (int64_t) vocab.size(); + } + if (!bind_raw(embed, hw, head->type(), head_rows, vocab, err)) return false; + std::fprintf(stderr, "strata dflash2: %lld-token draft head (%.1f MiB), drafter %.0f MiB of VRAM\n", (long long) n_dvocab_, + (double) (n_dvocab_ * row_bytes) / 1048576.0, (double) vram_ / 1048576.0); + return true; +} + +void Dflash2Drafter::quant(const float* x, int n_in, int ncols) { kernels::native_quantize_q8_1(x, xq_, n_in, ncols, cs_); } + +void Dflash2Drafter::mm(const std::string& name, const void* xq, float* y, int ncols) { + const Tensor& t = find(name); + kernels::native_q8_0_mmvq(blob_ + t.off, xq, y, (int) t.cols, (int) t.rows, ncols, cs_); +} + +bool Dflash2Drafter::record_context(const float* taps, int n, cudaStream_t cs, std::string& err) { + using namespace kernels; + try { + const int tap_n = (int) taps_.size() * N_; + df2_rope_table(d_meta_ + 0, n, theta_, rt_ctx_, cs); + stamp("ctx-start"); + quant(taps, tap_n, n); + mm("fc.weight", xq_, fcy_, n); + stamp("fc"); + native_qsa_rms_norm_weighted(fcy_, f32("hidden_norm.weight"), hctx_, N_, n, eps_, cs); + quant(hctx_, N_, n); + for (int l = 0; l < L_; ++l) { + const std::string p = "layers." + std::to_string(l) + "."; + mm(p + "self_attn.k_proj.weight", xq_, kc_, n); + mm(p + "self_attn.v_proj.weight", xq_, vc_, n); + df2_norm_rope(kc_, NKV_ * HD_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 0, rt_ctx_, kring_[l], kRing, n, NKV_, eps_, cs); + df2_copy_rows(vc_, vring_[l], d_meta_ + 0, kRing, n, NKV_ * HD_, cs); + } + stamp("ctx-kv"); + } catch (const std::exception& e) { + err = e.what(); + return false; + } + return true; +} + +bool Dflash2Drafter::record_block(cudaStream_t cs, std::string& err) { + using namespace kernels; + try { + const int B = kRows; + df2_rope_table(d_meta_ + 8, B, theta_, rt_blk_, cs); + embed_(d_meta_ + 24, B, h_, cs); + stamp("embed"); + for (int l = 0; l < L_; ++l) { + const std::string p = "layers." + std::to_string(l) + "."; + const float* base_a = f32(p + "attention_conv.base_kernel"); + const float* base_m = f32(p + "mlp_conv.base_kernel"); + native_qsa_rms_norm_weighted(h_, f32(p + "input_layernorm.weight"), xn_, N_, B, eps_, cs); + quant(xn_, N_, B); + mm(p + "attention_conv.kernel_projection.weight", xq_, dyn_, B); + df2_conv(xn_, dyn_, 640, base_a, nullptr, xc_, B, N_, group_, cs); + quant(xc_, N_, B); + stamp("attn-front"); + mm(p + "self_attn.q_proj.weight", xq_, q_, B); + mm(p + "self_attn.k_proj.weight", xq_, k_, B); + mm(p + "self_attn.v_proj.weight", xq_, v_, B); + stamp("qkv"); + df2_norm_rope(q_, NH_ * HD_, f32(p + "self_attn.q_norm.weight"), d_meta_ + 8, rt_blk_, qn_, 0, B, NH_, eps_, cs); + df2_norm_rope(k_, NKV_ * HD_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 8, rt_blk_, kblk_, 0, B, NKV_, eps_, cs); + df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, ao_, cs); + stamp("attention"); + quant(ao_, NH_ * HD_, B); + mm(p + "self_attn.o_proj.weight", xq_, o_, B); + stamp("o_proj"); + df2_conv(o_, dyn_ + 320, 640, base_a + 2 * N_, h_, h_, B, N_, group_, cs); + native_qsa_rms_norm_weighted(h_, f32(p + "post_attention_layernorm.weight"), xn_, N_, B, eps_, cs); + quant(xn_, N_, B); + mm(p + "mlp_conv.kernel_projection.weight", xq_, dyn_, B); + df2_conv(xn_, dyn_, 640, base_m, nullptr, xc_, B, N_, group_, cs); + quant(xc_, N_, B); + stamp("mlp-front"); + mm(p + "mlp.gate_proj.weight", xq_, gate_, B); + mm(p + "mlp.up_proj.weight", xq_, up_, B); + stamp("gate-up"); + native_swiglu_quantize_q8_1(gate_, up_, xq_, I_, B, cs); + mm(p + "mlp.down_proj.weight", xq_, mlp_, B); + stamp("down"); + df2_conv(mlp_, dyn_ + 320, 640, base_m + 2 * N_, h_, h_, B, N_, group_, cs); + } + native_qsa_rms_norm_weighted(h_, f32("norm.weight"), fn_, N_, B, eps_, cs); + quant(fn_ + N_, N_, kDrafts); // rows 1..7 + stamp("final-norm"); + native_mmvq(head_type_, head_w_, xq_, logits_, N_, (int) n_dvocab_, kDrafts, cs); + stamp("head"); + df2_topk(logits_, (int) n_dvocab_, dvocab_, kDrafts, topscratch_, topval_, toptok_, cs); + stamp("topk"); + mm("candidate_selector.hidden_projection.weight", xq_, hsel_, kDrafts); + df2_select(hsel_, topval_, toptok_, reinterpret_cast(blob_ + find("candidate_selector.predecessor_codebook").off), + reinterpret_cast(blob_ + find("candidate_selector.successor_codebook").off), rank_, kDrafts, d_meta_ + 16, out_tok_, + out_prob_, cs); + stamp("selector"); + } catch (const std::exception& e) { + err = e.what(); + return false; + } + return true; +} + +bool Dflash2Drafter::capture(int n, const float* taps, std::string& err) { + if (exec_[n]) return true; + if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "dflash2: begin capture"; return false; } + kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_); + bool ok = record_context(taps, n, cs_, err); + if (ok) ok = record_block(cs_, err); + cudaGraph_t graph = nullptr; + const cudaError_t ce = cudaStreamEndCapture(cs_, &graph); + if (!ok) { if (graph) cudaGraphDestroy(graph); return false; } + if (ce != cudaSuccess || cudaGraphInstantiate(&exec_[n], graph, 0) != cudaSuccess) { + if (graph) cudaGraphDestroy(graph); + err = std::string("dflash2: capture: ") + cudaGetErrorString(ce); + return false; + } + cudaGraphDestroy(graph); + cudaGraphUpload(exec_[n], cs_); + cudaStreamSynchronize(cs_); + return true; +} + +bool Dflash2Drafter::context(const float* taps, int64_t n, int64_t pos0, std::string& err) { + const OnDevice on_device(device_); + const int tap_n = (int) taps_.size() * N_; + for (int64_t r0 = 0; r0 < n; r0 += kRows) { + const int m = (int) std::min(kRows, n - r0); + for (int i = 0; i < m; ++i) h_meta_[i] = (int32_t) (pos0 + r0 + i); + std::atomic_thread_fence(std::memory_order_seq_cst); + kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_); + if (!record_context(taps + (size_t) r0 * (size_t) tap_n, m, cs_, err)) return false; + if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2: ") + cudaGetErrorString(cudaGetLastError()); return false; } + } + have_ctx_ = std::max(have_ctx_, pos0 + n); + return true; +} + +bool Dflash2Drafter::draft(const float* taps, int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err) { + if (!bound_) { err = "dflash2: not bound"; return false; } + if (n_new < 1 || n_new > kRows) { err = "dflash2: draft rows out of range"; return false; } + const OnDevice on_device(device_); + const Clock::time_point t0 = Clock::now(); + if (graph_taps_ != nullptr && graph_taps_ != taps) { err = "dflash2: the taps buffer moved after capture"; return false; } + if (!prof_ && !exec_[n_new]) { + // the staging must hold valid positions while the capture runs the (empty) kernels' parameter checks + for (int i = 0; i < 8; ++i) h_meta_[i] = (int32_t) (pos0 + i); + if (!capture(n_new, taps, err)) return false; + graph_taps_ = taps; + } + const int64_t s = pos0 + n_new; + for (int i = 0; i < 8; ++i) { h_meta_[i] = (int32_t) (pos0 + std::min(i, n_new - 1)); h_meta_[8 + i] = (int32_t) (s + i); } + h_meta_[16] = anchor; + h_meta_[17] = (int32_t) s; + h_meta_[24] = anchor; + for (int i = 1; i < 8; ++i) h_meta_[24 + i] = mask_token_; + for (int i = 0; i < kDrafts; ++i) { ((volatile int32_t*) h_out_)[i] = -1; } + std::atomic_thread_fence(std::memory_order_seq_cst); + if (timing_) cudaEventRecord(ev_a_, cs_); + if (prof_) { // the same round without its graph, an event after every stage + cudaStreamSynchronize(cs_); + for (cudaEvent_t e : prof_->ev) cudaEventDestroy(e); // the stamps of context() calls are not a round + prof_->ev.clear(); + prof_->name.clear(); + kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_); + stamp("start"); + if (!record_context(taps, n_new, cs_, err) || !record_block(cs_, err)) return false; + prof_collect(); + } else + if (cudaGraphLaunch(exec_[n_new], cs_) != cudaSuccess) { err = std::string("dflash2 draft: ") + cudaGetErrorString(cudaGetLastError()); return false; } + if (timing_) cudaEventRecord(ev_b_, cs_); + (void) cudaStreamQuery(cs_); + if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("dflash2 draft: ") + cudaGetErrorString(cudaGetLastError()); return false; } + for (int i = 0; i < kDrafts; ++i) { + drafts[i] = ((volatile int32_t*) h_out_)[i]; + if (probs) probs[i] = ((volatile float*) h_out_)[16 + i]; + } + if (timing_) { + float ms = 0; + if (cudaEventElapsedTime(&ms, ev_a_, ev_b_) == cudaSuccess) ms_gpu += ms; + } + have_ctx_ = std::max(have_ctx_, s); + ms_draft += ms_since(t0); + ++rounds; + return true; +} + +bool Dflash2Drafter::debug_rows(std::vector& rows, std::string& err) { + rows.resize((size_t) kRows * (size_t) N_); + if (cudaMemcpy(rows.data(), fn_, rows.size() * 4, cudaMemcpyDeviceToHost) != cudaSuccess) { err = "dflash2: debug copy"; return false; } + return true; +} + +} // namespace strata::core diff --git a/src/core/dflash2_parity.cpp b/src/core/dflash2_parity.cpp new file mode 100644 index 00000000..bf97887e --- /dev/null +++ b/src/core/dflash2_parity.cpp @@ -0,0 +1,95 @@ +// src/core/dflash2_parity.cpp - the engine's DFlash2 drafter against the torch port, on a synthetic case (GPU, no model). +// +// dflash2_parity [rounds] +// +// case.bin comes from tools/dflash2/mk_parity_case.py: n_ctx random tap rows, an anchor, a random Q8_0 head over a draft-vocabulary subset, the +// target embedding rows of the anchor and the mask token, and the torch answer (tokens, probabilities, the 8 final normalized rows). The engine's +// drafter reads the same pack (Q8_0 weights, Q8_1 activations), so the rows agree to quantization noise, not bitwise: the test checks the rows' +// cosine similarity, the walk's tokens and the time of a round. +#include "strata/core/dflash2.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +using strata::core::Dflash2Drafter; + +int main(int argc, char** argv) { + if (argc < 3) { std::fprintf(stderr, "usage: dflash2_parity [rounds]\n"); return 2; } + const int rounds = argc > 3 ? std::atoi(argv[3]) : 20; + std::FILE* f = std::fopen(argv[2], "rb"); + if (!f) { std::fprintf(stderr, "cannot open %s\n", argv[2]); return 2; } + int32_t hdr[4]; + if (std::fread(hdr, 4, 4, f) != 4) return 2; + const int n_ctx = hdr[0], anchor = hdr[1], vp = hdr[2]; + const int H = 2560, tapn = 5 * H; + std::vector taps((size_t) n_ctx * tapn), emb(2 * H), fn_ref(8 * H); + std::vector dvocab(vp), tok_ref(7); + std::vector prob_ref(7); + const size_t row_bytes = (size_t) (H / 32) * 34; + std::vector head((size_t) vp * row_bytes); + bool ok = std::fread(taps.data(), 4, taps.size(), f) == taps.size() && std::fread(emb.data(), 4, emb.size(), f) == emb.size() && + std::fread(dvocab.data(), 4, dvocab.size(), f) == dvocab.size() && std::fread(head.data(), 1, head.size(), f) == head.size() && + std::fread(tok_ref.data(), 4, 7, f) == 7 && std::fread(prob_ref.data(), 4, 7, f) == 7 && std::fread(fn_ref.data(), 4, fn_ref.size(), f) == fn_ref.size(); + std::fclose(f); + if (!ok) { std::fprintf(stderr, "case file is cut short\n"); return 2; } + + std::string err; + Dflash2Drafter d; + if (!d.load(argv[1], 0, err)) { std::fprintf(stderr, "load: %s\n", err.c_str()); return 1; } + float *d_taps = nullptr, *d_emb = nullptr; + uint8_t* d_head = nullptr; + cudaMalloc((void**) &d_taps, taps.size() * 4); + cudaMalloc((void**) &d_emb, emb.size() * 4); + cudaMalloc((void**) &d_head, head.size()); + cudaMemcpy(d_taps, taps.data(), taps.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(d_emb, emb.data(), emb.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(d_head, head.data(), head.size(), cudaMemcpyHostToDevice); + auto embed = [&](const int32_t*, int n, float* out, cudaStream_t cs) { + cudaMemcpyAsync(out, d_emb, (size_t) H * 4, cudaMemcpyDeviceToDevice, cs); + for (int i = 1; i < n; ++i) cudaMemcpyAsync(out + (size_t) i * H, d_emb + H, (size_t) H * 4, cudaMemcpyDeviceToDevice, cs); + }; + if (!d.bind_raw(embed, d_head, 8, vp, dvocab, err)) { std::fprintf(stderr, "bind: %s\n", err.c_str()); return 1; } + std::printf("drafter VRAM %.0f MiB\n", (double) d.vram_bytes() / 1048576.0); + + // the context but the last row, then one draft round that adds the last row + if (!d.context(d_taps, n_ctx - 1, 0, err)) { std::fprintf(stderr, "context: %s\n", err.c_str()); return 1; } + int32_t drafts[7]; + float probs[7]; + const float* last = d_taps + (size_t) (n_ctx - 1) * tapn; + if (!d.draft(last, 1, n_ctx - 1, anchor, drafts, probs, err)) { std::fprintf(stderr, "draft: %s\n", err.c_str()); return 1; } + std::vector rows; + d.debug_rows(rows, err); + int bad = 0; + double min_cos = 1.0; + for (int r = 0; r < 8; ++r) { + double dot = 0, na = 0, nb = 0; + for (int c = 0; c < H; ++c) { + const double a = rows[(size_t) r * H + c], b = fn_ref[(size_t) r * H + c]; + dot += a * b; na += a * a; nb += b * b; + } + const double cs = dot / std::sqrt(na * nb + 1e-30); + min_cos = std::min(min_cos, cs); + std::printf("row %d: cos %.5f norm ratio %.4f\n", r, cs, std::sqrt(na / (nb + 1e-30))); + } + int same = 0; + for (int i = 0; i < 7; ++i) { + same += drafts[i] == tok_ref[i]; + std::printf("draft %d: engine %d (p %.3f) torch %d (p %.3f)\n", i, drafts[i], probs[i], tok_ref[i], prob_ref[i]); + } + if (min_cos < 0.98) { std::printf("FAIL: a final row's cosine similarity %.4f is below 0.98\n", min_cos); ++bad; } + // timing: the same round again (the graph replays; the ring rewrites the same slot) + cudaDeviceSynchronize(); + const auto t0 = std::chrono::steady_clock::now(); + for (int i = 0; i < rounds; ++i) + if (!d.draft(last, 1, n_ctx - 1, anchor, drafts, probs, err)) { std::fprintf(stderr, "draft: %s\n", err.c_str()); return 1; } + const double ms = std::chrono::duration(std::chrono::steady_clock::now() - t0).count() / rounds; + std::printf("tokens equal %d of 7; %.3f ms per round (1 context row + the block), GPU %.3f ms\n", same, ms, d.rounds > 0 ? d.ms_gpu / (double) d.rounds : 0.0); + std::printf(bad ? "dflash2_parity: FAIL\n" : "dflash2_parity: ok\n"); + return bad ? 1 : 0; +} diff --git a/src/core/verify.cpp b/src/core/verify.cpp index c9f48a74..5b898f9d 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -56,6 +56,7 @@ #include "strata/core/progress.hpp" #include "strata/kernels/shared_expert.hpp" #include "strata/kernels/verify_kernels.hpp" +#include "strata/kernels/dflash2.hpp" #include #include @@ -779,35 +780,42 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) && mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_); if (!ok) { err = "verify: mapped staging allocation failed " + strata::core::pin_exhausted_hint(); return false; } - // STRATA_TAP_FILE: the DFlash2 experiment's hook (see verify.hpp); off unless the variable is set - if (const char* tap_path = std::getenv("STRATA_TAP_FILE"); tap_path != nullptr && tap_path[0] != '\0' && lb_ == 0 && - le_ == g.n_layers) { + // DFlash2 taps: set_taps (the drafter) or STRATA_TAP_FILE (the research dump); off, and nothing is allocated or captured, otherwise + const char* tap_path = std::getenv("STRATA_TAP_FILE"); + if (tap_path != nullptr && tap_path[0] == '\0') tap_path = nullptr; + if ((tap_path != nullptr || !tap_req_.empty()) && lb_ == 0 && le_ == g.n_layers) { tap_layers_.clear(); - const char* tl = std::getenv("STRATA_TAP_LAYERS"); - std::string list = tl != nullptr && tl[0] != '\0' ? tl : "5,15,25,35,45"; - for (size_t i = 0; i < list.size();) { - const size_t j = list.find(',', i); - const int l = std::atoi(list.substr(i, j == std::string::npos ? std::string::npos : j - i).c_str()); - if (l >= 0 && l < g.n_layers - 1) tap_layers_.push_back(l); - if (j == std::string::npos) break; - i = j + 1; + if (tap_path == nullptr) { + for (int l : tap_req_) if (l >= 0 && l < g.n_layers - 1) tap_layers_.push_back(l); + } else { + const char* tl = std::getenv("STRATA_TAP_LAYERS"); + std::string list = tl != nullptr && tl[0] != '\0' ? tl : "5,15,25,35,45"; + for (size_t i = 0; i < list.size();) { + const size_t j = list.find(',', i); + const int l = std::atoi(list.substr(i, j == std::string::npos ? std::string::npos : j - i).c_str()); + if (l >= 0 && l < g.n_layers - 1) tap_layers_.push_back(l); + if (j == std::string::npos) break; + i = j + 1; + } } tap_slot_.assign((size_t) g.n_layers, -1); for (size_t i = 0; i < tap_layers_.size(); ++i) tap_slot_[(size_t) tap_layers_[i]] = (int) i; const size_t nt = tap_layers_.size(); if (nt == 0 || cudaMalloc((void**) &tap_dev_, (size_t) T * nt * N * 4) != cudaSuccess || - cudaMalloc((void**) &tap_scratch_, (size_t) HC * N * 4) != cudaSuccess || - !mapped((size_t) T * nt * N * 4, (void**) &h_tap_, (void**) &m_tap_)) { - err = "verify: the STRATA_TAP_FILE buffers could not be allocated"; + (tap_path != nullptr && (cudaMalloc((void**) &tap_scratch_, (size_t) HC * N * 4) != cudaSuccess || + !mapped((size_t) T * nt * N * 4, (void**) &h_tap_, (void**) &m_tap_)))) { + err = "verify: the DFlash2 tap buffers could not be allocated"; return false; } - tap_file_ = std::fopen(tap_path, "wb"); - if (tap_file_ == nullptr) { err = std::string("verify: cannot write STRATA_TAP_FILE ") + tap_path; return false; } - const int32_t hdr[4] = {0x50415453 /* 'STAP' */, 1, (int32_t) N, (int32_t) nt}; - std::fwrite(hdr, sizeof hdr, 1, tap_file_); - for (int l : tap_layers_) { const int32_t v = l; std::fwrite(&v, sizeof v, 1, tap_file_); } + if (tap_path != nullptr) { + tap_file_ = std::fopen(tap_path, "wb"); + if (tap_file_ == nullptr) { err = std::string("verify: cannot write STRATA_TAP_FILE ") + tap_path; return false; } + const int32_t hdr[4] = {0x50415453 /* 'STAP' */, 1, (int32_t) N, (int32_t) nt}; + std::fwrite(hdr, sizeof hdr, 1, tap_file_); + for (int l : tap_layers_) { const int32_t v = l; std::fwrite(&v, sizeof v, 1, tap_file_); } + std::fprintf(stderr, "strata: STRATA_TAP_FILE %s: %zu taps of %lld floats per row\n", tap_path, nt, (long long) N); + } tap_on_ = true; - std::fprintf(stderr, "strata: STRATA_TAP_FILE %s: %zu taps of %lld floats per row\n", tap_path, nt, (long long) N); } if (bal_ != nullptr) { // set_pcie_balance: four stamp words per (layer, group) if (!mapped((size_t) g.n_layers * 2 * 4 * 8, (void**) &h_bal_, (void**) &m_bal_)) { @@ -2179,13 +2187,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { device_plan_ ? skip_ + grp : nullptr, ring, cs); stamp(l, 24, grp); if (tap_on_ && !batch_rec_ && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0) { - // the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it) + // the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it), the mean of + // the hc streams, all rows of the group in one launch const int64_t nt = (int64_t) tap_layers_.size(); - for (int t = tb; t < te; ++t) { - cudaMemcpyAsync(tap_scratch_, Rt(t), (size_t) HC * N * 4, cudaMemcpyDeviceToDevice, cs); - gr_write(tap_scratch_, bo_ + t * N, inj2_ + t * HC, gs, tap_scratch_, cs); - hc_mean_streams(tap_scratch_, tap_dev_ + ((size_t) t * nt + (size_t) tap_slot_[(size_t) l]) * N, N, (int) HC, cs); - } + strata::kernels::df2_tap_gr(Rt(tb), HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, tap_dev_ + ((size_t) tb * nt + (size_t) tap_slot_[(size_t) l]) * N, + nt * N, n, N, (int) HC, cs); } if (l == g.n_layers - 1) { if (!fuse_head_gr) { @@ -2314,7 +2320,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (nan_guard_on()) strata::kernels::logits_nonfinite_rows(head_logits_, T, (int) n_vocab_, m_nf_, cs); } stamp(g.n_layers, 1, 0); - if (tap_on_ && !batch_rec_) copy_from_mapped(m_tap_, tap_dev_, (int64_t) T * (int64_t) tap_layers_.size() * N, cs); + if (tap_on_ && !batch_rec_ && tap_file_ != nullptr) copy_from_mapped(m_tap_, tap_dev_, (int64_t) T * (int64_t) tap_layers_.size() * N, cs); return true; } @@ -3096,7 +3102,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, } } for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t]; - if (tap_on_ && !batch_rec_) tap_write(T, tokens, pos0); + if (tap_file_ != nullptr && !batch_rec_) tap_write(T, tokens, pos0); note_nonfinite(T, nullptr); if (static const bool dbg = std::getenv("STRATA_DBG_NAN") != nullptr; dbg) { // debug: the first non-finite head static bool reported = false; diff --git a/src/kernels/cuda/dflash2.cu b/src/kernels/cuda/dflash2.cu new file mode 100644 index 00000000..82c40ad6 --- /dev/null +++ b/src/kernels/cuda/dflash2.cu @@ -0,0 +1,412 @@ +// src/kernels/cuda/dflash2.cu - the small kernels of the DFlash2 drafter. See include/strata/kernels/dflash2.hpp. +#include "strata/kernels/dflash2.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace strata::kernels { +namespace { + +constexpr int HD = kDf2Hd; + +void check(const char* what) { + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "dflash2 kernel %s: %s\n", what, cudaGetErrorString(e)); + throw std::runtime_error(std::string("dflash2 kernel ") + what + ": " + cudaGetErrorString(e)); + } +} + +__device__ __forceinline__ float bf16f(uint16_t h) { return __uint_as_float((uint32_t) h << 16); } + +// ---- the grouped dynamic 2-tap convolution over the block's rows +__global__ void conv_kernel(const float* __restrict__ x, const float* __restrict__ dyn, int dyn_stride, const float* __restrict__ base, + const float* __restrict__ resid, float* __restrict__ out, int rows, int H, int group) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * H) return; + const int b = i / H, c = i % H; + const int groups = H / group; + float acc = 0.0f; +#pragma unroll + for (int o = 0; o < 2; ++o) { + if (b - o < 0) continue; + const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group]; + acc = fmaf(k, x[(size_t) (b - o) * H + c], acc); + } + out[i] = resid ? resid[i] + acc : acc; +} + +__global__ void rope_table_kernel(const int32_t* __restrict__ pos, int rows, float theta, float* __restrict__ table) { + const int r = blockIdx.x, i = threadIdx.x; // 64 threads + if (r >= rows) return; + const double inv = pow((double) theta, -(double) (2 * i) / (double) HD); + double ang = (double) pos[r] * inv; + const double two_pi = 6.283185307179586476925286766559; + ang -= two_pi * rint(ang / two_pi); // [-pi, pi] + float s, c; + sincosf((float) ang, &s, &c); + table[(r * 2 + 0) * 64 + i] = c; + table[(r * 2 + 1) * 64 + i] = s; +} + +// one block per (row, head), 128 threads: out = rope(rmsnorm(in) * gamma) +__global__ void norm_rope_kernel(const float* __restrict__ in, int in_stride, const float* __restrict__ gamma, const int32_t* __restrict__ pos, + const float* __restrict__ table, float* __restrict__ out, int slot_mod, int heads, float eps) { + const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x; + __shared__ float red[4]; + __shared__ float y[HD]; + const float x = in[(size_t) r * in_stride + h * HD + d]; + float ss = x * x; + for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + if ((d & 31) == 0) red[d >> 5] = ss; + __syncthreads(); + const float tot = red[0] + red[1] + red[2] + red[3]; + const float v = x * rsqrtf(tot / (float) HD + eps) * gamma[d]; + float res = v; + if (table != nullptr) { + y[d] = v; + __syncthreads(); + const int i = d & 63; + const float c = table[(r * 2 + 0) * 64 + i], s = table[(r * 2 + 1) * 64 + i]; + res = d < 64 ? v * c - y[d + 64] * s : v * c + y[d - 64] * s; + } + const int slot = slot_mod > 0 ? (int) (pos[r] % slot_mod) : r; + out[((size_t) slot * heads + h) * HD + d] = res; +} + +__global__ void copy_rows_kernel(const float* __restrict__ in, float* __restrict__ out, const int32_t* __restrict__ pos, int slot_mod, int rows, int cols) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * cols) return; + const int r = i / cols, c = i % cols; + const int slot = slot_mod > 0 ? (int) (pos[r] % slot_mod) : r; + out[(size_t) slot * cols + c] = in[i]; +} + +// ---- attention. grid (8 K/V heads, kDf2MaxChunks), 256 threads. 32 queries (4 heads x 8 rows) per block share each key tile. +constexpr int KS = 129; // smem row stride of the K / V / Q tiles (conflict-free) +__global__ void __launch_bounds__(256) attn_part_kernel(const float* __restrict__ q, const float* __restrict__ kring, const float* __restrict__ vring, + const float* __restrict__ kblk, const float* __restrict__ vblk, + const int32_t* __restrict__ anchor_pos, int ring_slots, int window, float* __restrict__ part) { + __shared__ float Qs[32 * KS]; + __shared__ float Ks[32 * KS]; // the K tile, then the V tile + __shared__ float Ss[32 * 33]; + const int kvh = blockIdx.x, chunk = blockIdx.y, tid = threadIdx.x; + const int s = *anchor_pos; + const int lo = s - (window - 1) > 0 ? s - (window - 1) : 0; + const int nctx = s - lo; + const int nkeys = nctx + kDf2Rows; + const int qi = tid >> 3, tg = tid & 7; + const int qrow = qi >> 2, qg = qi & 3; + float* const pout = part + (((size_t) chunk * kDf2Kv + kvh) * 32 + qi) * 130; + const int k_begin = chunk * kDf2Chunk; + if (k_begin >= nkeys) { + if (tg == 0) { pout[0] = -INFINITY; pout[1] = 0.0f; } + for (int e = 0; e < 16; ++e) pout[2 + e * 8 + tg] = 0.0f; + return; + } + const float scale = rsqrtf((float) HD); + for (int i = tid; i < 32 * HD; i += 256) { + const int a = i / HD, d = i % HD; + const int row = a >> 2, g = a & 3; + Qs[a * KS + d] = q[((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d] * scale; + } + float m = -INFINITY, l = 0.0f; + float O[16]; +#pragma unroll + for (int e = 0; e < 16; ++e) O[e] = 0.0f; + const int k_end = min(k_begin + kDf2Chunk, nkeys); + for (int k0 = k_begin; k0 < k_end; k0 += 32) { + __syncthreads(); // Ks free (previous tile's V reads done), Qs written (first tile) + for (int i = tid; i < 32 * HD; i += 256) { + const int t = i / HD, d = i % HD, k = k0 + t; + float v = 0.0f; + if (k < nctx) v = kring[((size_t) ((lo + k) % ring_slots) * kDf2Kv + kvh) * HD + d]; + else if (k < nkeys) v = kblk[((size_t) (k - nctx) * kDf2Kv + kvh) * HD + d]; + Ks[t * KS + d] = v; + } + __syncthreads(); + float sc[4] = {0.f, 0.f, 0.f, 0.f}; +#pragma unroll 8 + for (int d = 0; d < HD; ++d) { + const float qv = Qs[qi * KS + d]; +#pragma unroll + for (int u = 0; u < 4; ++u) sc[u] = fmaf(qv, Ks[(tg * 4 + u) * KS + d], sc[u]); + } + float tmax = -INFINITY; +#pragma unroll + for (int u = 0; u < 4; ++u) { + const int k = k0 + tg * 4 + u; + bool ok = k < nkeys; + if (ok && k < nctx) ok = (lo + k) > (s + qrow - window); // s + row - j < window + sc[u] = ok ? sc[u] : -INFINITY; + tmax = fmaxf(tmax, sc[u]); + } + tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 1)); + tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 2)); + tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 4)); + const float mn = fmaxf(m, tmax); + const float corr = (m == -INFINITY) ? 0.0f : __expf(m - mn); + float psum = 0.0f; +#pragma unroll + for (int u = 0; u < 4; ++u) { + const float p = sc[u] == -INFINITY ? 0.0f : __expf(sc[u] - mn); + Ss[qi * 33 + tg * 4 + u] = p; + psum += p; + } + psum += __shfl_xor_sync(0xffffffffu, psum, 1); + psum += __shfl_xor_sync(0xffffffffu, psum, 2); + psum += __shfl_xor_sync(0xffffffffu, psum, 4); + l = l * corr + psum; + m = mn; +#pragma unroll + for (int e = 0; e < 16; ++e) O[e] *= corr; + __syncthreads(); // Ss complete; every read of Ks done + for (int i = tid; i < 32 * HD; i += 256) { + const int t = i / HD, d = i % HD, k = k0 + t; + float v = 0.0f; + if (k < nctx) v = vring[((size_t) ((lo + k) % ring_slots) * kDf2Kv + kvh) * HD + d]; + else if (k < nkeys) v = vblk[((size_t) (k - nctx) * kDf2Kv + kvh) * HD + d]; + Ks[t * KS + d] = v; + } + __syncthreads(); + for (int t = 0; t < 32; ++t) { + const float p = Ss[qi * 33 + t]; +#pragma unroll + for (int e = 0; e < 16; ++e) O[e] = fmaf(p, Ks[t * KS + e * 8 + tg], O[e]); + } + } + if (tg == 0) { pout[0] = m; pout[1] = l; } +#pragma unroll + for (int e = 0; e < 16; ++e) pout[2 + e * 8 + tg] = O[e]; + (void) qg; +} + +__global__ void attn_merge_kernel(const float* __restrict__ part, float* __restrict__ out) { + const int a = blockIdx.x; // kvh * 32 + qi + const int kvh = a >> 5, qi = a & 31, d = threadIdx.x; + float M = -INFINITY; + for (int c = 0; c < kDf2MaxChunks; ++c) M = fmaxf(M, part[(((size_t) c * kDf2Kv + kvh) * 32 + qi) * 130]); + float L = 0.0f, o = 0.0f; + for (int c = 0; c < kDf2MaxChunks; ++c) { + const float* p = part + (((size_t) c * kDf2Kv + kvh) * 32 + qi) * 130; + const float mc = p[0]; + const float w = (mc == -INFINITY) ? 0.0f : __expf(mc - M); + L += p[1] * w; + o = fmaf(p[2 + d], w, o); + } + const int row = qi >> 2, g = qi & 3; + out[((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d] = L > 0.0f ? o / L : 0.0f; +} + +// ---- top-16 +constexpr int TK_CHUNK_MAX = 4096; +__device__ __forceinline__ bool better(float va, int ia, float vb, int ib) { return va > vb || (va == vb && ia < ib); } + +__global__ void topk_part_kernel(const float* __restrict__ logits, int n, float* __restrict__ cval, int32_t* __restrict__ cidx) { + __shared__ float vals[TK_CHUNK_MAX]; + __shared__ float wv[8]; + __shared__ int wi[8]; + __shared__ int win; + const int row = blockIdx.x, blk = blockIdx.y, tid = threadIdx.x; + const int cs = (n + kDf2TopBlocks - 1) / kDf2TopBlocks; + const int c0 = blk * cs, c1 = min(c0 + cs, n); + for (int i = tid; i < cs; i += 256) vals[i] = (c0 + i < c1) ? logits[(size_t) row * n + c0 + i] : -INFINITY; + __syncthreads(); + for (int k = 0; k < kDf2TopK; ++k) { + float bv = -INFINITY; + int bi = 0x7fffffff; + for (int i = tid; i < cs; i += 256) + if (better(vals[i], i, bv, bi)) { bv = vals[i]; bi = i; } + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o); + if (better(ov, oi, bv, bi)) { bv = ov; bi = oi; } + } + if ((tid & 31) == 0) { wv[tid >> 5] = bv; wi[tid >> 5] = bi; } + __syncthreads(); + if (tid == 0) { + float v = wv[0]; + int ix = wi[0]; + for (int w = 1; w < 8; ++w) + if (better(wv[w], wi[w], v, ix)) { v = wv[w]; ix = wi[w]; } + const size_t o = ((size_t) row * kDf2TopBlocks + blk) * kDf2TopK + k; + cval[o] = v; + cidx[o] = v == -INFINITY ? -1 : c0 + ix; + win = ix; + if (v != -INFINITY) vals[ix] = -INFINITY; + } + __syncthreads(); + } +} + +__global__ void topk_merge_kernel(const float* __restrict__ cval, const int32_t* __restrict__ cidx, const int32_t* __restrict__ idx_map, + float* __restrict__ val, int32_t* __restrict__ tok) { + constexpr int NC = kDf2TopBlocks * kDf2TopK; + __shared__ float sv[NC]; + __shared__ int si[NC]; + __shared__ float wv[8]; + __shared__ int wi[8], wp[8]; + const int row = blockIdx.x, tid = threadIdx.x; + for (int i = tid; i < NC; i += 256) { sv[i] = cval[(size_t) row * NC + i]; si[i] = cidx[(size_t) row * NC + i]; } + __syncthreads(); + for (int k = 0; k < kDf2TopK; ++k) { + float bv = -INFINITY; + int bi = 0x7fffffff, bp = -1; + for (int i = tid; i < NC; i += 256) + if (si[i] >= 0 && better(sv[i], si[i], bv, bi)) { bv = sv[i]; bi = si[i]; bp = i; } + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o); + const int op = __shfl_xor_sync(0xffffffffu, bp, o); + if (better(ov, oi, bv, bi)) { bv = ov; bi = oi; bp = op; } + } + if ((tid & 31) == 0) { wv[tid >> 5] = bv; wi[tid >> 5] = bi; wp[tid >> 5] = bp; } + __syncthreads(); + if (tid == 0) { + float v = wv[0]; + int ix = wi[0], p = wp[0]; + for (int w = 1; w < 8; ++w) + if (better(wv[w], wi[w], v, ix)) { v = wv[w]; ix = wi[w]; p = wp[w]; } + if (p >= 0) { si[p] = -1; } + val[row * kDf2TopK + k] = v; + tok[row * kDf2TopK + k] = p >= 0 ? (idx_map ? idx_map[ix] : ix) : 0; + } + __syncthreads(); + } +} + +// ---- the selector's walk: one block of 256 threads +__global__ void select_kernel(const float* __restrict__ hp, const float* __restrict__ unary, const int32_t* __restrict__ tok, + const uint16_t* __restrict__ pred_cb, const uint16_t* __restrict__ succ_cb, int rank, int rows, + const int32_t* __restrict__ anchor_tok, int32_t* __restrict__ out_tok, float* __restrict__ out_prob) { + __shared__ float vp[256]; + __shared__ float sc[kDf2TopK]; + __shared__ int prev; + const int tid = threadIdx.x, w = tid >> 5, lane = tid & 31; + if (tid == 0) prev = *anchor_tok; + __syncthreads(); + for (int i = 0; i < rows; ++i) { + vp[tid] = bf16f(pred_cb[(size_t) prev * rank + tid]) * hp[(size_t) i * rank + tid]; + __syncthreads(); + for (int j = w * 2; j < w * 2 + 2; ++j) { + const int t = tok[i * kDf2TopK + j]; + const uint4 raw = *reinterpret_cast(succ_cb + (size_t) t * rank + lane * 8); + const uint32_t u[4] = {raw.x, raw.y, raw.z, raw.w}; + float acc = 0.0f; +#pragma unroll + for (int e = 0; e < 4; ++e) { + acc = fmaf(__uint_as_float(u[e] << 16), vp[lane * 8 + e * 2], acc); + acc = fmaf(__uint_as_float(u[e] & 0xffff0000u), vp[lane * 8 + e * 2 + 1], acc); + } + for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor_sync(0xffffffffu, acc, o); + if (lane == 0) sc[j] = unary[i * kDf2TopK + j] + acc; + } + __syncthreads(); + if (tid == 0) { + int bj = 0; + float bv = sc[0]; + for (int j = 1; j < kDf2TopK; ++j) + if (sc[j] > bv) { bv = sc[j]; bj = j; } + float z = 0.0f; + for (int j = 0; j < kDf2TopK; ++j) z += __expf(sc[j] - bv); + out_tok[i] = tok[i * kDf2TopK + bj]; + out_prob[i] = 1.0f / z; + prev = out_tok[i]; + } + __syncthreads(); + } +} + +__global__ void tap_rows_kernel(const float* __restrict__ R, float* __restrict__ out, int64_t out_stride, int64_t n, int hc) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + const int r = blockIdx.y; + if (i >= n) return; + float s = 0.0f; + for (int c = 0; c < hc; ++c) s += R[((size_t) r * hc + c) * n + i]; + out[(size_t) r * out_stride + i] = s / (float) hc; +} + +__global__ void tap_gr_kernel(const float* __restrict__ R, int64_t R_stride, const float* __restrict__ bo, int64_t bo_stride, + const float* __restrict__ inject, int64_t inj_stride, float* __restrict__ out, int64_t out_stride, int64_t n, int hc) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + const int r = blockIdx.y; + if (i >= n) return; + float wsum = 0.0f, rs = 0.0f; + for (int c = 0; c < hc; ++c) { + const float x = inject[(size_t) r * inj_stride + c] / (float) hc; + wsum += 2.0f / (1.0f + expf(-x)); + rs += R[(size_t) r * R_stride + (size_t) c * n + i]; + } + out[(size_t) r * out_stride + i] = (rs + bo[(size_t) r * bo_stride + i] * wsum) / (float) hc; +} + +} // namespace + +void df2_tap_gr(const float* R, int64_t R_stride, const float* bo, int64_t bo_stride, const float* inject, int64_t inj_stride, float* out, int64_t out_stride, + int rows, int64_t n_embd, int hc, void* stream) { + tap_gr_kernel<<>>(R, R_stride, bo, bo_stride, inject, inj_stride, out, + out_stride, n_embd, hc); + check("tap_gr"); +} + +void df2_conv(const float* x, const float* dyn, int dyn_stride, const float* base, const float* resid, float* out, int rows, int H, int group, + void* stream) { + const int n = rows * H; + conv_kernel<<<(n + 255) / 256, 256, 0, (cudaStream_t) stream>>>(x, dyn, dyn_stride, base, resid, out, rows, H, group); + check("conv"); +} + +void df2_rope_table(const int32_t* pos, int rows, float theta, float* table, void* stream) { + rope_table_kernel<<>>(pos, rows, theta, table); + check("rope_table"); +} + +void df2_norm_rope(const float* in, int in_stride, const float* gamma, const int32_t* pos, const float* rope_table, float* out, int slot_mod, + int rows, int heads, float eps, void* stream) { + norm_rope_kernel<<>>(in, in_stride, gamma, pos, rope_table, out, slot_mod, heads, eps); + check("norm_rope"); +} + +void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod, int rows, int cols, void* stream) { + const int n = rows * cols; + copy_rows_kernel<<<(n + 255) / 256, 256, 0, (cudaStream_t) stream>>>(in, out, pos, slot_mod, rows, cols); + check("copy_rows"); +} + +void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, + int ring_slots, int window, float* part, float* out, void* stream) { + attn_part_kernel<<>>(q, kring, vring, kblk, vblk, anchor_pos, ring_slots, window, part); + check("attn_part"); + attn_merge_kernel<<>>(part, out); + check("attn_merge"); +} + +void df2_topk(const float* logits, int n, const int32_t* idx_map, int rows, uint32_t* scratch, float* val, int32_t* tok, void* stream) { + if ((n + kDf2TopBlocks - 1) / kDf2TopBlocks > TK_CHUNK_MAX) throw std::invalid_argument("df2_topk: too many logits per row"); + float* cval = reinterpret_cast(scratch); + int32_t* cidx = reinterpret_cast(scratch + (size_t) rows * kDf2TopBlocks * kDf2TopK); + topk_part_kernel<<>>(logits, n, cval, cidx); + check("topk_part"); + topk_merge_kernel<<>>(cval, cidx, idx_map, val, tok); + check("topk_merge"); +} + +void df2_select(const float* hp, const float* unary, const int32_t* tok, const uint16_t* pred_cb, const uint16_t* succ_cb, int rank, int rows, + const int32_t* anchor_tok, int32_t* out_tok, float* out_prob, void* stream) { + if (rank != 256) throw std::invalid_argument("df2_select: the selector rank must be 256"); + select_kernel<<<1, 256, 0, (cudaStream_t) stream>>>(hp, unary, tok, pred_cb, succ_cb, rank, rows, anchor_tok, out_tok, out_prob); + check("select"); +} + +void df2_tap_rows(const float* R, float* out, int64_t out_stride, int64_t n_embd, int hc, int rows, void* stream) { + tap_rows_kernel<<>>(R, out, out_stride, n_embd, hc); + check("tap_rows"); +} + +} // namespace strata::kernels diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index c9b45354..6cb888e5 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -1,6 +1,9 @@ // src/prefill/prefill.cpp - see include/strata/prefill/prefill.hpp. #include "strata/kernels/fused_gr.hpp" #include "strata/prefill/prefill.hpp" +#if defined(STRATA_HAVE_DFLASH2) +#include "strata/kernels/dflash2.hpp" +#endif #include "strata/prefill/warm_policy.hpp" #include #if defined(__cpp_lib_atomic_wait) @@ -1051,7 +1054,19 @@ strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, co } // namespace Prefill::Prefill() : impl_(new Impl) {} -Prefill::~Prefill() { release(); } +Prefill::~Prefill() { + clear_taps(); + release(); +} + +void Prefill::clear_taps() { + if (tap_dev_ != nullptr) { + cudaFree(tap_dev_); + tap_dev_ = nullptr; + } + tap_layers_.clear(); + on_taps = nullptr; +} void Prefill::reset() { release(); @@ -2680,6 +2695,20 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri int ple_buf = 0; if (hand_in_ == nullptr) stopped_at_ = -1; +#if defined(STRATA_HAVE_DFLASH2) + std::vector tap_slot; + if (!tap_layers_.empty() && stage_lb_ == 0 && (stage_le_ < 0 || stage_le_ == g.n_layers)) { + if (tap_dev_ == nullptr && + cudaMalloc((void**) &tap_dev_, (size_t) tap_cap_ * tap_layers_.size() * (size_t) g.n_embd * 4) != cudaSuccess) { + (void) cudaGetLastError(); + tap_dev_ = nullptr; + err = "prefill: the DFlash2 tap staging does not fit in VRAM"; + return false; + } + tap_slot.assign((size_t) g.n_layers, -1); + for (size_t i = 0; i < tap_layers_.size(); ++i) tap_slot[(size_t) tap_layers_[i]] = (int) i; + } +#endif for (int64_t c0 = 0; c0 < n; c0 += C) { if (should_stop && should_stop()) { err = "cancelled"; return false; } // the first stage: end the run before this chunk (every chunk before it is handed on; the caller's drain @@ -2691,6 +2720,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri if (std::getenv("STRATA_TRACE")) { std::fprintf(stderr, "strata trace: prompt chunk %lld of %lld\n", (long long) c0, (long long) n); std::fflush(stderr); } const int64_t T = std::min(C, n - c0), p0 = pos0 + c0; core::progress_at("reading the prompt (batched): preparing the chunk from token", p0); // #251 +#if defined(STRATA_HAVE_DFLASH2) + // DFlash2 prompt taps: the rows of this chunk at positions >= tap_first_ (the drafter looks back one window) + const int64_t tap_t0 = tap_dev_ != nullptr ? std::min(T, std::max(0, tap_first_ - p0)) : T; + const int64_t tap_rows = T - tap_t0; + if (tap_rows > tap_cap_) { err = "prefill: the DFlash2 tap staging is smaller than the chunk's tapped rows"; return false; } +#else + const int64_t tap_t0 = 0, tap_rows = 0; +#endif ++stats_.chunks; pt.mark(kPfStart, cs); const auto tsetup = Clock::now(); @@ -4836,6 +4873,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri } if (steered && !cv_fused) // --control-vector-scaled strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs); +#if defined(STRATA_HAVE_DFLASH2) + if (half == 1 && tap_rows > 0 && tap_slot[(size_t) l] >= 0) // DFlash2: this layer's completed output, mean of the streams + strata::kernels::df2_tap_rows(m.R + (size_t) tap_t0 * D, tap_dev_ + (size_t) tap_slot[(size_t) l] * N, (int64_t) tap_layers_.size() * N, N, + (int) HC, (int) tap_rows, m.cs); +#endif } } if (!ple_land()) return false; // a stage that ends before layer 1: the rows land anyway, the next gather starts @@ -4933,6 +4975,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri std::fclose(f); } } +#if defined(STRATA_HAVE_DFLASH2) + if (tap_rows > 0 && on_taps) { + if (cudaStreamSynchronize(m.cs) != cudaSuccess) { err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); return false; } + if (!on_taps(tap_dev_, tap_rows, p0 + tap_t0, err)) return false; + } +#endif if (on_chunk || on_stage_chunk) { const auto toc = Clock::now(); if (cudaStreamSynchronize(m.cs) != cudaSuccess) { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d7116d2d..4f75c9fe 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -66,6 +66,9 @@ #include "strata/core/native_head.hpp" #include "strata/core/verify.hpp" #include "strata/core/mtp.hpp" +#if defined(STRATA_HAVE_DFLASH2) +#include "strata/core/dflash2.hpp" +#endif #include "strata/prefill/prefill.hpp" #if defined(STRATA_PREFILL_MMQ) #include "strata/prefill/moe_mmq.hpp" @@ -781,6 +784,9 @@ struct Options { std::string mtp_q4; ///< "" (off), all, proj (the projections only) or head (the draft head only) /// --mtp-draft-vocab FILE (opt-in): the draft head's token subset from FILE instead of /draft_vocab.bin std::string mtp_draft_vocab; + /// --draft dflash2 --draft-model PACK (opt-in, CUDA / HIP): the DFlash2 block drafter for Qwen3.8-Flash-Next (tools/dflash2_pack.py) drafts instead + /// of the MTP layer, which stays loaded as the fallback. Needs --mtp, --spec and a native pack; a missing pack falls back to the MTP. + std::string draft, draft_model; /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. @@ -933,6 +939,8 @@ void usage() { " (default) or one per stream (llama.cpp's MTP graph)\n" " --mtp-q4 all|proj|head opt-in: the draft layer's projections and/or draft head as 4-bit copies\n" " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" + " --draft mtp|dflash2 the draft source (default mtp); dflash2 needs --draft-model PACK (tools/dflash2_pack.py)\n" + " and keeps the MTP layer loaded as the fallback (opt-in, Flash-Next, CUDA / HIP)\n" " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" " --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" @@ -2672,6 +2680,14 @@ int main(int argc, char** argv) { } } else if (a == "--mtp-draft-vocab") o.mtp_draft_vocab = next("--mtp-draft-vocab"); + else if (a == "--draft") { + o.draft = next("--draft"); + if (o.draft != "dflash2" && o.draft != "mtp") { + std::fprintf(stderr, "strata generate: --draft takes mtp or dflash2\n"); + std::exit(2); + } + } + else if (a == "--draft-model") o.draft_model = next("--draft-model"); else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); else if (a == "--control-vector-scaled") { // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive @@ -5395,6 +5411,10 @@ int main(int argc, char** argv) { // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts. // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages. strata::core::MtpDrafter mtp; +#if defined(STRATA_HAVE_DFLASH2) + strata::core::Dflash2Drafter df2; // --draft dflash2 (CLI spec loop only) + bool use_df2 = false; +#endif // the draft layer's geometry (the canonical model's MTP head), `static` because MtpDrafter keeps a reference; the batch // slots' draft-KV copies use this one too static const strata::core::ModelGeometry draft_geometry{}; @@ -5418,6 +5438,23 @@ int main(int argc, char** argv) { if (o.pipeline_windows >= 2) mtp.set_force_capture(true); if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st && !mtp_first ? last_st->ss : ss, mtp_t, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; } mtp.set_ple_session(&ss); +#if defined(STRATA_HAVE_DFLASH2) + if (o.draft == "dflash2") { + const char* why = o.mtp.empty() ? "it needs --mtp (the fallback) and --spec 2 or more" + : !native_pack ? "it needs a native pack" + : multi_gpu || o.batch > 0 || o.serve ? "it is for one card and the CLI run (not --serve, --batch or a layer split) in this build" + : o.draft_model.empty() ? "it needs --draft-model PACK (tools/dflash2_pack.py)" : nullptr; + if (why == nullptr) { + if (df2.load(o.draft_model, 0, err)) { + use_df2 = true; + } else { + std::fprintf(stderr, "strata generate: --draft dflash2: %s; the MTP drafts instead\n", err.c_str()); + } + } else { + std::fprintf(stderr, "strata generate: --draft dflash2 is off: %s; the MTP drafts instead\n", why); + } + } +#endif if (batch_mtp) { // Slot b's drafter lives where the solo drafter does (the guard above: the last stage's GPU), carved from the // LAST stage's slot-b session (bslot_ss.back(): stage 0's on one GPU): it borrows that session's context @@ -15636,6 +15673,13 @@ int main(int argc, char** argv) { return e.empty() && mtp.prefill(R_rows, nxt.data(), T, p0, e); }; } +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2) { // the drafter's context: the last 2047 prompt rows' taps + df2.reset(); + prefill.set_taps(df2.tap_layers(), std::max(0, n_prompt - 2047), 2048); + prefill.on_taps = [&](const float* taps, int64_t rows, int64_t pos0, std::string& e) -> bool { return df2.context(taps, rows, pos0, e); }; + } +#endif if (!kvg_started) { // the elastic K/V: every cell this run can reach (no loan) kvg_started = true; kvg_start(xcache.slots()); @@ -15672,6 +15716,9 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %zu lent slots refilled in %.1f ms\n", lent.size(), std::chrono::duration(Clock::now() - tr).count()); } +#if defined(STRATA_HAVE_DFLASH2) + prefill.clear_taps(); +#endif prefill_batched_ms = std::chrono::duration(Clock::now() - tp0).count(); prefill_ms += prefill_batched_ms; pos_start = n_batched; @@ -15959,6 +16006,9 @@ int main(int argc, char** argv) { vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers vh.n_slots = xcache.slots(); if (pcie_balance()) ver.set_pcie_balance(&drive.d.pcie_model); +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2) ver.set_taps(df2.tap_layers()); +#endif if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; @@ -15968,6 +16018,17 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2 && !ver.tapping()) { + std::fprintf(stderr, "strata generate: --draft dflash2: the verifier keeps no taps here; the MTP drafts instead\n"); + use_df2 = false; + } + if (use_df2 && !df2.bind(wt, &native_head, o.mtp_draft_vocab.empty() ? o.mtp + "/draft_vocab.bin" : o.mtp_draft_vocab, err)) { + std::fprintf(stderr, "strata generate: --draft dflash2: %s; the MTP drafts instead\n", err.c_str()); + use_df2 = false; + } + if (use_df2) std::fprintf(stderr, "strata generate: DFlash2 drafter on (%s), the MTP layer stays as the fallback\n", o.draft_model.c_str()); +#endif mem_mark("the verifier and the drafter's binding"); ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here if (use_mtp) mtp.set_draft_sampling(sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) @@ -16263,6 +16324,19 @@ int main(int argc, char** argv) { } }).detach(); } + // the next round's drafts after a commit: the MTP chain, or the DFlash2 block from the committed rows' taps + auto draft_next = [&](int T_, int a_) -> bool { +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2) { + int32_t dd[strata::core::Dflash2Drafter::kDrafts]; + float pp[strata::core::Dflash2Drafter::kDrafts]; + if (!df2.draft(ver.tap_dev(), a_ + 1, p, outv[(size_t) a_], dd, pp, err)) return false; + for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; } + return true; + } +#endif + return mtp.draft(T_, outv.data(), p, a_, drafts.data(), err, dprob.data(), (float) o.spec_min_p); + }; while ((int64_t) produced.size() < max_new) { const Clock::time_point t0 = Clock::now(); strata::core::progress_at("spec loop: choosing the window", (int64_t) produced.size()); @@ -16403,8 +16477,7 @@ int main(int argc, char** argv) { total_ms += std::chrono::duration(Clock::now() - t0).count(); break; } - const bool drafted = !use_mtp || (int64_t) produced.size() >= max_new || - mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) o.spec_min_p); + const bool drafted = !use_mtp || (int64_t) produced.size() >= max_new || draft_next(T, a); if (adapt_thr.joinable()) adapt_thr.join(); if (!adapt_ok) return 1; if (!drafted) { @@ -16528,6 +16601,12 @@ int main(int argc, char** argv) { 1000 * pm.g0, 1000 * pm.g); } (void) pool_ms0; +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2 && df2.rounds > 0) + std::printf("%-24s %.3f ms/round drafting (%lld rounds, GPU %.3f), %.0f MiB of VRAM\n", "dflash2", df2.ms_draft / (double) df2.rounds, + (long long) df2.rounds, df2.ms_gpu / (double) df2.rounds, (double) df2.vram_bytes() / 1048576.0); + else +#endif if (use_mtp && rounds > 0) std::printf("%-24s %.3f ms/round drafting (%lld rounds), MTP prompt %.1f ms, %.0f MiB of VRAM\n", "mtp", mtp.ms_draft / (double) mtp.rounds, (long long) mtp.rounds, mtp.ms_prefill, diff --git a/tools/dflash2/mk_parity_case.py b/tools/dflash2/mk_parity_case.py new file mode 100644 index 00000000..a812270c --- /dev/null +++ b/tools/dflash2/mk_parity_case.py @@ -0,0 +1,88 @@ +"""Builds the input of src/core/dflash2_parity.cpp and the torch reference answer. + + python mk_parity_case.py [n_ctx=2300] [vp=20000] [seed=1] + +The case: n_ctx random tap rows (positions 0 .. n_ctx-1), an anchor token at position n_ctx, a head of `vp` random rows (Q8_0, the draft vocabulary +subset path: dvocab maps a row to a token id) and the target embedding rows of the anchor and the mask token. The torch port (dflash2_ref.py, +equal to z-lab's module) gives the reference: the final normalized block rows, the walk's tokens and their probabilities. A context longer than the +2048-token window exercises the ring wrap and the window mask. +""" +import struct +import sys +from pathlib import Path + +import numpy as np +import torch + +sys.path.insert(0, str(Path(__file__).parent)) +import dflash2_ref as R + + +class Embed: + def __init__(self, rows): + self.rows = rows + + def __getitem__(self, ids): + return torch.stack([self.rows[int(i)] for i in ids]) + + +def quant_q8_0(w): + rows, cols = w.shape + b = w.reshape(rows, cols // 32, 32) + amax = np.abs(b).max(axis=-1) + d = amax / 127.0 + inv = np.where(d != 0, 1.0 / np.where(d == 0, 1, d), 0.0) + q = np.rint(b * inv[..., None]).astype(np.int8) + out = np.empty((rows, cols // 32, 34), np.uint8) + out[..., :2] = d.astype(np.float16).view(np.uint8).reshape(rows, cols // 32, 2) + out[..., 2:] = q.view(np.uint8) + return out.tobytes(), (q.astype(np.float32) * d.astype(np.float16).astype(np.float32)[..., None]).reshape(rows, cols) + + +def main(): + st, cfgp, out = sys.argv[1:4] + n_ctx = int(sys.argv[4]) if len(sys.argv) > 4 else 2300 + vp = int(sys.argv[5]) if len(sys.argv) > 5 else 20000 + seed = int(sys.argv[6]) if len(sys.argv) > 6 else 1 + rng = np.random.default_rng(seed) + H, V = 2560, 248320 + mask_id = 248077 + anchor = int(rng.integers(1000, 200000)) + taps = (rng.standard_normal((n_ctx, 5 * H)) * 1.0).astype(np.float32) + emb = (rng.standard_normal((2, H)) * 1.0).astype(np.float32) + dvocab = np.sort(rng.choice(V, size=vp, replace=False)).astype(np.int32) + head = (rng.standard_normal((vp, H)) * 0.05).astype(np.float32) + head_blob, head_dq = quant_q8_0(head) + embed = Embed({anchor: torch.from_numpy(emb[0]), mask_id: torch.from_numpy(emb[1])}) + d = R.Drafter(st, cfgp, embed, torch.from_numpy(head_dq), threads=6) + d.set_context(torch.from_numpy(taps)) + path, _ = d.draft(n_ctx, anchor, 8) # runs the forward; the tail below redoes the selector with the token map + fn = d.last_all.clone() # [8][H] + out_rows = fn[1:] + logits = out_rows @ torch.from_numpy(head_dq).T + unary, idx = torch.topk(logits, 16, dim=-1) + cand = torch.from_numpy(dvocab.astype(np.int64))[idx] + hp = out_rows @ d.w["candidate_selector.hidden_projection.weight"].T + A, B = d.w["candidate_selector.predecessor_codebook"], d.w["candidate_selector.successor_codebook"] + pred = anchor + toks, probs = [], [] + for i in range(7): + sc = unary[i] + (B[cand[i]].float() @ (A[pred].float() * hp[i])) + j = int(torch.argmax(sc)) + probs.append(float(torch.softmax(sc, dim=-1)[j])) + pred = int(cand[i][j]) + toks.append(pred) + with open(out, "wb") as f: + f.write(struct.pack("<4i", n_ctx, anchor, vp, 0)) + f.write(taps.tobytes()) + f.write(emb.tobytes()) + f.write(dvocab.tobytes()) + f.write(head_blob) + f.write(struct.pack("<7i", *toks)) + f.write(struct.pack("<7f", *probs)) + f.write(fn.numpy().astype(np.float32).tobytes()) + print("case written:", out, "n_ctx", n_ctx, "anchor", anchor, "tokens", toks, "probs", [round(p, 3) for p in probs]) + + +if __name__ == "__main__": + main() diff --git a/tools/dflash2_pack.py b/tools/dflash2_pack.py new file mode 100644 index 00000000..8949c148 --- /dev/null +++ b/tools/dflash2_pack.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Pack the incoai DFlash2 drafter for Qwen3.8-Flash-Next (safetensors) into the engine's runtime file. + + python tools/dflash2_pack.py model.safetensors config.json out.pack [--bf16] + +Format (little endian): "DF2P", u32 version (1), u32 index_len, a text index (padded with spaces so the data starts on a 4096 multiple), then +the tensors, each 256-byte aligned at its offset (from the end of the index). Index lines: "cfg ", "t + " (a matrix [out][in] is rows x cols; a vector or codebook row set is the leading dims folded into rows), "end". +dtypes: "q8_0" (ggml Q8_0 blocks, 34 bytes per 32 values, rows of the weight matrix [out][in] one after the other: what the engine's +multi-column MMVQ reads), "f32" (norms, the two conv base kernels), "bf16" (the selector's two codebooks: only gathered rows are read). +The matrices' quantization matches ggml's quantize_row_q8_0 (d = amax / 127, q = round(x / d), d stored as fp16); the research harness +(tools/dflash2/q8test.py) measured no acceptance loss from it. +""" +import json +import struct +import sys + +import numpy as np + +try: + from safetensors import safe_open +except ImportError: # pragma: no cover + sys.exit("needs the safetensors package") + + +def load_tensor(f, name): + """-> float32 ndarray (bf16 tensors are widened exactly)""" + return f.get_tensor(name).float().numpy() + + +def raw_bf16(f, name): + import torch + t = f.get_tensor(name) + return np.ascontiguousarray(t.view(torch.int16).numpy().view(np.uint16)) + + +def quant_q8_0(w): + """w: float32 [rows, cols], cols % 32 == 0 -> bytes of rows * cols/32 blocks (fp16 d, 32 int8)""" + rows, cols = w.shape + assert cols % 32 == 0 + b = w.reshape(rows, cols // 32, 32) + amax = np.abs(b).max(axis=-1) + d = amax / 127.0 + inv = np.where(d != 0, 1.0 / np.where(d == 0, 1, d), 0.0) + q = np.rint(b * inv[..., None]).astype(np.int8) # round half to even; ggml uses roundf (ties are measure-zero for these weights) + out = np.empty((rows, cols // 32, 34), np.uint8) + out[..., :2] = d.astype(np.float16).view(np.uint8).reshape(rows, cols // 32, 2) + out[..., 2:] = q.view(np.uint8) + return out.tobytes() + + +def main(): + if len(sys.argv) < 4: + sys.exit(__doc__) + st_path, cfg_path, out_path = sys.argv[1:4] + cfg = json.load(open(cfg_path)) + dc = cfg["dflash_config"] + f = safe_open(st_path, "pt") + tensors = [] + blobs = [] + + def add(name, dtype, shape, data): + tensors.append({"name": name, "dtype": dtype, "shape": list(shape), "bytes": len(data)}) + blobs.append(data) + + def mat(name, new=None): + w = load_tensor(f, name) + assert w.ndim == 2 + add(new or name, "q8_0", w.shape, quant_q8_0(w)) + + def vec(name, new=None): + w = load_tensor(f, name) + add(new or name, "f32", w.shape, np.ascontiguousarray(w, np.float32).tobytes()) + + L = cfg["num_hidden_layers"] + mat("fc.weight") + vec("hidden_norm.weight") + vec("norm.weight") + for l in range(L): + p = "layers.%d." % l + for n in ("self_attn.q_proj", "self_attn.k_proj", "self_attn.v_proj", "self_attn.o_proj", "mlp.gate_proj", "mlp.up_proj", + "mlp.down_proj", "attention_conv.kernel_projection", "mlp_conv.kernel_projection"): + mat(p + n + ".weight") + for n in ("input_layernorm", "post_attention_layernorm", "self_attn.q_norm", "self_attn.k_norm"): + vec(p + n + ".weight") + vec(p + "attention_conv.base_kernel") + vec(p + "mlp_conv.base_kernel") + mat("candidate_selector.hidden_projection.weight") + for n in ("predecessor_codebook", "successor_codebook"): + a = raw_bf16(f, "candidate_selector." + n) + add("candidate_selector." + n, "bf16", a.shape, a.tobytes()) + + meta = { + "hidden": cfg["hidden_size"], "layers": L, "heads": cfg["num_attention_heads"], "kv_heads": cfg["num_key_value_heads"], + "head_dim": cfg["head_dim"], "inter": cfg["intermediate_size"], "window": cfg["sliding_window"], "rope_theta": cfg["rope_parameters"]["rope_theta"], + "eps": cfg["rms_norm_eps"], "block": dc["block_size"], "conv_group": dc["conv_group_size"], "conv_kernel": dc["conv_kernel_size"], + "mask_token": dc["mask_token_id"], "rank": dc["selector_rank"], "top_k": dc["selector_top_k"], "taps": dc["target_layer_ids"], + "vocab": cfg["vocab_size"], "source": "incoai/Qwen3.8-Flash-Next-DFlash2 a22a1744", + } + # offsets: relative to the end of the (padded) index; 256-byte aligned + off = 0 + for t in tensors: + off = (off + 255) & ~255 + t["offset"] = off + off += t["bytes"] + lines = [] + for k, v in meta.items(): + if k == "taps": + v = ",".join(str(x) for x in v) + lines.append("cfg %s %s" % (k, str(v).replace(" ", "_"))) + for t in tensors: + sh = t["shape"] + [1] * (2 - len(t["shape"])) if len(t["shape"]) < 2 else t["shape"] + lines.append("t %s %s %d %d %d %d" % (t["name"], t["dtype"], int(np.prod(sh[:-1])), sh[-1], t["offset"], t["bytes"])) + lines.append("end") + js = ("\n".join(lines) + "\n").encode() + js += b" " * ((-(len(js) + 12)) % 4096) + with open(out_path, "wb") as o: + o.write(b"DF2P" + struct.pack(" Date: Wed, 21 Oct 2026 15:31:29 +0200 Subject: [PATCH 06/12] dflash2: tiled Q8 GEMM, fused quantizers, head-major K/V ring with a prefetching attention, forked context update, PLE read-ahead, benches --- CMakeLists.txt | 20 +- include/strata/core/dflash2.hpp | 20 +- include/strata/kernels/dflash2.hpp | 27 +- src/core/dflash2.cpp | 205 +++++++++----- src/core/dflash2_attn_bench.cpp | 58 ++++ src/core/dflash2_gemm_bench.cpp | 62 +++++ src/core/dflash2_launch_bench.cu | 68 +++++ src/kernels/cuda/dflash2.cu | 416 ++++++++++++++++++++++++----- src/program/generate.cpp | 23 +- 9 files changed, 750 insertions(+), 149 deletions(-) create mode 100644 src/core/dflash2_attn_bench.cpp create mode 100644 src/core/dflash2_gemm_bench.cpp create mode 100644 src/core/dflash2_launch_bench.cu diff --git a/CMakeLists.txt b/CMakeLists.txt index 4ee0af93..0a918bc5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -735,6 +735,21 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(tune_rocblas PRIVATE hip::host roc::rocblas) endif() + # DFlash2 drafter tools (not built by default: cmake --build --target dflash2_parity dflash2_gemm_bench dflash2_attn_bench): the drafter against + # the torch port on a synthetic case (needs the pack and a case file, tools/dflash2/mk_parity_case.py), and the timing of its Q8 GEMM and attention + add_executable(dflash2_parity EXCLUDE_FROM_ALL src/core/dflash2_parity.cpp) + target_include_directories(dflash2_parity PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_parity PRIVATE strata_engine strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_gemm_bench EXCLUDE_FROM_ALL src/core/dflash2_gemm_bench.cpp) + target_include_directories(dflash2_gemm_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_gemm_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(dflash2_launch_bench EXCLUDE_FROM_ALL src/core/dflash2_launch_bench.cu) + target_include_directories(dflash2_launch_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_launch_bench PRIVATE ${_strata_gpu_runtime_target}) + add_executable(dflash2_attn_bench EXCLUDE_FROM_ALL src/core/dflash2_attn_bench.cpp) + target_include_directories(dflash2_attn_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_attn_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + add_executable(strata src/program/generate.cpp) strata_utf8_manifest(strata) target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) @@ -1084,11 +1099,6 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME verify_parity COMMAND verify_parity --selftest) endif() - # the DFlash2 drafter against the torch port on a synthetic case: needs the pack and a case file (tools/dflash2/mk_parity_case.py), so not a ctest - add_executable(dflash2_parity src/core/dflash2_parity.cpp) - target_include_directories(dflash2_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dflash2_parity PRIVATE strata_engine strata_kernels ${_strata_gpu_runtime_target}) - add_executable(fused_gr_bench src/kernels/fused_gr_bench.cpp) target_include_directories(fused_gr_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(fused_gr_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) diff --git a/include/strata/core/dflash2.hpp b/include/strata/core/dflash2.hpp index 75aadb07..205bff3d 100644 --- a/include/strata/core/dflash2.hpp +++ b/include/strata/core/dflash2.hpp @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -57,6 +58,9 @@ public: /// selector's pick and its probability). The taps pointer must be the same device buffer on every call (graphs are captured on it). bool draft(const float* taps_dev, int n_new, int64_t pos0, int32_t anchor, int32_t* drafts, float* probs, std::string& err); + /// Captures the eight round graphs (n_new = 1..8) on `taps` now, so no round pays for a capture. + bool prepare(const float* taps_dev, std::string& err); + uint64_t vram_bytes() const { return vram_; } int64_t n_draft_vocab() const { return n_dvocab_; } int n_embd() const { return N_; } @@ -65,7 +69,7 @@ public: /// Diagnostics (STRATA_DF2_DUMP): the final normalized block rows of the last draft(), host copy. bool debug_rows(std::vector& rows, std::string& err); - double ms_draft = 0, ms_gpu = 0, ms_ctx = 0; + double ms_draft = 0, ms_gpu = 0, ms_ctx = 0, ms_capture = 0; int64_t rounds = 0; private: @@ -73,8 +77,8 @@ private: const Tensor& find(const std::string& name) const; const void* q8(const std::string& name) const { return blob_ + find(name).off; } const float* f32(const std::string& name) const { return reinterpret_cast(blob_ + find(name).off); } - void mm(const std::string& name, const void* xq, float* y, int ncols); ///< Q8_0 matrix x ncols activation columns (quantized in xq) - void quant(const float* x, int n_in, int ncols); + /// planar Q8 matrices (1..3 of them, same input width) times the planar activations in xqp_ / xdp_ (ncols columns) + void gemm(std::initializer_list names, std::initializer_list outs, int ncols, cudaStream_t cs, const uint8_t* xq, const float* xd); bool record_context(const float* taps, int n, cudaStream_t cs, std::string& err); bool record_block(cudaStream_t cs, std::string& err); bool capture(int n, const float* taps, std::string& err); @@ -84,6 +88,7 @@ private: void stamp(const char* name); void prof_collect(); void prof_report() const; + void prof_free(); int device_ = -1; cudaStream_t cs_ = nullptr; @@ -112,7 +117,14 @@ private: float* hp_out_ = nullptr; float *kring_[8] = {}, *vring_[8] = {}; float *rt_ctx_ = nullptr, *rt_blk_ = nullptr; - uint8_t* xq_ = nullptr; + uint8_t* xq_ = nullptr; ///< the head's q8_1 activations + uint8_t* xqp_ = nullptr; ///< planar activations of the drafter's own GEMMs (kernels/dflash2.hpp) + float* xdp_ = nullptr; + uint8_t* xqc_ = nullptr; ///< the same for the context update, which runs beside the block + float* xdc_ = nullptr; + cudaStream_t cs2_ = nullptr; ///< the context update's branch of the round graph + cudaEvent_t ev_fork_ = nullptr, ev_join_ = nullptr, ev_ctx_[8] = {}; + bool fork_ = false; ///< recording the forked graph: layer l's attention waits for ev_ctx_[l] float *fcy_ = nullptr, *hctx_ = nullptr, *kc_ = nullptr, *vc_ = nullptr; float *h_ = nullptr, *xn_ = nullptr, *xc_ = nullptr, *dyn_ = nullptr, *q_ = nullptr, *qn_ = nullptr, *k_ = nullptr, *v_ = nullptr, *kblk_ = nullptr; float *ao_ = nullptr, *o_ = nullptr, *gate_ = nullptr, *up_ = nullptr, *mlp_ = nullptr, *part_ = nullptr, *fn_ = nullptr; diff --git a/include/strata/kernels/dflash2.hpp b/include/strata/kernels/dflash2.hpp index 8a544f29..0ce4775b 100644 --- a/include/strata/kernels/dflash2.hpp +++ b/include/strata/kernels/dflash2.hpp @@ -14,8 +14,8 @@ constexpr int kDf2Rows = 8; ///< block rows (the anchor + 7 masks) an constexpr int kDf2Kv = 8; ///< K/V heads constexpr int kDf2Gqa = 4; ///< query heads per K/V head constexpr int kDf2Hd = 128; ///< head dim -constexpr int kDf2Chunk = 256; ///< keys per attention block -constexpr int kDf2MaxChunks = 9; ///< ceil((2047 context keys + 8 block keys) / kDf2Chunk) +constexpr int kDf2Chunk = 128; ///< keys per attention block +constexpr int kDf2MaxChunks = 17; ///< ceil((2047 context keys + 8 block keys) / kDf2Chunk) constexpr int kDf2TopK = 16; constexpr int kDf2TopBlocks = 64; ///< partial top-k blocks per row (a block holds at most 4096 logits) @@ -38,12 +38,33 @@ void df2_norm_rope(const float* in, int in_stride, const float* gamma, const int void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod, int rows, int cols, void* stream); /// Attention of the block's 8 query rows (q: [8][32][128], already normed and rotated) over the context ring (kring, vring: -/// [ring_slots][8][128]) and the block's own keys (kblk, vblk: [8][8][128]). Row i at position s + i sees context position j when +/// head-major [8][ring_slots][128]) and the block's own keys (kblk, vblk: [8][8][128]). Row i at position s + i sees context position j when /// s + i - j < window (j in [max(0, s - window + 1), s - 1], slot j % ring_slots) and every block key. `s` is read from *anchor_pos /// on the device. Partials in `part` ([kDf2MaxChunks][8][32][130] floats) are combined into out [8][32*128]. void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, int ring_slots, int window, float* part, float* out, void* stream); +/// The Q8 GEMM the drafter's matrices run on. A weight matrix is TILED (see the layout note in dflash2.cu; df2_q8_tile makes it from GGUF Q8_0 blocks): +/// the int8 plane at `w` (n_out * n_in bytes) then the fp16 scale plane. Activations are planar (df2_quant_rows and the fused quantizers below): +/// xq is int8 [col][n_in] (8 columns of n_in bytes), xd float [col][n_in / 32]. Up to 3 matrices that share the input run in one launch; y (matrix i) +/// is [ncols][n_out]. n_in a multiple of 512, n_out of 16, ncols 1..8 (the other columns of xq are read and dropped). +/// Bench only: pick a GEMM kernel variant (0 = the default). +void df2_gemm_variant(int v); +/// Bench only: attention variants (bit 0 skips Q K^T, bit 1 skips P V). +void df2_attention_variant(int v); +struct Df2Mat { const void* w; float* y; int n_out; }; +void df2_gemm(const Df2Mat* mats, int n, const void* xq, const float* xd, int n_in, int ncols, void* stream); +/// Planar quantization of rows x[ncols][K]. +void df2_quant_rows(const float* x, int K, int ncols, void* xq, float* xd, void* stream); +/// RMS norm (weights gamma) of `rows` rows of N, written to xn (optional) and quantized. +void df2_rms_quant(const float* h, const float* gamma, float* xn, int rows, int N, float eps, void* xq, float* xd, void* stream); +/// df2_conv without residual, then quantized. +void df2_conv_quant(const float* x, const float* dyn, int dyn_stride, const float* base, int rows, int H, int group, void* xq, float* xd, void* stream); +/// silu(gate) * up of `rows` rows of I, quantized. +void df2_swiglu_quant(const float* gate, const float* up, int rows, int I, void* xq, float* xd, void* stream); +/// GGUF Q8_0 blocks (34 bytes) of a matrix with rows of n_in -> the tiled qs plane and the tiled d plane (count = rows * n_in / 32 blocks). +void df2_q8_tile(const void* blocks, void* qs, void* dpl, int n_in, int64_t count, void* stream); + /// Top-16 per row of logits [rows][n] (value-descending; ties to the lower index). idx_map (optional) maps a column to a token id. /// scratch: rows * kDf2TopBlocks * 16 * 2 words. Outputs val[rows][16] and tok[rows][16]. n <= 4096 * kDf2TopBlocks. void df2_topk(const float* logits, int n, const int32_t* idx_map, int rows, uint32_t* scratch, float* val, int32_t* tok, void* stream); diff --git a/src/core/dflash2.cpp b/src/core/dflash2.cpp index 80687d3f..6a04146b 100644 --- a/src/core/dflash2.cpp +++ b/src/core/dflash2.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include namespace strata::core { @@ -38,13 +39,13 @@ constexpr int GGML_Q8_0 = 8; Dflash2Drafter::~Dflash2Drafter() { if (device_ < 0) return; prof_report(); - delete prof_; + prof_free(); const OnDevice on_device(device_); if (cs_) cudaStreamSynchronize(cs_); for (cudaGraphExec_t& e : exec_) if (e) cudaGraphExecDestroy(e); auto fr = [](void* p) { if (p) cudaFree(p); }; - fr(blob_); fr(d_meta_); fr(xq_); fr(rt_ctx_); fr(rt_blk_); + fr(blob_); fr(d_meta_); fr(xq_); fr(xqp_); fr(xdp_); fr(xqc_); fr(xdc_); fr(rt_ctx_); fr(rt_blk_); for (int l = 0; l < 8; ++l) { fr(kring_[l]); fr(vring_[l]); } fr(fcy_); fr(hctx_); fr(kc_); fr(vc_); fr(h_); fr(xn_); fr(xc_); fr(dyn_); fr(q_); fr(qn_); fr(k_); fr(v_); fr(kblk_); fr(ao_); fr(o_); fr(gate_); fr(up_); fr(mlp_); fr(part_); fr(fn_); fr(logits_); fr(topval_); fr(hsel_); fr(toptok_); fr(topscratch_); @@ -52,6 +53,10 @@ Dflash2Drafter::~Dflash2Drafter() { if (h_meta_) cudaFreeHost(h_meta_); if (h_out_) cudaFreeHost(h_out_); if (cs_) cudaStreamDestroy(cs_); + if (cs2_) cudaStreamDestroy(cs2_); + if (ev_fork_) cudaEventDestroy(ev_fork_); + if (ev_join_) cudaEventDestroy(ev_join_); + for (cudaEvent_t e : ev_ctx_) if (e) cudaEventDestroy(e); if (ev_a_) cudaEventDestroy(ev_a_); if (ev_b_) cudaEventDestroy(ev_b_); } @@ -64,6 +69,17 @@ struct Dflash2Drafter::Prof { int64_t rounds = 0; }; +void Dflash2Drafter::prof_free() { + delete prof_; + prof_ = nullptr; +} + +// STRATA_DF2_SKIP=attn,head,ctx,mlp,qkvo (measurement only): leaves those parts out of the round, so the graph's GPU time without them can be read +static bool skip_part(const char* what) { + static const std::string list = [] { const char* e = std::getenv("STRATA_DF2_SKIP"); return std::string(e ? e : ""); }(); + return !list.empty() && list.find(what) != std::string::npos; +} + void Dflash2Drafter::stamp(const char* name) { if (!prof_) return; cudaEvent_t e; @@ -154,19 +170,38 @@ bool Dflash2Drafter::load(const std::string& path, int device, std::string& err) } if (cudaMalloc((void**) &blob_, total) != cudaSuccess) { err = "dflash2: the pack does not fit in VRAM (" + std::to_string(total >> 20) + " MiB)"; return false; } vram_ += total; - std::vector stage(64u << 20); + uint64_t max_bytes = 0; + for (const Tensor& t : tensors_) max_bytes = std::max(max_bytes, t.bytes); + std::vector stage(max_bytes); + uint8_t* tmp = nullptr; + if (cudaMalloc((void**) &tmp, max_bytes) != cudaSuccess) { err = "dflash2: upload scratch"; return false; } + struct TmpFree { uint8_t* p; ~TmpFree() { cudaFree(p); } } tmp_free{tmp}; + for (const Tensor& t : tensors_) { #if defined(_WIN32) - _fseeki64(f, data_off, SEEK_SET); + _fseeki64(f, data_off + (long long) t.off, SEEK_SET); #else - fseeko(f, data_off, SEEK_SET); + fseeko(f, data_off + (off_t) t.off, SEEK_SET); #endif - for (uint64_t o = 0; o < total;) { - const size_t n = (size_t) std::min(stage.size(), total - o); - if (std::fread(stage.data(), 1, n, f) != n) { err = "dflash2: the pack is shorter than its index"; return false; } - if (cudaMemcpy(blob_ + o, stage.data(), n, cudaMemcpyHostToDevice) != cudaSuccess) { err = "dflash2: weight upload failed"; return false; } - o += n; + if (std::fread(stage.data(), 1, t.bytes, f) != t.bytes) { err = "dflash2: the pack is shorter than its index"; return false; } + if (t.dtype == "q8_0") { // GGUF blocks -> the tiled qs plane at the tensor's offset, then the d plane (same total bytes) + if (cudaMemcpy(tmp, stage.data(), t.bytes, cudaMemcpyHostToDevice) != cudaSuccess) { err = "dflash2: weight upload failed"; return false; } + kernels::df2_q8_tile(tmp, blob_ + t.off, blob_ + t.off + (uint64_t) t.rows * (uint64_t) t.cols, (int) t.cols, t.rows * t.cols / 32, nullptr); + if (cudaDeviceSynchronize() != cudaSuccess) { err = "dflash2: weight conversion failed"; return false; } + } else if (cudaMemcpy(blob_ + t.off, stage.data(), t.bytes, cudaMemcpyHostToDevice) != cudaSuccess) { + err = "dflash2: weight upload failed"; + return false; + } } - if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "dflash2: stream"; return false; } + if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess || cudaStreamCreateWithFlags(&cs2_, cudaStreamNonBlocking) != cudaSuccess) { + err = "dflash2: stream"; + return false; + } + if (cudaEventCreateWithFlags(&ev_fork_, cudaEventDisableTiming) != cudaSuccess || cudaEventCreateWithFlags(&ev_join_, cudaEventDisableTiming) != cudaSuccess) { + err = "dflash2: events"; + return false; + } + for (int l = 0; l < 8; ++l) + if (cudaEventCreateWithFlags(&ev_ctx_[l], cudaEventDisableTiming) != cudaSuccess) { err = "dflash2: events"; return false; } if (const char* e = std::getenv("STRATA_DF2_PROFILE"); e && e[0] == '1') prof_ = new Prof(); if (const char* e = std::getenv("STRATA_DF2_TIMING"); e && e[0] == '1') { timing_ = true; @@ -184,7 +219,7 @@ bool Dflash2Drafter::alloc(std::string& err) { return true; }; const size_t B = kRows; - bool ok = dev(&d_meta_, 32) && dev(&xq_, kernels::native_q8_1_bytes(std::max(N_ * 5, I_), kRows) + 4096) && dev(&rt_ctx_, B * 128) && dev(&rt_blk_, B * 128) && + bool ok = dev(&d_meta_, 32) && dev(&xq_, kernels::native_q8_1_bytes(N_, kRows) + 4096) && dev(&xqp_, (size_t) 5 * N_ * 8 + 4096) && dev(&xdp_, (size_t) 5 * N_ / 32 * 8 + 64) && dev(&xqc_, (size_t) 5 * N_ * 8 + 4096) && dev(&xdc_, (size_t) 5 * N_ / 32 * 8 + 64) && dev(&rt_ctx_, B * 128) && dev(&rt_blk_, B * 128) && dev(&fcy_, B * N_) && dev(&hctx_, B * N_) && dev(&kc_, B * NKV_ * HD_) && dev(&vc_, B * NKV_ * HD_) && dev(&h_, B * N_) && dev(&xn_, B * N_) && dev(&xc_, B * N_) && dev(&dyn_, B * 640) && dev(&q_, B * NH_ * HD_) && dev(&qn_, B * NH_ * HD_) && dev(&k_, B * NKV_ * HD_) && dev(&v_, B * NKV_ * HD_) && dev(&kblk_, B * NKV_ * HD_) && dev(&ao_, B * NH_ * HD_) && dev(&o_, B * N_) && dev(&gate_, B * I_) && dev(&up_, B * I_) && dev(&mlp_, B * N_) && @@ -202,6 +237,10 @@ bool Dflash2Drafter::alloc(std::string& err) { out_tok_ = (int32_t*) dd; // the select kernel writes the 7 picks here (host-visible) ... out_prob_ = (float*) dd + 16; // ... and their probabilities at +16 ints cudaMemset(rt_ctx_, 0, B * 128 * 4); + cudaMemset(xqp_, 0, (size_t) 5 * N_ * 8 + 4096); + cudaMemset(xdp_, 0, ((size_t) 5 * N_ / 32 * 8 + 64) * 4); + cudaMemset(xqc_, 0, (size_t) 5 * N_ * 8 + 4096); + cudaMemset(xdc_, 0, ((size_t) 5 * N_ / 32 * 8 + 64) * 4); for (int l = 0; l < L_; ++l) { cudaMemset(kring_[l], 0, (size_t) kRing * NKV_ * HD_ * 4); cudaMemset(vring_[l], 0, (size_t) kRing * NKV_ * HD_ * 4); } return cudaDeviceSynchronize() == cudaSuccess; } @@ -278,32 +317,43 @@ bool Dflash2Drafter::bind(const WeightTable& wt, const NativeHead* head, const s return true; } -void Dflash2Drafter::quant(const float* x, int n_in, int ncols) { kernels::native_quantize_q8_1(x, xq_, n_in, ncols, cs_); } - -void Dflash2Drafter::mm(const std::string& name, const void* xq, float* y, int ncols) { - const Tensor& t = find(name); - kernels::native_q8_0_mmvq(blob_ + t.off, xq, y, (int) t.cols, (int) t.rows, ncols, cs_); +void Dflash2Drafter::gemm(std::initializer_list names, std::initializer_list outs, int ncols, cudaStream_t cs, const uint8_t* xq, const float* xd) { + kernels::Df2Mat mats[3]; + int n = 0, n_in = 0; + auto o = outs.begin(); + for (const char* name : names) { + const Tensor& t = find(name); + mats[n] = kernels::Df2Mat{blob_ + t.off, *o++, (int) t.rows}; + if (n == 0) n_in = (int) t.cols; + ++n; + } + kernels::df2_gemm(mats, n, xq, xd, n_in, ncols, cs); } bool Dflash2Drafter::record_context(const float* taps, int n, cudaStream_t cs, std::string& err) { using namespace kernels; + if (skip_part("ctx")) return true; try { const int tap_n = (int) taps_.size() * N_; df2_rope_table(d_meta_ + 0, n, theta_, rt_ctx_, cs); - stamp("ctx-start"); - quant(taps, tap_n, n); - mm("fc.weight", xq_, fcy_, n); - stamp("fc"); - native_qsa_rms_norm_weighted(fcy_, f32("hidden_norm.weight"), hctx_, N_, n, eps_, cs); - quant(hctx_, N_, n); + stamp("df2_rope_table"); + df2_quant_rows(taps, tap_n, n, xqc_, xdc_, cs); + stamp("df2_quant_rows"); + gemm({"fc.weight"}, {fcy_}, n, cs, xqc_, xdc_); + stamp("gemm:fc"); + df2_rms_quant(fcy_, f32("hidden_norm.weight"), nullptr, n, N_, eps_, xqc_, xdc_, cs); + stamp("df2_rms_quant"); for (int l = 0; l < L_; ++l) { const std::string p = "layers." + std::to_string(l) + "."; - mm(p + "self_attn.k_proj.weight", xq_, kc_, n); - mm(p + "self_attn.v_proj.weight", xq_, vc_, n); + const std::string kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight"; + gemm({kp.c_str(), vp.c_str()}, {kc_, vc_}, n, cs, xqc_, xdc_); + stamp("gemm:kp"); df2_norm_rope(kc_, NKV_ * HD_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 0, rt_ctx_, kring_[l], kRing, n, NKV_, eps_, cs); + stamp("df2_norm_rope"); df2_copy_rows(vc_, vring_[l], d_meta_ + 0, kRing, n, NKV_ * HD_, cs); + stamp("df2_copy_rows"); + if (fork_) cudaEventRecord(ev_ctx_[l], cs); // layer l's keys and values are in the ring } - stamp("ctx-kv"); } catch (const std::exception& e) { err = e.what(); return false; @@ -316,56 +366,65 @@ bool Dflash2Drafter::record_block(cudaStream_t cs, std::string& err) { try { const int B = kRows; df2_rope_table(d_meta_ + 8, B, theta_, rt_blk_, cs); + stamp("df2_rope_table"); embed_(d_meta_ + 24, B, h_, cs); - stamp("embed"); + stamp("embed_"); for (int l = 0; l < L_; ++l) { const std::string p = "layers." + std::to_string(l) + "."; const float* base_a = f32(p + "attention_conv.base_kernel"); const float* base_m = f32(p + "mlp_conv.base_kernel"); - native_qsa_rms_norm_weighted(h_, f32(p + "input_layernorm.weight"), xn_, N_, B, eps_, cs); - quant(xn_, N_, B); - mm(p + "attention_conv.kernel_projection.weight", xq_, dyn_, B); - df2_conv(xn_, dyn_, 640, base_a, nullptr, xc_, B, N_, group_, cs); - quant(xc_, N_, B); - stamp("attn-front"); - mm(p + "self_attn.q_proj.weight", xq_, q_, B); - mm(p + "self_attn.k_proj.weight", xq_, k_, B); - mm(p + "self_attn.v_proj.weight", xq_, v_, B); - stamp("qkv"); + const std::string akp = p + "attention_conv.kernel_projection.weight", mkp = p + "mlp_conv.kernel_projection.weight"; + const std::string qp = p + "self_attn.q_proj.weight", kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight"; + const std::string gp = p + "mlp.gate_proj.weight", up = p + "mlp.up_proj.weight"; + df2_rms_quant(h_, f32(p + "input_layernorm.weight"), xn_, B, N_, eps_, xqp_, xdp_, cs); + stamp("df2_rms_quant"); + gemm({akp.c_str()}, {dyn_}, B, cs, xqp_, xdp_); + stamp("gemm:akp"); + df2_conv_quant(xn_, dyn_, 640, base_a, B, N_, group_, xqp_, xdp_, cs); + stamp("df2_conv_quant"); + if (!skip_part("qkvo")) gemm({qp.c_str(), kp.c_str(), vp.c_str()}, {q_, k_, v_}, B, cs, xqp_, xdp_); + stamp("gemm:qp"); df2_norm_rope(q_, NH_ * HD_, f32(p + "self_attn.q_norm.weight"), d_meta_ + 8, rt_blk_, qn_, 0, B, NH_, eps_, cs); + stamp("df2_norm_rope"); df2_norm_rope(k_, NKV_ * HD_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 8, rt_blk_, kblk_, 0, B, NKV_, eps_, cs); - df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, ao_, cs); - stamp("attention"); - quant(ao_, NH_ * HD_, B); - mm(p + "self_attn.o_proj.weight", xq_, o_, B); - stamp("o_proj"); + stamp("df2_norm_rope"); + if (fork_) cudaStreamWaitEvent(cs, ev_ctx_[l], 0); // the context update has written this layer's ring + if (!skip_part("attn")) df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, ao_, cs); + stamp("df2_attention"); + df2_quant_rows(ao_, NH_ * HD_, B, xqp_, xdp_, cs); + stamp("df2_quant_rows"); + if (!skip_part("qkvo")) gemm({(p + "self_attn.o_proj.weight").c_str()}, {o_}, B, cs, xqp_, xdp_); + stamp("gemm:o_proj"); df2_conv(o_, dyn_ + 320, 640, base_a + 2 * N_, h_, h_, B, N_, group_, cs); - native_qsa_rms_norm_weighted(h_, f32(p + "post_attention_layernorm.weight"), xn_, N_, B, eps_, cs); - quant(xn_, N_, B); - mm(p + "mlp_conv.kernel_projection.weight", xq_, dyn_, B); - df2_conv(xn_, dyn_, 640, base_m, nullptr, xc_, B, N_, group_, cs); - quant(xc_, N_, B); - stamp("mlp-front"); - mm(p + "mlp.gate_proj.weight", xq_, gate_, B); - mm(p + "mlp.up_proj.weight", xq_, up_, B); - stamp("gate-up"); - native_swiglu_quantize_q8_1(gate_, up_, xq_, I_, B, cs); - mm(p + "mlp.down_proj.weight", xq_, mlp_, B); - stamp("down"); + stamp("df2_conv"); + df2_rms_quant(h_, f32(p + "post_attention_layernorm.weight"), xn_, B, N_, eps_, xqp_, xdp_, cs); + stamp("df2_rms_quant"); + gemm({mkp.c_str()}, {dyn_}, B, cs, xqp_, xdp_); + stamp("gemm:mkp"); + df2_conv_quant(xn_, dyn_, 640, base_m, B, N_, group_, xqp_, xdp_, cs); + stamp("df2_conv_quant"); + if (!skip_part("mlp")) gemm({gp.c_str(), up.c_str()}, {gate_, up_}, B, cs, xqp_, xdp_); + stamp("gemm:gp"); + df2_swiglu_quant(gate_, up_, B, I_, xqp_, xdp_, cs); + stamp("df2_swiglu_quant"); + if (!skip_part("mlp")) gemm({(p + "mlp.down_proj.weight").c_str()}, {mlp_}, B, cs, xqp_, xdp_); + stamp("gemm:mlp.down_proj"); df2_conv(mlp_, dyn_ + 320, 640, base_m + 2 * N_, h_, h_, B, N_, group_, cs); + stamp("df2_conv"); } native_qsa_rms_norm_weighted(h_, f32("norm.weight"), fn_, N_, B, eps_, cs); - quant(fn_ + N_, N_, kDrafts); // rows 1..7 - stamp("final-norm"); - native_mmvq(head_type_, head_w_, xq_, logits_, N_, (int) n_dvocab_, kDrafts, cs); - stamp("head"); + stamp("native_qsa_rms_norm_weighted"); + native_quantize_q8_1(fn_ + N_, xq_, N_, kDrafts, cs); // rows 1..7, the head's format + df2_quant_rows(fn_ + N_, N_, kDrafts, xqp_, xdp_, cs); // and the selector projection's + if (!skip_part("head")) native_mmvq(head_type_, head_w_, xq_, logits_, N_, (int) n_dvocab_, kDrafts, cs); + stamp("native_mmvq"); df2_topk(logits_, (int) n_dvocab_, dvocab_, kDrafts, topscratch_, topval_, toptok_, cs); - stamp("topk"); - mm("candidate_selector.hidden_projection.weight", xq_, hsel_, kDrafts); + stamp("df2_topk"); + gemm({"candidate_selector.hidden_projection.weight"}, {hsel_}, kDrafts, cs, xqp_, xdp_); + stamp("gemm:candidate_selector.hidden_projection"); df2_select(hsel_, topval_, toptok_, reinterpret_cast(blob_ + find("candidate_selector.predecessor_codebook").off), reinterpret_cast(blob_ + find("candidate_selector.successor_codebook").off), rank_, kDrafts, d_meta_ + 16, out_tok_, out_prob_, cs); - stamp("selector"); } catch (const std::exception& e) { err = e.what(); return false; @@ -377,8 +436,17 @@ bool Dflash2Drafter::capture(int n, const float* taps, std::string& err) { if (exec_[n]) return true; if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "dflash2: begin capture"; return false; } kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_); - bool ok = record_context(taps, n, cs_, err); + // the context update (fc, the keys and values) and the block's front run side by side: they meet before each layer's attention + fork_ = prof_ == nullptr && cs2_ != nullptr; + if (fork_) { + cudaEventRecord(ev_fork_, cs_); + cudaStreamWaitEvent(cs2_, ev_fork_, 0); + } + bool ok = record_context(taps, n, fork_ ? cs2_ : cs_, err); + if (fork_) cudaEventRecord(ev_join_, cs2_); if (ok) ok = record_block(cs_, err); + if (fork_) cudaStreamWaitEvent(cs_, ev_join_, 0); + fork_ = false; cudaGraph_t graph = nullptr; const cudaError_t ce = cudaStreamEndCapture(cs_, &graph); if (!ok) { if (graph) cudaGraphDestroy(graph); return false; } @@ -393,6 +461,19 @@ bool Dflash2Drafter::capture(int n, const float* taps, std::string& err) { return true; } +bool Dflash2Drafter::prepare(const float* taps, std::string& err) { + if (!bound_) { err = "dflash2: not bound"; return false; } + if (prof_ != nullptr) return true; // the profile runs without graphs + const OnDevice on_device(device_); + const Clock::time_point t0 = Clock::now(); + for (int i = 0; i < 8; ++i) h_meta_[i] = i; + for (int n = 1; n <= kRows; ++n) + if (!capture(n, taps, err)) return false; + graph_taps_ = taps; + ms_capture = ms_since(t0); + return true; +} + bool Dflash2Drafter::context(const float* taps, int64_t n, int64_t pos0, std::string& err) { const OnDevice on_device(device_); const int tap_n = (int) taps_.size() * N_; diff --git a/src/core/dflash2_attn_bench.cpp b/src/core/dflash2_attn_bench.cpp new file mode 100644 index 00000000..897b5b82 --- /dev/null +++ b/src/core/dflash2_attn_bench.cpp @@ -0,0 +1,58 @@ +// src/core/dflash2_attn_bench.cpp - the drafter's attention (kernels/dflash2.hpp df2_attention) on random K/V: time per call and GB/s of K/V read. +// +// dflash2_attn_bench [iters] [context] +#include "strata/kernels/dflash2.hpp" + +#include + +#include +#include +#include +#include + +int main(int argc, char** argv) { + const int iters = argc > 1 ? std::atoi(argv[1]) : 100; + const int ctx = argc > 2 ? std::atoi(argv[2]) : 2047; + const int ring = 2064; + using namespace strata::kernels; + float *q, *kr, *vr, *kb, *vb, *part, *out; + int32_t* pos; + cudaMalloc((void**) &q, 8 * 32 * 128 * 4); + cudaMalloc((void**) &kr, (size_t) ring * 1024 * 4); + cudaMalloc((void**) &vr, (size_t) ring * 1024 * 4); + cudaMalloc((void**) &kb, 8 * 1024 * 4); + cudaMalloc((void**) &vb, 8 * 1024 * 4); + cudaMalloc((void**) &part, (size_t) kDf2MaxChunks * 8 * 32 * 130 * 4); + cudaMalloc((void**) &out, 8 * 32 * 128 * 4); + cudaMalloc((void**) &pos, 4); + std::vector h((size_t) ring * 1024); + for (size_t i = 0; i < h.size(); ++i) h[i] = (float) ((int) (i * 2654435761u >> 20) % 2001 - 1000) / 1000.0f; + cudaMemcpy(kr, h.data(), h.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(vr, h.data(), h.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(q, h.data(), 8 * 32 * 128 * 4, cudaMemcpyHostToDevice); + cudaMemcpy(kb, h.data(), 8 * 1024 * 4, cudaMemcpyHostToDevice); + cudaMemcpy(vb, h.data(), 8 * 1024 * 4, cudaMemcpyHostToDevice); + const int32_t s = ctx + 5000; + cudaMemcpy(pos, &s, 4, cudaMemcpyHostToDevice); + cudaEvent_t a, b; + cudaEventCreate(&a); + cudaEventCreate(&b); + for (int v : {0, 1, 2, 3}) { + df2_attention_variant(v); + df2_attention(q, kr, vr, kb, vb, pos, ring, 2048, part, out, nullptr); + cudaDeviceSynchronize(); + cudaEventRecord(a); + for (int i = 0; i < iters; ++i) df2_attention(q, kr, vr, kb, vb, pos, ring, 2048, part, out, nullptr); + cudaEventRecord(b); + cudaEventSynchronize(b); + float ms; + cudaEventElapsedTime(&ms, a, b); + std::vector o(8 * 32 * 128); + cudaMemcpy(o.data(), out, o.size() * 4, cudaMemcpyDeviceToHost); + double sum = 0; + for (float x : o) sum += x; + const double kv_bytes = 2.0 * (ctx + 8) * 1024 * 4; + std::printf("variant %d: %.1f us per call, K/V %.1f GB/s (checksum %.6f)\n", v, 1000.0 * ms / iters, kv_bytes * iters / (ms / 1000.0) / 1e9, sum); + } + return 0; +} diff --git a/src/core/dflash2_gemm_bench.cpp b/src/core/dflash2_gemm_bench.cpp new file mode 100644 index 00000000..26a55685 --- /dev/null +++ b/src/core/dflash2_gemm_bench.cpp @@ -0,0 +1,62 @@ +// src/core/dflash2_gemm_bench.cpp - the drafter's Q8 GEMM (kernels/dflash2.hpp df2_gemm) on random planar weights: GB/s per shape and column count. +// +// dflash2_gemm_bench [iters] +// +// Weight sets are cycled through 2 GiB of distinct matrices so the L2 cache cannot hold them (the drafter reads each matrix once per round). +#include "strata/kernels/dflash2.hpp" + +#include + +#include +#include +#include +#include + +int main(int argc, char** argv) { + const int iters = argc > 1 ? std::atoi(argv[1]) : 50; + struct Shape { const char* name; int n_in, n_out; int mats; }; + const Shape shapes[] = {{"gate+up 2560->7680 x2", 2560, 7680, 2}, {"down 7680->2560", 7680, 2560, 1}, {"qkv 2560->(4096,1024,1024)", 2560, 4096, 3}, + {"o 4096->2560", 4096, 2560, 1}, {"fc 12800->2560", 12800, 2560, 1}, {"kv 2560->1024 x2", 2560, 1024, 2}}; + cudaEvent_t a, b; + cudaEventCreate(&a); + cudaEventCreate(&b); + for (const Shape& sh : shapes) { + const size_t wbytes = (size_t) sh.n_out * sh.n_in * 34 / 32; + const size_t per_set = wbytes * sh.mats; + const int sets = (int) std::max(2, ((size_t) 1 << 30) / per_set); + std::vector w((size_t) sets * sh.mats); + for (auto& p : w) { + if (cudaMalloc((void**) &p, wbytes) != cudaSuccess) { std::fprintf(stderr, "alloc\n"); return 1; } + cudaMemset(p, 0x11, wbytes); + } + uint8_t* xq; + float *xd, *y; + cudaMalloc((void**) &xq, (size_t) sh.n_in * 8); + cudaMalloc((void**) &xd, (size_t) sh.n_in / 32 * 8 * 4); + cudaMalloc((void**) &y, (size_t) 8 * sh.n_out * 3 * 4); + cudaMemset(xq, 3, (size_t) sh.n_in * 8); + std::vector ones((size_t) sh.n_in / 32 * 8, 0.01f); + cudaMemcpy(xd, ones.data(), ones.size() * 4, cudaMemcpyHostToDevice); + for (int var : {1, 2, 3, 4, 5, 6, 7, 8, 9}) { + strata::kernels::df2_gemm_variant(var); + const int ncols = 8; + cudaDeviceSynchronize(); + cudaEventRecord(a); + for (int it = 0; it < iters; ++it) { + strata::kernels::Df2Mat m[3]; + for (int i = 0; i < sh.mats; ++i) m[i] = {w[(size_t) (it % sets) * sh.mats + i], y + (size_t) i * 8 * sh.n_out, sh.n_out}; + if (sh.mats == 3) { m[1].n_out = 1024; m[2].n_out = 1024; } + strata::kernels::df2_gemm(m, sh.mats, xq, xd, sh.n_in, ncols, nullptr); + } + cudaEventRecord(b); + cudaEventSynchronize(b); + float ms; + cudaEventElapsedTime(&ms, a, b); + const double bytes = sh.mats == 3 ? (double) (4096 + 1024 + 1024) * sh.n_in * 34 / 32 : (double) per_set; + std::printf("%-30s variant %d: %7.1f us %6.1f GB/s\n", sh.name, var, 1000.0 * ms / iters, bytes * iters / (ms / 1000.0) / 1e9); + } + for (auto p : w) cudaFree(p); + cudaFree(xq); cudaFree(xd); cudaFree(y); + } + return 0; +} diff --git a/src/core/dflash2_launch_bench.cu b/src/core/dflash2_launch_bench.cu new file mode 100644 index 00000000..d4fae689 --- /dev/null +++ b/src/core/dflash2_launch_bench.cu @@ -0,0 +1,68 @@ +// src/core/dflash2_launch_bench.cpp - what a dependent kernel costs inside a captured graph on this GPU: N tiny kernels in a chain, and N kernels of 256 blocks. +// +// dflash2_launch_bench [n=100] +#include + +#include +#include +#include + +__global__ void tiny(float* x, int n) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) x[i] = x[i] * 1.0001f + 1.0f; +} + +int main(int argc, char** argv) { + const int n = argc > 1 ? std::atoi(argv[1]) : 100; + float* x; + cudaMalloc((void**) &x, 1 << 24); + cudaMemset(x, 0, 1 << 24); + cudaStream_t cs; + cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking); + cudaEvent_t a, b; + cudaEventCreate(&a); + cudaEventCreate(&b); + for (int blocks : {1, 64, 256, 1024}) { + cudaGraph_t g; + cudaGraphExec_t ge; + cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal); + for (int i = 0; i < n; ++i) tiny<<>>(x, blocks * 256); + cudaStreamEndCapture(cs, &g); + cudaGraphInstantiate(&ge, g, 0); + cudaGraphLaunch(ge, cs); + cudaStreamSynchronize(cs); + cudaEventRecord(a, cs); + for (int it = 0; it < 50; ++it) cudaGraphLaunch(ge, cs); + cudaEventRecord(b, cs); + cudaEventSynchronize(b); + float ms; + cudaEventElapsedTime(&ms, a, b); + std::printf("graph of %d chained kernels, %4d blocks: %.2f us per kernel\n", n, blocks, 1000.0 * ms / 50 / n); + // one launch from an idle stream: event, launch, event, wait (what the drafter does each round) + { + double tot = 0, wall = 0; + for (int it = 0; it < 20; ++it) { + cudaStreamSynchronize(cs); + auto t0 = std::chrono::steady_clock::now(); + cudaEventRecord(a, cs); + cudaGraphLaunch(ge, cs); + cudaEventRecord(b, cs); + cudaStreamSynchronize(cs); + wall += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + float m; + cudaEventElapsedTime(&m, a, b); + tot += m; + } + std::printf("single launch from idle, %d kernels, %4d blocks: events %.3f ms, wall %.3f ms\n", n, blocks, tot / 20, wall / 20); + } + // the same without a graph + cudaEventRecord(a, cs); + for (int it = 0; it < 5; ++it) + for (int i = 0; i < n; ++i) tiny<<>>(x, blocks * 256); + cudaEventRecord(b, cs); + cudaEventSynchronize(b); + cudaEventElapsedTime(&ms, a, b); + std::printf("stream of %d chained kernels, %4d blocks: %.2f us per kernel\n", n, blocks, 1000.0 * ms / 5 / n); + } + return 0; +} diff --git a/src/kernels/cuda/dflash2.cu b/src/kernels/cuda/dflash2.cu index 82c40ad6..fb98c4e2 100644 --- a/src/kernels/cuda/dflash2.cu +++ b/src/kernels/cuda/dflash2.cu @@ -1,6 +1,9 @@ // src/kernels/cuda/dflash2.cu - the small kernels of the DFlash2 drafter. See include/strata/kernels/dflash2.hpp. #include "strata/kernels/dflash2.hpp" +#include "strata/kernels/dp4a.hpp" + +#include #include #include @@ -14,6 +17,8 @@ namespace strata::kernels { namespace { constexpr int HD = kDf2Hd; +int g_gemm_variant = 0; // bench only (df2_gemm_variant) +int g_attn_variant = 0; // bench only (df2_attention_variant) void check(const char* what) { const cudaError_t e = cudaGetLastError(); @@ -77,7 +82,8 @@ __global__ void norm_rope_kernel(const float* __restrict__ in, int in_stride, co res = d < 64 ? v * c - y[d + 64] * s : v * c + y[d - 64] * s; } const int slot = slot_mod > 0 ? (int) (pos[r] % slot_mod) : r; - out[((size_t) slot * heads + h) * HD + d] = res; + // a ring (slot_mod > 0) is head-major [head][slot][128], the block's own keys row-major [row][head][128] + out[slot_mod > 0 ? ((size_t) h * slot_mod + slot) * HD + d : ((size_t) slot * heads + h) * HD + d] = res; } __global__ void copy_rows_kernel(const float* __restrict__ in, float* __restrict__ out, const int32_t* __restrict__ pos, int slot_mod, int rows, int cols) { @@ -85,106 +91,160 @@ __global__ void copy_rows_kernel(const float* __restrict__ in, float* __restrict if (i >= rows * cols) return; const int r = i / cols, c = i % cols; const int slot = slot_mod > 0 ? (int) (pos[r] % slot_mod) : r; - out[(size_t) slot * cols + c] = in[i]; + out[slot_mod > 0 ? ((size_t) (c / HD) * slot_mod + slot) * HD + c % HD : (size_t) slot * cols + c] = in[i]; } -// ---- attention. grid (8 K/V heads, kDf2MaxChunks), 256 threads. 32 queries (4 heads x 8 rows) per block share each key tile. -constexpr int KS = 129; // smem row stride of the K / V / Q tiles (conflict-free) -__global__ void __launch_bounds__(256) attn_part_kernel(const float* __restrict__ q, const float* __restrict__ kring, const float* __restrict__ vring, +// ---- attention. grid (8 K/V heads, kDf2MaxChunks), 128 threads. The 32 queries (4 heads x 8 rows) of a K/V head share each key tile; +// S = Q K^T in 4 x 4 register tiles (64 threads), the online softmax per query, O += P V in 4 x 8 register tiles (128 threads). +constexpr int AS = 132; // smem row stride of the Q / K / V tiles (float4 aligned, conflict-free for the 4 x 4 tiles) +constexpr int PS = 36; // stride of the transposed probabilities P[key][query] +__global__ void __launch_bounds__(128) attn_part_kernel(const float* __restrict__ q, const float* __restrict__ kring, const float* __restrict__ vring, const float* __restrict__ kblk, const float* __restrict__ vblk, - const int32_t* __restrict__ anchor_pos, int ring_slots, int window, float* __restrict__ part) { - __shared__ float Qs[32 * KS]; - __shared__ float Ks[32 * KS]; // the K tile, then the V tile - __shared__ float Ss[32 * 33]; + const int32_t* __restrict__ anchor_pos, int ring_slots, int window, float* __restrict__ part, int variant) { + __shared__ __align__(16) float Qs[32 * AS]; + __shared__ __align__(16) float Ks[32 * AS]; // the K tile, then the V tile + __shared__ __align__(16) float Ps[32 * PS]; + __shared__ float Sc[32 * 33]; + __shared__ float m_s[32], l_s[32], corr_s[32]; const int kvh = blockIdx.x, chunk = blockIdx.y, tid = threadIdx.x; const int s = *anchor_pos; const int lo = s - (window - 1) > 0 ? s - (window - 1) : 0; const int nctx = s - lo; const int nkeys = nctx + kDf2Rows; - const int qi = tid >> 3, tg = tid & 7; - const int qrow = qi >> 2, qg = qi & 3; - float* const pout = part + (((size_t) chunk * kDf2Kv + kvh) * 32 + qi) * 130; const int k_begin = chunk * kDf2Chunk; + float* const pbase = part + (((size_t) chunk * kDf2Kv + kvh) * 32) * 130; if (k_begin >= nkeys) { - if (tg == 0) { pout[0] = -INFINITY; pout[1] = 0.0f; } - for (int e = 0; e < 16; ++e) pout[2 + e * 8 + tg] = 0.0f; + for (int i = tid; i < 32 * 130; i += 128) pbase[i] = (i % 130 == 0) ? -INFINITY : 0.0f; return; } const float scale = rsqrtf((float) HD); - for (int i = tid; i < 32 * HD; i += 256) { - const int a = i / HD, d = i % HD; + for (int i = tid; i < 32 * HD / 4; i += 128) { // Q: 32 queries x 128, float4 + const int a = i / (HD / 4), d4 = i % (HD / 4); const int row = a >> 2, g = a & 3; - Qs[a * KS + d] = q[((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d] * scale; + float4 v = *reinterpret_cast(q + ((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d4 * 4); + v.x *= scale; v.y *= scale; v.z *= scale; v.w *= scale; + *reinterpret_cast(&Qs[a * AS + d4 * 4]) = v; } - float m = -INFINITY, l = 0.0f; - float O[16]; + if (tid < 32) { m_s[tid] = -INFINITY; l_s[tid] = 0.0f; } + float O[4][8]; #pragma unroll - for (int e = 0; e < 16; ++e) O[e] = 0.0f; + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) O[i][j] = 0.0f; + const int qg_pv = tid >> 4, dg_pv = tid & 15; // PV: queries qg*4 .. +3, dims dg*8 .. +7 const int k_end = min(k_begin + kDf2Chunk, nkeys); + // a tile is 32 keys x 128 dims = 1024 float4: eight per thread, loaded into registers ahead of their use + auto fetch = [&](int k0, float4 (®)[8], const float* ring, const float* blk) { +#pragma unroll + for (int u = 0; u < 8; ++u) { + const int i = tid + u * 128, t = i / (HD / 4), d4 = i % (HD / 4), k = k0 + t; + float4 v = make_float4(0.f, 0.f, 0.f, 0.f); + if (k < nctx) v = *reinterpret_cast(ring + ((size_t) kvh * ring_slots + (lo + k) % ring_slots) * HD + d4 * 4); + else if (k < nkeys) v = *reinterpret_cast(blk + ((size_t) (k - nctx) * kDf2Kv + kvh) * HD + d4 * 4); + reg[u] = v; + } + }; + auto put = [&](const float4 (®)[8]) { +#pragma unroll + for (int u = 0; u < 8; ++u) { + const int i = tid + u * 128, t = i / (HD / 4), d4 = i % (HD / 4); + *reinterpret_cast(&Ks[t * AS + d4 * 4]) = reg[u]; + } + }; + float4 kreg[8], vreg[8]; + fetch(k_begin, kreg, kring, kblk); for (int k0 = k_begin; k0 < k_end; k0 += 32) { - __syncthreads(); // Ks free (previous tile's V reads done), Qs written (first tile) - for (int i = tid; i < 32 * HD; i += 256) { - const int t = i / HD, d = i % HD, k = k0 + t; - float v = 0.0f; - if (k < nctx) v = kring[((size_t) ((lo + k) % ring_slots) * kDf2Kv + kvh) * HD + d]; - else if (k < nkeys) v = kblk[((size_t) (k - nctx) * kDf2Kv + kvh) * HD + d]; - Ks[t * KS + d] = v; + __syncthreads(); // Ks free (the last tile's V reads done); Qs / m_s written on the first pass + put(kreg); + fetch(k0, vreg, vring, vblk); // this tile's V, hidden behind the S stage and the softmax + __syncthreads(); + if (tid < 64) { // S tile: 4 queries x 4 keys per thread + const int qg = tid >> 3, kg = tid & 7; + float acc[4][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) acc[i][j] = 0.0f; +#pragma unroll 4 + for (int d = 0; d < ((variant & 1) ? 0 : HD); d += 4) { + float4 qv[4], kv[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) qv[i] = *reinterpret_cast(&Qs[(qg * 4 + i) * AS + d]); +#pragma unroll + for (int j = 0; j < 4; ++j) kv[j] = *reinterpret_cast(&Ks[(kg * 4 + j) * AS + d]); +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) + acc[i][j] += qv[i].x * kv[j].x + qv[i].y * kv[j].y + qv[i].z * kv[j].z + qv[i].w * kv[j].w; + } +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int qi = qg * 4 + i, t = kg * 4 + j, k = k0 + t, row = qi >> 2; + bool ok = k < nkeys; + if (ok && k < nctx) ok = (lo + k) > (s + row - window); // s + row - j < window + Sc[qi * 33 + t] = ok ? acc[i][j] : -INFINITY; + } } __syncthreads(); - float sc[4] = {0.f, 0.f, 0.f, 0.f}; -#pragma unroll 8 - for (int d = 0; d < HD; ++d) { - const float qv = Qs[qi * KS + d]; + { // online softmax: query = tid / 4, 8 keys each, 4 lanes per query + const int qi = tid >> 2, sub = tid & 3; + float v[8], tmax = -INFINITY; #pragma unroll - for (int u = 0; u < 4; ++u) sc[u] = fmaf(qv, Ks[(tg * 4 + u) * KS + d], sc[u]); - } - float tmax = -INFINITY; + for (int u = 0; u < 8; ++u) { v[u] = Sc[qi * 33 + sub * 8 + u]; tmax = fmaxf(tmax, v[u]); } + tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 1)); + tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 2)); + const float m_old = m_s[qi]; + const float mn = fmaxf(m_old, tmax); + const float corr = (m_old == -INFINITY) ? 0.0f : __expf(m_old - mn); + float psum = 0.0f; #pragma unroll - for (int u = 0; u < 4; ++u) { - const int k = k0 + tg * 4 + u; - bool ok = k < nkeys; - if (ok && k < nctx) ok = (lo + k) > (s + qrow - window); // s + row - j < window - sc[u] = ok ? sc[u] : -INFINITY; - tmax = fmaxf(tmax, sc[u]); - } - tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 1)); - tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 2)); - tmax = fmaxf(tmax, __shfl_xor_sync(0xffffffffu, tmax, 4)); - const float mn = fmaxf(m, tmax); - const float corr = (m == -INFINITY) ? 0.0f : __expf(m - mn); - float psum = 0.0f; -#pragma unroll - for (int u = 0; u < 4; ++u) { - const float p = sc[u] == -INFINITY ? 0.0f : __expf(sc[u] - mn); - Ss[qi * 33 + tg * 4 + u] = p; - psum += p; - } - psum += __shfl_xor_sync(0xffffffffu, psum, 1); - psum += __shfl_xor_sync(0xffffffffu, psum, 2); - psum += __shfl_xor_sync(0xffffffffu, psum, 4); - l = l * corr + psum; - m = mn; -#pragma unroll - for (int e = 0; e < 16; ++e) O[e] *= corr; - __syncthreads(); // Ss complete; every read of Ks done - for (int i = tid; i < 32 * HD; i += 256) { - const int t = i / HD, d = i % HD, k = k0 + t; - float v = 0.0f; - if (k < nctx) v = vring[((size_t) ((lo + k) % ring_slots) * kDf2Kv + kvh) * HD + d]; - else if (k < nkeys) v = vblk[((size_t) (k - nctx) * kDf2Kv + kvh) * HD + d]; - Ks[t * KS + d] = v; + for (int u = 0; u < 8; ++u) { + const float p = v[u] == -INFINITY ? 0.0f : __expf(v[u] - mn); + Ps[(sub * 8 + u) * PS + qi] = p; + psum += p; + } + psum += __shfl_xor_sync(0xffffffffu, psum, 1); + psum += __shfl_xor_sync(0xffffffffu, psum, 2); + if (sub == 0) { l_s[qi] = l_s[qi] * corr + psum; m_s[qi] = mn; corr_s[qi] = corr; } } + __syncthreads(); // Ps, corr_s complete; every read of Ks (the S tile) done + put(vreg); + if (k0 + 32 < k_end) fetch(k0 + 32, kreg, kring, kblk); // the next tile's K, hidden behind the PV stage __syncthreads(); - for (int t = 0; t < 32; ++t) { - const float p = Ss[qi * 33 + t]; + { + const float4 c4 = *reinterpret_cast(&corr_s[qg_pv * 4]); + const float cr[4] = {c4.x, c4.y, c4.z, c4.w}; #pragma unroll - for (int e = 0; e < 16; ++e) O[e] = fmaf(p, Ks[t * KS + e * 8 + tg], O[e]); + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) O[i][j] *= cr[i]; +#pragma unroll 4 + for (int t = 0; t < ((variant & 2) ? 0 : 32); ++t) { + const float4 p4 = *reinterpret_cast(&Ps[t * PS + qg_pv * 4]); + const float4 va = *reinterpret_cast(&Ks[t * AS + dg_pv * 8]); + const float4 vb = *reinterpret_cast(&Ks[t * AS + dg_pv * 8 + 4]); + const float pv[4] = {p4.x, p4.y, p4.z, p4.w}; + const float vv[8] = {va.x, va.y, va.z, va.w, vb.x, vb.y, vb.z, vb.w}; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int j = 0; j < 8; ++j) O[i][j] = fmaf(pv[i], vv[j], O[i][j]); + } } } - if (tg == 0) { pout[0] = m; pout[1] = l; } + __syncthreads(); + if (tid < 32) { pbase[tid * 130] = m_s[tid]; pbase[tid * 130 + 1] = l_s[tid]; } #pragma unroll - for (int e = 0; e < 16; ++e) pout[2 + e * 8 + tg] = O[e]; - (void) qg; + for (int i = 0; i < 4; ++i) { + float* o = pbase + (size_t) (qg_pv * 4 + i) * 130 + 2 + dg_pv * 8; + *reinterpret_cast(o) = make_float2(O[i][0], O[i][1]); + *reinterpret_cast(o + 2) = make_float2(O[i][2], O[i][3]); + *reinterpret_cast(o + 4) = make_float2(O[i][4], O[i][5]); + *reinterpret_cast(o + 6) = make_float2(O[i][6], O[i][7]); + } } __global__ void attn_merge_kernel(const float* __restrict__ part, float* __restrict__ out) { @@ -204,6 +264,157 @@ __global__ void attn_merge_kernel(const float* __restrict__ part, float* __restr out[((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d] = L > 0.0f ? o / L : 0.0f; } +// ---- Q8 GEMM for up to 8 activation columns (the drafter's matrices) +// +// Weights are TILED (df2_q8_tile makes them from GGUF Q8_0 blocks): a group of 8 rows is one unit; per 512 values of the reduction axis (a "step", +// 16 Q8 blocks) the group stores the 8 rows' 512 int8 one after the other (4 KB), so a warp that works on a group reads 4 KB contiguous per step +// (lane = block * 2 + half: one 16-byte load per row). The fp16 block scales follow all the int8 of the matrix, in the same tile order (8 rows x 16 +// blocks = 256 bytes a step). Activations: x_q (int8 [col][n_in]) and x_d (float [col][n_in / 32]); a column's 512 bytes of a step are contiguous. +struct Df2Seg { const int8_t* q; const __half* d; float* y; int n_out; int row0; }; +struct Df2Segs { Df2Seg s[3]; int n; }; + +template +__global__ void __launch_bounds__(WARPS * 32) gemm8_kernel(Df2Segs segs, const int8_t* __restrict__ xq, const float* __restrict__ xd, int n_in, int ncols) { + constexpr int R = 8; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int row_g = (blockIdx.x * WARPS + warp) * R; // first row of this warp's group, over all the launch's matrices + int si = 0; + while (si + 1 < segs.n && row_g >= segs.s[si + 1].row0) ++si; + const Df2Seg sg = segs.s[si]; + const int row0 = row_g - sg.row0; + const int nb = n_in / 32, steps = nb / 16; + const int4* wq = reinterpret_cast(sg.q + (size_t) row0 * n_in) + lane; + const __half* wd = sg.d + (size_t) row0 * nb + (lane >> 1); + const int4* xv = reinterpret_cast(xq) + lane; + float acc[R][8]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < 8; ++c) acc[r][c] = 0.0f; +#pragma unroll UNR + for (int st = 0; st < steps; ++st) { + int4 w[R]; + float dw[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + w[r] = wq[(size_t) st * 256 + r * 32]; + dw[r] = __half2float(wd[(size_t) st * 128 + r * 16]); + } + if (!COMPUTE) { // bench only: the same loads, almost no arithmetic + for (int r = 0; r < R; ++r) acc[r][0] += (float) (w[r].x ^ w[r].y ^ w[r].z ^ w[r].w) * dw[r]; + continue; + } + float xs[8]; +#pragma unroll + for (int c = 0; c < 8; ++c) xs[c] = xd[(size_t) c * nb + st * 16 + (lane >> 1)]; +#pragma unroll + for (int c = 0; c < 8; ++c) { + const int4 x = xv[(size_t) c * (n_in / 16) + st * 32]; +#pragma unroll + for (int r = 0; r < R; ++r) { + int isum = STRATA_DP4A(w[r].x, x.x, 0); + isum = STRATA_DP4A(w[r].y, x.y, isum); + isum = STRATA_DP4A(w[r].z, x.z, isum); + isum = STRATA_DP4A(w[r].w, x.w, isum); + acc[r][c] = fmaf(dw[r] * xs[c], (float) isum, acc[r][c]); + } + } + } +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int c = 0; c < 8; ++c) { + float v = acc[r][c]; + v += __shfl_xor_sync(0xffffffffu, v, 16); + v += __shfl_xor_sync(0xffffffffu, v, 8); + v += __shfl_xor_sync(0xffffffffu, v, 4); + v += __shfl_xor_sync(0xffffffffu, v, 2); + v += __shfl_xor_sync(0xffffffffu, v, 1); + if (lane == 0 && c < ncols) sg.y[(size_t) c * sg.n_out + row0 + r] = v; + } +} + +// quantize one 32-block of one row to the planar activation layout (a warp: lane = element) +__device__ __forceinline__ void quant_block(float v, int blk, int col, int K, int8_t* __restrict__ xq, float* __restrict__ xd) { + const int lane = threadIdx.x & 31; + float amax = fabsf(v); + for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); + const float d = amax / 127.0f; + const float inv = amax > 0.0f ? 127.0f / amax : 0.0f; + const int q = __float2int_rn(v * inv); + xq[(size_t) col * K + blk * 32 + lane] = (int8_t) q; + if (lane == 0) xd[(size_t) col * (K / 32) + blk] = d; +} + +// rows [ncols][K] -> planar; grid (ceil(K / 32 / 8), ncols), 256 threads (a warp per block) +__global__ void quant_rows_kernel(const float* __restrict__ x, int K, int8_t* __restrict__ xq, float* __restrict__ xd) { + const int blk = blockIdx.x * 8 + (threadIdx.x >> 5), col = blockIdx.y, lane = threadIdx.x & 31; + if (blk * 32 >= K) return; + quant_block(x[(size_t) col * K + blk * 32 + lane], blk, col, K, xq, xd); +} + +// RMS norm of row `col` (N values) then the planar quantization of the normalized values; also writes them when xn != null. One block of 256 per row. +__global__ void rms_quant_kernel(const float* __restrict__ h, const float* __restrict__ gamma, float* __restrict__ xn, int N, float eps, + int8_t* __restrict__ xq, float* __restrict__ xd) { + const int col = blockIdx.x, tid = threadIdx.x, warp = tid >> 5, lane = tid & 31; + __shared__ float red[8]; + float ss = 0.0f; + for (int i = tid; i < N; i += 256) { const float v = h[(size_t) col * N + i]; ss += v * v; } + for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + if (lane == 0) red[warp] = ss; + __syncthreads(); + float tot = 0.0f; + for (int w = 0; w < 8; ++w) tot += red[w]; + const float scale = rsqrtf(tot / (float) N + eps); + for (int blk = warp; blk * 32 < N; blk += 8) { + const int i = blk * 32 + lane; + const float v = h[(size_t) col * N + i] * scale * gamma[i]; + if (xn) xn[(size_t) col * N + i] = v; + quant_block(v, blk, col, N, xq, xd); + } +} + +// conv (as conv_kernel, no residual) then the planar quantization: grid (ceil(H / 32 / 8), rows), 256 threads +__global__ void conv_quant_kernel(const float* __restrict__ x, const float* __restrict__ dyn, int dyn_stride, const float* __restrict__ base, int H, int group, + int8_t* __restrict__ xq, float* __restrict__ xd) { + const int blk = blockIdx.x * 8 + (threadIdx.x >> 5), b = blockIdx.y, lane = threadIdx.x & 31; + if (blk * 32 >= H) return; + const int c = blk * 32 + lane, groups = H / group; + float acc = 0.0f; +#pragma unroll + for (int o = 0; o < 2; ++o) { + if (b - o < 0) continue; + const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group]; + acc = fmaf(k, x[(size_t) (b - o) * H + c], acc); + } + quant_block(acc, blk, b, H, xq, xd); +} + +// silu(gate) * up then the planar quantization: grid (ceil(I / 32 / 8), rows), 256 threads +__global__ void swiglu_quant_kernel(const float* __restrict__ gate, const float* __restrict__ up, int I, int8_t* __restrict__ xq, float* __restrict__ xd) { + const int blk = blockIdx.x * 8 + (threadIdx.x >> 5), b = blockIdx.y, lane = threadIdx.x & 31; + if (blk * 32 >= I) return; + const size_t i = (size_t) b * I + blk * 32 + lane; + const float g = gate[i]; + quant_block(g / (1.0f + __expf(-g)) * up[i], blk, b, I, xq, xd); +} + +// GGUF Q8_0 blocks (34 bytes: fp16 d, 32 int8) of a [n_out][n_in] matrix -> the tiled qs plane (n_out * n_in bytes) and the tiled d plane; one thread per block +__global__ void q8_tile_kernel(const uint8_t* __restrict__ blocks, int8_t* __restrict__ qs, __half* __restrict__ dpl, int n_in, int64_t count) { + const int64_t b = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (b >= count) return; + const int nb = n_in / 32; + const int64_t row = b / nb; + const int blk = (int) (b % nb); + const int64_t g = row / 8; + const int r = (int) (row % 8), st = blk / 16, bi = blk % 16; + const uint8_t* src = blocks + b * 34; + const uint16_t dh = (uint16_t) src[0] | ((uint16_t) src[1] << 8); + dpl[(g * 8 * nb) + (int64_t) st * 128 + r * 16 + bi] = __ushort_as_half(dh); + int8_t* o = qs + g * 8 * n_in + (int64_t) st * 4096 + r * 512 + bi * 32; + for (int i = 0; i < 32; ++i) o[i] = (int8_t) src[2 + i]; +} + // ---- top-16 constexpr int TK_CHUNK_MAX = 4096; __device__ __forceinline__ bool better(float va, int ia, float vb, int ib) { return va > vb || (va == vb && ia < ib); } @@ -381,12 +592,69 @@ void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, int ring_slots, int window, float* part, float* out, void* stream) { - attn_part_kernel<<>>(q, kring, vring, kblk, vblk, anchor_pos, ring_slots, window, part); + attn_part_kernel<<>>(q, kring, vring, kblk, vblk, anchor_pos, ring_slots, window, part, g_attn_variant); check("attn_part"); attn_merge_kernel<<>>(part, out); check("attn_merge"); } +void df2_gemm_variant(int v) { g_gemm_variant = v; } +void df2_attention_variant(int v) { g_attn_variant = v; } + +void df2_gemm(const Df2Mat* mats, int n, const void* xq, const float* xd, int n_in, int ncols, void* stream) { + if (n < 1 || n > 3 || n_in % 512 != 0 || ncols < 1 || ncols > 8) throw std::invalid_argument("df2_gemm: unsupported shape"); + Df2Segs segs; + int rows = 0; + for (int i = 0; i < n; ++i) { + if (mats[i].n_out % 16 != 0) throw std::invalid_argument("df2_gemm: n_out must be a multiple of 16"); + const int8_t* q = static_cast(mats[i].w); + segs.s[i] = Df2Seg{q, reinterpret_cast(q + (size_t) mats[i].n_out * n_in), mats[i].y, mats[i].n_out, rows}; + rows += mats[i].n_out; + } + segs.n = n; + const int8_t* xqp = static_cast(xq); + cudaStream_t st = (cudaStream_t) stream; + const int variant = g_gemm_variant != 0 ? g_gemm_variant : (rows % 32 == 0 ? 1 : 2); + switch (variant) { + case 3: gemm8_kernel<2, false><<>>(segs, xqp, xd, n_in, ncols); break; + case 4: gemm8_kernel<1, true, 2><<>>(segs, xqp, xd, n_in, ncols); break; + case 5: gemm8_kernel<2, true, 1><<>>(segs, xqp, xd, n_in, ncols); break; + case 6: gemm8_kernel<2, true, 4><<>>(segs, xqp, xd, n_in, ncols); break; + case 7: gemm8_kernel<4, true, 4><<>>(segs, xqp, xd, n_in, ncols); break; + case 8: gemm8_kernel<8, true, 2><<>>(segs, xqp, xd, n_in, ncols); break; + case 9: gemm8_kernel<4, false><<>>(segs, xqp, xd, n_in, ncols); break; + case 2: gemm8_kernel<2, true><<>>(segs, xqp, xd, n_in, ncols); break; // 16 rows a block: every n_out is a multiple of 16 + default: gemm8_kernel<4, true><<>>(segs, xqp, xd, n_in, ncols); break; + } + check("gemm8"); +} + +void df2_quant_rows(const float* x, int K, int ncols, void* xq, float* xd, void* stream) { + quant_rows_kernel<<>>(x, K, static_cast(xq), xd); + check("quant_rows"); +} + +void df2_rms_quant(const float* h, const float* gamma, float* xn, int rows, int N, float eps, void* xq, float* xd, void* stream) { + rms_quant_kernel<<>>(h, gamma, xn, N, eps, static_cast(xq), xd); + check("rms_quant"); +} + +void df2_conv_quant(const float* x, const float* dyn, int dyn_stride, const float* base, int rows, int H, int group, void* xq, float* xd, void* stream) { + conv_quant_kernel<<>>(x, dyn, dyn_stride, base, H, group, static_cast(xq), xd); + check("conv_quant"); +} + +void df2_swiglu_quant(const float* gate, const float* up, int rows, int I, void* xq, float* xd, void* stream) { + swiglu_quant_kernel<<>>(gate, up, I, static_cast(xq), xd); + check("swiglu_quant"); +} + +void df2_q8_tile(const void* blocks, void* qs, void* dpl, int n_in, int64_t count, void* stream) { + q8_tile_kernel<<<(unsigned) ((count + 255) / 256), 256, 0, (cudaStream_t) stream>>>(static_cast(blocks), static_cast(qs), + static_cast<__half*>(dpl), n_in, count); + check("q8_tile"); +} + void df2_topk(const float* logits, int n, const int32_t* idx_map, int rows, uint32_t* scratch, float* val, int32_t* tok, void* stream) { if ((n + kDf2TopBlocks - 1) / kDf2TopBlocks > TK_CHUNK_MAX) throw std::invalid_argument("df2_topk: too many logits per row"); float* cval = reinterpret_cast(scratch); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 4f75c9fe..d7ec9a69 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -16027,7 +16027,11 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: --draft dflash2: %s; the MTP drafts instead\n", err.c_str()); use_df2 = false; } - if (use_df2) std::fprintf(stderr, "strata generate: DFlash2 drafter on (%s), the MTP layer stays as the fallback\n", o.draft_model.c_str()); + if (use_df2 && !df2.prepare(ver.tap_dev(), err)) { + std::fprintf(stderr, "strata generate: --draft dflash2: %s; the MTP drafts instead\n", err.c_str()); + use_df2 = false; + } + if (use_df2) std::fprintf(stderr, "strata generate: DFlash2 drafter on (%s, graphs captured in %.0f ms), the MTP layer stays as the fallback\n", o.draft_model.c_str(), df2.ms_capture); #endif mem_mark("the verifier and the drafter's binding"); ver.set_sampling(sp); // the CLI's own sampling (until 0.1.19 this loop was always greedy); no penalties here @@ -16332,6 +16336,23 @@ int main(int argc, char** argv) { float pp[strata::core::Dflash2Drafter::kDrafts]; if (!df2.draft(ver.tap_dev(), a_ + 1, p, outv[(size_t) a_], dd, pp, err)) return false; for (size_t i = 0; i < drafts.size() && i < (size_t) strata::core::Dflash2Drafter::kDrafts; ++i) { drafts[i] = dd[i]; dprob[i] = pp[i]; } + // what the MTP does while it drafts: the PLE rows of the tokens the next window will hold are read ahead + // (the window's gather would otherwise wait for them: 1.8 ms a round on strix) + if (ss.ple.ready() && ss.ple.table != nullptr) { + int n_pf = 0; + const int cap = std::min(S_mtp, (int) drafts.size() + 1); + for (int t = 1; t < cap && (o.spec_min_p <= 0.0 || dprob[(size_t) t - 1] >= (float) o.spec_min_p); ++t) ++n_pf; + int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + auto pf = [&](int32_t tok) { + uint32_t rows16[strata::kernels::PLE_N_HEADS]; + strata::kernels::ngram_rows(&tok, prev, 1, ss.ple.consts, rows16); + prev[0] = prev[1]; + prev[1] = tok; + ss.ple.table->prefetch_rows(rows16); + }; + pf(outv[(size_t) a_]); + for (int i = 0; i < n_pf; ++i) pf(drafts[(size_t) i]); + } return true; } #endif From 89799596a6380d738911a8444419422fbe04ad5c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 21 Oct 2026 16:34:27 +0200 Subject: [PATCH 07/12] dflash2: fused conv+residual+norm+quant, q/k norm+rope, K/V ring write and attention-output quantization; stage skip switches and small benches --- CMakeLists.txt | 6 ++ include/strata/core/dflash2.hpp | 3 + include/strata/kernels/dflash2.hpp | 18 +++- src/core/dflash2.cpp | 60 ++++++------ src/core/dflash2_attn_bench.cpp | 10 +- src/core/dflash2_bw_bench.cu | 41 +++++++++ src/core/dflash2_small_bench.cpp | 82 +++++++++++++++++ src/kernels/cuda/dflash2.cu | 141 ++++++++++++++++++++++++++++- src/program/generate.cpp | 2 + 9 files changed, 326 insertions(+), 37 deletions(-) create mode 100644 src/core/dflash2_bw_bench.cu create mode 100644 src/core/dflash2_small_bench.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a918bc5..77671a8b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -746,6 +746,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) add_executable(dflash2_launch_bench EXCLUDE_FROM_ALL src/core/dflash2_launch_bench.cu) target_include_directories(dflash2_launch_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(dflash2_launch_bench PRIVATE ${_strata_gpu_runtime_target}) + add_executable(dflash2_bw_bench EXCLUDE_FROM_ALL src/core/dflash2_bw_bench.cu) + target_include_directories(dflash2_bw_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_bw_bench PRIVATE ${_strata_gpu_runtime_target}) + add_executable(dflash2_small_bench EXCLUDE_FROM_ALL src/core/dflash2_small_bench.cpp) + target_include_directories(dflash2_small_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(dflash2_small_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_executable(dflash2_attn_bench EXCLUDE_FROM_ALL src/core/dflash2_attn_bench.cpp) target_include_directories(dflash2_attn_bench PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(dflash2_attn_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) diff --git a/include/strata/core/dflash2.hpp b/include/strata/core/dflash2.hpp index 205bff3d..bad2bf5e 100644 --- a/include/strata/core/dflash2.hpp +++ b/include/strata/core/dflash2.hpp @@ -124,6 +124,9 @@ private: float* xdc_ = nullptr; cudaStream_t cs2_ = nullptr; ///< the context update's branch of the round graph cudaEvent_t ev_fork_ = nullptr, ev_join_ = nullptr, ev_ctx_[8] = {}; + const float* touch_p_[48] = {}; + int touch_c_[48] = {}; + int touch_n_ = 0; bool fork_ = false; ///< recording the forked graph: layer l's attention waits for ev_ctx_[l] float *fcy_ = nullptr, *hctx_ = nullptr, *kc_ = nullptr, *vc_ = nullptr; float *h_ = nullptr, *xn_ = nullptr, *xc_ = nullptr, *dyn_ = nullptr, *q_ = nullptr, *qn_ = nullptr, *k_ = nullptr, *v_ = nullptr, *kblk_ = nullptr; diff --git a/include/strata/kernels/dflash2.hpp b/include/strata/kernels/dflash2.hpp index 0ce4775b..28617498 100644 --- a/include/strata/kernels/dflash2.hpp +++ b/include/strata/kernels/dflash2.hpp @@ -40,9 +40,9 @@ void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod /// Attention of the block's 8 query rows (q: [8][32][128], already normed and rotated) over the context ring (kring, vring: /// head-major [8][ring_slots][128]) and the block's own keys (kblk, vblk: [8][8][128]). Row i at position s + i sees context position j when /// s + i - j < window (j in [max(0, s - window + 1), s - 1], slot j % ring_slots) and every block key. `s` is read from *anchor_pos -/// on the device. Partials in `part` ([kDf2MaxChunks][8][32][130] floats) are combined into out [8][32*128]. +/// on the device. Partials in `part` ([kDf2MaxChunks][8][32][130] floats) are combined and the 8 output rows (4096 wide) written planar-quantized to xq / xd. void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, - int ring_slots, int window, float* part, float* out, void* stream); + int ring_slots, int window, float* part, void* xq, float* xd, void* stream); /// The Q8 GEMM the drafter's matrices run on. A weight matrix is TILED (see the layout note in dflash2.cu; df2_q8_tile makes it from GGUF Q8_0 blocks): /// the int8 plane at `w` (n_out * n_in bytes) then the fp16 scale plane. Activations are planar (df2_quant_rows and the fused quantizers below): @@ -65,6 +65,20 @@ void df2_swiglu_quant(const float* gate, const float* up, int rows, int I, void* /// GGUF Q8_0 blocks (34 bytes) of a matrix with rows of n_in -> the tiled qs plane and the tiled d plane (count = rows * n_in / 32 blocks). void df2_q8_tile(const void* blocks, void* qs, void* dpl, int n_in, int64_t count, void* stream); +/// h += conv(x) (the finish convolution with the residual), then the RMS norm of the new h (weights gamma) -> xn (optional) and the planar quantization. +/// rows <= 8, H <= 3072 (H a multiple of 32). +void df2_conv_rms_quant(const float* x, const float* dyn, int dyn_stride, const float* base, float* h, const float* gamma, float* xn, int rows, int H, int group, + float eps, void* xq, float* xd, void* stream); +/// The block's q (q_heads x 128) and k (k_heads x 128) per row: RMS norm and rope with the table of the block's positions -> qo, ko (row-major). +void df2_norm_rope_qk(const float* q, const float* k, const float* gq, const float* gk, const float* table, float* qo, float* ko, int rows, int q_heads, int k_heads, + float eps, void* stream); +/// The context update's write: K (norm + rope) and V of `rows` rows into the head-major rings at slot pos[r] % slots. +void df2_kv_ring(const float* kin, const float* vin, const float* gk, const int32_t* pos, const float* table, float* kring, float* vring, int slots, int rows, + int heads, float eps, void* stream); + +/// Reads n small f32 tensors (ptrs[i], counts[i] floats; n <= 48) once to bring them into the caches; sink: one float of scratch. +void df2_touch(const float* const* ptrs, const int* counts, int n, float* sink, void* stream); + /// Top-16 per row of logits [rows][n] (value-descending; ties to the lower index). idx_map (optional) maps a column to a token id. /// scratch: rows * kDf2TopBlocks * 16 * 2 words. Outputs val[rows][16] and tok[rows][16]. n <= 4096 * kDf2TopBlocks. void df2_topk(const float* logits, int n, const int32_t* idx_map, int rows, uint32_t* scratch, float* val, int32_t* tok, void* stream); diff --git a/src/core/dflash2.cpp b/src/core/dflash2.cpp index 6a04146b..3da70987 100644 --- a/src/core/dflash2.cpp +++ b/src/core/dflash2.cpp @@ -208,6 +208,12 @@ bool Dflash2Drafter::load(const std::string& path, int device, std::string& err) cudaEventCreate(&ev_a_); cudaEventCreate(&ev_b_); } + // the small f32 tensors the round touches first (see df2_touch) + for (const Tensor& t : tensors_) + if (t.dtype == "f32" && t.rows * t.cols * 4 <= (1 << 20) && touch_n_ < 48) { + touch_p_[touch_n_] = reinterpret_cast(blob_ + t.off); + touch_c_[touch_n_++] = (int) (t.rows * t.cols); + } return alloc(err); } @@ -348,10 +354,8 @@ bool Dflash2Drafter::record_context(const float* taps, int n, cudaStream_t cs, s const std::string kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight"; gemm({kp.c_str(), vp.c_str()}, {kc_, vc_}, n, cs, xqc_, xdc_); stamp("gemm:kp"); - df2_norm_rope(kc_, NKV_ * HD_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 0, rt_ctx_, kring_[l], kRing, n, NKV_, eps_, cs); - stamp("df2_norm_rope"); - df2_copy_rows(vc_, vring_[l], d_meta_ + 0, kRing, n, NKV_ * HD_, cs); - stamp("df2_copy_rows"); + df2_kv_ring(kc_, vc_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 0, rt_ctx_, kring_[l], vring_[l], kRing, n, NKV_, eps_, cs); + stamp("df2_kv_ring"); if (fork_) cudaEventRecord(ev_ctx_[l], cs); // layer l's keys and values are in the ring } } catch (const std::exception& e) { @@ -369,6 +373,8 @@ bool Dflash2Drafter::record_block(cudaStream_t cs, std::string& err) { stamp("df2_rope_table"); embed_(d_meta_ + 24, B, h_, cs); stamp("embed_"); + df2_rms_quant(h_, f32("layers.0.input_layernorm.weight"), xn_, B, N_, eps_, xqp_, xdp_, cs); + stamp("df2_rms_quant"); for (int l = 0; l < L_; ++l) { const std::string p = "layers." + std::to_string(l) + "."; const float* base_a = f32(p + "attention_conv.base_kernel"); @@ -376,44 +382,36 @@ bool Dflash2Drafter::record_block(cudaStream_t cs, std::string& err) { const std::string akp = p + "attention_conv.kernel_projection.weight", mkp = p + "mlp_conv.kernel_projection.weight"; const std::string qp = p + "self_attn.q_proj.weight", kp = p + "self_attn.k_proj.weight", vp = p + "self_attn.v_proj.weight"; const std::string gp = p + "mlp.gate_proj.weight", up = p + "mlp.up_proj.weight"; - df2_rms_quant(h_, f32(p + "input_layernorm.weight"), xn_, B, N_, eps_, xqp_, xdp_, cs); - stamp("df2_rms_quant"); - gemm({akp.c_str()}, {dyn_}, B, cs, xqp_, xdp_); + if (!skip_part("tiny")) gemm({akp.c_str()}, {dyn_}, B, cs, xqp_, xdp_); stamp("gemm:akp"); - df2_conv_quant(xn_, dyn_, 640, base_a, B, N_, group_, xqp_, xdp_, cs); + if (!skip_part("small")) df2_conv_quant(xn_, dyn_, 640, base_a, B, N_, group_, xqp_, xdp_, cs); stamp("df2_conv_quant"); if (!skip_part("qkvo")) gemm({qp.c_str(), kp.c_str(), vp.c_str()}, {q_, k_, v_}, B, cs, xqp_, xdp_); stamp("gemm:qp"); - df2_norm_rope(q_, NH_ * HD_, f32(p + "self_attn.q_norm.weight"), d_meta_ + 8, rt_blk_, qn_, 0, B, NH_, eps_, cs); - stamp("df2_norm_rope"); - df2_norm_rope(k_, NKV_ * HD_, f32(p + "self_attn.k_norm.weight"), d_meta_ + 8, rt_blk_, kblk_, 0, B, NKV_, eps_, cs); - stamp("df2_norm_rope"); + if (!skip_part("small")) df2_norm_rope_qk(q_, k_, f32(p + "self_attn.q_norm.weight"), f32(p + "self_attn.k_norm.weight"), rt_blk_, qn_, kblk_, B, NH_, NKV_, eps_, cs); + stamp("df2_norm_rope_qk"); if (fork_) cudaStreamWaitEvent(cs, ev_ctx_[l], 0); // the context update has written this layer's ring - if (!skip_part("attn")) df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, ao_, cs); + if (!skip_part("attn")) df2_attention(qn_, kring_[l], vring_[l], kblk_, v_, d_meta_ + 17, kRing, window_, part_, xqp_, xdp_, cs); stamp("df2_attention"); - df2_quant_rows(ao_, NH_ * HD_, B, xqp_, xdp_, cs); - stamp("df2_quant_rows"); if (!skip_part("qkvo")) gemm({(p + "self_attn.o_proj.weight").c_str()}, {o_}, B, cs, xqp_, xdp_); stamp("gemm:o_proj"); - df2_conv(o_, dyn_ + 320, 640, base_a + 2 * N_, h_, h_, B, N_, group_, cs); - stamp("df2_conv"); - df2_rms_quant(h_, f32(p + "post_attention_layernorm.weight"), xn_, B, N_, eps_, xqp_, xdp_, cs); - stamp("df2_rms_quant"); - gemm({mkp.c_str()}, {dyn_}, B, cs, xqp_, xdp_); + if (!skip_part("small")) df2_conv_rms_quant(o_, dyn_ + 320, 640, base_a + 2 * N_, h_, f32(p + "post_attention_layernorm.weight"), xn_, B, N_, group_, eps_, xqp_, xdp_, cs); + stamp("df2_conv_rms_quant"); + if (!skip_part("tiny")) gemm({mkp.c_str()}, {dyn_}, B, cs, xqp_, xdp_); stamp("gemm:mkp"); - df2_conv_quant(xn_, dyn_, 640, base_m, B, N_, group_, xqp_, xdp_, cs); + if (!skip_part("small")) df2_conv_quant(xn_, dyn_, 640, base_m, B, N_, group_, xqp_, xdp_, cs); stamp("df2_conv_quant"); if (!skip_part("mlp")) gemm({gp.c_str(), up.c_str()}, {gate_, up_}, B, cs, xqp_, xdp_); stamp("gemm:gp"); - df2_swiglu_quant(gate_, up_, B, I_, xqp_, xdp_, cs); + if (!skip_part("small")) df2_swiglu_quant(gate_, up_, B, I_, xqp_, xdp_, cs); stamp("df2_swiglu_quant"); if (!skip_part("mlp")) gemm({(p + "mlp.down_proj.weight").c_str()}, {mlp_}, B, cs, xqp_, xdp_); stamp("gemm:mlp.down_proj"); - df2_conv(mlp_, dyn_ + 320, 640, base_m + 2 * N_, h_, h_, B, N_, group_, cs); - stamp("df2_conv"); + // the next layer's input norm, or after the last layer the final norm (-> fn_, the rows the head and the selector read) + const std::string next_gamma = l + 1 < L_ ? "layers." + std::to_string(l + 1) + ".input_layernorm.weight" : std::string("norm.weight"); + if (!skip_part("small")) df2_conv_rms_quant(mlp_, dyn_ + 320, 640, base_m + 2 * N_, h_, f32(next_gamma), l + 1 < L_ ? xn_ : fn_, B, N_, group_, eps_, xqp_, xdp_, cs); + stamp("df2_conv_rms_quant"); } - native_qsa_rms_norm_weighted(h_, f32("norm.weight"), fn_, N_, B, eps_, cs); - stamp("native_qsa_rms_norm_weighted"); native_quantize_q8_1(fn_ + N_, xq_, N_, kDrafts, cs); // rows 1..7, the head's format df2_quant_rows(fn_ + N_, N_, kDrafts, xqp_, xdp_, cs); // and the selector projection's if (!skip_part("head")) native_mmvq(head_type_, head_w_, xq_, logits_, N_, (int) n_dvocab_, kDrafts, cs); @@ -437,11 +435,19 @@ bool Dflash2Drafter::capture(int n, const float* taps, std::string& err) { if (cudaStreamBeginCapture(cs_, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { err = "dflash2: begin capture"; return false; } kernels::copy_i32_from_mapped(d_meta_, m_meta_, 32, cs_); // the context update (fc, the keys and values) and the block's front run side by side: they meet before each layer's attention - fork_ = prof_ == nullptr && cs2_ != nullptr; + // measured: -0.3 ms a round on an RTX 3060, +0.0..0.7 on a Strix Halo (gfx1151), so the HIP builds keep one stream (STRATA_DF2_FORK=1 / 0 overrides) +#if defined(STRATA_USE_HIP) + static const bool fork_default = false; +#else + static const bool fork_default = true; +#endif + static const bool fork_on = [] { const char* e = std::getenv("STRATA_DF2_FORK"); return e && e[0] ? e[0] == '1' : fork_default; }(); + fork_ = fork_on && prof_ == nullptr && cs2_ != nullptr; if (fork_) { cudaEventRecord(ev_fork_, cs_); cudaStreamWaitEvent(cs2_, ev_fork_, 0); } + if (touch_n_ > 0 && prof_ == nullptr && !skip_part("notouch")) kernels::df2_touch(touch_p_, touch_c_, touch_n_, hsel_, cs_); bool ok = record_context(taps, n, fork_ ? cs2_ : cs_, err); if (fork_) cudaEventRecord(ev_join_, cs2_); if (ok) ok = record_block(cs_, err); diff --git a/src/core/dflash2_attn_bench.cpp b/src/core/dflash2_attn_bench.cpp index 897b5b82..17253171 100644 --- a/src/core/dflash2_attn_bench.cpp +++ b/src/core/dflash2_attn_bench.cpp @@ -24,6 +24,8 @@ int main(int argc, char** argv) { cudaMalloc((void**) &vb, 8 * 1024 * 4); cudaMalloc((void**) &part, (size_t) kDf2MaxChunks * 8 * 32 * 130 * 4); cudaMalloc((void**) &out, 8 * 32 * 128 * 4); + float* xdb; + cudaMalloc((void**) &xdb, 8 * 128 * 4); cudaMalloc((void**) &pos, 4); std::vector h((size_t) ring * 1024); for (size_t i = 0; i < h.size(); ++i) h[i] = (float) ((int) (i * 2654435761u >> 20) % 2001 - 1000) / 1000.0f; @@ -39,16 +41,16 @@ int main(int argc, char** argv) { cudaEventCreate(&b); for (int v : {0, 1, 2, 3}) { df2_attention_variant(v); - df2_attention(q, kr, vr, kb, vb, pos, ring, 2048, part, out, nullptr); + df2_attention(q, kr, vr, kb, vb, pos, ring, 2048, part, out, xdb, nullptr); cudaDeviceSynchronize(); cudaEventRecord(a); - for (int i = 0; i < iters; ++i) df2_attention(q, kr, vr, kb, vb, pos, ring, 2048, part, out, nullptr); + for (int i = 0; i < iters; ++i) df2_attention(q, kr, vr, kb, vb, pos, ring, 2048, part, out, xdb, nullptr); cudaEventRecord(b); cudaEventSynchronize(b); float ms; cudaEventElapsedTime(&ms, a, b); - std::vector o(8 * 32 * 128); - cudaMemcpy(o.data(), out, o.size() * 4, cudaMemcpyDeviceToHost); + std::vector o(8 * 128); + cudaMemcpy(o.data(), xdb, o.size() * 4, cudaMemcpyDeviceToHost); double sum = 0; for (float x : o) sum += x; const double kv_bytes = 2.0 * (ctx + 8) * 1024 * 4; diff --git a/src/core/dflash2_bw_bench.cu b/src/core/dflash2_bw_bench.cu new file mode 100644 index 00000000..974a579a --- /dev/null +++ b/src/core/dflash2_bw_bench.cu @@ -0,0 +1,41 @@ +// read-bandwidth probe: sum of a 256 MB buffer with float4 loads, a few launch shapes +#include +#include +__global__ void rd(const float4* __restrict__ p, size_t n, float* out) { + float s = 0; + for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) { + float4 v = p[i]; + s += v.x + v.y + v.z + v.w; + } + if (s == 1234.5f) out[0] = s; +} +__global__ void rd_unroll(const int4* __restrict__ p, size_t n, int* out) { + int s = 0; + size_t stride = (size_t) gridDim.x * blockDim.x; + size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; + for (; i + 3 * stride < n; i += 4 * stride) { + int4 a = p[i], b = p[i + stride], c = p[i + 2 * stride], d = p[i + 3 * stride]; + s += a.x ^ a.y ^ a.z ^ a.w ^ b.x ^ b.y ^ b.z ^ b.w ^ c.x ^ c.y ^ c.z ^ c.w ^ d.x ^ d.y ^ d.z ^ d.w; + } + if (s == 1234) out[0] = s; +} +int main() { + const size_t bytes = 256u << 20, n = bytes / 16; + void* p; float* o; + cudaMalloc(&p, bytes); cudaMalloc(&o, 4); + cudaMemset(p, 1, bytes); + cudaEvent_t a, b; cudaEventCreate(&a); cudaEventCreate(&b); + for (int blocks : {112, 224, 448, 896, 3584, 14336}) { + for (int k = 0; k < 2; ++k) { + cudaEventRecord(a); + for (int it = 0; it < 20; ++it) { + if (k == 0) rd<<>>((const float4*) p, n, o); + else rd_unroll<<>>((const int4*) p, n, (int*) o); + } + cudaEventRecord(b); cudaEventSynchronize(b); + float ms; cudaEventElapsedTime(&ms, a, b); + printf("%s blocks %5d: %.1f GB/s\n", k == 0 ? "loop " : "unroll", blocks, 20.0 * bytes / (ms / 1000) / 1e9); + } + } + return 0; +} diff --git a/src/core/dflash2_small_bench.cpp b/src/core/dflash2_small_bench.cpp new file mode 100644 index 00000000..e608410d --- /dev/null +++ b/src/core/dflash2_small_bench.cpp @@ -0,0 +1,82 @@ +// src/core/dflash2_small_bench.cpp - time of each of the drafter's small kernels, back to back (graph-free), on dummy data. +// +// dflash2_small_bench [iters] +#include "strata/kernels/dflash2.hpp" + +#include + +#include +#include +#include +#include +#include + +using namespace strata::kernels; + +static float* dev(size_t n, float v = 0.5f) { + float* p; + cudaMalloc((void**) &p, n * 4); + std::vector h(n); + for (size_t i = 0; i < n; ++i) h[i] = v * (float) ((i * 2654435761u >> 12) % 1000) / 1000.0f + 0.01f; + cudaMemcpy(p, h.data(), n * 4, cudaMemcpyHostToDevice); + return p; +} + +int main(int argc, char** argv) { + const int iters = argc > 1 ? std::atoi(argv[1]) : 200; + const int N = 2560, B = 8, I = 7680; + float *h = dev(B * N), *xn = dev(B * N), *o = dev(B * N), *dyn = dev(B * 640), *base = dev(4 * N), *gamma = dev(I), *gate = dev(B * I), *up = dev(B * I); + float *q = dev(B * 4096), *k = dev(B * 1024), *qn = dev(B * 4096), *kb = dev(B * 1024), *tab = dev(B * 128), *xd = dev(5 * N / 32 * 8); + float *kr = dev((size_t) 2064 * 1024), *vr = dev((size_t) 2064 * 1024), *lg = dev((size_t) 7 * 106299), *tv = dev(7 * 16), *scr = dev(7 * 64 * 32), *hp = dev(7 * 256); + uint8_t* xq; + cudaMalloc((void**) &xq, 5 * N * 8 + 4096); + cudaMemset(xq, 1, 5 * N * 8); + int32_t *pos, *tok, *outt; + float* outp; + cudaMalloc((void**) &pos, 64); + cudaMalloc((void**) &tok, 7 * 16 * 4); + cudaMalloc((void**) &outt, 64); + cudaMalloc((void**) &outp, 64); + int32_t hpos[16] = {100, 101, 102, 103, 104, 105, 106, 107}; + cudaMemcpy(pos, hpos, 64, cudaMemcpyHostToDevice); + cudaMemset(tok, 0, 7 * 16 * 4); + uint16_t* cb; + cudaMalloc((void**) &cb, (size_t) 1000 * 256 * 2); + cudaMemset(cb, 0, (size_t) 1000 * 256 * 2); + float* part; + cudaMalloc((void**) &part, (size_t) kDf2MaxChunks * 8 * 32 * 130 * 4); + cudaMemset(part, 0, (size_t) kDf2MaxChunks * 8 * 32 * 130 * 4); + uint8_t* w; + cudaMalloc((void**) &w, (size_t) 640 * N * 34 / 32); + cudaMemset(w, 1, (size_t) 640 * N * 34 / 32); + float* y = dev(8 * 640); + cudaEvent_t a, b; + cudaEventCreate(&a); + cudaEventCreate(&b); + auto time = [&](const char* name, const std::function& f) { + f(); + cudaDeviceSynchronize(); + cudaEventRecord(a); + for (int i = 0; i < iters; ++i) f(); + cudaEventRecord(b); + cudaEventSynchronize(b); + float ms; + cudaEventElapsedTime(&ms, a, b); + std::printf("%-28s %7.2f us\n", name, 1000.0 * ms / iters); + }; + time("rms_quant (8 x 2560)", [&] { df2_rms_quant(h, gamma, xn, B, N, 1e-6f, xq, xd, nullptr); }); + time("conv_quant", [&] { df2_conv_quant(xn, dyn, 640, base, B, N, 16, xq, xd, nullptr); }); + time("conv_rms_quant", [&] { df2_conv_rms_quant(o, dyn, 640, base, h, gamma, xn, B, N, 16, 1e-6f, xq, xd, nullptr); }); + time("swiglu_quant (8 x 7680)", [&] { df2_swiglu_quant(gate, up, B, I, xq, xd, nullptr); }); + time("quant_rows (8 x 4096)", [&] { df2_quant_rows(q, 4096, B, xq, xd, nullptr); }); + time("norm_rope_qk", [&] { df2_norm_rope_qk(q, k, gamma, gamma, tab, qn, kb, B, 32, 8, 1e-6f, nullptr); }); + time("kv_ring (3 rows)", [&] { df2_kv_ring(k, k, gamma, pos, tab, kr, vr, 2064, 3, 8, 1e-6f, nullptr); }); + time("rope_table (8)", [&] { df2_rope_table(pos, 8, 10000.0f, tab, nullptr); }); + time("topk (7 x 106299)", [&] { df2_topk(lg, 106299, nullptr, 7, reinterpret_cast(scr), tv, tok, nullptr); }); + time("select (7 rows)", [&] { df2_select(hp, tv, tok, cb, cb, 256, 7, tok, outt, outp, nullptr); }); + time("conv (resid)", [&] { df2_conv(o, dyn, 640, base, h, h, B, N, 16, nullptr); }); + time("attention merge+quant only", [&] { df2_attention(q, kr, vr, kr, vr, pos, 2064, 2048, part, xq, xd, nullptr); }); + Df2Mat m{w, y, 640}; + time("gemm 640 x 2560 (tiny)", [&] { df2_gemm(&m, 1, xq, xd, N, 8, nullptr); }); + return 0; +} diff --git a/src/kernels/cuda/dflash2.cu b/src/kernels/cuda/dflash2.cu index fb98c4e2..43f10145 100644 --- a/src/kernels/cuda/dflash2.cu +++ b/src/kernels/cuda/dflash2.cu @@ -247,7 +247,9 @@ __global__ void __launch_bounds__(128) attn_part_kernel(const float* __restrict_ } } -__global__ void attn_merge_kernel(const float* __restrict__ part, float* __restrict__ out) { +__device__ __forceinline__ void quant_block(float v, int blk, int col, int K, int8_t* __restrict__ xq, float* __restrict__ xd); + +__global__ void attn_merge_kernel(const float* __restrict__ part, int8_t* __restrict__ xq, float* __restrict__ xd) { const int a = blockIdx.x; // kvh * 32 + qi const int kvh = a >> 5, qi = a & 31, d = threadIdx.x; float M = -INFINITY; @@ -261,7 +263,8 @@ __global__ void attn_merge_kernel(const float* __restrict__ part, float* __restr o = fmaf(p[2 + d], w, o); } const int row = qi >> 2, g = qi & 3; - out[((size_t) row * 32 + kvh * kDf2Gqa + g) * HD + d] = L > 0.0f ? o / L : 0.0f; + // the output row `row`, head kvh * 4 + g, dims d: quant block (kvh * 4 + g) * 4 + d / 32 of the 4096-wide row + quant_block(L > 0.0f ? o / L : 0.0f, (kvh * kDf2Gqa + g) * (HD / 32) + (d >> 5), row, 32 * HD, xq, xd); } // ---- Q8 GEMM for up to 8 activation columns (the drafter's matrices) @@ -390,6 +393,98 @@ __global__ void conv_quant_kernel(const float* __restrict__ x, const float* __re quant_block(acc, blk, b, H, xq, xd); } +// h += conv(x) (the finish convolution with its residual), then RMS norm of the new h with `gamma` -> xn (optional) and the planar quantization. +// One block of 1024 threads per row: a warp owns whole 32-blocks (80 of them for 2560), so the quantization needs no exchange. +__global__ void __launch_bounds__(1024) conv_rms_quant_kernel(const float* __restrict__ x, const float* __restrict__ dyn, int dyn_stride, const float* __restrict__ base, + float* __restrict__ h, const float* __restrict__ gamma, float* __restrict__ xn, int H, int group, + float eps, int8_t* __restrict__ xq, float* __restrict__ xd) { + const int b = blockIdx.x, warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int groups = H / group, nb = H / 32; + __shared__ float red[32]; + float v[3]; + float ss = 0.0f; +#pragma unroll + for (int j = 0; j < 3; ++j) { + const int blk = warp + j * 32; + v[j] = 0.0f; + if (blk < nb) { + const int c = blk * 32 + lane; + float acc = 0.0f; +#pragma unroll + for (int o = 0; o < 2; ++o) { + if (b - o < 0) continue; + const float k = base[o * H + c] + dyn[(size_t) b * dyn_stride + o * groups + c / group]; + acc = fmaf(k, x[(size_t) (b - o) * H + c], acc); + } + v[j] = h[(size_t) b * H + c] + acc; + h[(size_t) b * H + c] = v[j]; + ss += v[j] * v[j]; + } + } + for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + if (lane == 0) red[warp] = ss; + __syncthreads(); + float tot = 0.0f; + for (int w = 0; w < 32; ++w) tot += red[w]; + const float scale = rsqrtf(tot / (float) H + eps); +#pragma unroll + for (int j = 0; j < 3; ++j) { + const int blk = warp + j * 32; + if (blk < nb) { + const int c = blk * 32 + lane; + const float y = v[j] * scale * gamma[c]; + if (xn) xn[(size_t) b * H + c] = y; + quant_block(y, blk, b, H, xq, xd); + } + } +} + +// q and k of the block: per (row, head) RMS norm and rope; blockIdx.y < q_heads is a q head (-> qo, row-major rows), the rest k heads (-> ko) +__global__ void norm_rope_qk_kernel(const float* __restrict__ q, const float* __restrict__ k, const float* __restrict__ gq, const float* __restrict__ gk, + const float* __restrict__ table, float* __restrict__ qo, float* __restrict__ ko, int q_heads, int k_heads, float eps) { + const int r = blockIdx.x, hh = blockIdx.y, d = threadIdx.x; + const bool isq = hh < q_heads; + const int h = isq ? hh : hh - q_heads, heads = isq ? q_heads : k_heads; + const float* in = isq ? q : k; + const float* gamma = isq ? gq : gk; + float* out = isq ? qo : ko; + __shared__ float red[4]; + __shared__ float y[HD]; + const float x = in[((size_t) r * heads + h) * HD + d]; + float ss = x * x; + for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + if ((d & 31) == 0) red[d >> 5] = ss; + __syncthreads(); + const float v = x * rsqrtf((red[0] + red[1] + red[2] + red[3]) / (float) HD + eps) * gamma[d]; + y[d] = v; + __syncthreads(); + const int i = d & 63; + const float c = table[(r * 2 + 0) * 64 + i], sn = table[(r * 2 + 1) * 64 + i]; + out[((size_t) r * heads + h) * HD + d] = d < 64 ? v * c - y[d + 64] * sn : v * c + y[d - 64] * sn; +} + +// the context update's ring write: K norm + rope of (row, head) and the V copy, both into the head-major ring slot pos % slots +__global__ void kv_ring_kernel(const float* __restrict__ kin, const float* __restrict__ vin, const float* __restrict__ gk, const int32_t* __restrict__ pos, + const float* __restrict__ table, float* __restrict__ kring, float* __restrict__ vring, int slots, int heads, float eps) { + const int r = blockIdx.x, h = blockIdx.y, d = threadIdx.x; + __shared__ float red[4]; + __shared__ float y[HD]; + const float x = kin[((size_t) r * heads + h) * HD + d]; + float ss = x * x; + for (int o = 16; o > 0; o >>= 1) ss += __shfl_xor_sync(0xffffffffu, ss, o); + if ((d & 31) == 0) red[d >> 5] = ss; + __syncthreads(); + const float v = x * rsqrtf((red[0] + red[1] + red[2] + red[3]) / (float) HD + eps) * gk[d]; + y[d] = v; + __syncthreads(); + const int i = d & 63; + const float c = table[(r * 2 + 0) * 64 + i], sn = table[(r * 2 + 1) * 64 + i]; + const int slot = (int) (pos[r] % slots); + const size_t at = ((size_t) h * slots + slot) * HD + d; + kring[at] = d < 64 ? v * c - y[d + 64] * sn : v * c + y[d - 64] * sn; + vring[at] = vin[((size_t) r * heads + h) * HD + d]; +} + // silu(gate) * up then the planar quantization: grid (ceil(I / 32 / 8), rows), 256 threads __global__ void swiglu_quant_kernel(const float* __restrict__ gate, const float* __restrict__ up, int I, int8_t* __restrict__ xq, float* __restrict__ xd) { const int blk = blockIdx.x * 8 + (threadIdx.x >> 5), b = blockIdx.y, lane = threadIdx.x & 31; @@ -415,6 +510,16 @@ __global__ void q8_tile_kernel(const uint8_t* __restrict__ blocks, int8_t* __res for (int i = 0; i < 32; ++i) o[i] = (int8_t) src[2 + i]; } +// Reads a list of small tensors (norm weights, the convolutions' base kernels, ...) once, so they sit in the caches before the first kernel that needs them +// (the verify window before the drafter streams gigabytes through them, and every dependent small kernel would otherwise wait for DRAM). +struct Df2Touch { const float* p[48]; int n[48]; int count; }; +__global__ void touch_kernel(Df2Touch t, float* __restrict__ sink) { + float s = 0.0f; + for (int i = 0; i < t.count; ++i) + for (int j = blockIdx.x * blockDim.x + threadIdx.x; j < t.n[i]; j += gridDim.x * blockDim.x) s += t.p[i][j]; + if (s == 1.2345e30f) sink[0] = s; +} + // ---- top-16 constexpr int TK_CHUNK_MAX = 4096; __device__ __forceinline__ bool better(float va, int ia, float vb, int ib) { return va > vb || (va == vb && ia < ib); } @@ -591,13 +696,41 @@ void df2_copy_rows(const float* in, float* out, const int32_t* pos, int slot_mod } void df2_attention(const float* q, const float* kring, const float* vring, const float* kblk, const float* vblk, const int32_t* anchor_pos, - int ring_slots, int window, float* part, float* out, void* stream) { + int ring_slots, int window, float* part, void* xq, float* xd, void* stream) { attn_part_kernel<<>>(q, kring, vring, kblk, vblk, anchor_pos, ring_slots, window, part, g_attn_variant); check("attn_part"); - attn_merge_kernel<<>>(part, out); + attn_merge_kernel<<>>(part, static_cast(xq), xd); check("attn_merge"); } +void df2_conv_rms_quant(const float* x, const float* dyn, int dyn_stride, const float* base, float* h, const float* gamma, float* xn, int rows, int H, int group, + float eps, void* xq, float* xd, void* stream) { + if (H > 3 * 1024) throw std::invalid_argument("df2_conv_rms_quant: H too large"); + conv_rms_quant_kernel<<>>(x, dyn, dyn_stride, base, h, gamma, xn, H, group, eps, static_cast(xq), xd); + check("conv_rms_quant"); +} + +void df2_norm_rope_qk(const float* q, const float* k, const float* gq, const float* gk, const float* table, float* qo, float* ko, int rows, int q_heads, int k_heads, + float eps, void* stream) { + norm_rope_qk_kernel<<>>(q, k, gq, gk, table, qo, ko, q_heads, k_heads, eps); + check("norm_rope_qk"); +} + +void df2_kv_ring(const float* kin, const float* vin, const float* gk, const int32_t* pos, const float* table, float* kring, float* vring, int slots, int rows, + int heads, float eps, void* stream) { + kv_ring_kernel<<>>(kin, vin, gk, pos, table, kring, vring, slots, heads, eps); + check("kv_ring"); +} + +void df2_touch(const float* const* ptrs, const int* counts, int n, float* sink, void* stream) { + Df2Touch t; + if (n > 48) n = 48; + for (int i = 0; i < n; ++i) { t.p[i] = ptrs[i]; t.n[i] = counts[i]; } + t.count = n; + touch_kernel<<<40, 256, 0, (cudaStream_t) stream>>>(t, sink); + check("touch"); +} + void df2_gemm_variant(int v) { g_gemm_variant = v; } void df2_attention_variant(int v) { g_attn_variant = v; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d7ec9a69..42e1c779 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -16332,6 +16332,8 @@ int main(int argc, char** argv) { auto draft_next = [&](int T_, int a_) -> bool { #if defined(STRATA_HAVE_DFLASH2) if (use_df2) { + static const bool wait_commit_first = std::getenv("STRATA_DF2_WAITCOMMIT") != nullptr; // measurement: no overlap with the async commit + if (wait_commit_first && !ver.wait_commit(err)) return false; int32_t dd[strata::core::Dflash2Drafter::kDrafts]; float pp[strata::core::Dflash2Drafter::kDrafts]; if (!df2.draft(ver.tap_dev(), a_ + 1, p, outv[(size_t) a_], dd, pp, err)) return false; From 6f83fe2c42837c83c6363b40913d54710e300620 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 21 Oct 2026 19:46:26 +0200 Subject: [PATCH 08/12] dflash2: drop the cache-touch kernel (no gain), wait-commit measurement switch --- include/strata/core/dflash2.hpp | 3 --- include/strata/kernels/dflash2.hpp | 3 --- src/core/dflash2.cpp | 7 ------- src/kernels/cuda/dflash2.cu | 19 ------------------- 4 files changed, 32 deletions(-) diff --git a/include/strata/core/dflash2.hpp b/include/strata/core/dflash2.hpp index bad2bf5e..205bff3d 100644 --- a/include/strata/core/dflash2.hpp +++ b/include/strata/core/dflash2.hpp @@ -124,9 +124,6 @@ private: float* xdc_ = nullptr; cudaStream_t cs2_ = nullptr; ///< the context update's branch of the round graph cudaEvent_t ev_fork_ = nullptr, ev_join_ = nullptr, ev_ctx_[8] = {}; - const float* touch_p_[48] = {}; - int touch_c_[48] = {}; - int touch_n_ = 0; bool fork_ = false; ///< recording the forked graph: layer l's attention waits for ev_ctx_[l] float *fcy_ = nullptr, *hctx_ = nullptr, *kc_ = nullptr, *vc_ = nullptr; float *h_ = nullptr, *xn_ = nullptr, *xc_ = nullptr, *dyn_ = nullptr, *q_ = nullptr, *qn_ = nullptr, *k_ = nullptr, *v_ = nullptr, *kblk_ = nullptr; diff --git a/include/strata/kernels/dflash2.hpp b/include/strata/kernels/dflash2.hpp index 28617498..bdcf0cbe 100644 --- a/include/strata/kernels/dflash2.hpp +++ b/include/strata/kernels/dflash2.hpp @@ -76,9 +76,6 @@ void df2_norm_rope_qk(const float* q, const float* k, const float* gq, const flo void df2_kv_ring(const float* kin, const float* vin, const float* gk, const int32_t* pos, const float* table, float* kring, float* vring, int slots, int rows, int heads, float eps, void* stream); -/// Reads n small f32 tensors (ptrs[i], counts[i] floats; n <= 48) once to bring them into the caches; sink: one float of scratch. -void df2_touch(const float* const* ptrs, const int* counts, int n, float* sink, void* stream); - /// Top-16 per row of logits [rows][n] (value-descending; ties to the lower index). idx_map (optional) maps a column to a token id. /// scratch: rows * kDf2TopBlocks * 16 * 2 words. Outputs val[rows][16] and tok[rows][16]. n <= 4096 * kDf2TopBlocks. void df2_topk(const float* logits, int n, const int32_t* idx_map, int rows, uint32_t* scratch, float* val, int32_t* tok, void* stream); diff --git a/src/core/dflash2.cpp b/src/core/dflash2.cpp index 3da70987..5acd7683 100644 --- a/src/core/dflash2.cpp +++ b/src/core/dflash2.cpp @@ -208,12 +208,6 @@ bool Dflash2Drafter::load(const std::string& path, int device, std::string& err) cudaEventCreate(&ev_a_); cudaEventCreate(&ev_b_); } - // the small f32 tensors the round touches first (see df2_touch) - for (const Tensor& t : tensors_) - if (t.dtype == "f32" && t.rows * t.cols * 4 <= (1 << 20) && touch_n_ < 48) { - touch_p_[touch_n_] = reinterpret_cast(blob_ + t.off); - touch_c_[touch_n_++] = (int) (t.rows * t.cols); - } return alloc(err); } @@ -447,7 +441,6 @@ bool Dflash2Drafter::capture(int n, const float* taps, std::string& err) { cudaEventRecord(ev_fork_, cs_); cudaStreamWaitEvent(cs2_, ev_fork_, 0); } - if (touch_n_ > 0 && prof_ == nullptr && !skip_part("notouch")) kernels::df2_touch(touch_p_, touch_c_, touch_n_, hsel_, cs_); bool ok = record_context(taps, n, fork_ ? cs2_ : cs_, err); if (fork_) cudaEventRecord(ev_join_, cs2_); if (ok) ok = record_block(cs_, err); diff --git a/src/kernels/cuda/dflash2.cu b/src/kernels/cuda/dflash2.cu index 43f10145..997a3e35 100644 --- a/src/kernels/cuda/dflash2.cu +++ b/src/kernels/cuda/dflash2.cu @@ -510,16 +510,6 @@ __global__ void q8_tile_kernel(const uint8_t* __restrict__ blocks, int8_t* __res for (int i = 0; i < 32; ++i) o[i] = (int8_t) src[2 + i]; } -// Reads a list of small tensors (norm weights, the convolutions' base kernels, ...) once, so they sit in the caches before the first kernel that needs them -// (the verify window before the drafter streams gigabytes through them, and every dependent small kernel would otherwise wait for DRAM). -struct Df2Touch { const float* p[48]; int n[48]; int count; }; -__global__ void touch_kernel(Df2Touch t, float* __restrict__ sink) { - float s = 0.0f; - for (int i = 0; i < t.count; ++i) - for (int j = blockIdx.x * blockDim.x + threadIdx.x; j < t.n[i]; j += gridDim.x * blockDim.x) s += t.p[i][j]; - if (s == 1.2345e30f) sink[0] = s; -} - // ---- top-16 constexpr int TK_CHUNK_MAX = 4096; __device__ __forceinline__ bool better(float va, int ia, float vb, int ib) { return va > vb || (va == vb && ia < ib); } @@ -722,15 +712,6 @@ void df2_kv_ring(const float* kin, const float* vin, const float* gk, const int3 check("kv_ring"); } -void df2_touch(const float* const* ptrs, const int* counts, int n, float* sink, void* stream) { - Df2Touch t; - if (n > 48) n = 48; - for (int i = 0; i < n; ++i) { t.p[i] = ptrs[i]; t.n[i] = counts[i]; } - t.count = n; - touch_kernel<<<40, 256, 0, (cudaStream_t) stream>>>(t, sink); - check("touch"); -} - void df2_gemm_variant(int v) { g_gemm_variant = v; } void df2_attention_variant(int v) { g_attn_variant = v; } From ba6966d83f81b66f572f0b827e049332ad89fe40 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 21 Oct 2026 19:52:11 +0200 Subject: [PATCH 09/12] verify: the DFlash2 tap kernel only where the DFlash2 sources are built (Metal and SYCL keep the per-row dump path) --- src/core/verify.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 5b898f9d..13d1aac4 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -56,7 +56,9 @@ #include "strata/core/progress.hpp" #include "strata/kernels/shared_expert.hpp" #include "strata/kernels/verify_kernels.hpp" +#if defined(STRATA_HAVE_DFLASH2) #include "strata/kernels/dflash2.hpp" +#endif #include #include @@ -2190,8 +2192,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { // the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it), the mean of // the hc streams, all rows of the group in one launch const int64_t nt = (int64_t) tap_layers_.size(); +#if defined(STRATA_HAVE_DFLASH2) strata::kernels::df2_tap_gr(Rt(tb), HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, tap_dev_ + ((size_t) tb * nt + (size_t) tap_slot_[(size_t) l]) * N, nt * N, n, N, (int) HC, cs); +#else // builds without the DFlash2 kernels (Metal, SYCL): the research dump's per-row path + for (int t = tb; t < te; ++t) { + cudaMemcpyAsync(tap_scratch_, Rt(t), (size_t) HC * N * 4, cudaMemcpyDeviceToDevice, cs); + gr_write(tap_scratch_, bo_ + t * N, inj2_ + t * HC, gs, tap_scratch_, cs); + hc_mean_streams(tap_scratch_, tap_dev_ + ((size_t) t * nt + (size_t) tap_slot_[(size_t) l]) * N, N, (int) HC, cs); + } +#endif } if (l == g.n_layers - 1) { if (!fuse_head_gr) { From ff9ca03f3c473aef8b83c874b6b079489e80b607 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 22 Oct 2026 06:24:00 +0200 Subject: [PATCH 10/12] dflash2: a verify window whose graph runs out of memory narrows the window instead of failing; --draft-cap, 5 by default on Strix Halo, a plain line on 12 GB NVIDIA --- src/program/generate.cpp | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 42e1c779..cb9305c9 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -787,6 +787,7 @@ struct Options { /// --draft dflash2 --draft-model PACK (opt-in, CUDA / HIP): the DFlash2 block drafter for Qwen3.8-Flash-Next (tools/dflash2_pack.py) drafts instead /// of the MTP layer, which stays loaded as the fallback. Needs --mtp, --spec and a native pack; a missing pack falls back to the MTP. std::string draft, draft_model; + int draft_cap = 0; ///< --draft-cap N: the widest verify window with --draft dflash2 (0 = by card class, see where the drafter loads) /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range /// 4 44 --cvec-mode project --cvec-dir per-layer`. None by default; --serve switches a loaded one per request. @@ -941,6 +942,7 @@ void usage() { " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" " --draft mtp|dflash2 the draft source (default mtp); dflash2 needs --draft-model PACK (tools/dflash2_pack.py)\n" " and keeps the MTP layer loaded as the fallback (opt-in, Flash-Next, CUDA / HIP)\n" + " --draft-cap N the widest verify window with --draft dflash2 (default by card: 5 on Strix Halo / iGPU, --spec as given elsewhere)\n" " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" " --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n" @@ -2688,6 +2690,7 @@ int main(int argc, char** argv) { } } else if (a == "--draft-model") o.draft_model = next("--draft-model"); + else if (a == "--draft-cap") o.draft_cap = std::max(0, std::atoi(next("--draft-cap"))); else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); else if (a == "--control-vector-scaled") { // FILE:SCALE, comma-separated; the LAST colon splits, so a Windows path (C:\...) keeps its drive @@ -5447,6 +5450,28 @@ int main(int argc, char** argv) { if (why == nullptr) { if (df2.load(o.draft_model, 0, err)) { use_df2 = true; + // Per card class, from the measured A/Bs (notes-dflash2-p1.md): on Strix Halo a window of 5 is the agent-safe pick (cap 6 ties on + // agent prompts); a 12 GB NVIDIA card is slower with DFlash2 than with the MTP at every cap but code, which only the user can know. + // Recommend, never force: the window is capped for the card unless --draft-cap says otherwise, and a small NVIDIA card gets one plain line. + cudaDeviceProp dp{}; + if (cudaGetDeviceProperties(&dp, 0) == cudaSuccess) { +#if defined(STRATA_USE_HIP) + const bool uma = strata::kernels::gfx_arch_is_gfx1151(dp.gcnArchName); +#else + const bool uma = false; +#endif + const int cap = o.draft_cap > 0 ? o.draft_cap : (uma ? 5 : 0); + if (cap > 0 && o.spec > cap) { + std::fprintf(stderr, "strata generate: --draft dflash2: windows capped at %d tokens (%s; --draft-cap N changes it)\n", cap, + o.draft_cap > 0 ? "as asked" : "the width measured best on this card"); + o.spec = cap; + } +#if !defined(STRATA_USE_HIP) + if (o.draft_cap == 0 && dp.totalGlobalMem < (size_t) 13 << 30) + std::fprintf(stderr, "strata generate: --draft dflash2: on a 12 GB NVIDIA card the MTP drafter was faster in most measurements " + "(code prompts at a window of 6 gained 3%%); continuing as asked\n"); +#endif + } } else { std::fprintf(stderr, "strata generate: --draft dflash2: %s; the MTP drafts instead\n", err.c_str()); } @@ -16360,8 +16385,10 @@ int main(int argc, char** argv) { #endif return mtp.draft(T_, outv.data(), p, a_, drafts.data(), err, dprob.data(), (float) o.spec_min_p); }; + int win_cap = o.spec; // the widest window the VRAM allows (lowered on an out-of-memory capture, see below) while ((int64_t) produced.size() < max_new) { const Clock::time_point t0 = Clock::now(); + retry_round: strata::core::progress_at("spec loop: choosing the window", (int64_t) produced.size()); int T = S_mtp; if (use_mtp && o.spec_min_p > 0.0) { @@ -16383,7 +16410,7 @@ int main(int argc, char** argv) { // The window's rows sit at p .. p + T - 1, and past the context there is no cell to verify them in: near // its end the window takes only the rows that fit (the admission checked the prompt and max_new, which a // full window can overrun) - const int room = (int) std::min(o.spec, o.max_context - p); + const int room = (int) std::min(win_cap, o.max_context - p); T = std::min(T, room); // --lookup-chain: what followed an earlier occurrence of the context + the MTP's drafts, after them int chain_n = 0, cm = 0; @@ -16426,6 +16453,15 @@ int main(int argc, char** argv) { else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true); if (use_mtp && mtp.prob() && !from_sfx && T_mtp > 1 && o.spec_corrupt <= 0) ver.set_spec_q(mtp.spec_q(), T_mtp - 1); if (!ver.run(T, window.data(), p, &drive_pool_multi, &drive, outv.data(), err)) { + // The graph of a window size is captured the first time it is used, and the draft source took VRAM: when the capture runs + // out of memory the window gets one row narrower (the widths below it are already captured) instead of the run failing. + if (T > 2 && !first_window && err.find("out of memory") != std::string::npos) { + win_cap = T - 1; + --window_hist[(size_t) T]; + std::fprintf(stderr, "strata generate: not enough VRAM left for a %d-token verify window: windows are %d tokens at most from here\n", T, win_cap); + err.clear(); + goto retry_round; + } std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } From 3ae2123bcedb4ddf9ff2ef6249eebd7e9ab0d649 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 22 Oct 2026 08:51:54 +0200 Subject: [PATCH 11/12] dflash2: --draft-conf (window cut by the selector's cumulative probability), drafter streams at high priority on CUDA --- src/core/dflash2.cpp | 15 ++++++++++++++- src/program/generate.cpp | 17 ++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/core/dflash2.cpp b/src/core/dflash2.cpp index 5acd7683..bf9855c0 100644 --- a/src/core/dflash2.cpp +++ b/src/core/dflash2.cpp @@ -192,7 +192,20 @@ bool Dflash2Drafter::load(const std::string& path, int device, std::string& err) return false; } } - if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess || cudaStreamCreateWithFlags(&cs2_, cudaStreamNonBlocking) != cudaSuccess) { + // the draft round runs while the verifier's async commit still has work on the card: a high-priority stream keeps it from queueing behind that + // (CUDA by default; on HIP only with STRATA_DF2_PRIO=1, where the engine's other streams keep the default priority) + int prio_lo = 0, prio_hi = 0; +#if defined(STRATA_USE_HIP) + static const bool hi_prio = [] { const char* e = std::getenv("STRATA_DF2_PRIO"); return e && e[0] == '1'; }(); + if (hi_prio) hipDeviceGetStreamPriorityRange(&prio_lo, &prio_hi); + if (hipStreamCreateWithPriority(&cs_, hipStreamNonBlocking, hi_prio ? prio_hi : 0) != cudaSuccess || + hipStreamCreateWithPriority(&cs2_, hipStreamNonBlocking, hi_prio ? prio_hi : 0) != cudaSuccess) { +#else + static const bool hi_prio = [] { const char* e = std::getenv("STRATA_DF2_PRIO"); return !(e && e[0] == '0'); }(); + cudaDeviceGetStreamPriorityRange(&prio_lo, &prio_hi); + if (cudaStreamCreateWithPriority(&cs_, cudaStreamNonBlocking, hi_prio ? prio_hi : 0) != cudaSuccess || + cudaStreamCreateWithPriority(&cs2_, cudaStreamNonBlocking, hi_prio ? prio_hi : 0) != cudaSuccess) { +#endif err = "dflash2: stream"; return false; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index cb9305c9..9840d4f1 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -787,6 +787,7 @@ struct Options { /// --draft dflash2 --draft-model PACK (opt-in, CUDA / HIP): the DFlash2 block drafter for Qwen3.8-Flash-Next (tools/dflash2_pack.py) drafts instead /// of the MTP layer, which stays loaded as the fallback. Needs --mtp, --spec and a native pack; a missing pack falls back to the MTP. std::string draft, draft_model; + double draft_conf = 0.0; ///< --draft-conf P: with --draft dflash2 the window ends where the product of the selector's probabilities falls below P (replaces --spec-min-p) int draft_cap = 0; ///< --draft-cap N: the widest verify window with --draft dflash2 (0 = by card class, see where the drafter loads) /// A control vector on the residual stream (strata/kernels/cvec.hpp), with llama.cpp's flags: the /// `experimental-speed-projection` profile passes `--control-vector-scaled FILE:1.0 --control-vector-layer-range @@ -942,6 +943,7 @@ void usage() { " --mtp-draft-vocab FILE opt-in: the draft head's token subset (default /draft_vocab.bin)\n" " --draft mtp|dflash2 the draft source (default mtp); dflash2 needs --draft-model PACK (tools/dflash2_pack.py)\n" " and keeps the MTP layer loaded as the fallback (opt-in, Flash-Next, CUDA / HIP)\n" + " --draft-conf P with --draft dflash2: end the window where the product of the selector's probabilities falls below P (default 0 = --spec-min-p)\n" " --draft-cap N the widest verify window with --draft dflash2 (default by card: 5 on Strix Halo / iGPU, --spec as given elsewhere)\n" " --control-vector-scaled FILE:SCALE[,...] a control vector GGUF on the residual stream (llama.cpp's\n" " format; --control-vector FILE = scale 1). --serve: requests switch it (cvec=0|1)\n" @@ -2690,6 +2692,7 @@ int main(int argc, char** argv) { } } else if (a == "--draft-model") o.draft_model = next("--draft-model"); + else if (a == "--draft-conf") o.draft_conf = std::clamp(std::atof(next("--draft-conf")), 0.0, 1.0); else if (a == "--draft-cap") o.draft_cap = std::max(0, std::atoi(next("--draft-cap"))); else if (a == "--control-vector") o.cvec_files.push_back({next("--control-vector"), 1.0f}); else if (a == "--control-vector-scaled") { @@ -16368,7 +16371,12 @@ int main(int argc, char** argv) { if (ss.ple.ready() && ss.ple.table != nullptr) { int n_pf = 0; const int cap = std::min(S_mtp, (int) drafts.size() + 1); - for (int t = 1; t < cap && (o.spec_min_p <= 0.0 || dprob[(size_t) t - 1] >= (float) o.spec_min_p); ++t) ++n_pf; + double chain = 1.0; + for (int t = 1; t < cap; ++t) { + if (o.draft_conf > 0.0) { if ((chain *= (double) dprob[(size_t) t - 1]) < o.draft_conf) break; } + else if (o.spec_min_p > 0.0 && dprob[(size_t) t - 1] < (float) o.spec_min_p) break; + ++n_pf; + } int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; auto pf = [&](int32_t tok) { uint32_t rows16[strata::kernels::PLE_N_HEADS]; @@ -16395,6 +16403,13 @@ int main(int argc, char** argv) { T = 1; while (T < S_mtp && dprob[(size_t) T - 1] >= (float) o.spec_min_p) ++T; } +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2 && o.draft_conf > 0.0) { // DFlash2's own confidence: the chance that every draft so far holds, from the selector's probabilities + T = 1; + double chain = 1.0; + while (T < S_mtp && (chain *= (double) dprob[(size_t) T - 1]) >= o.draft_conf) ++T; + } +#endif if (first_window) T = 1; if (!t_cycle.empty() && !first_window) T = t_cycle[(size_t) (rounds % (int64_t) t_cycle.size())]; bool from_sfx = false; From eebb870922b708d02f6557629e20cae0555151c5 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 22 Oct 2026 12:44:45 +0200 Subject: [PATCH 12/12] dflash2: reserve the drafter's head before the expert cache is sized, loud fallback lines naming the VRAM needed, Blackwell window cap 6 (draft_cap_test) --- CMakeLists.txt | 4 ++++ include/strata/core/draft_cap.hpp | 21 +++++++++++++++++++++ src/core/draft_cap_test.cpp | 21 +++++++++++++++++++++ src/program/generate.cpp | 28 +++++++++++++++++++++++----- 4 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 include/strata/core/draft_cap.hpp create mode 100644 src/core/draft_cap_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 77671a8b..009d526f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1476,6 +1476,10 @@ if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) add_executable(spec_prob_test src/core/spec_prob_test.cpp) target_include_directories(spec_prob_test PRIVATE include) add_test(NAME spec_prob_test COMMAND spec_prob_test) + # the per-card window cap of --draft dflash2 (header-only, CPU) + add_executable(draft_cap_test src/core/draft_cap_test.cpp) + target_include_directories(draft_cap_test PRIVATE include) + add_test(NAME draft_cap_test COMMAND draft_cap_test) # the f32 -> bf16 rounding against ggml's, NaN included, over every f32 bit pattern (header-only, CPU) add_executable(bf16_bits_test src/kernels/bf16_bits_test.cpp) target_include_directories(bf16_bits_test PRIVATE include) diff --git a/include/strata/core/draft_cap.hpp b/include/strata/core/draft_cap.hpp new file mode 100644 index 00000000..42d2038d --- /dev/null +++ b/include/strata/core/draft_cap.hpp @@ -0,0 +1,21 @@ +// include/strata/core/draft_cap.hpp - the widest verify window --draft dflash2 uses on each card class (measured A/Bs, notes-dflash2-p1.md; recommend, never force). +#pragma once + +#include + +namespace strata::core { + +/// 0 = no cap (the --spec given stays). `uma`: Strix Halo / iGPU (gfx1151); `cc_major`: the CUDA compute capability's major (0 on HIP). +/// - Strix Halo / UMA: 5 (agent-safe; 6 ties on agent prompts) +/// - Blackwell (sm_120, cc 12): 6 (+1.9% at 6 on an RTX PRO 5000, 8 was worse) +/// - everything else: unmeasured, --spec as given +inline int dflash2_auto_cap(bool uma, int cc_major) { + if (uma) return 5; + if (cc_major == 12) return 6; + return 0; +} + +/// A 12 GB NVIDIA card (< 13 GiB, CUDA): the MTP drafter was faster in most measurements, which the engine says once. +inline bool dflash2_small_nvidia(bool cuda, size_t total_bytes) { return cuda && total_bytes < ((size_t) 13 << 30); } + +} // namespace strata::core diff --git a/src/core/draft_cap_test.cpp b/src/core/draft_cap_test.cpp new file mode 100644 index 00000000..7137a923 --- /dev/null +++ b/src/core/draft_cap_test.cpp @@ -0,0 +1,21 @@ +// src/core/draft_cap_test.cpp - the per-card window cap of --draft dflash2 (CPU only). +#include "strata/core/draft_cap.hpp" + +#include + +using namespace strata::core; + +static int fails = 0; +#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++fails; } } while (0) + +int main() { + CHECK(dflash2_auto_cap(true, 0) == 5); // Strix Halo + CHECK(dflash2_auto_cap(false, 12) == 6); // Blackwell (sm_120) + CHECK(dflash2_auto_cap(false, 8) == 0); // Ampere / Ada: --spec as given + CHECK(dflash2_auto_cap(false, 0) == 0); // another AMD card + CHECK(dflash2_small_nvidia(true, (size_t) 12 << 30)); + CHECK(!dflash2_small_nvidia(true, (size_t) 16 << 30)); + CHECK(!dflash2_small_nvidia(false, (size_t) 8 << 30)); + if (fails == 0) std::printf("draft_cap_test: ok\n"); + return fails == 0 ? 0 : 1; +} diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 9840d4f1..3ec65053 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -68,6 +68,7 @@ #include "strata/core/mtp.hpp" #if defined(STRATA_HAVE_DFLASH2) #include "strata/core/dflash2.hpp" +#include "strata/core/draft_cap.hpp" #endif #include "strata/prefill/prefill.hpp" #if defined(STRATA_PREFILL_MMQ) @@ -5463,20 +5464,27 @@ int main(int argc, char** argv) { #else const bool uma = false; #endif - const int cap = o.draft_cap > 0 ? o.draft_cap : (uma ? 5 : 0); +#if defined(STRATA_USE_HIP) + const int cc_major = 0; +#else + const int cc_major = dp.major; +#endif + const int cap = o.draft_cap > 0 ? o.draft_cap : strata::core::dflash2_auto_cap(uma, cc_major); if (cap > 0 && o.spec > cap) { std::fprintf(stderr, "strata generate: --draft dflash2: windows capped at %d tokens (%s; --draft-cap N changes it)\n", cap, o.draft_cap > 0 ? "as asked" : "the width measured best on this card"); o.spec = cap; } #if !defined(STRATA_USE_HIP) - if (o.draft_cap == 0 && dp.totalGlobalMem < (size_t) 13 << 30) + if (o.draft_cap == 0 && strata::core::dflash2_small_nvidia(true, dp.totalGlobalMem)) std::fprintf(stderr, "strata generate: --draft dflash2: on a 12 GB NVIDIA card the MTP drafter was faster in most measurements " "(code prompts at a window of 6 gained 3%%); continuing as asked\n"); #endif } } else { - std::fprintf(stderr, "strata generate: --draft dflash2: %s; the MTP drafts instead\n", err.c_str()); + std::fprintf(stderr, "strata generate: --draft dflash2: %s. DFlash2 needs about 1.2 GiB of VRAM (the pack 0.76 GiB, its buffers and K/V ring " + "0.25 GiB, a draft head 0.2 GiB); start with --vram-reserve-mib 1900 to keep it (the expert cache then gives up about 2.5%% " + "of its experts to the CPU), or a smaller --max-context. The MTP drafts instead.\n", err.c_str()); } } else { std::fprintf(stderr, "strata generate: --draft dflash2 is off: %s; the MTP drafts instead\n", why); @@ -5826,6 +5834,9 @@ int main(int argc, char** argv) { const int64_t pf_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; int64_t mtp_b = (!o.mtp.empty() && native_head.loaded()) ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2 && native_head.loaded()) mtp_b += (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) + (48 << 20); // DFlash2's own draft head and logits +#endif if (stages.empty()) for (const auto& d : slot_mtp) mtp_b += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); const int64_t pipe_b = o.pipeline_windows <= 0 ? 0 @@ -6070,6 +6081,9 @@ int main(int argc, char** argv) { if (stages.empty()) for (const auto& d : slot_mtp) mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); +#if defined(STRATA_HAVE_DFLASH2) + if (use_df2 && native_head.loaded()) mtp_bind += (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) + (48 << 20); // DFlash2's own draft head and logits, bound after this +#endif const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first; const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; int64_t slots = ((int64_t) free_b - reserve) / blob; @@ -16052,11 +16066,15 @@ int main(int argc, char** argv) { use_df2 = false; } if (use_df2 && !df2.bind(wt, &native_head, o.mtp_draft_vocab.empty() ? o.mtp + "/draft_vocab.bin" : o.mtp_draft_vocab, err)) { - std::fprintf(stderr, "strata generate: --draft dflash2: %s; the MTP drafts instead\n", err.c_str()); + std::fprintf(stderr, "strata generate: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (the pack 0.76 GiB, buffers and K/V ring " + "0.25 GiB, a draft head 0.2 GiB); --vram-reserve-mib 1900 keeps it (the expert cache gives up about 2.5%% of its experts " + "to the CPU). The MTP drafts instead.\n", err.c_str()); use_df2 = false; } if (use_df2 && !df2.prepare(ver.tap_dev(), err)) { - std::fprintf(stderr, "strata generate: --draft dflash2: %s; the MTP drafts instead\n", err.c_str()); + std::fprintf(stderr, "strata generate: --draft dflash2: %s. It needs about 1.2 GiB of VRAM in all (the pack 0.76 GiB, buffers and K/V ring " + "0.25 GiB, a draft head 0.2 GiB); --vram-reserve-mib 1900 keeps it (the expert cache gives up about 2.5%% of its experts " + "to the CPU). The MTP drafts instead.\n", err.c_str()); use_df2 = false; } if (use_df2) std::fprintf(stderr, "strata generate: DFlash2 drafter on (%s, graphs captured in %.0f ms), the MTP layer stays as the fallback\n", o.draft_model.c_str(), df2.ms_capture);