diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index 74a529334..e2bd09089 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -11,7 +11,7 @@ A number or a word is set like any environment variable, for example `STRATA_KVA (`terminal/strata-.json`), which the server passes to the engine. The Strata project's Terminal writes it there with `strata launch --set NAME=value`. -## Switches you can turn on (368) +## Switches you can turn on (369) Off unless you set them. The last column says where each one is described. @@ -317,6 +317,7 @@ Off unless you set them. The last column says where each one is described. | `STRATA_QSA_CLUSTER` | number | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md) | | `STRATA_QSA_SPLIT_ATTN` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | | `STRATA_QUANT_IQ4XS_X4_V2` | on / off | NVIDIA and AMD | [TEST_REQUESTS.md](TEST_REQUESTS.md) | +| `STRATA_QWEN4_DRAFT_HEAD2` | on / off | NVIDIA and AMD | [qwen4.md](models/qwen4.md) | | `STRATA_RAM_ADAPT` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md), [release-notes-0.2.7.md](release-notes-0.2.7.md) | | `STRATA_RAM_KEEP_GIB` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md), [UNSLOTH_Q4.md](UNSLOTH_Q4.md) | | `STRATA_RDNA2_SGEMM` | number | AMD | [AMD_HIP.md](AMD_HIP.md), [README.md](bench-results/2026-10-04-rdna2-fp16-prompt/README.md) | diff --git a/docs/models/qwen4.md b/docs/models/qwen4.md index 0f6ab6d91..f21502fe0 100644 --- a/docs/models/qwen4.md +++ b/docs/models/qwen4.md @@ -38,7 +38,10 @@ Useful options: `--mtp off` or `--no-draft` to disable it (`--no-draft` in the run config). Pass `--drafter dflash2` on Windows / Linux (CUDA & HIP) or macOS (Apple Silicon Metal) to fetch the optional DFlash2 drafter (`RadixArk/Qwen4-35B-A3B-Dflash2`, 790 MB, passed via `--draft-model`). On Metal, DFlash2 defaults to `Q8_0` weights (542 MiB VRAM); set - `STRATA_POLY_DF2_QUANT=q4_0` for `Q4_0` (414 MiB VRAM). + `STRATA_POLY_DF2_QUANT=q4_0` for `Q4_0` (414 MiB VRAM). The MTP block guesses among the first 131,072 tokens; + for answers in other languages than English, `STRATA_QWEN4_DRAFT_HEAD2=1` (CUDA and HIP) has it guess among all of + them from a 2-bit copy of the output matrix (152 MiB of VRAM), the best rows scored again exactly. The answer + is the verify step's, as with any guesses; greedy answers can turn where two tokens are close, as with `--window`. - **Long-context sparse KV offload (`--basinkv`):** opt-in BasinKV sparse KV offload (`--basinkv`, off by default) keeps a fixed `2,048`-token FP16 hot slab in VRAM (`62–122 MiB` total GPU KV at 128K, `84–204 MiB` at 256K) and streams top-scoring cold blocks from pinned RAM, passing 100% of NIAH checks through 256K on RTX 4090 D (`UD-IQ2_XS`) and on diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 0da6fe0bf..bf5dc0b2c 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -11789,8 +11789,8 @@ int32_t Engine::draft(int32_t token, int i, float* prob) { sync_st("draft"); draft_step(token, i); // The guess and its probability are found on the card. On the host a vocabulary's softmax takes up to 2 ms - // where the block is unsure, four times what the block takes. - likeliest(logits_, draft_rows(), h_guess_, st_); + // where the block is unsure, four times what the block takes. An architecture may pick it its own way. + if (!pick_guess(h_guess_)) likeliest(logits_, draft_rows(), h_guess_, st_); sync_st("draft"); if (i == 0) { ahead_pos_ = pos_; diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index 546ea67f4..1aef36a1e 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -611,6 +611,9 @@ class Engine { /// model's output for the token before pos(); the second is this step's to leave and the next step's to read. /// The engine's own runs the draft block. virtual void draft_step(int32_t token, int i); + /// After draft_step(): the guess and its probability into *out (mapped host memory) on the stream, true where the + /// architecture picks them itself (and draft_step() left logits_ alone); false: likeliest() over logits_. + virtual bool pick_guess(Likeliest* out) { (void) out; return false; } /// The floats of every recurrent layer's state together. They are state_'s first. virtual size_t recurrent_floats() const = 0; /// Whether the recurrent layers leave their state after any tokens of a call, and not only after its first diff --git a/engine/src/poly/qwen4.cpp b/engine/src/poly/qwen4.cpp index 73fb10286..a10ebfc79 100644 --- a/engine/src/poly/qwen4.cpp +++ b/engine/src/poly/qwen4.cpp @@ -469,8 +469,36 @@ void Qwen4::load_drafter() { d_enorm_ = part("nextn.enorm.weight", n_embd_, 1, kF32); d_hnorm_ = load_hc_norm(tensor(n_layer_, "nextn.hnorm.weight"), blk(n_layer_, "nextn.hnorm.weight")); d_hc_head_ = load_gr(n_layer_, "nextn.hc_head", false); +#if !defined(STRATA_GPU_METAL) + // STRATA_QWEN4_DRAFT_HEAD2=1 (opt-in): the block's guesses from a 2-bit copy of the whole output matrix + // (pick_guess()), every token of the vocabulary where the head's own product takes the first 131,072 + // (guess_vocab()), in less time: a guess outside them has no chance, and in French, Dutch or Russian prose 13 to 66% + // of the tokens are. It costs 152 MiB of VRAM, which English text, nearly all below 131,072, gets nothing for. + const char* h2 = std::getenv("STRATA_QWEN4_DRAFT_HEAD2"); + // (not with --no-draft, --window 1 or a DFlash2 drafter: the block does not guess then) + if (h2 && h2[0] == '1' && opt_.draft && opt_.window != 1 && opt_.draft_model.empty() && output_.p && + output_.type == 14u /* Q6_K */ && output_.n_in == 2048) { + head2_rows_ = opt_.draft_vocab > 0 ? std::min(opt_.draft_vocab, n_vocab_) : n_vocab_; + head2_ = dmalloc(q4_head2_bytes(head2_rows_), "the draft head's 2-bit copy"); + head2_scratch_ = dmalloc(q4_head2_scratch_bytes(head2_rows_), "scratch"); + q4_head2_pack(output_.p, output_.n_in, head2_rows_, head2_, st_); + ck(cudaStreamSynchronize(cs(st_)), "the draft head's 2-bit copy"); + std::fprintf(stderr, + "strata-poly: qwen4: the draft block's guesses from a 2-bit copy of the output matrix (%d rows, " + "%.0f MiB)\n", + head2_rows_, q4_head2_bytes(head2_rows_) / 1048576.0); + } +#endif } +#if !defined(STRATA_GPU_METAL) +bool Qwen4::pick_guess(Likeliest* out) { + if (!head2_) return false; + q4_head2_pick(head2_, output_.p, xn_, head2_rows_, head2_scratch_, out, st_); + return true; +} +#endif + void Qwen4::load_block_drafter() { if (opt_.draft_model.empty() || !opt_.draft || opt_.window <= 1 || dg_) return; if (split_ || opt_.batch > 0) { @@ -3038,6 +3066,7 @@ void Qwen4::draft_step(int32_t token, int i) { copy2(r_, own, hc_dim_, nullptr, nullptr, 0, st_); // Final MTP head collapses 4 streams via nextn.hc_head_* then projects via shared output.weight gr_read(d_hc_head_, r_, xn_, xq_, nullptr, 1); + if (head2_) return; // pick_guess() scores the rows from xn_ Dev head = output_; head.n_out = Engine::draft_rows(); lin(head, xn_, logits_, 1, xq_); diff --git a/engine/src/poly/qwen4.cu b/engine/src/poly/qwen4.cu index 8b4c39ab5..aa186d434 100644 --- a/engine/src/poly/qwen4.cu +++ b/engine/src/poly/qwen4.cu @@ -2514,4 +2514,284 @@ void q4_loop_cd_hidden(float* s_final, const float* s_ref, float omega, launched("q4_loop_cd_hidden"); } +// ---- The MTP draft head screened by a 2-bit copy of the output matrix (q4_head2_*) ---- +// +// A guess only has to be the head's most likely token: the window checks it. The copy holds each Q6_K row of the +// output matrix as 2-bit levels (l - 1.5) * s with an FP16 scale s a 32 values, 640 bytes a row of 2,048 where the +// row has 1,680: every row is scored from it, the rows near the best are scored again from the Q6_K rows, and the +// best of those is the guess. Its probability is the softmax's, with the other rows at their copies' scores. + +namespace { + +constexpr int kH2In = 2048; // the rows' width (a lane takes 64 values) +constexpr int kH2RowCodes = kH2In / 4; // bytes of 2-bit codes a row +constexpr int kH2RowScales = kH2In / 32; // FP16 scales a row +constexpr int kH2BlockRows = 256; // rows a score block takes (8 warps of 32) +constexpr int kH2Keep = 4; // candidates a score block keeps +constexpr int kH2Cand = 64; // rows scored exactly at most +constexpr float kH2Delta = 5.0f; // a row is scored exactly when its copy's score is within this of the best + +// value i (0 .. 255) of a Q6_K block (210 bytes: ql[128], qh[64], scales[16], d) +__device__ __forceinline__ float h2_q6k(const uint8_t* __restrict__ b, int i) { + const uint8_t* ql = b; + const uint8_t* qh = b + 128; + const int8_t* sc = (const int8_t*) (b + 192); + const float d = __half2float(__ushort_as_half(*(const unsigned short*) (b + 208))); + const int half = i >> 7, r = i & 127, quad = r >> 5, l = r & 31; + ql += half * 64; + qh += half * 32; + sc += half * 8; + const int lo = (quad & 1) ? ql[l + 32] : ql[l]; + const int q = ((quad & 2) ? (lo >> 4) : (lo & 0xF)) | (((qh[l] >> (2 * quad)) & 3) << 4); + return d * (float) sc[(l >> 4) + 2 * quad] * (float) (q - 32); +} + +__device__ __forceinline__ int h2_level(float w, float s) { return min(3, max(0, (int) floorf(w / s + 2.0f))); } + +// a thread a 32-value group: the Q6_K group to 2-bit codes and a scale of least squared error among a few, then +// stretched so the copy's dot products keep the row's length +__global__ void q4_head2_pack_kernel(const uint8_t* __restrict__ head, int64_t n_rows, uint8_t* __restrict__ codes, + unsigned short* __restrict__ scales) { + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n_rows * kH2RowScales) return; + const int64_t row = i / kH2RowScales; + const int g = (int) (i % kH2RowScales); + const uint8_t* blk = head + (size_t) row * (kH2In / 256) * 210 + (size_t) (g >> 3) * 210; + float w[32]; + float amax = 1e-9f; + for (int l = 0; l < 32; ++l) { + w[l] = h2_q6k(blk, (g & 7) * 32 + l); + amax = fmaxf(amax, fabsf(w[l])); + } + float best_s = amax / 1.5f, best_e = INFINITY; + for (int t = 0; t < 6; ++t) { + const float sc = __half2float(__float2half(amax / 1.5f * (1.0f - 0.1f * (float) t))); + float e = 0.0f; + for (int l = 0; l < 32; ++l) { + const float r = ((float) h2_level(w[l], sc) - 1.5f) * sc - w[l]; + e += r * r; + } + if (e < best_e) best_e = e, best_s = sc; + } + const float sh = __half2float(__float2half(best_s)); + float ww = 0.0f, wr = 0.0f; + uint32_t c0 = 0, c1 = 0; + for (int l = 0; l < 32; ++l) { + const int lv = h2_level(w[l], sh); + const float r = ((float) lv - 1.5f) * sh; + ww += w[l] * w[l]; + wr += w[l] * r; + if (l < 16) c0 |= (uint32_t) lv << (2 * l); + else c1 |= (uint32_t) lv << (2 * (l - 16)); + } + uint32_t* out = (uint32_t*) (codes + (size_t) row * kH2RowCodes + (size_t) g * 8); + out[0] = c0; + out[1] = c1; + scales[(size_t) row * kH2RowScales + g] = __half_as_ushort(__float2half(wr > 0.0f ? sh * sqrtf(ww / wr) : sh)); +} + +// sum over the 16 values of a code word: levels times x +__device__ __forceinline__ float h2_word(uint32_t c, const float* x) { + float a = 0.0f; +#pragma unroll + for (int k = 0; k < 16; ++k) a = fmaf((float) ((c >> (2 * k)) & 3u), x[k], a); + return a; +} + +// 8 warps of 32 rows: a row's copy score by the whole warp, lane j keeping row j's; then each block's best kH2Keep +// and its rows' max and sum of exp(score - max) +__global__ void __launch_bounds__(256) q4_head2_score_kernel(const uint4* __restrict__ codes, const uint32_t* __restrict__ sc2, + const float* __restrict__ x, int64_t n_rows, + float* __restrict__ part_val, int32_t* __restrict__ part_idx, + float2* __restrict__ part_ms) { + __shared__ float wv[8 * 2]; + __shared__ int wi[8 * 2]; + __shared__ float wm[8], ws[8]; + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + float xr[64]; +#pragma unroll + for (int k = 0; k < 64; ++k) xr[k] = x[64 * lane + k]; + float gs0 = 0.0f, gs1 = 0.0f; +#pragma unroll + for (int k = 0; k < 32; ++k) gs0 += xr[k], gs1 += xr[32 + k]; + const int64_t row0 = (int64_t) blockIdx.x * kH2BlockRows + warp * 32; + float my = -INFINITY; + constexpr int U = 4; // rows whose loads are out at once + for (int j0 = 0; j0 < 32; j0 += U) { + if (row0 + j0 >= n_rows) break; + uint4 c[U]; + uint32_t s[U]; +#pragma unroll + for (int u = 0; u < U; ++u) { + const int64_t row = min(row0 + j0 + u, n_rows - 1); // (a row past the end: scored, not kept) + c[u] = codes[(size_t) row * (kH2RowCodes / 16) + lane]; + s[u] = sc2[(size_t) row * (kH2RowScales / 2) + lane]; + } +#pragma unroll + for (int u = 0; u < U; ++u) { + const float s0 = __half2float(__ushort_as_half((unsigned short) (s[u] & 0xFFFFu))); + const float s1 = __half2float(__ushort_as_half((unsigned short) (s[u] >> 16))); + const float a0 = h2_word(c[u].x, xr) + h2_word(c[u].y, xr + 16); + const float a1 = h2_word(c[u].z, xr + 32) + h2_word(c[u].w, xr + 48); + float d = s0 * (a0 - 1.5f * gs0) + s1 * (a1 - 1.5f * gs1); + d = warp_sum(d); + if (lane == j0 + u && row0 + j0 + u < n_rows) my = d; + } + } + const int64_t mine = row0 + lane; + const float m = warp_max(my); + const float e = my > -INFINITY ? __expf(my - m) : 0.0f; + const float sum = warp_sum(e); + // the warp's two best (the lower row of a tie) + float v = my; + for (int k = 0; k < 2; ++k) { + float bv = v; + int bi = v > -INFINITY ? (int) mine : 0x7fffffff; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + const float ov = __shfl_xor_sync(0xffffffffu, bv, o, 32); + const int oi = __shfl_xor_sync(0xffffffffu, bi, o, 32); + if (ov > bv || (ov == bv && oi < bi)) bv = ov, bi = oi; + } + if (lane == 0) wv[warp * 2 + k] = bv, wi[warp * 2 + k] = bi; + if (bi == (int) mine) v = -INFINITY; + } + if (lane == 0) wm[warp] = m, ws[warp] = sum; + __syncthreads(); + if (threadIdx.x == 0) { + float M = -INFINITY; + for (int w = 0; w < 8; ++w) M = fmaxf(M, wm[w]); + float S = 0.0f; + for (int w = 0; w < 8; ++w) + if (wm[w] > -INFINITY) S += ws[w] * __expf(wm[w] - M); + part_ms[blockIdx.x] = make_float2(M, S); + for (int k = 0; k < kH2Keep; ++k) { + int b = -1; + for (int c = 0; c < 16; ++c) + if (wi[c] != 0x7fffffff && (b < 0 || wv[c] > wv[b] || (wv[c] == wv[b] && wi[c] < wi[b]))) b = c; + part_val[(size_t) blockIdx.x * kH2Keep + k] = b >= 0 ? wv[b] : -INFINITY; + part_idx[(size_t) blockIdx.x * kH2Keep + k] = b >= 0 ? wi[b] : -1; + if (b >= 0) wi[b] = 0x7fffffff; + } + } +} + +// one block of 256: the candidates within kH2Delta of the best copy score (at most kH2Cand, the best of them), +// scored exactly from the Q6_K rows (a warp a row), the best the guess, its probability the softmax's +__global__ void __launch_bounds__(256) q4_head2_final_kernel(const float* __restrict__ part_val, + const int32_t* __restrict__ part_idx, + const float2* __restrict__ part_ms, int n_parts, + const uint8_t* __restrict__ head, const float* __restrict__ x, + Likeliest* __restrict__ out) { + __shared__ float xs[kH2In]; + __shared__ float red[8]; + __shared__ float cv[kH2Cand], ev[kH2Cand]; + __shared__ int ci[kH2Cand]; + __shared__ int n_c; + __shared__ float thr; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + for (int k = tid; k < kH2In; k += 256) xs[k] = x[k]; + // the rows' max and sum + float M = -INFINITY; + for (int p = tid; p < n_parts; p += 256) M = fmaxf(M, part_ms[p].x); + M = warp_max(M); + if (lane == 0) red[warp] = M; + __syncthreads(); + M = red[0]; + for (int w = 1; w < 8; ++w) M = fmaxf(M, red[w]); + __syncthreads(); + float S = 0.0f; + for (int p = tid; p < n_parts; p += 256) + if (part_ms[p].x > -INFINITY) S += part_ms[p].y * __expf(part_ms[p].x - M); + S = warp_sum(S); + if (lane == 0) red[warp] = S; + __syncthreads(); + S = 0.0f; + for (int w = 0; w < 8; ++w) S += red[w]; + // candidates: the copy scores within delta of the best, the delta halved until at most kH2Cand are in it + const int n_all = n_parts * kH2Keep; + if (tid == 0) thr = M - kH2Delta; + __syncthreads(); + for (int tries = 0; tries < 12; ++tries) { + if (tid == 0) n_c = 0; + __syncthreads(); + int cnt = 0; + for (int k = tid; k < n_all; k += 256) cnt += part_idx[k] >= 0 && part_val[k] >= thr; + atomicAdd(&n_c, cnt); + __syncthreads(); + const bool ok = n_c <= kH2Cand; + __syncthreads(); + if (ok) break; + if (tid == 0) thr = M - (M - thr) * 0.5f; + __syncthreads(); + } + if (tid == 0) n_c = 0; + __syncthreads(); + for (int k = tid; k < n_all; k += 256) + if (part_idx[k] >= 0 && part_val[k] >= thr) { + const int at = atomicAdd(&n_c, 1); + if (at < kH2Cand) ci[at] = part_idx[k], cv[at] = part_val[k]; + } + __syncthreads(); + const int nc = min(n_c, kH2Cand); + // exact scores + for (int c = warp; c < nc; c += 8) { + const uint8_t* row = head + (size_t) ci[c] * (kH2In / 256) * 210; + float a = 0.0f; + for (int i = lane; i < kH2In; i += 32) a = fmaf(h2_q6k(row + (size_t) (i >> 8) * 210, i & 255), xs[i], a); + a = warp_sum(a); + if (lane == 0) ev[c] = a; + } + __syncthreads(); + if (tid == 0) { + int b = -1; + for (int c = 0; c < nc; ++c) + if (b < 0 || ev[c] > ev[b] || (ev[c] == ev[b] && ci[c] < ci[b])) b = c; + if (b < 0) { + out->token = 0; + out->prob = 0.0f; + } else { + const float Mx = fmaxf(M, ev[b]); + float Z = S * __expf(M - Mx); + for (int c = 0; c < nc; ++c) Z += __expf(ev[c] - Mx) - __expf(cv[c] - Mx); + const float top = __expf(ev[b] - Mx); + out->token = ci[b]; + out->prob = top / fmaxf(Z, top); + } + } +} + +} // namespace + +size_t q4_head2_bytes(int64_t n_rows) { return (size_t) n_rows * (kH2RowCodes + 2 * kH2RowScales); } + +size_t q4_head2_scratch_bytes(int64_t n_rows) { + const size_t nb = (size_t) ((n_rows + kH2BlockRows - 1) / kH2BlockRows); + return nb * kH2Keep * (sizeof(float) + sizeof(int32_t)) + nb * sizeof(float2) + 64; +} + +void q4_head2_pack(const void* head_q6k, int n_in, int64_t n_rows, void* copy, void* stream) { + if (n_in != kH2In) throw std::logic_error("q4_head2_pack: rows of 2,048"); + uint8_t* codes = (uint8_t*) copy; + unsigned short* scales = (unsigned short*) (codes + (size_t) n_rows * kH2RowCodes); // FP16 bits + const int64_t n = n_rows * kH2RowScales; + q4_head2_pack_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, cs(stream)>>>((const uint8_t*) head_q6k, n_rows, codes, + scales); + launched("q4_head2_pack"); +} + +void q4_head2_pick(const void* copy, const void* head_q6k, const float* x, int64_t n_rows, void* scratch, + Likeliest* out, void* stream) { + const int nb = (int) ((n_rows + kH2BlockRows - 1) / kH2BlockRows); + const uint8_t* codes = (const uint8_t*) copy; + const uint32_t* sc2 = (const uint32_t*) (codes + (size_t) n_rows * kH2RowCodes); + float2* part_ms = (float2*) scratch; + float* part_val = (float*) (part_ms + nb); + int32_t* part_idx = (int32_t*) (part_val + (size_t) nb * kH2Keep); + q4_head2_score_kernel<<>>((const uint4*) codes, sc2, x, n_rows, part_val, part_idx, part_ms); + launched("q4_head2_score"); + q4_head2_final_kernel<<<1, 256, 0, cs(stream)>>>(part_val, part_idx, part_ms, nb, (const uint8_t*) head_q6k, x, out); + launched("q4_head2_final"); +} + } // namespace strata::poly diff --git a/engine/src/poly/qwen4.hpp b/engine/src/poly/qwen4.hpp index 29d597b42..1ce497319 100644 --- a/engine/src/poly/qwen4.hpp +++ b/engine/src/poly/qwen4.hpp @@ -78,6 +78,9 @@ class Qwen4 final : public Engine { int streams() const override { return hc_; } void reset_call() override; void begin_step(const int32_t* tokens, int n) override; +#if !defined(STRATA_GPU_METAL) + bool pick_guess(Likeliest* out) override; // the 2-bit draft head (STRATA_QWEN4_DRAFT_HEAD2=1); not on Metal +#endif void on_copy_seq(int from, int to) override; void layer_head(Layer& L, int il, int n) override; void layer_tail(Layer& L, int il, int n) override; @@ -319,6 +322,9 @@ class Qwen4 final : public Engine { uint32_t ple_type_ = 0; size_t ple_row_bytes_ = 0; uint64_t ple_table_rows_ = 0; + void* head2_ = nullptr; ///< the output matrix's 2-bit copy for the draft block's guesses (pick_guess()) + void* head2_scratch_ = nullptr; + int head2_rows_ = 0; std::vector> ple_ring_; std::vector ple_idx_; float* h_ple_emb_ = nullptr; ///< pinned [rows_, ple_dim_] diff --git a/engine/src/poly/qwen4_kernels.hpp b/engine/src/poly/qwen4_kernels.hpp index 6aab9ce81..8e8b75ca7 100644 --- a/engine/src/poly/qwen4_kernels.hpp +++ b/engine/src/poly/qwen4_kernels.hpp @@ -223,4 +223,20 @@ void q4_loop_cd_hidden(float* s_final, const float* s_ref, float omega, int n_embd, int hc, int rows, bool per_stream, float eps, void* stream); #endif +#if !defined(STRATA_GPU_METAL) +// ---- The MTP draft head screened by a 2-bit copy of the output matrix (CUDA, HIP; qwen4.cu) ---- + +/// Bytes of the 2-bit copy of n_rows rows of 2,048 (640 a row). +size_t q4_head2_bytes(int64_t n_rows); +/// Bytes of the scratch q4_head2_pick() takes. +size_t q4_head2_scratch_bytes(int64_t n_rows); +/// The copy of n_rows Q6_K rows of n_in (2,048) values: 2-bit levels, an FP16 scale a 32 values. +void q4_head2_pack(const void* head_q6k, int n_in, int64_t n_rows, void* copy, void* stream); +/// The guess for the head's input x (2,048 floats): every row scored from the copy, the ones within 5 of the best +/// (64 at most) from the Q6_K rows, the best of those into *out with its softmax probability, the other rows at +/// their copy's scores. *out may be mapped host memory. +void q4_head2_pick(const void* copy, const void* head_q6k, const float* x, int64_t n_rows, void* scratch, + Likeliest* out, void* stream); +#endif + } // namespace strata::poly diff --git a/engine/src/poly/qwen4_test.cu b/engine/src/poly/qwen4_test.cu index 639d6094a..77560821b 100644 --- a/engine/src/poly/qwen4_test.cu +++ b/engine/src/poly/qwen4_test.cu @@ -1700,6 +1700,103 @@ void test_route_rows_nan_safety(cudaStream_t st) { std::printf("PASS route_rows_nan_safety (gates=0/1/2/3, NaN/-inf/+inf/finite)\n"); } +// q4_head2_pack + q4_head2_pick against the exact Q6_K product on the host: the pick is the best row of the exact +// scores (a near tie may go to the other row), and its probability is the softmax's (the model's own output matrix +// gave 0.009 off on average) +float h2_q6k_host(const uint8_t* b, int i) { + const uint8_t* ql = b; + const uint8_t* qh = b + 128; + const int8_t* sc = (const int8_t*) (b + 192); + __half_raw hr; + std::memcpy(&hr.x, b + 208, 2); + const float d = __half2float(__half(hr)); + const int half = i >> 7, r = i & 127, quad = r >> 5, l = r & 31; + ql += half * 64; + qh += half * 32; + sc += half * 8; + const int lo = (quad & 1) ? ql[l + 32] : ql[l]; + const int q = ((quad & 2) ? (lo >> 4) : (lo & 0xF)) | (((qh[l] >> (2 * quad)) & 3) << 4); + return d * (float) sc[(l >> 4) + 2 * quad] * (float) (q - 32); +} + +void test_head2_pick(cudaStream_t st) { + std::mt19937 rng(4242); // its own: the other tests' draws do not change its inputs + const int n_in = 2048, nb = n_in / 256; + const int64_t n_rows = 5000; // not a whole number of score blocks + std::vector head((size_t) n_rows * nb * 210); + std::uniform_int_distribution byte(0, 255), scale(-64, 64); + for (int64_t r = 0; r < n_rows; ++r) + for (int b = 0; b < nb; ++b) { + uint8_t* blk = head.data() + ((size_t) r * nb + b) * 210; + for (int k = 0; k < 192; ++k) blk[k] = (uint8_t) byte(rng); + for (int k = 0; k < 16; ++k) blk[192 + k] = (uint8_t) (int8_t) scale(rng); + const __half d = __float2half(0.0005f); + std::memcpy(blk + 208, &d, 2); + } + void *d_head = nullptr, *d_copy = nullptr, *d_scr = nullptr; + float* d_x = nullptr; + Likeliest* d_out = nullptr; + ck(cudaMalloc(&d_head, head.size()), "m"); + ck(cudaMalloc(&d_copy, q4_head2_bytes(n_rows)), "m"); + ck(cudaMalloc(&d_scr, q4_head2_scratch_bytes(n_rows)), "m"); + ck(cudaMalloc(&d_x, n_in * sizeof(float)), "m"); + ck(cudaMalloc(&d_out, sizeof(Likeliest)), "m"); + ck(cudaMemcpy(d_head, head.data(), head.size(), cudaMemcpyHostToDevice), "c"); + q4_head2_pack(d_head, n_in, n_rows, d_copy, st); + // half the trials: x leans towards one row, as a model's output does towards its likely token (a clear best, the + // probability checked to 0.05); the other half: x at random, uniform rows' worst case for the copy (the best + // checked, the probability only to 0.25: rows near the best that the copy scores low count at the copy's score) + int exact = 0; + const int trials = 20; + for (int t = 0; t < trials; ++t) { + const bool lean = t % 2 == 0; + auto x = rand_vec(n_in, rng, 1.0f); + const int64_t planted = (int64_t) (rng() % (uint32_t) n_rows); + if (lean) { + double nn = 0.0; + std::vector w((size_t) n_in); + for (int i = 0; i < n_in; ++i) { + w[(size_t) i] = h2_q6k_host(head.data() + ((size_t) planted * nb + i / 256) * 210, i % 256); + nn += (double) w[(size_t) i] * w[(size_t) i]; + } + for (int i = 0; i < n_in; ++i) x[(size_t) i] = 0.3f * x[(size_t) i] + (float) (40.0 * w[(size_t) i] / nn); + } + ck(cudaMemcpyAsync(d_x, x.data(), n_in * sizeof(float), cudaMemcpyHostToDevice, st), "c"); + q4_head2_pick(d_copy, d_head, d_x, n_rows, d_scr, d_out, st); + Likeliest got{}; + ck(cudaMemcpyAsync(&got, d_out, sizeof(got), cudaMemcpyDeviceToHost, st), "c"); + ck(cudaStreamSynchronize(st), "sync"); + std::vector lg((size_t) n_rows); + int64_t best = 0; + for (int64_t r = 0; r < n_rows; ++r) { + double a = 0.0; + for (int i = 0; i < n_in; ++i) + a += (double) h2_q6k_host(head.data() + ((size_t) r * nb + i / 256) * 210, i % 256) * x[(size_t) i]; + lg[(size_t) r] = a; + if (a > lg[(size_t) best]) best = r; + } + double z = 0.0; + for (double v : lg) z += std::exp(v - lg[(size_t) best]); + const double p_ref = 1.0 / z, p_tol = lean ? 0.05 : 0.25; + // leaning: the planted row, exactly; random: any row (a miss of the exact best counts below, 2 allowed) + if (got.token < 0 || got.token >= n_rows || std::fabs(got.prob - p_ref) > p_tol || + (lean && (got.token != planted || lg[(size_t) best] - lg[(size_t) got.token] > 1e-3))) { + std::fprintf(stderr, "FAIL q4_head2_pick trial %d (%s): token %d (%.5f) prob %.4f, best %lld (%.5f) prob %.4f\n", + t, lean ? "leaning" : "random", got.token, + got.token >= 0 && got.token < n_rows ? lg[(size_t) got.token] : 0.0, got.prob, (long long) best, + lg[(size_t) best], p_ref); + std::exit(1); + } + exact += got.token == best; + } + if (exact < trials - 2) { + std::fprintf(stderr, "FAIL q4_head2_pick: the exact best in %d of %d trials\n", exact, trials); + std::exit(1); + } + cudaFree(d_head); cudaFree(d_copy); cudaFree(d_scr); cudaFree(d_x); cudaFree(d_out); + std::printf("PASS head2_pick (%d of %d the exact best; probabilities within 0.05 leaning, 0.25 random)\n", exact, + trials); +} } // namespace int main() { @@ -1720,6 +1817,7 @@ int main() { test_mul_sigmoid_q8_1(rng, st); test_loop_kernels(rng, st); test_loop_adapter_loader(rng, st); + test_head2_pick(st); #endif test_route_rows_nan_safety(st); ck(cudaStreamDestroy(st), "destroy"); diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 71439bf66..5e49dc776 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -42649,6 +42649,36 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_QWEN4_DRAFT_HEAD2", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/qwen4.cpp", + "line": 477, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "flag", + "default_state": "off", + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [ + "docs/models/qwen4.md:42" + ], + "status": "opt-in", + "owner": "poly", + "note": "1: Qwen4 (qwen4exp) with its MTP draft block on CUDA/HIP and a Q6_K output matrix of rows of 2,048 takes the block's guesses from a 2-bit copy of the whole output matrix (640 bytes a row, 152 MiB for 248,320 rows), the rows within 5 of the best copy score scored again from the Q6_K rows (q4_head2_pick()), where the head's product takes the first 131,072 rows (guess_vocab()). Only the guesses change; the answer is the verify step's, which can differ in late bits with other guesses, as with --window. Off by default: English text gains nothing for the VRAM (engine/src/poly/qwen4.cpp, qwen4.cu)", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_QWEN4_KERNEL_TABLES", "backends": [