Download basalt-ajean-inkling.patch from nathaninline/Inkling-2-Mini-NVFP4-Basalt: direct link, hf CLI and curl.
- Browser
- Download file 56 kB
-
https://huggingface.co/nathaninline/Inkling-2-Mini-NVFP4-Basalt/resolve/main/basalt-ajean-inkling.patch
- Command line
-
hf download hf://nathaninline/Inkling-2-Mini-NVFP4-Basalt/basalt-ajean-inkling.patch
-
curl -L -o basalt-ajean-inkling.patch https://huggingface.co/nathaninline/Inkling-2-Mini-NVFP4-Basalt/resolve/main/basalt-ajean-inkling.patch
56 kB
From 2ef97d2bf4ea697b9e0e1a8aacc025693a326896 Mon Sep 17 00:00:00 2001
From: nathaninline <mail@nathaninline.com>
Date: Sun, 22 Nov 2026 17:11:37 +0000
Subject: [PATCH 1/5] AJEAN: Inkling 2 Mini sur une carte de 16 Go
- tools/convert/inkling2_requant.py : experts Q8_0 des couches 20 a 23 du pack officiel en NVFP4 (-1,9 Gio)
- tranches de prompt de 1024 lignes (AJEAN_PROMPT_CHUNK, 4096 en amont) : ~0,7 Gio de tampons en moins
- xq prend la plus grande des deux tailles (les plans FP4 debordaient sous 4096 lignes)
- AJEAN_CARD_SPARE_MIB et AJEAN_SHARED_FIXED_MIB : marges de l estimation reglables (surestimees de ~0,9 Gio sur une 5060 Ti)
- ligne de journal AJEAN budget
---
src/models/inkling2/model.cpp | 20 ++++-
src/models/inkling2/prompt.cpp | 14 +--
src/models/inkling2/prompt.hpp | 7 +-
tools/convert/inkling2_requant.py | 140 ++++++++++++++++++++++++++++++
4 files changed, 172 insertions(+), 9 deletions(-)
create mode 100644 tools/convert/inkling2_requant.py
diff --git a/src/models/inkling2/model.cpp b/src/models/inkling2/model.cpp
index cd1c3a67d..ae273f19c 100644
--- a/src/models/inkling2/model.cpp
+++ b/src/models/inkling2/model.cpp
@@ -32,9 +32,21 @@ constexpr uint64_t kQ8Row = (uint64_t) kWidth / 32 * 34; // bytes of a Q8_0 ro
// what the sessions share once (the forward's row buffers and expert scratch, the batch windows' logits), what each one
// needs beside its caches (its logits, its windows' graphs) and what the card keeps free for the kernels' modules and the
// driver
-constexpr uint64_t kSharedFixed = 768 * kMiB;
+// AJEAN: AJEAN_SHARED_FIXED_MIB overrides the shared estimate (768 MiB upstream; about 0.9 GiB above what an RTX 5060 Ti uses)
+uint64_t ajean_shared_fixed() {
+ const char* v = std::getenv("AJEAN_SHARED_FIXED_MIB");
+ const long long m = v && *v ? std::atoll(v) : 768;
+ return (uint64_t) (m < 0 ? 0 : m) * kMiB;
+}
+const uint64_t kSharedFixed = ajean_shared_fixed();
constexpr uint64_t kSessionFixed = 96 * kMiB;
-constexpr uint64_t kCardSpare = 1024 * kMiB;
+// AJEAN: AJEAN_CARD_SPARE_MIB overrides the card spare (1024 MiB upstream); measured unused on an RTX 5060 Ti.
+uint64_t ajean_card_spare() {
+ const char* v = std::getenv("AJEAN_CARD_SPARE_MIB");
+ const long long m = v && *v ? std::atoll(v) : 1024;
+ return (uint64_t) (m < 64 ? 64 : m) * kMiB;
+}
+const uint64_t kCardSpare = ajean_card_spare();
// The fused projection rows of a layer: tensor suffix, first row, rows, needed on a full layer only.
struct ProjPart {
@@ -334,6 +346,10 @@ model::Result InklingModel::plan(const model::LoadRequest& req, core::LoadPlan&
uint64_t full = 0;
for (uint64_t st : stride) full += st * (uint64_t) g.n_expert;
const uint64_t want_b = full + bytes_at(want) * n_sess + shared + spare;
+ basalt::log::info("basalt inkling2", "AJEAN budget: free %.0f MiB, experts %.0f, session %.0f x %llu, shared %.0f (prompt %.0f), spare %.0f",
+ (double) free_b / (double) kMiB, (double) full / (double) kMiB, (double) bytes_at(want) / (double) kMiB,
+ (unsigned long long) n_sess, (double) shared / (double) kMiB, (double) prompt_bytes(g) / (double) kMiB,
+ (double) spare / (double) kMiB);
// when some must go: a margin for the tables and maps allocated after the plan and the driver's own rounding
const uint64_t short_b = want_b > free_b ? want_b - free_b + 128 * kMiB : 0;
const int64_t keep = req.expert_cache > 0 ? req.expert_cache : -1;
diff --git a/src/models/inkling2/prompt.cpp b/src/models/inkling2/prompt.cpp
index 049b66a78..2f1889e32 100644
--- a/src/models/inkling2/prompt.cpp
+++ b/src/models/inkling2/prompt.cpp
@@ -93,17 +93,19 @@ void carve(Carve& c, Bufs& b, const Geometry& g) {
// the experts' buffers, from the arena's base: the MLP's input (mix, its controller, nrm) is read before any is written
Carve x = c;
x.at = arena;
- b.xq = x.take<uint8_t>(mmq::q8_bytes((int64_t) P, (int64_t) E));
+ // the NVFP4 experts' FP4 planes take xq's place (an NVFP4 layer has no q8_1 rows); AJEAN: with chunks under 4096 rows
+ // the planes' per-expert padding outgrows the q8_1 rows, so xq takes the larger of the two
+ const size_t a4h = fp4::a4_bytes((int64_t) P, 2 * g.n_ff_exp, (int) g.n_expert), a4x = fp4::token_bytes((int64_t) R, 2 * (int64_t) E);
+ const size_t a4h_al = (a4h + 255) / 256 * 256;
+ const size_t xq_bytes = std::max<size_t>(mmq::q8_bytes((int64_t) P, (int64_t) E), a4h_al + a4x);
+ b.xq = x.take<uint8_t>(xq_bytes);
b.gu = x.take<float>(P * 2 * (size_t) g.n_ff_exp);
b.h = x.take<float>(P * (size_t) g.n_ff_exp);
b.moe = b.h;
- // the NVFP4 experts' FP4 planes take xq's place (an NVFP4 layer has no q8_1 rows)
- const size_t a4h = fp4::a4_bytes((int64_t) P, 2 * g.n_ff_exp, (int) g.n_expert), a4x = fp4::token_bytes((int64_t) R, 2 * (int64_t) E);
- if (a4h + 256 + a4x > mmq::q8_bytes((int64_t) P, (int64_t) E)) throw std::logic_error("inkling2 prompt: the FP4 planes outgrow xq");
b.a4h = b.xq;
- b.a4x = b.xq ? (uint8_t*) b.xq + ((a4h + 255) & ~(size_t) 255) : nullptr;
+ b.a4x = b.xq ? (uint8_t*) b.xq + a4h_al : nullptr;
// the experts' input rows are rounded from nrm while it is read, so they end before it
- if (c.base && (uint8_t*) b.xq + mmq::q8_bytes((int64_t) P, (int64_t) E) > (uint8_t*) b.nrm)
+ if (c.base && (uint8_t*) b.xq + xq_bytes > (uint8_t*) b.nrm)
throw std::logic_error("inkling2 prompt: the experts' input rows overlap the MLP's normed rows");
c.at = std::max(end_a, x.at);
b.xqd = c.take<uint8_t>(mmq::q8_bytes((int64_t) R, std::max<int64_t>((int64_t) E, kOut)));
diff --git a/src/models/inkling2/prompt.hpp b/src/models/inkling2/prompt.hpp
index 03de6ca86..bda6b5e8c 100644
--- a/src/models/inkling2/prompt.hpp
+++ b/src/models/inkling2/prompt.hpp
@@ -16,7 +16,12 @@ namespace basalt::models::inkling2 {
class DsparkHook;
/// The most rows one prompt chunk runs (the drafter's tap holds as many).
-constexpr int kPromptChunk = 4096;
+// AJEAN: 1024 rows by default (4096 upstream): the chunk scratch drops from ~1 GiB to ~0.25 GiB, so a 16 GB card keeps
+// every expert; -DAJEAN_PROMPT_CHUNK=4096 restores upstream.
+#ifndef AJEAN_PROMPT_CHUNK
+#define AJEAN_PROMPT_CHUNK 1024
+#endif
+constexpr int kPromptChunk = AJEAN_PROMPT_CHUNK;
class PromptRunner {
public:
diff --git a/tools/convert/inkling2_requant.py b/tools/convert/inkling2_requant.py
new file mode 100644
index 000000000..4e63584bc
--- /dev/null
+++ b/tools/convert/inkling2_requant.py
@@ -0,0 +1,140 @@
+"""AJEAN : réécrit un pack inkling2 en passant les experts Q8_0 (couches 20 à 23 du pack officiel) en NVFP4.
+
+ python3 tools/convert/inkling2_requant.py --pack IN.basalt --out OUT.basalt [--layers 20,21,22,23] [--workers 12]
+
+Chaque matrice (gate, up, down) d'un expert Q8_0 est déquantifiée puis arrondie en NVFP4 comme le fait
+hy4flash_bf16.py (échelle de tenseur amax / (6 x 448), échelle UE4M3 par 16 valeurs choisie au moindre carré).
+gate et up partagent leur échelle de tenseur, comme dans les couches NVFP4 du pack officiel ({s_gu, s_gu, s_d, 0}).
+Les autres sections sont copiées telles quelles. Gain : ~1,9 Gio d'experts en moins sur la carte.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import multiprocessing
+import os
+import pathlib
+import sys
+import time
+
+import numpy as np
+
+HERE = pathlib.Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE))
+sys.path.insert(0, str(HERE.parent))
+import checkpoint as C # noqa: E402
+import checkpoint_qwen35 as Q # noqa: E402
+import model_sections as S # noqa: E402
+from model_file import ModelFile, ModelWriter # noqa: E402
+
+H, FF, NE = 2304, 1152, 128
+Q8_ROW_H = H // 32 * 34 # a Q8_0 row of H values
+Q8_ROW_FF = FF // 32 * 34
+Q8_BLOB = 2 * FF * Q8_ROW_H + H * Q8_ROW_FF
+F4_BLOB = 2 * FF * S.nvfp4_row_bytes(H) + H * S.nvfp4_row_bytes(FF) + S.NVFP4_TAIL
+
+
+def q8_values(raw: bytes, rows: int, cols: int) -> np.ndarray:
+ b = np.frombuffer(raw, np.uint8).reshape(rows * cols // 32, 34)
+ d = b[:, :2].copy().view(np.float16).astype(np.float32)
+ q = b[:, 2:].view(np.int8).astype(np.float32)
+ return (q * d).reshape(rows, cols)
+
+
+def _job(args):
+ path, off, e0, n = args
+ with open(path, "rb") as f:
+ f.seek(off + e0 * Q8_BLOB)
+ raw = f.read(n * Q8_BLOB)
+ out = []
+ for e in range(n):
+ b = raw[e * Q8_BLOB:(e + 1) * Q8_BLOB]
+ g = q8_values(b[:FF * Q8_ROW_H], FF, H)
+ u = q8_values(b[FF * Q8_ROW_H:2 * FF * Q8_ROW_H], FF, H)
+ d = q8_values(b[2 * FF * Q8_ROW_H:], H, FF)
+ gs_gu = Q.fp4q_global(float(max(np.abs(g).max(), np.abs(u).max())))
+ gs_d = Q.fp4q_global(float(np.abs(d).max()))
+ err = 0.0
+ for x, gs in ((g, gs_gu), (u, gs_gu), (d, gs_d)):
+ codes, sc = Q.fp4q_rows(x, gs)
+ out.append(C.nvfp4_rows(codes, sc).tobytes())
+ v = np.empty(x.shape, np.float32)
+ v[:, 0::2] = C.E2M1[codes & 15]
+ v[:, 1::2] = C.E2M1[codes >> 4]
+ v *= np.repeat(Q.UE4M3[sc], 16, axis=1) * gs
+ err += float(((v - x) ** 2).sum()) / max(float((x ** 2).sum()), 1e-30)
+ out.append(np.array([gs_gu, gs_gu, gs_d, 0.0], dtype="<f4").tobytes())
+ return b"".join(out), err / 3
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--pack", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--layers", default="20,21,22,23")
+ ap.add_argument("--workers", type=int, default=12)
+ a = ap.parse_args()
+ if os.path.exists(a.out):
+ sys.exit(f"{a.out} existe déjà")
+ want = {int(x) for x in a.layers.split(",")}
+ m = ModelFile(a.pack)
+ lay = [l for l in m.read("experts.layout").decode().splitlines() if l and not l.startswith("#")]
+ rows = [tuple(int(x) for x in l.split()) for l in lay] # layer gu d off blob
+ eoff, _ = m.section("experts")
+ new, off = [], 0
+ for l, gu, dt, o, blob in rows:
+ if l in want:
+ if gu != 8 or blob != Q8_BLOB:
+ sys.exit(f"couche {l} : type {gu} blob {blob}, attendu Q8_0 {Q8_BLOB}")
+ new.append((l, 40, 40, off, F4_BLOB))
+ off += F4_BLOB * NE
+ else:
+ new.append((l, gu, dt, off, blob))
+ off += blob * NE
+ total = off
+ t0 = time.time()
+ errs = []
+
+ def experts_chunks(pool):
+ for (l, gu, dt, o, blob), nl in zip(rows, new):
+ if l not in want:
+ left, at = blob * NE, eoff + o
+ with open(a.pack, "rb") as f:
+ f.seek(at)
+ while left:
+ b = f.read(min(64 << 20, left))
+ left -= len(b)
+ yield b
+ continue
+ jobs = [(a.pack, eoff + o, e, 4) for e in range(0, NE, 4)]
+ for b, err in pool.imap(_job, jobs):
+ errs.append(err)
+ yield b
+ print(f"couche {l} : NVFP4, erreur relative moyenne {np.mean(errs[-len(jobs):]):.5f} ({time.time() - t0:.0f} s)", flush=True)
+
+ w = ModelWriter(a.out)
+ with multiprocessing.Pool(a.workers) as pool:
+ for name in m.names():
+ so, sz = m.section(name)
+ if name == "experts":
+ n = w.add_chunks(name, experts_chunks(pool))
+ if n != total:
+ sys.exit(f"experts : {n} octets, attendu {total}")
+ elif name == "experts.layout":
+ w.add_bytes(name, S.nvfp4_layout_text(NE, total, new))
+ elif name == "meta":
+ j = json.loads(m.read("meta"))
+ j["name"] = j.get("name", "Inkling 2 Mini")
+ j["ajean_requant"] = {"tool": "tools/convert/inkling2_requant.py", "from": os.path.basename(a.pack),
+ "layers_nvfp4": sorted(want),
+ "method": "Q8_0 -> float32 -> NVFP4 (amax/(6x448) tensor scale, gate/up shared; "
+ "UE4M3 per 16 at least squared error)"}
+ w.add_bytes(name, json.dumps(j, ensure_ascii=False).encode())
+ else:
+ w.add_file(name, a.pack, so, sz)
+ w.close()
+ print(f"écrit {a.out} : experts {total / 2**30:.2f} Gio (avant {sum(r[4] for r in rows) * NE / 2**30:.2f}), {time.time() - t0:.0f} s")
+
+
+if __name__ == "__main__":
+ main()
--
2.43.0
From 83d4832b1adc302868fea4d2d82118b8c0496eb1 Mon Sep 17 00:00:00 2001
From: nathaninline <mail@nathaninline.com>
Date: Sun, 22 Nov 2026 17:32:07 +0000
Subject: [PATCH 2/5] AJEAN: plus d experts sur la carte (KV elastique, copies
en blocs, cache du drafter plafonne)
- base du KV elastique a 8192 positions (AJEAN_KV_BASE, 32768 en amont) et marge de 128 Mio (AJEAN_ELASTIC_KEEP_MIB, 512)
- copies des experts recuperes en blocs de 15 : un expert seul s arrondissait aux pages de 2 Mio (40 % perdus)
- tranche de prompt : chaque expert en RAM depuis sa copie carte quand elle existe, les autres en suites contigues
- couche pleine du drafter en anneau de 16384 positions (AJEAN_DRAFT_CTX) : 0,5 Gio rendus aux experts a 131k
- journal : VRAM au debut du plan, cout reel des copies
---
src/models/inkling2/dspark.cpp | 26 +++++-
src/models/inkling2/dspark.hpp | 1 +
src/models/inkling2/model.cpp | 135 +++++++++++++++++++++++++++-----
src/models/inkling2/model.hpp | 19 +++++
src/models/inkling2/session.cpp | 12 +--
5 files changed, 164 insertions(+), 29 deletions(-)
diff --git a/src/models/inkling2/dspark.cpp b/src/models/inkling2/dspark.cpp
index 5ee0646f9..57d1ccde7 100644
--- a/src/models/inkling2/dspark.cpp
+++ b/src/models/inkling2/dspark.cpp
@@ -50,6 +50,18 @@ uint64_t q8_bytes(uint64_t rows, uint64_t n_in) { return rows * (n_in / 32) * 34
int64_t ring_cells(const DsparkGeometry& d) { return (int64_t) d.window + kRingExtra; }
int64_t full_cells(int64_t context) { return context + kDsBlock; }
+// AJEAN: the full layer's cache keeps at most AJEAN_DRAFT_CTX positions (default 16384) as a ring over the last ones: at
+// 131K its fp16 cells took 0.5 GiB of the card from the experts. Only the drafts see less; the output does not change.
+int64_t draft_ctx() {
+ static const int64_t v = [] {
+ const char* e = std::getenv("AJEAN_DRAFT_CTX");
+ const long long n = e && *e ? std::atoll(e) : 16384;
+ return (int64_t) std::max<long long>(n, 2048);
+ }();
+ return v;
+}
+bool full_capped(int64_t context) { return context > draft_ctx(); }
+int64_t full_layer_cells(int64_t context) { return full_capped(context) ? draft_ctx() + kRingExtra : full_cells(context); }
bk::RopeSpec rope_of(const DsparkGeometry& d) {
bk::RopeSpec r;
@@ -302,10 +314,10 @@ uint64_t dspark_session_bytes(const Pack& pack, int64_t context) {
uint64_t n = 3 * kSlice * E * 4 + kFrRing * E * 4 + 2 * kSlice * kKV * 4 + 64; // a commit step's rows
n += bk::native_q8_1_bytes(kE, kSlice);
for (int l = 0; l < d.n_layers; ++l) // the caches, fp16 K and V
- n += 2ull * (uint64_t) (d.swa[(size_t) l] ? ring_cells(d) : full_cells(context)) * kKV * 2;
+ n += 2ull * (uint64_t) (d.swa[(size_t) l] ? ring_cells(d) : full_layer_cells(context)) * kKV * 2;
n += (2 * R * E + 3 * R * kQ) * 4; // the block's rows
n += 2 * bk::wgemm::act_bytes((int64_t) std::max<uint64_t>(ff, kQ)) + dspark_ws_bytes(d) + 1024; // the window gemm's
- n += bk::gqa_decode_scratch_floats(std::max(ring_cells(d), full_cells(context)), kDsBlock, kHeads, kHeadDim) * 4;
+ n += bk::gqa_decode_scratch_floats(std::max(ring_cells(d), full_layer_cells(context)), kDsBlock, kHeads, kHeadDim) * 4;
n += ((uint64_t) kDsDrafts * dspark_screen_rows((int64_t) V) + (uint64_t) kDsDrafts * kDsRnn + kDsRnn + 3 * kDsRank) * 4; // the head's
n += bk::native_q8_1_bytes(kE, kDsDrafts) + bk::native_q8_1_bytes(kDsRank, kDsDrafts) + dspark_head_scratch_bytes((int64_t) V) + 1024;
return n;
@@ -361,6 +373,12 @@ bool DsparkHook::init(const DsparkWeights* w, const Geometry& g, int64_t context
Cache& c = cache_[(size_t) l];
c.ring = d.swa[(size_t) l];
c.cap = c.ring ? ring_cells(d) : full_cells(context);
+ c.win = c.ring ? (int64_t) d.window + 1 : 0;
+ if (!c.ring && full_capped(context)) { // AJEAN: the full layer as a ring of its last draft_ctx() positions
+ c.ring = true;
+ c.cap = draft_ctx() + kRingExtra;
+ c.win = draft_ctx() + 1;
+ }
c.k = (uint16_t*) dev((size_t) c.cap * kKV * 2, ok);
c.v = (uint16_t*) dev((size_t) c.cap * kKV * 2, ok);
}
@@ -380,7 +398,7 @@ bool DsparkHook::init(const DsparkWeights* w, const Geometry& g, int64_t context
ws_.tickets_n = tk;
}
pos3b_ = (int32_t*) dev(R * 3 * 4, ok);
- att_cells_ = std::max(ring_cells(d), full_cells(context));
+ att_cells_ = std::max(ring_cells(d), full_layer_cells(context));
att_scr_ = f(bk::gqa_decode_scratch_floats(att_cells_, kDsBlock, kHeads, kHeadDim));
approx_ = f((size_t) kDsDrafts * dspark_screen_rows((int64_t) V));
hq_ = dev(bk::native_q8_1_bytes(kE, kDsDrafts), ok);
@@ -588,7 +606,7 @@ model::Result DsparkHook::draft_begin(int32_t anchor, int64_t pos, int n, void*
if (k > 0) {
const Cache& c = cache_[(size_t) k - 1];
// a sliding-window layer sees its window before the block, the full one every position, and both the block
- const int64_t window = c.ring ? (int64_t) d.window + 1 : pos + kDsBlock;
+ const int64_t window = c.win > 0 ? c.win : pos + kDsBlock;
// the splits from the cells the block reads, not from the scratch's capacity (this call is not captured): a
// short context runs few splits; the drafts only shape the speed
const int64_t cells = pos + kDsBlock - std::max<int64_t>(0, pos - window + 1) + 64;
diff --git a/src/models/inkling2/dspark.hpp b/src/models/inkling2/dspark.hpp
index 689cd7b65..f334fdd13 100644
--- a/src/models/inkling2/dspark.hpp
+++ b/src/models/inkling2/dspark.hpp
@@ -146,6 +146,7 @@ private:
uint16_t *k = nullptr, *v = nullptr; ///< fp16 [cap][kv heads][head width], position p at cell p % cap
int64_t cap = 0;
bool ring = false;
+ int64_t win = 0; ///< AJEAN: the attention window of a ring (0: every position)
};
void* dev(size_t bytes, bool& ok);
void stage(int k, int n, void* stream);
diff --git a/src/models/inkling2/model.cpp b/src/models/inkling2/model.cpp
index ae273f19c..632134736 100644
--- a/src/models/inkling2/model.cpp
+++ b/src/models/inkling2/model.cpp
@@ -89,12 +89,30 @@ uint64_t shared_bytes(const Geometry& g, bool drafter) {
return kSharedFixed + prompt_bytes(g) + (drafter ? dspark_tap_bytes(std::max(kDecodeRows, kPromptChunk)) : 0); // PROMPT, DSPARK HOOKS
}
+int64_t ajean_kv_base() {
+ static const int64_t v = [] {
+ const char* e = std::getenv("AJEAN_KV_BASE");
+ const long long n = e && *e ? std::atoll(e) : 8192;
+ return (int64_t) std::clamp<long long>(n, 1024, core::kElasticKvBase);
+ }();
+ return v;
+}
+
+uint64_t ajean_elastic_keep() {
+ static const uint64_t v = [] {
+ const char* e = std::getenv("AJEAN_ELASTIC_KEEP_MIB");
+ const long long n = e && *e ? std::atoll(e) : 128;
+ return (uint64_t) std::max<long long>(n, 32) << 20;
+ }();
+ return v;
+}
+
InklingModel::InklingModel() = default;
InklingModel::~InklingModel() {
for (void* p : dev_) cudaFree(p);
- for (void* p : copy_)
- if (p) cudaFree(p);
+ for (CopySlab& sl : slabs_)
+ if (sl.base) cudaFree(sl.base);
for (const Range& r : ranges_) {
if (r.handle) core::vmm::unmap(r.va, r.own, r.handle);
core::vmm::unmap_only(r.va + r.own, r.bytes - r.own);
@@ -164,6 +182,11 @@ model::Result InklingModel::plan(const model::LoadRequest& req, core::LoadPlan&
if (!open_pack(path, pack_, err)) return {model::Status::Error, "inkling2: " + err};
flags_ = req;
cudaGetDevice(&device_);
+ {
+ size_t f0 = 0, t0 = 0;
+ cudaMemGetInfo(&f0, &t0);
+ basalt::log::info("basalt inkling2", "AJEAN vram at plan start: free %.0f MiB of %.0f", (double) f0 / (double) kMiB, (double) t0 / (double) kMiB);
+ }
const Geometry& g = pack_.geo;
desc_.arch = "inkling2";
desc_.n_layers = g.n_layers;
@@ -373,7 +396,7 @@ model::Result InklingModel::plan(const model::LoadRequest& req, core::LoadPlan&
for (int l = 0; l < g.n_layers; ++l)
for (int e = 0; e < g.n_expert; ++e)
if (!on_card(l, e)) spill_order_.emplace_back(l, e);
- elastic_ = keep < 0 && want > core::kElasticKvBase;
+ elastic_ = keep < 0 && want > ajean_kv_base();
uint64_t ram = 0;
for (int l = 0; l < g.n_layers; ++l) ram += (uint64_t) spill_.n_spill[(size_t) l] * stride[(size_t) l];
basalt::log::info("basalt inkling2",
@@ -423,6 +446,7 @@ model::Result InklingModel::load_experts(core::LoadPlan& reads, int file, uint64
const uint64_t gran = spill_.any() ? core::vmm::granularity() : 0;
if (spill_.any()) {
copy_.assign((size_t) g.n_layers * g.n_expert, nullptr);
+ copy_slab_.assign((size_t) g.n_layers * g.n_expert, -1);
layer_copies_.assign((size_t) g.n_layers, 0);
host_addr_.assign((size_t) g.n_layers * g.n_expert, 0);
}
@@ -554,7 +578,12 @@ model::Result InklingModel::attach(const model::LoadRequest&, std::vector<std::u
for (auto& s : sessions)
if (model::Result r = s->prepare(); !r.ok()) return r;
if (elastic_) { // the caches back only their base yet: the RAM experts come back while the card has room
+ size_t fa = 0, fb = 0, tt = 0;
+ cudaMemGetInfo(&fa, &tt);
const uint64_t moved = promote(held_free(kCardSpare));
+ cudaMemGetInfo(&fb, &tt);
+ basalt::log::info("basalt inkling2", "AJEAN promote: %.0f MiB of copies took %.0f MiB of the card", (double) moved / (double) kMiB,
+ (double) (fa - fb) / (double) kMiB);
basalt::log::info("basalt inkling2", "elastic spill: %lld of %lld RAM experts copied back to the card (%.2f GiB); they go back "
"to RAM, the least routed first, as a conversation's caches grow",
(long long) n_copy_, (long long) spill_.spilled, (double) moved / (double) kGiB);
@@ -562,6 +591,56 @@ model::Result InklingModel::attach(const model::LoadRequest&, std::vector<std::u
return {};
}
+void* InklingModel::slab_take(uint64_t stride, uint64_t keep_free, int& slab) {
+ constexpr int kSlabExperts = 15; // 15 x 4,478,992 bytes = 32.04 pages of 2 MiB: 3 % lost
+ for (size_t k = slabs_.size(); k-- > 0;) {
+ CopySlab& sl = slabs_[k];
+ if (!sl.base || sl.stride != stride || sl.used == sl.n) continue;
+ for (int j = 0; j < sl.n; ++j)
+ if (!sl.busy[(size_t) j]) {
+ sl.busy[(size_t) j] = 1;
+ ++sl.used;
+ slab = (int) k;
+ return sl.base + (uint64_t) j * stride;
+ }
+ }
+ size_t free_b = 0, total_b = 0;
+ cudaMemGetInfo(&free_b, &total_b);
+ if (free_b < keep_free + stride) return nullptr;
+ const int n = (int) std::min<uint64_t>(kSlabExperts, (free_b - keep_free) / stride);
+ void* p = nullptr;
+ if (n < 1 || cudaMalloc(&p, (uint64_t) n * stride) != cudaSuccess) {
+ cudaGetLastError();
+ return nullptr;
+ }
+ CopySlab sl;
+ sl.base = static_cast<uint8_t*>(p);
+ sl.stride = stride;
+ sl.n = n;
+ sl.used = 1;
+ sl.busy.assign((size_t) n, 0);
+ sl.busy[0] = 1;
+ size_t k = 0;
+ while (k < slabs_.size() && slabs_[k].base) ++k;
+ if (k == slabs_.size()) slabs_.push_back(std::move(sl));
+ else slabs_[k] = std::move(sl);
+ slab = (int) k;
+ return p;
+}
+
+uint64_t InklingModel::slab_give(int slab, const void* p) {
+ if (slab < 0 || (size_t) slab >= slabs_.size()) return 0;
+ CopySlab& sl = slabs_[(size_t) slab];
+ const size_t j = (size_t) ((const uint8_t*) p - sl.base) / sl.stride;
+ if (j >= sl.busy.size() || !sl.busy[j]) return 0;
+ sl.busy[j] = 0;
+ if (--sl.used > 0) return 0;
+ const uint64_t bytes = (uint64_t) sl.n * sl.stride;
+ cudaFree(sl.base);
+ sl = CopySlab{};
+ return bytes;
+}
+
uint64_t InklingModel::promote(uint64_t keep_free) {
const int ne = geo().n_expert;
uint64_t moved = 0;
@@ -569,23 +648,19 @@ uint64_t InklingModel::promote(uint64_t keep_free) {
const size_t i = (size_t) l * ne + e;
if (copy_[i]) continue;
const LayerWeights& w = layers_[(size_t) l];
- size_t free_b = 0, total_b = 0;
- cudaMemGetInfo(&free_b, &total_b);
- if (free_b < keep_free + w.expert_stride) break;
- void* p = nullptr;
- if (cudaMalloc(&p, w.expert_stride) != cudaSuccess) {
- cudaGetLastError();
- break;
- }
+ int slab = -1;
+ void* p = slab_take(w.expert_stride, keep_free, slab);
+ if (!p) break;
const int keep = ne - w.n_spill;
const uint8_t* src = w.spill_host + (uint64_t) (spill_.slot[(size_t) l][(size_t) e] - keep) * w.expert_stride;
const unsigned long long at = (unsigned long long) p;
if (cudaMemcpy(p, src, w.expert_stride, cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(w.blob_table + e, &at, 8, cudaMemcpyHostToDevice) != cudaSuccess) {
- cudaFree(p);
+ slab_give(slab, p);
break;
}
copy_[i] = p;
+ copy_slab_[i] = slab;
++n_copy_;
++layer_copies_[(size_t) l];
moved += w.expert_stride;
@@ -616,13 +691,30 @@ void InklingModel::lend(bool low, void* stream) {
}
bool InklingModel::stage_from_card(int l, void* stream) const {
+ // AJEAN: every RAM expert of the layer from its card copy when it has one, the others from RAM in runs of adjacent
+ // slots (upstream read the whole layer's RAM experts over the bus unless every one had a copy: at 131K a 38-token
+ // prompt waited about 0.2 s on it)
const LayerWeights& w = layers_[(size_t) l];
- if (copy_.empty() || w.n_spill == 0 || layer_copies_[(size_t) l] < w.n_spill) return false;
- const int ne = geo().n_expert;
- for (int e = 0; e < ne; ++e)
+ if (copy_.empty() || w.n_spill == 0) return false;
+ const int ne = geo().n_expert, keep = ne - w.n_spill;
+ std::vector<int> host;
+ for (int e = 0; e < ne; ++e) {
+ const int slot = spill_.slot[(size_t) l][(size_t) e];
+ if (slot < keep) continue;
if (const void* c = copy_[(size_t) l * ne + e])
- cudaMemcpyAsync(w.experts + (uint64_t) spill_.slot[(size_t) l][(size_t) e] * w.expert_stride, c, w.expert_stride,
- cudaMemcpyDeviceToDevice, (cudaStream_t) stream);
+ cudaMemcpyAsync(w.experts + (uint64_t) slot * w.expert_stride, c, w.expert_stride, cudaMemcpyDeviceToDevice,
+ (cudaStream_t) stream);
+ else
+ host.push_back(slot);
+ }
+ std::sort(host.begin(), host.end());
+ for (size_t i = 0; i < host.size();) {
+ size_t j = i + 1;
+ while (j < host.size() && host[j] == host[j - 1] + 1) ++j;
+ cudaMemcpyAsync(w.experts + (uint64_t) host[i] * w.expert_stride, w.spill_host + (uint64_t) (host[i] - keep) * w.expert_stride,
+ (size_t) (j - i) * w.expert_stride, cudaMemcpyHostToDevice, (cudaStream_t) stream);
+ i = j;
+ }
return true;
}
@@ -630,17 +722,22 @@ uint64_t InklingModel::demote(uint64_t bytes, void* stream) {
const int ne = geo().n_expert;
std::vector<size_t> out;
uint64_t freed = 0;
+ // AJEAN: a slab frees its memory once all its copies leave: count what each slab would give back
+ std::vector<int> left(slabs_.size());
+ for (size_t k = 0; k < slabs_.size(); ++k) left[k] = slabs_[k].used;
for (auto it = spill_order_.rbegin(); it != spill_order_.rend() && freed < bytes; ++it) {
const size_t i = (size_t) it->first * ne + it->second;
if (!copy_[i]) continue;
cudaMemcpyAsync(layers_[(size_t) it->first].blob_table + it->second, &host_addr_[i], 8, cudaMemcpyHostToDevice, (cudaStream_t) stream);
out.push_back(i);
- freed += layers_[(size_t) it->first].expert_stride;
+ const int k = copy_slab_[i];
+ if (k >= 0 && --left[(size_t) k] == 0) freed += (uint64_t) slabs_[(size_t) k].n * slabs_[(size_t) k].stride;
}
if (out.empty()) return 0;
cudaStreamSynchronize((cudaStream_t) stream);
for (size_t i : out) {
- cudaFree(copy_[i]);
+ slab_give(copy_slab_[i], copy_[i]);
+ copy_slab_[i] = -1;
copy_[i] = nullptr;
--n_copy_;
--layer_copies_[i / (size_t) ne];
diff --git a/src/models/inkling2/model.hpp b/src/models/inkling2/model.hpp
index d38166f35..8b62000e6 100644
--- a/src/models/inkling2/model.hpp
+++ b/src/models/inkling2/model.hpp
@@ -17,6 +17,12 @@
namespace basalt::models::inkling2 {
+/// AJEAN: the cells a session's full caches back at start with an elastic context (core::kElasticKvBase, 32768, upstream);
+/// AJEAN_KV_BASE overrides it (default 8192: a short chat leaves about 0.4 GiB more to the experts on a 16 GB card).
+int64_t ajean_kv_base();
+/// AJEAN: the free bytes a cache growth or a return of experts leaves on the card (512 MiB upstream); AJEAN_ELASTIC_KEEP_MIB.
+uint64_t ajean_elastic_keep();
+
constexpr int64_t kDefaultContext = 8192;
/// The four loop controllers of a core layer: the query, key, value and MLP inputs' messages.
@@ -162,6 +168,19 @@ private:
std::vector<unsigned long long> host_addr_;
int64_t n_copy_ = 0;
std::vector<int> layer_copies_; ///< [layer] RAM experts with a card copy
+ // AJEAN: the card copies sit in slabs of kSlabExperts slots (one cudaMalloc each); an expert alone rounds up to the
+ // driver's 2 MiB pages (4.27 MiB -> 6 MiB, 40 % lost). A slab is freed when its last copy leaves; promote fills in
+ // spill order and demote empties in reverse, so the least routed slabs go first.
+ struct CopySlab {
+ uint8_t* base = nullptr;
+ uint64_t stride = 0;
+ int n = 0, used = 0;
+ std::vector<char> busy;
+ };
+ std::vector<CopySlab> slabs_;
+ std::vector<int> copy_slab_; ///< [layer * n_expert + expert] the slab of its copy (-1: none)
+ void* slab_take(uint64_t stride, uint64_t keep_free, int& slab);
+ uint64_t slab_give(int slab, const void* p); ///< bytes the card got back (the slab's when it emptied)
// [vision] the experts' memory lent to the image encoder: each lent range's bytes, in RAM until refill
struct LentRange {
size_t range = 0;
diff --git a/src/models/inkling2/session.cpp b/src/models/inkling2/session.cpp
index d2208b3e2..97e8ea6cf 100644
--- a/src/models/inkling2/session.cpp
+++ b/src/models/inkling2/session.cpp
@@ -204,11 +204,11 @@ public:
if (!c.ring && m_.elastic()) { // the elastic KV: the range reserved, its first kElasticKvBase cells backed
for (int j = 0; j < 2; ++j) {
auto a = std::make_unique<core::ElasticArray>();
- if (ok && (!a->open(bytes, err) || !a->ensure(cell_bytes() * (uint64_t) core::kElasticKvBase, 0, err))) ok = false;
+ if (ok && (!a->open(bytes, err) || !a->ensure(cell_bytes() * (uint64_t) ajean_kv_base(), 0, err))) ok = false;
(j ? c.v : c.k) = a->data();
elastic_.push_back(std::move(a));
}
- backed_ = core::kElasticKvBase;
+ backed_ = ajean_kv_base();
} else {
c.k = alloc(bytes, ok);
c.v = alloc(bytes, ok);
@@ -460,7 +460,7 @@ public:
// and when the card has no room the RAM experts' card copies go back to RAM first, the least routed first. False when
// even without any copy there is no room.
static constexpr int64_t kElasticKvStep = 8192;
- static constexpr uint64_t kElasticKeep = 512ull << 20; // free bytes a grow leaves (the driver, the graphs)
+ static uint64_t kElasticKeep_() { return ajean_elastic_keep(); } // AJEAN: free bytes a grow leaves (512 MiB upstream)
bool ensure_positions(int64_t positions, std::string& err) {
if (elastic_.empty() || positions <= backed_) return true;
const int64_t target = std::min<int64_t>(m_.context(), (positions + kElasticKvStep - 1) / kElasticKvStep * kElasticKvStep);
@@ -468,7 +468,7 @@ public:
const uint64_t grow = (uint64_t) elastic_.size() * (bytes - std::min<uint64_t>(bytes, elastic_[0]->backed())) + (64ull << 20);
size_t free_b = 0, total_b = 0;
cudaMemGetInfo(&free_b, &total_b);
- const uint64_t keep_free = m_.held_free(kElasticKeep);
+ const uint64_t keep_free = m_.held_free(kElasticKeep_());
if (free_b < grow + keep_free) {
const uint64_t freed = m_.demote(grow + keep_free - free_b, stream_);
basalt::log::info("basalt inkling2", "elastic spill: the caches grow to %lld positions; %.2f GiB of expert copies go back to RAM "
@@ -486,7 +486,7 @@ public:
// the base), and the RAM experts come back to the card while it has room.
void restart_positions(int64_t positions) {
if (elastic_.empty()) return;
- const int64_t keep = std::max<int64_t>(core::kElasticKvBase, (positions + kElasticKvStep - 1) / kElasticKvStep * kElasticKvStep);
+ const int64_t keep = std::max<int64_t>(ajean_kv_base(), (positions + kElasticKvStep - 1) / kElasticKvStep * kElasticKvStep);
if (keep < backed_) {
cudaStreamSynchronize(stream_);
for (auto& a : elastic_) a->trim(cell_bytes() * (uint64_t) keep);
@@ -494,7 +494,7 @@ public:
}
if (m_.promoted() < m_.spill().spilled && !m_.lent()) {
cudaStreamSynchronize(stream_);
- m_.promote(m_.held_free(kElasticKeep) + (uint64_t) elastic_.size() * cell_bytes() * (uint64_t) std::max<int64_t>(0, keep - backed_));
+ m_.promote(m_.held_free(kElasticKeep_()) + (uint64_t) elastic_.size() * cell_bytes() * (uint64_t) std::max<int64_t>(0, keep - backed_));
}
}
size_t kv_bytes_of(const VisitCache& c) const { return (size_t) kKvHeads * (size_t) c.cap * kHeadDim * elem(); }
--
2.43.0
From e2837d78b39f5e4db910d89b04e1c8b5bec7bf0c Mon Sep 17 00:00:00 2001
From: nathaninline <mail@nathaninline.com>
Date: Sun, 22 Nov 2026 17:45:29 +0000
Subject: [PATCH 3/5] AJEAN: le serveur accepte tout nom de modele (comme
llama-server)
---
serve/handler.py | 2 ++
1 file changed, 2 insertions(+)
diff --git a/serve/handler.py b/serve/handler.py
index e5b162e14..98af20c2c 100644
--- a/serve/handler.py
+++ b/serve/handler.py
@@ -518,6 +518,8 @@ def make_handler(target: Service | Router):
# llama.cpp's tokenizer routes name no model: the shown one's tokenizer, as /props describes it
self.svc = router.shown() if requested is None and path in ("/tokenize", "/detokenize") else \
router.service_for(requested)
+ if self.svc is None: # AJEAN: any model name reaches the model shown, as with llama-server
+ self.svc = router.shown()
if self.svc is None:
self._unknown_model(path, requested)
return
--
2.43.0
From a3f06956b3e64320f48af1273a2579d2c01f94b6 Mon Sep 17 00:00:00 2001
From: nathaninline <mail@nathaninline.com>
Date: Sun, 22 Nov 2026 17:59:26 +0000
Subject: [PATCH 4/5] AJEAN: carte pleine sans arret du moteur
- graphe de fenetre qui ne s instancie pas faute de memoire : 256 Mio de copies d experts rendus a la RAM et nouvelle capture, sinon cette forme tourne sans graphe (le moteur sortait sur cudaGraphInstantiate: out of memory)
- reservoir MMQ : en cas d echec de cudaMalloc, copies d experts rendues puis nouvel essai (le moteur sortait sur mmq: out of memory)
---
src/models/inkling2/model.cpp | 11 +++++++++++
src/models/inkling2/session.cpp | 30 +++++++++++++++++++++++++++---
src/prefill/mmq/mmq_host.cu | 15 ++++++++++++++-
3 files changed, 52 insertions(+), 4 deletions(-)
diff --git a/src/models/inkling2/model.cpp b/src/models/inkling2/model.cpp
index 632134736..f17302ff0 100644
--- a/src/models/inkling2/model.cpp
+++ b/src/models/inkling2/model.cpp
@@ -15,11 +15,16 @@
#include <cuda_runtime.h>
#include <algorithm>
+#include <functional>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <new>
+namespace basalt {
+extern std::function<uint64_t(uint64_t)> g_ajean_oom_hook; // src/prefill/mmq/mmq_host.cu
+}
+
namespace basalt::models::inkling2 {
namespace {
constexpr uint64_t kGiB = 1ull << 30;
@@ -577,6 +582,12 @@ model::Result InklingModel::attach(const model::LoadRequest&, std::vector<std::u
if (model::Result r = dspark_->finish(head_, embd_dev_, embed_norm_, nullptr); !r.ok()) return r;
for (auto& s : sessions)
if (model::Result r = s->prepare(); !r.ok()) return r;
+ if (spill_.any()) // AJEAN: a full card gives expert copies back when MMQ's pool needs room
+ ::basalt::g_ajean_oom_hook = [this](uint64_t bytes) {
+ const uint64_t freed = demote(bytes, nullptr);
+ basalt::log::warn("basalt inkling2", "card full: %.0f MiB of expert copies back to RAM", (double) freed / (double) kMiB);
+ return freed;
+ };
if (elastic_) { // the caches back only their base yet: the RAM experts come back while the card has room
size_t fa = 0, fb = 0, tt = 0;
cudaMemGetInfo(&fa, &tt);
diff --git a/src/models/inkling2/session.cpp b/src/models/inkling2/session.cpp
index 97e8ea6cf..47c8d11cb 100644
--- a/src/models/inkling2/session.cpp
+++ b/src/models/inkling2/session.cpp
@@ -922,15 +922,38 @@ private:
const uint64_t key = ((uint64_t) full_keys << 16) | ((uint64_t) head << 8) | (uint64_t) rows;
auto it = graphs_.find(key);
if (it != graphs_.end()) return it->second.launch(stream_, err);
- if (direct_.insert(key).second) {
+ if (direct_.insert(key).second || nograph_.count(key)) {
body(rows, head, full_keys);
return true;
}
core::CapturedGraph g;
if (!g.begin(stream_, err)) return false;
body(rows, head, full_keys);
- if (!g.end(stream_, err)) return false;
- return graphs_.emplace(key, std::move(g)).first->second.launch(stream_, err);
+ if (g.end(stream_, err)) return graphs_.emplace(key, std::move(g)).first->second.launch(stream_, err);
+ // AJEAN: a card kept nearly full of experts can lack the memory to instantiate a new shape's graph (the engine
+ // exited on it): give 256 MiB of expert copies back to RAM and capture again; failing that, run this shape direct
+ for (int attempt = 0; attempt < 2; ++attempt) {
+ cudaGetLastError();
+ const uint64_t freed = m_.demote(256ull << 20, stream_);
+ basalt::log::warn("basalt inkling2", "graph of %d rows: %s; %.0f MiB of expert copies back to RAM, capturing again", rows,
+ err.c_str(), (double) freed / (double) (1 << 20));
+ core::CapturedGraph h;
+ std::string e2;
+ if (!h.begin(stream_, e2)) break;
+ body(rows, head, full_keys);
+ if (h.end(stream_, e2)) {
+ err.clear();
+ return graphs_.emplace(key, std::move(h)).first->second.launch(stream_, err);
+ }
+ err = e2;
+ if (freed == 0) break;
+ }
+ cudaGetLastError();
+ basalt::log::warn("basalt inkling2", "graph of %d rows: %s; this shape runs without a graph", rows, err.c_str());
+ err.clear();
+ nograph_.insert(key);
+ body(rows, head, full_keys);
+ return true;
}
// Launches only: the visits, then the head. Each kernel may start while the one before it finishes (it waits for it
@@ -1090,6 +1113,7 @@ private:
DsparkHook dspark_; // DSPARK HOOK
Walk walk_;
std::map<uint64_t, core::CapturedGraph> graphs_; // by window shape: rows, head rows, the full visits' launch bound
+ std::set<uint64_t> nograph_; // AJEAN: shapes whose graph could not be instantiated
std::set<uint64_t> direct_; // the shapes whose first window has run
const model::BatchView* view_ = nullptr; // the batch window in flight, while batch_forward runs it
float* logits_ = nullptr; // the last window's head rows (row_logprobs, copy_logits, resample_row)
diff --git a/src/prefill/mmq/mmq_host.cu b/src/prefill/mmq/mmq_host.cu
index be8cd273f..444c751eb 100644
--- a/src/prefill/mmq/mmq_host.cu
+++ b/src/prefill/mmq/mmq_host.cu
@@ -1,3 +1,4 @@
+#include <functional>
// The host side of the MMQ kernels: error reporting, the properties of each device and the cache of scratch buffers
// that the stream-k fixup of a launch takes from, and the explicit load of a kernel.
#include "mmq_common.cuh"
@@ -63,6 +64,12 @@ const ggml_cuda_device_info & ggml_cuda_info() {
return info;
}
+namespace basalt {
+// AJEAN: called when a pool allocation finds the card full (a model that keeps the card full of expert copies frees
+// some); returns the bytes it gave back. Empty: no retry.
+std::function<uint64_t(uint64_t)> g_ajean_oom_hook;
+} // namespace basalt
+
namespace {
// Buffers are kept and reused: MMQ asks for the same few sizes every launch (its stream-k fixup tiles).
struct CachingPool : ggml_cuda_pool {
@@ -74,7 +81,13 @@ struct CachingPool : ggml_cuda_pool {
for (auto & b : bufs)
if (!b.used && b.size >= size) { b.used = true; *actual_size = b.size; return b.p; }
void * p = nullptr;
- CUDA_CHECK(cudaMalloc(&p, size));
+ cudaError_t e = cudaMalloc(&p, size);
+ if (e != cudaSuccess && basalt::g_ajean_oom_hook) { // AJEAN
+ cudaGetLastError();
+ basalt::g_ajean_oom_hook((uint64_t) size + (64ull << 20));
+ e = cudaMalloc(&p, size);
+ }
+ if (e != cudaSuccess) CUDA_CHECK(e);
bufs.push_back({p, size, true});
*actual_size = size;
return p;
--
2.43.0
From 7fe1b04d802bbfdb7866e4fd653dc557304f090a Mon Sep 17 00:00:00 2001
From: nathaninline <mail@nathaninline.com>
Date: Sun, 22 Nov 2026 19:34:37 +0000
Subject: [PATCH 5/5] AJEAN: inkling2_requant.py in English
---
tools/convert/inkling2_requant.py | 280 +++++++++++++++---------------
1 file changed, 140 insertions(+), 140 deletions(-)
diff --git a/tools/convert/inkling2_requant.py b/tools/convert/inkling2_requant.py
index 4e63584bc..df6e42d5b 100644
--- a/tools/convert/inkling2_requant.py
+++ b/tools/convert/inkling2_requant.py
@@ -1,140 +1,140 @@
-"""AJEAN : réécrit un pack inkling2 en passant les experts Q8_0 (couches 20 à 23 du pack officiel) en NVFP4.
-
- python3 tools/convert/inkling2_requant.py --pack IN.basalt --out OUT.basalt [--layers 20,21,22,23] [--workers 12]
-
-Chaque matrice (gate, up, down) d'un expert Q8_0 est déquantifiée puis arrondie en NVFP4 comme le fait
-hy4flash_bf16.py (échelle de tenseur amax / (6 x 448), échelle UE4M3 par 16 valeurs choisie au moindre carré).
-gate et up partagent leur échelle de tenseur, comme dans les couches NVFP4 du pack officiel ({s_gu, s_gu, s_d, 0}).
-Les autres sections sont copiées telles quelles. Gain : ~1,9 Gio d'experts en moins sur la carte.
-"""
-from __future__ import annotations
-
-import argparse
-import json
-import multiprocessing
-import os
-import pathlib
-import sys
-import time
-
-import numpy as np
-
-HERE = pathlib.Path(__file__).resolve().parent
-sys.path.insert(0, str(HERE))
-sys.path.insert(0, str(HERE.parent))
-import checkpoint as C # noqa: E402
-import checkpoint_qwen35 as Q # noqa: E402
-import model_sections as S # noqa: E402
-from model_file import ModelFile, ModelWriter # noqa: E402
-
-H, FF, NE = 2304, 1152, 128
-Q8_ROW_H = H // 32 * 34 # a Q8_0 row of H values
-Q8_ROW_FF = FF // 32 * 34
-Q8_BLOB = 2 * FF * Q8_ROW_H + H * Q8_ROW_FF
-F4_BLOB = 2 * FF * S.nvfp4_row_bytes(H) + H * S.nvfp4_row_bytes(FF) + S.NVFP4_TAIL
-
-
-def q8_values(raw: bytes, rows: int, cols: int) -> np.ndarray:
- b = np.frombuffer(raw, np.uint8).reshape(rows * cols // 32, 34)
- d = b[:, :2].copy().view(np.float16).astype(np.float32)
- q = b[:, 2:].view(np.int8).astype(np.float32)
- return (q * d).reshape(rows, cols)
-
-
-def _job(args):
- path, off, e0, n = args
- with open(path, "rb") as f:
- f.seek(off + e0 * Q8_BLOB)
- raw = f.read(n * Q8_BLOB)
- out = []
- for e in range(n):
- b = raw[e * Q8_BLOB:(e + 1) * Q8_BLOB]
- g = q8_values(b[:FF * Q8_ROW_H], FF, H)
- u = q8_values(b[FF * Q8_ROW_H:2 * FF * Q8_ROW_H], FF, H)
- d = q8_values(b[2 * FF * Q8_ROW_H:], H, FF)
- gs_gu = Q.fp4q_global(float(max(np.abs(g).max(), np.abs(u).max())))
- gs_d = Q.fp4q_global(float(np.abs(d).max()))
- err = 0.0
- for x, gs in ((g, gs_gu), (u, gs_gu), (d, gs_d)):
- codes, sc = Q.fp4q_rows(x, gs)
- out.append(C.nvfp4_rows(codes, sc).tobytes())
- v = np.empty(x.shape, np.float32)
- v[:, 0::2] = C.E2M1[codes & 15]
- v[:, 1::2] = C.E2M1[codes >> 4]
- v *= np.repeat(Q.UE4M3[sc], 16, axis=1) * gs
- err += float(((v - x) ** 2).sum()) / max(float((x ** 2).sum()), 1e-30)
- out.append(np.array([gs_gu, gs_gu, gs_d, 0.0], dtype="<f4").tobytes())
- return b"".join(out), err / 3
-
-
-def main() -> None:
- ap = argparse.ArgumentParser()
- ap.add_argument("--pack", required=True)
- ap.add_argument("--out", required=True)
- ap.add_argument("--layers", default="20,21,22,23")
- ap.add_argument("--workers", type=int, default=12)
- a = ap.parse_args()
- if os.path.exists(a.out):
- sys.exit(f"{a.out} existe déjà")
- want = {int(x) for x in a.layers.split(",")}
- m = ModelFile(a.pack)
- lay = [l for l in m.read("experts.layout").decode().splitlines() if l and not l.startswith("#")]
- rows = [tuple(int(x) for x in l.split()) for l in lay] # layer gu d off blob
- eoff, _ = m.section("experts")
- new, off = [], 0
- for l, gu, dt, o, blob in rows:
- if l in want:
- if gu != 8 or blob != Q8_BLOB:
- sys.exit(f"couche {l} : type {gu} blob {blob}, attendu Q8_0 {Q8_BLOB}")
- new.append((l, 40, 40, off, F4_BLOB))
- off += F4_BLOB * NE
- else:
- new.append((l, gu, dt, off, blob))
- off += blob * NE
- total = off
- t0 = time.time()
- errs = []
-
- def experts_chunks(pool):
- for (l, gu, dt, o, blob), nl in zip(rows, new):
- if l not in want:
- left, at = blob * NE, eoff + o
- with open(a.pack, "rb") as f:
- f.seek(at)
- while left:
- b = f.read(min(64 << 20, left))
- left -= len(b)
- yield b
- continue
- jobs = [(a.pack, eoff + o, e, 4) for e in range(0, NE, 4)]
- for b, err in pool.imap(_job, jobs):
- errs.append(err)
- yield b
- print(f"couche {l} : NVFP4, erreur relative moyenne {np.mean(errs[-len(jobs):]):.5f} ({time.time() - t0:.0f} s)", flush=True)
-
- w = ModelWriter(a.out)
- with multiprocessing.Pool(a.workers) as pool:
- for name in m.names():
- so, sz = m.section(name)
- if name == "experts":
- n = w.add_chunks(name, experts_chunks(pool))
- if n != total:
- sys.exit(f"experts : {n} octets, attendu {total}")
- elif name == "experts.layout":
- w.add_bytes(name, S.nvfp4_layout_text(NE, total, new))
- elif name == "meta":
- j = json.loads(m.read("meta"))
- j["name"] = j.get("name", "Inkling 2 Mini")
- j["ajean_requant"] = {"tool": "tools/convert/inkling2_requant.py", "from": os.path.basename(a.pack),
- "layers_nvfp4": sorted(want),
- "method": "Q8_0 -> float32 -> NVFP4 (amax/(6x448) tensor scale, gate/up shared; "
- "UE4M3 per 16 at least squared error)"}
- w.add_bytes(name, json.dumps(j, ensure_ascii=False).encode())
- else:
- w.add_file(name, a.pack, so, sz)
- w.close()
- print(f"écrit {a.out} : experts {total / 2**30:.2f} Gio (avant {sum(r[4] for r in rows) * NE / 2**30:.2f}), {time.time() - t0:.0f} s")
-
-
-if __name__ == "__main__":
- main()
+"""Rewrite an inkling2 pack with its Q8_0 routed experts (layers 20 to 23 of the official pack) as NVFP4.
+
+ python3 tools/convert/inkling2_requant.py --pack IN.basalt --out OUT.basalt [--layers 20,21,22,23] [--workers 12]
+
+Each matrix (gate, up, down) of a Q8_0 expert is dequantized, then rounded to NVFP4 the way hy4flash_bf16.py does it
+(tensor scale amax / (6 x 448), one UE4M3 scale per 16 values picked at least squared error). gate and up share their
+tensor scale, as in the official pack's NVFP4 layers ({s_gu, s_gu, s_d, 0}). Every other section is copied as is.
+Gain: about 1.9 GiB less of experts on the card.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import multiprocessing
+import os
+import pathlib
+import sys
+import time
+
+import numpy as np
+
+HERE = pathlib.Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE))
+sys.path.insert(0, str(HERE.parent))
+import checkpoint as C # noqa: E402
+import checkpoint_qwen35 as Q # noqa: E402
+import model_sections as S # noqa: E402
+from model_file import ModelFile, ModelWriter # noqa: E402
+
+H, FF, NE = 2304, 1152, 128
+Q8_ROW_H = H // 32 * 34 # a Q8_0 row of H values
+Q8_ROW_FF = FF // 32 * 34
+Q8_BLOB = 2 * FF * Q8_ROW_H + H * Q8_ROW_FF
+F4_BLOB = 2 * FF * S.nvfp4_row_bytes(H) + H * S.nvfp4_row_bytes(FF) + S.NVFP4_TAIL
+
+
+def q8_values(raw: bytes, rows: int, cols: int) -> np.ndarray:
+ b = np.frombuffer(raw, np.uint8).reshape(rows * cols // 32, 34)
+ d = b[:, :2].copy().view(np.float16).astype(np.float32)
+ q = b[:, 2:].view(np.int8).astype(np.float32)
+ return (q * d).reshape(rows, cols)
+
+
+def _job(args):
+ path, off, e0, n = args
+ with open(path, "rb") as f:
+ f.seek(off + e0 * Q8_BLOB)
+ raw = f.read(n * Q8_BLOB)
+ out = []
+ for e in range(n):
+ b = raw[e * Q8_BLOB:(e + 1) * Q8_BLOB]
+ g = q8_values(b[:FF * Q8_ROW_H], FF, H)
+ u = q8_values(b[FF * Q8_ROW_H:2 * FF * Q8_ROW_H], FF, H)
+ d = q8_values(b[2 * FF * Q8_ROW_H:], H, FF)
+ gs_gu = Q.fp4q_global(float(max(np.abs(g).max(), np.abs(u).max())))
+ gs_d = Q.fp4q_global(float(np.abs(d).max()))
+ err = 0.0
+ for x, gs in ((g, gs_gu), (u, gs_gu), (d, gs_d)):
+ codes, sc = Q.fp4q_rows(x, gs)
+ out.append(C.nvfp4_rows(codes, sc).tobytes())
+ v = np.empty(x.shape, np.float32)
+ v[:, 0::2] = C.E2M1[codes & 15]
+ v[:, 1::2] = C.E2M1[codes >> 4]
+ v *= np.repeat(Q.UE4M3[sc], 16, axis=1) * gs
+ err += float(((v - x) ** 2).sum()) / max(float((x ** 2).sum()), 1e-30)
+ out.append(np.array([gs_gu, gs_gu, gs_d, 0.0], dtype="<f4").tobytes())
+ return b"".join(out), err / 3
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--pack", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--layers", default="20,21,22,23")
+ ap.add_argument("--workers", type=int, default=12)
+ a = ap.parse_args()
+ if os.path.exists(a.out):
+ sys.exit(f"{a.out} already exists")
+ want = {int(x) for x in a.layers.split(",")}
+ m = ModelFile(a.pack)
+ lay = [l for l in m.read("experts.layout").decode().splitlines() if l and not l.startswith("#")]
+ rows = [tuple(int(x) for x in l.split()) for l in lay] # layer gu d off blob
+ eoff, _ = m.section("experts")
+ new, off = [], 0
+ for l, gu, dt, o, blob in rows:
+ if l in want:
+ if gu != 8 or blob != Q8_BLOB:
+ sys.exit(f"layer {l}: type {gu} blob {blob}, expected Q8_0 {Q8_BLOB}")
+ new.append((l, 40, 40, off, F4_BLOB))
+ off += F4_BLOB * NE
+ else:
+ new.append((l, gu, dt, off, blob))
+ off += blob * NE
+ total = off
+ t0 = time.time()
+ errs = []
+
+ def experts_chunks(pool):
+ for (l, gu, dt, o, blob), nl in zip(rows, new):
+ if l not in want:
+ left, at = blob * NE, eoff + o
+ with open(a.pack, "rb") as f:
+ f.seek(at)
+ while left:
+ b = f.read(min(64 << 20, left))
+ left -= len(b)
+ yield b
+ continue
+ jobs = [(a.pack, eoff + o, e, 4) for e in range(0, NE, 4)]
+ for b, err in pool.imap(_job, jobs):
+ errs.append(err)
+ yield b
+ print(f"layer {l}: NVFP4, mean relative squared error {np.mean(errs[-len(jobs):]):.5f} ({time.time() - t0:.0f} s)", flush=True)
+
+ w = ModelWriter(a.out)
+ with multiprocessing.Pool(a.workers) as pool:
+ for name in m.names():
+ so, sz = m.section(name)
+ if name == "experts":
+ n = w.add_chunks(name, experts_chunks(pool))
+ if n != total:
+ sys.exit(f"experts: {n} bytes, expected {total}")
+ elif name == "experts.layout":
+ w.add_bytes(name, S.nvfp4_layout_text(NE, total, new))
+ elif name == "meta":
+ j = json.loads(m.read("meta"))
+ j["name"] = j.get("name", "Inkling 2 Mini")
+ j["ajean_requant"] = {"tool": "tools/convert/inkling2_requant.py", "from": os.path.basename(a.pack),
+ "layers_nvfp4": sorted(want),
+ "method": "Q8_0 -> float32 -> NVFP4 (amax/(6x448) tensor scale, gate/up shared; "
+ "UE4M3 per 16 at least squared error)"}
+ w.add_bytes(name, json.dumps(j, ensure_ascii=False).encode())
+ else:
+ w.add_file(name, a.pack, so, sz)
+ w.close()
+ print(f"wrote {a.out}: experts {total / 2**30:.2f} GiB (was {sum(r[4] for r in rows) * NE / 2**30:.2f}), {time.time() - t0:.0f} s")
+
+
+if __name__ == "__main__":
+ main()
--
2.43.0
From 2ef97d2bf4ea697b9e0e1a8aacc025693a326896 Mon Sep 17 00:00:00 2001
From: nathaninline <mail@nathaninline.com>
Date: Sun, 22 Nov 2026 17:11:37 +0000
Subject: [PATCH 1/5] AJEAN: Inkling 2 Mini sur une carte de 16 Go
- tools/convert/inkling2_requant.py : experts Q8_0 des couches 20 a 23 du pack officiel en NVFP4 (-1,9 Gio)
- tranches de prompt de 1024 lignes (AJEAN_PROMPT_CHUNK, 4096 en amont) : ~0,7 Gio de tampons en moins
- xq prend la plus grande des deux tailles (les plans FP4 debordaient sous 4096 lignes)
- AJEAN_CARD_SPARE_MIB et AJEAN_SHARED_FIXED_MIB : marges de l estimation reglables (surestimees de ~0,9 Gio sur une 5060 Ti)
- ligne de journal AJEAN budget
---
src/models/inkling2/model.cpp | 20 ++++-
src/models/inkling2/prompt.cpp | 14 +--
src/models/inkling2/prompt.hpp | 7 +-
tools/convert/inkling2_requant.py | 140 ++++++++++++++++++++++++++++++
4 files changed, 172 insertions(+), 9 deletions(-)
create mode 100644 tools/convert/inkling2_requant.py
diff --git a/src/models/inkling2/model.cpp b/src/models/inkling2/model.cpp
index cd1c3a67d..ae273f19c 100644
--- a/src/models/inkling2/model.cpp
+++ b/src/models/inkling2/model.cpp
constexpr uint64_t kQ8Row = (uint64_t) kWidth / 32 * 34; // bytes of a Q8_0 ro
// what the sessions share once (the forward's row buffers and expert scratch, the batch windows' logits), what each one
// needs beside its caches (its logits, its windows' graphs) and what the card keeps free for the kernels' modules and the
// driver
-constexpr uint64_t kSharedFixed = 768 * kMiB;
+// AJEAN: AJEAN_SHARED_FIXED_MIB overrides the shared estimate (768 MiB upstream; about 0.9 GiB above what an RTX 5060 Ti uses)
+uint64_t ajean_shared_fixed() {
+ const char* v = std::getenv("AJEAN_SHARED_FIXED_MIB");
+ const long long m = v && *v ? std::atoll(v) : 768;
+ return (uint64_t) (m < 0 ? 0 : m) * kMiB;
+}
+const uint64_t kSharedFixed = ajean_shared_fixed();
constexpr uint64_t kSessionFixed = 96 * kMiB;
-constexpr uint64_t kCardSpare = 1024 * kMiB;
+// AJEAN: AJEAN_CARD_SPARE_MIB overrides the card spare (1024 MiB upstream); measured unused on an RTX 5060 Ti.
+uint64_t ajean_card_spare() {
+ const char* v = std::getenv("AJEAN_CARD_SPARE_MIB");
+ const long long m = v && *v ? std::atoll(v) : 1024;
+ return (uint64_t) (m < 64 ? 64 : m) * kMiB;
+}
+const uint64_t kCardSpare = ajean_card_spare();
// The fused projection rows of a layer: tensor suffix, first row, rows, needed on a full layer only.
struct ProjPart {
model::Result InklingModel::plan(const model::LoadRequest& req, core::LoadPlan&
uint64_t full = 0;
for (uint64_t st : stride) full += st * (uint64_t) g.n_expert;
const uint64_t want_b = full + bytes_at(want) * n_sess + shared + spare;
+ basalt::log::info("basalt inkling2", "AJEAN budget: free %.0f MiB, experts %.0f, session %.0f x %llu, shared %.0f (prompt %.0f), spare %.0f",
+ (double) free_b / (double) kMiB, (double) full / (double) kMiB, (double) bytes_at(want) / (double) kMiB,
+ (unsigned long long) n_sess, (double) shared / (double) kMiB, (double) prompt_bytes(g) / (double) kMiB,
+ (double) spare / (double) kMiB);
// when some must go: a margin for the tables and maps allocated after the plan and the driver's own rounding
const uint64_t short_b = want_b > free_b ? want_b - free_b + 128 * kMiB : 0;
const int64_t keep = req.expert_cache > 0 ? req.expert_cache : -1;
diff --git a/src/models/inkling2/prompt.cpp b/src/models/inkling2/prompt.cpp
index 049b66a78..2f1889e32 100644
--- a/src/models/inkling2/prompt.cpp
+++ b/src/models/inkling2/prompt.cpp
void carve(Carve& c, Bufs& b, const Geometry& g) {
// the experts' buffers, from the arena's base: the MLP's input (mix, its controller, nrm) is read before any is written
Carve x = c;
x.at = arena;
- b.xq = x.take<uint8_t>(mmq::q8_bytes((int64_t) P, (int64_t) E));
+ // the NVFP4 experts' FP4 planes take xq's place (an NVFP4 layer has no q8_1 rows); AJEAN: with chunks under 4096 rows
+ // the planes' per-expert padding outgrows the q8_1 rows, so xq takes the larger of the two
+ const size_t a4h = fp4::a4_bytes((int64_t) P, 2 * g.n_ff_exp, (int) g.n_expert), a4x = fp4::token_bytes((int64_t) R, 2 * (int64_t) E);
+ const size_t a4h_al = (a4h + 255) / 256 * 256;
+ const size_t xq_bytes = std::max<size_t>(mmq::q8_bytes((int64_t) P, (int64_t) E), a4h_al + a4x);
+ b.xq = x.take<uint8_t>(xq_bytes);
b.gu = x.take<float>(P * 2 * (size_t) g.n_ff_exp);
b.h = x.take<float>(P * (size_t) g.n_ff_exp);
b.moe = b.h;
- // the NVFP4 experts' FP4 planes take xq's place (an NVFP4 layer has no q8_1 rows)
- const size_t a4h = fp4::a4_bytes((int64_t) P, 2 * g.n_ff_exp, (int) g.n_expert), a4x = fp4::token_bytes((int64_t) R, 2 * (int64_t) E);
- if (a4h + 256 + a4x > mmq::q8_bytes((int64_t) P, (int64_t) E)) throw std::logic_error("inkling2 prompt: the FP4 planes outgrow xq");
b.a4h = b.xq;
- b.a4x = b.xq ? (uint8_t*) b.xq + ((a4h + 255) & ~(size_t) 255) : nullptr;
+ b.a4x = b.xq ? (uint8_t*) b.xq + a4h_al : nullptr;
// the experts' input rows are rounded from nrm while it is read, so they end before it
- if (c.base && (uint8_t*) b.xq + mmq::q8_bytes((int64_t) P, (int64_t) E) > (uint8_t*) b.nrm)
+ if (c.base && (uint8_t*) b.xq + xq_bytes > (uint8_t*) b.nrm)
throw std::logic_error("inkling2 prompt: the experts' input rows overlap the MLP's normed rows");
c.at = std::max(end_a, x.at);
b.xqd = c.take<uint8_t>(mmq::q8_bytes((int64_t) R, std::max<int64_t>((int64_t) E, kOut)));
diff --git a/src/models/inkling2/prompt.hpp b/src/models/inkling2/prompt.hpp
index 03de6ca86..bda6b5e8c 100644
--- a/src/models/inkling2/prompt.hpp
+++ b/src/models/inkling2/prompt.hpp
namespace basalt::models::inkling2 {
class DsparkHook;
/// The most rows one prompt chunk runs (the drafter's tap holds as many).
-constexpr int kPromptChunk = 4096;
+// AJEAN: 1024 rows by default (4096 upstream): the chunk scratch drops from ~1 GiB to ~0.25 GiB, so a 16 GB card keeps
+// every expert; -DAJEAN_PROMPT_CHUNK=4096 restores upstream.
+#ifndef AJEAN_PROMPT_CHUNK
+#define AJEAN_PROMPT_CHUNK 1024