Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Token embedding in BF16 from the checkpoint (--embd-gguf)
sergiywith32727a7a9461
diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hppindex 1beb9a149..c2bb2b5c9 100644--- a/include/strata/kernels/iq_kernels.hpp+++ b/include/strata/kernels/iq_kernels.hpp@@ -14,6 +14,8 @@ namespace strata::kernels {/// ggml type ids handled here.bool iq_supported(int ggml_type) noexcept;+/// The token-embedding types iq_embed_rows and iq_dequant_f32 read: the i-quants above and BF16 (30).+bool embed_type_supported(int ggml_type) noexcept;/// Bytes of one row of `n` values of `ggml_type` (n a multiple of the type's block).size_t iq_row_bytes(int ggml_type, int64_t n) noexcept;diff --git a/src/core/native_head.cpp b/src/core/native_head.cppindex 5eed99d12..e47dfe144 100644--- a/src/core/native_head.cpp+++ b/src/core/native_head.cpp@@ -108,13 +108,15 @@ NativeEmbed::~NativeEmbed() {bool NativeEmbed::load(const std::vector<std::string>& shards, int64_t n_embd, int64_t n_vocab, std::string& err) {try {const strata::GgufModel model(shards);- err = strata::check_architecture(model.meta());+ // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked+ const strata::MetaValue* arch = model.meta().get("general.architecture");+ err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_architecture(model.meta());if (!err.empty()) { err = "native embedding: " + err; return false; }size_t at = 0;const strata::TensorInfo* t = model.find("token_embd.weight", &at);const strata::GgufFile& gguf = model.shard(at);if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab ||- !strata::kernels::iq_supported((int) t->type) || n_embd % 256) {+ !strata::kernels::embed_type_supported((int) t->type) || n_embd % 256) {err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU ""dequantizer";return false;diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cuindex 61ace84a1..3081c82c3 100644--- a/src/kernels/cuda/iq_kernels.cu+++ b/src/kernels/cuda/iq_kernels.cu@@ -1218,7 +1218,15 @@ __device__ void dq_q8_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {for (int j = 0; j < 8; ++j) y[j] = cvt<dst_t>((float) x[ib].qs[8 * il + j] * d);}-// Every type below must also be in is_iq(): the host entry points refuse the others, so the default is unreachable.+// BF16 (the token embedding as the checkpoint ships it, tools/embd_bf16_pack.py): 8 values per thread.+template<typename dst_t>+__device__ void dq_bf16(const void* vx, int64_t ibs, dst_t* yy, int tid) {+ const uint16_t* x = (const uint16_t*) vx + ibs * 256 + tid * 8;+ for (int j = 0; j < 8; ++j) yy[tid * 8 + j] = cvt<dst_t>(__uint_as_float((uint32_t) x[j] << 16));+}++// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others,+// so the default is unreachable.template<typename dst_t>__device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, dst_t* y, int tid) {switch (ty) {@@ -1236,6 +1244,7 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs,case 13: dq_q5_k(vx, ibs, y, tid); break;case 7: dq_q5_1(vx, ibs, y, tid); break;case 8: dq_q8_0(vx, ibs, y, tid); break;+ case 30: dq_bf16(vx, ibs, y, tid); break;default: break;}}@@ -1321,6 +1330,7 @@ void iq_set_old_kernels(bool old) { g_old_kernels = old; }bool iq_old_kernels() { return g_old_kernels; }bool iq_supported(int t) noexcept { return is_iq(t); }+bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30; }size_t iq_row_bytes(int t, int64_t n) noexcept {switch (t) {@@ -1338,6 +1348,7 @@ size_t iq_row_bytes(int t, int64_t n) noexcept {case 13: return (size_t) (n / 256) * sizeof(block_q5_K);case 7: return (size_t) (n / 32) * sizeof(block_q5_1);case 8: return (size_t) (n / 32) * sizeof(block_q8_0);+ case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)default: return 0;}}@@ -1382,14 +1393,14 @@ __global__ void embed_rows_kernel(int ty, const uint8_t* __restrict__ table, sizvoid iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, int64_t n_embd,float* out, void* stream) {if (n_tok <= 0) return;- if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); }+ if (n_embd % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); }embed_rows_kernel<<<dim3((unsigned) (n_embd / 256), (unsigned) n_tok), 32, 0, (cudaStream_t) stream>>>(t, (const uint8_t*) table, row_bytes, tokens, n_embd, out);check("iq_embed_rows");}void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) {- if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); }+ if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); }dequant_flat_kernel<float><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst);check("iq_dequant_f32");}diff --git a/src/program/generate.cpp b/src/program/generate.cppindex f91a9177a..45412f906 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -216,6 +216,8 @@ struct Options {/// combination recorded in bench/results/2026-09-23-attention-ple plus the native indexer, and never the/// <=256-token attention adapter. It becomes the default once P0 shows it is not slower.std::string native_preset;+ /// The token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py: BF16 as shipped)+ std::string embd_gguf;/// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM.std::string ple_io = "direct";int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables@@ -456,6 +458,8 @@ void usage() {" indexer, RoPE, PLE postops, and the CPU q8_0 contract unless the\n"" expert cache is on. Individual --native-* flags stay for A/B.\n"" --native-head-gguf PATH native Q5_K head from model shard 1; requires --stream-token\n"+ " --embd-gguf PATH the token embedding from this GGUF instead of --native's (tools/embd_bf16_pack.py:\n"+ " BF16 as the checkpoint ships it; mapped host memory, no VRAM)\n"" --native-dense-gguf PATH native GDN/QSA/shared projections; repeat for each source model shard\n"" --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n"" --max-new N tokens to generate (default 16)\n"@@ -1068,6 +1072,7 @@ int main(int argc, char** argv) {else if (a == "--cpu-oracle-q8-0") o.cpu_oracle_q8_0 = true;else if (a == "--native") o.native_preset = next("--native");else if (a == "--native-head-gguf") o.native_head_gguf = next("--native-head-gguf");+ else if (a == "--embd-gguf") o.embd_gguf = next("--embd-gguf");else if (a == "--native-dense-gguf") o.native_dense_gguf.push_back(next("--native-dense-gguf"));else if (a == "--no-capture") o.no_capture = true;else if (a == "--no-pool") o.no_pool = true;@@ -1766,15 +1771,16 @@ int main(int argc, char** argv) {return 2;}const strata::core::ModelGeometry g0;- if (!native_embed.load(o.native_shards, g0.n_embd, 248320, err)) {+ if (!native_embed.load(o.embd_gguf.empty() ? o.native_shards : std::vector<std::string>{o.embd_gguf}, g0.n_embd,+ 248320, err)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}strata::core::set_native_embed(&native_embed);std::fprintf(stderr, "strata generate: native pack: %s experts (largest blob %.2f MB), token embedding "- "type %d in mapped host memory (%.0f MiB)\n",+ "%s in mapped host memory (%.0f MiB)\n",o.pack.c_str(), (double) strata::kernels::cpu::expert_layout().max_blob / 1e6,- native_embed.type(), (double) native_embed.bytes() / 1048576.0);+ strata::ggml_type_name((uint32_t) native_embed.type()), (double) native_embed.bytes() / 1048576.0);}// Plan v0.3 P1: tensors served in native form are not also loaded in canonical form (~2.7 GB of VRAM back// to the expert cache with --native). `--keep-canonical` loads both, as before.diff --git a/tools/embd_bf16_pack.py b/tools/embd_bf16_pack.pynew file mode 100644index 000000000..1ed2d6423--- /dev/null+++ b/tools/embd_bf16_pack.py@@ -0,0 +1,87 @@+"""tools/embd_bf16_pack.py - the token embedding exactly as the checkpoint ships it (BF16), as a GGUF the engine reads.++ python tools/embd_bf16_pack.py --model <checkpoint dir> --out <token-embd-bf16.gguf>++nvfp4_convert.py stores token_embd as Q8_0 (0.56% off per value). The engine keeps the table in mapped host memory+and reads one row per token, so BF16 costs 0.6 GB of RAM more and no VRAM; `--embd-gguf` takes it from this file.++The output is a one-tensor GGUF: `token_embd.weight`, ne = [n_embd, n_vocab], type BF16, the bytes copied straight+out of the safetensors file - nothing decoded or rounded.+"""+import argparse+import json+import pathlib+import struct+import sys++GGUF_TYPE_STRING = 8+GGML_TYPE_BF16 = 30+ALIGN = 32+CHUNK = 64 << 20+++def safetensors_header(path):+ with open(path, "rb") as f:+ n = struct.unpack("<Q", f.read(8))[0]+ return json.loads(f.read(n)), 8 + n+++def gguf_string(s):+ b = s.encode("utf-8")+ return struct.pack("<Q", len(b)) + b+++def kv_string(key, val):+ return gguf_string(key) + struct.pack("<I", GGUF_TYPE_STRING) + gguf_string(val)+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("--model", required=True, help="the checkpoint directory (model.safetensors.index.json)")+ ap.add_argument("--out", required=True)+ a = ap.parse_args()+ model, out = pathlib.Path(a.model), pathlib.Path(a.out)+ wmap = json.loads((model / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]++ names = [n for n in wmap if n.endswith("embed_tokens.weight") and "visual" not in n and "mtp" not in n]+ if len(names) != 1:+ sys.exit("expected one text embed_tokens.weight in %s, found %s" % (model, names))+ name = names[0]+ hdr, base = safetensors_header(model / wmap[name])+ t = hdr[name]+ if t["dtype"] != "BF16" or len(t["shape"]) != 2:+ sys.exit("%s is %s %s, not a 2-D BF16 tensor" % (name, t["dtype"], t["shape"]))+ vocab, dim = t["shape"]+ n = vocab * dim * 2+ if t["data_offsets"][1] - t["data_offsets"][0] != n:+ sys.exit("%s: data size does not match its shape" % name)+ print("%s: %d x %d BF16, %.2f GB" % (name, vocab, dim, n / 1e9), flush=True)++ kvs = [kv_string("general.architecture", "strata-embd"),+ kv_string("general.name", "token embedding, BF16 as shipped"),+ kv_string("strata.embd.source", model.name)]+ head = b"GGUF" + struct.pack("<IQQ", 3, 1, len(kvs)) + b"".join(kvs)+ head += gguf_string("token_embd.weight") + struct.pack("<I", 2) + struct.pack("<QQ", dim, vocab)+ head += struct.pack("<I", GGML_TYPE_BF16) + struct.pack("<Q", 0)+ head += b"\0" * ((-len(head)) % ALIGN)++ out.parent.mkdir(parents=True, exist_ok=True)+ tmp = out.with_suffix(out.suffix + ".part")+ with open(tmp, "wb") as w, open(model / wmap[name], "rb") as f:+ w.write(head)+ f.seek(base + t["data_offsets"][0])+ left = n+ while left:+ b = f.read(min(CHUNK, left))+ if not b:+ sys.exit("short read in " + str(model / wmap[name]))+ w.write(b)+ left -= len(b)+ if tmp.stat().st_size != len(head) + n:+ sys.exit("size check failed: %d != %d" % (tmp.stat().st_size, len(head) + n))+ tmp.replace(out)+ print("wrote %s (header %d B)" % (out, len(head)))+++if __name__ == "__main__":+ main()