Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/SETTINGS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ A number or a word is set like any environment variable, for example `STRATA_KVA
(`terminal/strata-<model>.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.

Expand Down Expand Up @@ -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) |
Expand Down
5 changes: 4 additions & 1 deletion docs/models/qwen4.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions engine/src/poly/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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_;
Expand Down
3 changes: 3 additions & 0 deletions engine/src/poly/engine.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions engine/src/poly/qwen4.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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_);
Expand Down
280 changes: 280 additions & 0 deletions engine/src/poly/qwen4.cu
Original file line number Diff line number Diff line change
Expand Up @@ -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<<<nb, 256, 0, cs(stream)>>>((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
Loading