Files
Strata/engine/src/ling32/ling32_main.cpp
T
Niko1221 dc10bc0a03 ling32 tier store: adaptive warm RAM tier on by default for the Windows iGPU plain decode
The adaptive warm tier (decayed use counts, promotion of SSD-resident experts from the ring into spare
RAM-tier slots, quarantined demotion) is now on by default where the RAM tier is read in place
(zero-copy, Windows iGPU).  Spare slots 8 per size class, quarantine 24, queue 16; knobs
STRATA_L32_AD_Q / AD_SPARE / AD_QUAR; STRATA_L32_ADAPT=0 / 1 still overrides.

It is only used for single-token decode: promotion and use counting are skipped for MTP verify
batches, and main sets StoreOptions::adaptive_default = false when --mtp is given (the first
default-on build cost -10 % with MTP: the copies and the spare slots taken from the warm prefix
buy nothing there).  Drop-reason counters (ring slot gone / no spare / not hotter / queue full)
are printed with the PF_COV statistics.

Strix Halo (gfx1151), 48 short prompts, greedy ids identical to the switched-off runs in every arm:
plain 23.6 tok/s vs 22.9-23.0 off (+2.6 %, SSD wait 45 s vs 55 s); MTP default 31.2 vs 31.4 off
(parity, ids identical).
2026-12-01 22:06:23 +01:00

1437 lines
88 KiB
C++

// src/ling32/ling32_main.cpp - strata-ling32: the Ling-3.2-Air (.strata v1.1) runner (CUDA, Mode A: everything resident).
//
// strata-ling32 --info FILE.strata config, layer kinds, sections, tensor counts
// strata-ling32 --selfcheck FILE.strata Section 5 golden vectors (codecs + FWHT-128), the start-up check
// strata-ling32 --export-tokenizer FILE.strata DIR DIR/tokenizer.hf.json, DIR/chat_template.jinja, DIR/ling32_tokens.json
// (text <-> ids is the Python side's job, as for Hy4: terminal/tools/ling32_tokenizer.py)
// strata-ling32 --model FILE.strata (--ids 1,2,3 | --tokens ids.txt) [--gen N] [options] prefill + generate, token ids in / out
// strata-ling32 --model FILE.strata --jobs jobs.jsonl --out DIR [options] the golden-set run (one model load, many prompts)
//
// options: --act f32|q8 (default f32) --clamp after|before (default after silu, as upstream) --ctx N --chunk N --device N --lookahead
// --temp T --top-p P --top-k K --seed S (default greedy) --stop ID (repeatable; default 156895 156892) --no-selfcheck
// jobs: one JSON object per line {"id": "p01", "prompt_ids": [..], "cont_ids": [..], "gen": 128, "tf": 64}: teacher-forced top-K per position for
// prompt + the first `tf` of cont_ids (decode steps one token at a time) and the greedy continuation, written to DIR/<id>.tf.bin / <id>.gen.json.
#include "strata/ling32/ling32_file.hpp"
#include "strata/ling32/ling32_selfcheck.hpp"
#include "strata/ling32/ling32_vision.hpp"
#include "strata/ling32/ling32_tier_planner.hpp"
#ifdef LING32_HAVE_CUDA
#include "ling32_engine.hpp"
#include "ling32_tier_store.hpp"
#include "ling32_serve.hpp"
#include "ling32_vision_run.hpp"
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#endif
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#endif
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <functional>
#include <numeric>
#include <random>
#include <sstream>
#include <string>
#include <memory>
#include <thread>
using namespace strata::ling32;
namespace {
bool write_text(const std::filesystem::path& p, const std::string& s) {
std::ofstream f(p, std::ios::binary);
f.write(s.data(), static_cast<std::streamsize>(s.size()));
return static_cast<bool>(f);
}
double now_s() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
int cmd_info(const std::string& file) {
Ling32File f;
std::string err;
if (!f.open(file, err, false)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
const Cfg& c = f.cfg();
int mla = 0;
for (int il = 0; il < c.n_layers; ++il) mla += c.is_mla(il);
std::printf("Ling-3.2-Air %s\n", file.c_str());
std::printf(" layers %d (%d KDA + %d MLA), %d dense + %d MoE, hidden %d, vocab %d, heads %d x %d\n", c.n_layers, c.n_layers - mla, mla, c.first_k_dense, c.n_moe(), c.D, c.V, c.H, c.hd);
std::printf(" MoE: %d experts, top-%d of %d groups x %d, inter %d, shared %d, scale %.2f; MLA: kv_lora %d nope %d rope %d v %d theta %.0f\n", c.n_exp, c.top_k, c.n_group, c.n_exp / c.n_group,
c.I_moe, c.I_shared, c.routed_scale, c.kv_lora, c.nope, c.rope, c.vhead, c.rope_theta);
for (int i = 0; i < 6; ++i) {
const auto& s = f.reader().header().sections[i];
std::printf(" section %d: offset %llu, %llu B\n", i, static_cast<unsigned long long>(s.file_offset), static_cast<unsigned long long>(s.byte_length));
}
std::printf(" trunk tensors %zu, Section 2 tensors %zu, expert slabs %zu\n", f.man().trunk.size(), f.man().sec2.size(), f.reader().expert_directory().size());
std::string derr;
std::printf(" Section 3 directory vs manifest: %s\n", f.validate_directory(derr) ? "ok" : derr.c_str());
return 0;
}
// one key=value line for the launcher: arch=ling32 layers=42 vocab=157184 drafter=none mtp=1 images=0 tiers=A,B,C
int cmd_info_kv(const std::string& file) {
Ling32File f;
std::string err;
if (!f.open(file, err, false)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::printf("arch=ling32 layers=%d vocab=%d drafter=none mtp=1 images=1 tiers=A,B,C\n", f.cfg().n_layers, f.cfg().V); // mtp=1: this engine takes --mtp FILE --spec mtp
return 0;
}
int cmd_selfcheck(const std::string& file) {
Ling32File f;
std::string err;
if (!f.open(file, err, false)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
const SelfcheckResult r = verify_section5_selfcheck(f);
for (const auto& rec : r.records) {
if (rec.skipped) { std::printf(" code %d: no decoder in this engine (skipped)\n", rec.code_id); continue; }
std::printf(" code %d: %zu weights, fp16 mismatches %zu (+%zu one step off), dot err %.2e, fwht dot err %.2e (Q8_1 activation path %.2e / %.2e)\n", rec.code_id, rec.n, rec.dec_mismatch, rec.dec_ulp1, rec.err_dot,
rec.err_dot_fwht, rec.err_q8_dot, rec.err_q8_fwht);
}
std::printf("Section 5 self-check: %s (max relative error %.2e)%s%s\n", r.ok ? "PASS" : "FAIL", r.max_rel_err, r.error.empty() ? "" : ": ", r.error.c_str());
return r.ok ? 0 : 1;
}
int cmd_export_tokenizer(const std::string& file, const std::string& dir) {
Ling32File f;
std::string err;
if (!f.open(file, err, true)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::error_code ec;
std::filesystem::create_directories(dir, ec);
const std::filesystem::path d(dir);
if (f.man().tokenizer_json.empty() || f.man().chat_template.empty()) {
std::fprintf(stderr, "strata-ling32: this file's Section 0 has no tokenizer_json / chat_template\n");
return 1;
}
char tok[256];
std::snprintf(tok, sizeof tok, "{\"eos\":[%d,156892],\"pad\":%d,\"sampling\":{\"temperature\":0.6,\"top_p\":0.95,\"top_k\":20,\"repetition_penalty\":1.0}}\n", f.cfg().eos_id, f.cfg().pad_id);
if (!write_text(d / "tokenizer.hf.json", f.man().tokenizer_json) || !write_text(d / "chat_template.jinja", f.man().chat_template) || !write_text(d / "ling32_tokens.json", tok)) {
std::fprintf(stderr, "strata-ling32: cannot write into %s\n", dir.c_str());
return 1;
}
std::printf("tokenizer: %zu bytes, chat template: %zu bytes\n", f.man().tokenizer_json.size(), f.man().chat_template.size());
return 0;
}
// ------------------------------------------------------------------------------------------------ the run
struct RunOpts {
std::string model, ids_csv, tokens_file, jobs, out;
bool serve = false; // --serve: the engine line protocol on stdin / stdout (ling32_serve.hpp)
int gen = 0, ctx = 8192, chunk = 0, device = 0, topk = 64; // chunk 0 = by the card (2048 from 30 GiB, else 1024; AMD: at most 1024)
bool act_q8 = false, clamp_after = true, lookahead = false, selfcheck = true;
float temp = 0, top_p = 1.0f;
int top_k = 0;
uint64_t seed = 1;
std::vector<int> stop = {156895, 156892};
std::string lookahead_json;
bool kda_seq = false; // --kda seq: the sequential recurrence for prompts too
bool profile = false; // --profile: GPU time per section
int tc_min_n = 16; // --tc N (0 = off): trunk projections of batches of >= N tokens on the tensor cores (exact integer weights, group-scaled hi/lo activations)
bool graph = true; // CUDA graph per step (--no-graph)
bool no_dual = false; // --no-dual
bool fuse_router = true; // --no-fuse-router
bool kda_par = true; // --no-kda-par
bool pdl = false; // --pdl
bool fuse_experts = false; // --fuse-experts (bit-identical but 2 % slower than the three kernels on GB10 and A4000-class decode: off)
bool s8_packed = true; // --no-s8-packed
int invariance = 0; // --invariance K: the last K ids as K single-token steps against one K-token batch: are the logits bit-identical?
int tc_mode = 2; // --tc-mode N: tensor-core precision (bit 0: three-term split, bit 1: fresh accumulator per MMA); 2 measured best on the real model
bool moe_q8 = false; // --moe-q8
int tc_moe_min_n = 128; // --tc-moe N (0 = off): routed experts of batches of >= N tokens grouped by expert on the tensor cores
bool map_experts = false; // --map-experts: read the slabs from the mapped file (unified memory)
bool lock_mapped = false; // --lock-mapped
// memory tiers (P2): --tier auto|vram|hybrid|nvme, --vram-budget-gib, --ram-budget-gib, --turbo-ssd, --prefetch on|off, --prefetch-width, --io-qd, --miss zc|stage
bool coverage = false; // --coverage: tier runs measure how well BOTH lookahead predictors (k = 2, 4) cover the true top-8 (counters of the store), without prefetching from the second one
float turbo_threshold = 0.90f; // --turbo-ssd-threshold
int cpu_coexec = 0, cpu_threads = 0; // --cpu-coexec N: up to N cold experts per decode layer on the CPU (bit-identical arithmetic), --cpu-threads T
bool fast_jobs = false; // --fast-jobs: jobs mode with last-position logits only (speed and identity runs)
std::string tier = "auto";
double vram_budget_gib = 0, ram_budget_gib = 0, hw_vram_gib = 0, hw_ram_gib = 0;
bool turbo_ssd = false, prefetch = true, miss_stage = true, miss_explicit = false, plan_table = false, plan_only = false; // miss_stage: misses are DMA-copied into a card slot (measured 3x faster than reading them in place)
int prefetch_width = -1, io_qd = 16, prefill_budget = 192;
int force_vram_ranks = -1, force_ram_ranks = -1, force_dyn = -1, force_ring = -1; // tests: choose the split by hand (--force-vram-ranks / -ram-ranks / -dyn-slots / -ring-slots)
bool la_nomask = false; // --la-nomask: lookahead ranking without the group mask
int mla_prefill_kernel = -1; // --mla-prefill off|simt|tc|tcfast: the MLA kernel of prefill chunks (default: by the device, default_mla_prefill_kernel(): tc where the mma kernel is built and sm_80+, else simt)
int mla_kernel = 1; // --mla-kernel old|simt|tc|tcfast (default simt: Strata's multi-head latent-attention kernel, fp32)
bool latent_f16 = false; // --latent f16 (default f32)
std::string configs = "base"; // jobs mode: engine variants, one after the other in this process (base, lat32, rope32, chunkN, before; joined with +)
std::string layers_for; // jobs mode: ids (comma list) whose per-layer residual at the last prompt position is written (<id>.layers.f32)
std::string layer_out; // --layer-out FILE: the residual after every layer at the last prompt position (float32 [layers][D]), for bisecting against the golden's layer_out_last
VisionRunOpts vis; // --vision FILE --image F [--image G ...] --vision-device auto|cpu|gpu --vision-idle S --vision-threads N --newline-id N (pictures: the prompt's <|image_pad|> placeholders)
double vision_hold = 0; // --vision-hold S: after generating, wait S seconds and report the GPU memory (shows the idle unload of the GPU encoder)
std::string vision_dump; // --vision-dump FILE: the picture embeddings (float32 [rows][2560], all pictures) are written there
std::string mm_runs; // --mm-runs FILE: many prompts (with or without pictures) in one process, see run_mm_batch
// speculative decoding (MTP drafting)
bool spec = false; // --spec mtp
bool spec_mtp = false; // --spec mtp: the MTP layer of the sidecar (--mtp FILE) drafts
std::string mtp_file; // --mtp FILE: Ling-3.2-Air-MTP.strata
bool spec_block_set = false;
int spec_block = 8; // --spec-block N: slots drafted per cycle (<= 8)
bool spec_adaptive = false; // --spec-adaptive: the guide's EMA controller picks K_max (0..--spec-block) per cycle
std::string spec_sweep; // --spec-sweep "tap=in;tap=out,ctx=0;...": with --genjobs, one run of the job file per entry in this process (keys: tap, ctx, cut, rerank, block, temp, label)
std::string spec_oracle; // --spec-oracle FILE: replace the drafts by the tokens of a baseline continuation (ids in FILE), each corrupted with probability --spec-oracle-err (test of the accept / rollback paths)
float spec_oracle_err = 0.3f;
bool hidden_decode = false; // --hidden-decode (with --dump-hidden-jobs): the continuation rows go through the one-token decode path
std::string hidden_jobs; // --dump-hidden-jobs FILE --out DIR: for every {"id","prompt_ids"[,"cont_ids"]} line the sequence prompt ++ cont: DIR/<id>.hpre.f32 [n][D] (residual after the last layer), .hfin.f32 [n][D] (after the final norm), .ids.i32; no drafter needed
std::string genjobs; // --genjobs FILE: {"id","prompt_ids","gen"} per line: greedy / sampled continuation only (no teacher-forced pass), spec on or off
int dist_n = 0, dist_len = 4; // --dist-test N [--dist-len L]: N sampled continuations of the first prompt, histogram of the first L tokens
};
std::vector<int> parse_ids(const std::string& s) {
std::vector<int> v;
std::string t;
for (char ch : s + ",") {
if ((ch >= '0' && ch <= '9') || ch == '-') t += ch;
else if (!t.empty()) { v.push_back(std::atoi(t.c_str())); t.clear(); }
}
return v;
}
// ------------------------------------------------------------------------------------------------ the memory-tier plan
// ---- device defaults (the same rule for every backend; each flag stays an override)
// MLA kernel of prefill chunks: the tensor-core kernel (mma.sync, hi/lo split) exists for NVIDIA sm_80+ only; on AMD (and on older cards) the scalar fp32 kernel serves.
int default_mla_prefill_kernel(int device) {
#if defined(STRATA_USE_HIP)
(void)device;
return 1;
#else
int major = 0;
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, device);
cudaGetLastError();
return major >= 8 ? 2 : 1;
#endif
}
// Prefill chunk (tokens per forward): by the card's memory as before (the grouped-expert tiles fill better the more tokens a chunk holds, the activations cost ~0.6 MB per token), but never
// more than the scratch of the AMD WMMA kernels is sized for (1024 tokens, ling32_wmma2.inc / w2_reserve) and, on a Windows integrated GPU, never more than the real allocatable memory
// allows: the runtime reports 108 GiB there while a process can allocate about 63 (the planner probes the cap; here the visible size is not trusted).
int default_prefill_chunk(int device) {
cudaDeviceProp dp{};
double gib = 24.0;
if (cudaGetDeviceProperties(&dp, device) == cudaSuccess) gib = static_cast<double>(dp.totalGlobalMem) / 1073741824.0;
cudaGetLastError();
int chunk = gib >= 70.0 ? 4096 : gib >= 30.0 ? 2048 : 1024; // measured on the PRO 6000: 4096 prefills ~5 % faster than 2048 (the expert weights are streamed once per chunk) at twice the activation memory
#if defined(STRATA_USE_HIP)
chunk = std::min(chunk, 1024);
#endif
return chunk;
}
uint64_t host_ram_available() {
#if defined(_WIN32)
MEMORYSTATUSEX ms;
ms.dwLength = sizeof ms;
return GlobalMemoryStatusEx(&ms) ? static_cast<uint64_t>(ms.ullAvailPhys) : 0;
#else
if (FILE* mi = std::fopen("/proc/meminfo", "r")) {
char line[256];
unsigned long long kb = 0;
while (std::fgets(line, sizeof line, mi))
if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) break;
std::fclose(mi);
return static_cast<uint64_t>(kb) * 1024ull;
}
return 0;
#endif
}
// Windows (HIP) integrated GPU: a process can allocate only part of the memory the runtime reports (about 63 GiB of 108 on Strix Halo), and hipMalloc and hipHostMalloc draw from the SAME cap.
// Probe it: 1 GiB pieces until the allocation fails (a few seconds at most), everything freed again. Pageable pages registered with the driver (hipHostRegister) are not counted.
uint64_t probe_gpu_alloc_cap(int device) {
cudaSetDevice(device);
std::vector<void*> v;
constexpr size_t kGiB = 1ull << 30;
for (int i = 0; i < 512; ++i) {
void* p = nullptr;
if (cudaMalloc(&p, kGiB) != cudaSuccess) { cudaGetLastError(); break; }
v.push_back(p);
}
for (void* p : v) cudaFree(p);
return static_cast<uint64_t>(v.size()) * kGiB;
}
constexpr double kGiB = 1073741824.0;
// Linux: a "Key: N kB" line of /proc/meminfo or /proc/self/status
long long proc_kb(const char* path, const char* key) {
#if defined(__linux__)
if (FILE* f = std::fopen(path, "r")) {
char line[256];
const size_t kl = std::strlen(key);
long long kb = -1;
while (std::fgets(line, sizeof line, f))
if (!std::strncmp(line, key, kl) && line[kl] == ':') { kb = std::atoll(line + kl + 1); break; }
std::fclose(f);
return kb;
}
#else
(void)path; (void)key;
#endif
return -1;
}
long long g_cached0_kb = -1; // page cache (Cached) when the tier store was ready
std::string host_mem_line() {
char b[400];
const long long cached = proc_kb("/proc/meminfo", "Cached");
std::snprintf(b, sizeof b, "host memory: RSS %.2f GiB (peak %.2f), locked %.2f GiB, page cache (Cached) %.2f GiB%s", proc_kb("/proc/self/status", "VmRSS") / 1048576.0, proc_kb("/proc/self/status", "VmHWM") / 1048576.0,
proc_kb("/proc/self/status", "VmLck") / 1048576.0, cached / 1048576.0,
(g_cached0_kb >= 0 && cached >= 0) ? (std::string(", change since the store was ready ") + std::to_string((cached - g_cached0_kb) / 1024) + " MiB").c_str() : "");
return b;
}
TierRequestOpts make_request(const RunOpts& o) {
TierRequestOpts rq;
rq.tier = o.tier == "vram" ? TierRequest::Vram : o.tier == "hybrid" ? TierRequest::Hybrid : o.tier == "nvme" ? TierRequest::Nvme : TierRequest::Auto;
rq.vram_budget = static_cast<uint64_t>(o.vram_budget_gib * kGiB);
rq.ram_budget = static_cast<uint64_t>(o.ram_budget_gib * kGiB);
rq.turbo_ssd = o.turbo_ssd;
rq.prefetch = o.prefetch;
rq.prefetch_width = o.prefetch_width;
rq.io_qd = o.io_qd;
return rq;
}
// What the engine needs on the card besides the slabs: the trunk (Section 1 without the drafter and the sq.* tables, plus the MLA split), the latent cache, the chunk.
TierSizes make_sizes(const Ling32File& f, const RunOpts& o) {
TierSizes sz;
uint64_t trunk = 0;
for (const auto& kv : f.man().trunk) {
if (kv.first.rfind("model.dfly.", 0) == 0 || kv.first.rfind("sq.", 0) == 0) continue;
trunk += kv.second.bytes;
}
sz.trunk_bytes = trunk + 56ull * 1048576ull;
sz.lookahead_bytes = static_cast<uint64_t>(51.25 * 1048576.0);
sz.latent_bytes = static_cast<uint64_t>(o.ctx) * 7 * 576 * 4;
sz.chunk = o.chunk;
sz.vocab = f.cfg().V;
sz.hidden = f.cfg().D;
return sz;
}
bool make_plan(const Ling32File& f, const RunOpts& o, uint64_t vram_free, uint64_t ram_avail, TierPlan& plan, RankTable& rt, std::string& err) {
const auto& dir = f.reader().expert_directory();
if (!build_rank_table(dir.data(), dir.size(), f.cfg().n_exp, rt, err)) return false;
TierHardware hw;
hw.vram_bytes = vram_free;
hw.ram_bytes = ram_avail;
plan = plan_tier(hw, make_request(o), rt, make_sizes(f, o));
if (!plan.ok) { err = plan.error; return false; }
if (o.force_vram_ranks >= 0 || o.force_ram_ranks >= 0 || o.force_dyn >= 0 || o.force_ring >= 0) { // tests and experiments: choose the split by hand
const int vr = o.force_vram_ranks >= 0 ? std::min(o.force_vram_ranks, rt.n_exp) : plan.vram_ranks;
const int rr = o.force_ram_ranks >= 0 ? std::min(o.force_ram_ranks, rt.n_exp - vr) : (plan.mode == TierMode::C ? plan.ram_ranks : rt.n_exp - vr);
plan.vram_ranks = vr;
plan.ram_ranks = rr;
plan.vram_prefix_bytes = rt.bytes_of_ranks(vr);
plan.ram_prefix_bytes = rt.bytes_of_ranks(vr + rr) - plan.vram_prefix_bytes;
plan.ssd_bytes = rt.total - plan.vram_prefix_bytes - plan.ram_prefix_bytes;
plan.mode = vr >= rt.n_exp ? TierMode::A : plan.ssd_bytes == 0 ? TierMode::B : TierMode::C;
plan.lookahead_k = plan.mode == TierMode::A ? 0 : 4;
plan.prefetch = plan.mode != TierMode::A && o.prefetch;
if (o.prefetch_width < 0) plan.prefetch_width = 4;
if (o.force_dyn >= 0) plan.dyn_slots = o.force_dyn;
else if (plan.dyn_slots < 24) plan.dyn_slots = 24;
plan.slot_bytes = rt.max_slab;
plan.dyn_bytes = static_cast<uint64_t>(plan.dyn_slots) * rt.max_slab;
plan.ring_slots = plan.mode == TierMode::C ? (o.force_ring >= 0 ? o.force_ring : std::max(plan.ring_slots, 40)) : 0;
plan.ring_bytes = static_cast<uint64_t>(plan.ring_slots) * rt.max_slab;
plan.notes.push_back("the split was forced by --force-* options");
}
return true;
}
// strata-ling32 --plan FILE [--tier ..] [--vram-budget-gib N] [--ram-budget-gib N] [--hw-vram-gib N --hw-ram-gib N | --plan-table]: what the planner would do
int cmd_plan(const RunOpts& o) {
std::string err;
Ling32File f;
if (!f.open(o.model, err, false)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
const auto& dir = f.reader().expert_directory();
RankTable rt;
if (!build_rank_table(dir.data(), dir.size(), f.cfg().n_exp, rt, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::printf("Section 4: %.2f GiB, %d ranks x %d layers, slab %.2f..%.2f MiB; ranks are %.1f..%.1f MiB per layer-set (rank 0 %.1f, rank 511 %.1f)\n", rt.total / kGiB, rt.n_exp, rt.n_moe,
rt.min_slab / 1048576.0, rt.max_slab / 1048576.0, (rt.prefix[1] - rt.prefix[0]) / 1048576.0, (rt.prefix[rt.n_exp] - rt.prefix[rt.n_exp - 1]) / 1048576.0,
(rt.prefix[1] - rt.prefix[0]) / 1048576.0, (rt.prefix[rt.n_exp] - rt.prefix[rt.n_exp - 1]) / 1048576.0);
for (int r : {1, 23, 50, 71, 125, 178, 256, 512}) std::printf(" prefix of %3d ranks: %7.3f GiB\n", r, rt.bytes_of_ranks(r) / kGiB);
const TierSizes sz = make_sizes(f, o);
std::printf("engine sizes: trunk %.2f GiB, latent cache %.0f MiB (ctx %d), chunk %d\n", sz.trunk_bytes / kGiB, sz.latent_bytes / 1048576.0, o.ctx, o.chunk);
auto show = [&](double vg, double rg, const RunOpts& oo) {
TierHardware hw;
hw.vram_bytes = static_cast<uint64_t>(vg * kGiB);
hw.ram_bytes = static_cast<uint64_t>(rg * kGiB);
const TierPlan p = plan_tier(hw, make_request(oo), rt, make_sizes(f, oo));
std::printf(" card %5.1f GiB + RAM %6.1f GiB: %s\n", vg, rg, p.describe().c_str());
for (const auto& n : p.notes) std::printf(" note: %s\n", n.c_str());
};
if (o.plan_table) {
for (double vg : {8.0, 12.0, 16.0, 24.0, 32.0, 48.0, 96.0})
for (double rg : {16.0, 32.0, 64.0, 128.0}) show(vg, rg, o);
} else {
show(o.hw_vram_gib > 0 ? o.hw_vram_gib : 24.0, o.hw_ram_gib > 0 ? o.hw_ram_gib : static_cast<double>(host_ram_available()) / kGiB, o);
}
return 0;
}
struct Sampler {
const RunOpts& o;
std::mt19937_64 rng;
explicit Sampler(const RunOpts& op) : o(op), rng(op.seed) {}
int pick(const float* lg, int V) {
if (o.temp <= 0) return static_cast<int>(std::max_element(lg, lg + V) - lg);
std::vector<int> idx(V);
std::iota(idx.begin(), idx.end(), 0);
const int k = o.top_k > 0 ? std::min(o.top_k, V) : V;
std::partial_sort(idx.begin(), idx.begin() + k, idx.end(), [&](int a, int b) { return lg[a] > lg[b]; });
std::vector<double> p(k);
const double mx = lg[idx[0]];
double z = 0;
for (int i = 0; i < k; ++i) { p[i] = std::exp((lg[idx[i]] - mx) / o.temp); z += p[i]; }
double acc = 0;
int cut = k;
for (int i = 0; i < k; ++i) { acc += p[i] / z; if (acc >= o.top_p) { cut = i + 1; break; } }
double zc = 0;
for (int i = 0; i < cut; ++i) zc += p[i];
double r = std::uniform_real_distribution<double>(0, zc)(rng);
for (int i = 0; i < cut; ++i) { r -= p[i]; if (r <= 0) return idx[i]; }
return idx[cut - 1];
}
};
bool is_stop(const RunOpts& o, int t) { return std::find(o.stop.begin(), o.stop.end(), t) != o.stop.end(); }
#ifdef LING32_HAVE_CUDA
// prefill `ids` in chunks; the logits of the last token (and all of them when `all` is given)
bool prefill(Ling32Engine& E, const RunOpts& o, const std::vector<int>& ids, std::vector<float>* all, std::vector<float>* last, std::string& err) {
const int V = E.model().cfg.V;
for (size_t t0 = 0; t0 < ids.size(); t0 += o.chunk) {
const int n = static_cast<int>(std::min<size_t>(o.chunk, ids.size() - t0));
std::vector<float> lg;
const bool is_last = t0 + n >= ids.size();
if (!E.forward(ids.data() + t0, n, all ? n : (is_last ? 1 : 0), (all || is_last) ? &lg : nullptr, err)) return false;
if (all) all->insert(all->end(), lg.begin(), lg.end());
else if (is_last && last) last->assign(lg.end() - V, lg.end());
}
if (all && last && !all->empty()) last->assign(all->end() - V, all->end());
return true;
}
// prefill `ids` in chunks, handing the logits of every position (rows of V floats) to `sink` chunk by chunk, so a long prompt never holds them all
bool prefill_rows(Ling32Engine& E, const RunOpts& o, const std::vector<int>& ids, const std::function<void(const float*, int)>& sink, std::string& err) {
for (size_t t0 = 0; t0 < ids.size(); t0 += o.chunk) {
const int n = static_cast<int>(std::min<size_t>(o.chunk, ids.size() - t0));
std::vector<float> lg;
if (!E.forward(ids.data() + t0, n, n, &lg, err)) return false;
sink(lg.data(), n);
}
return true;
}
void top_k_row(const float* lg, int V, int K, int* ids, float* vals, float* lse) {
std::vector<int> idx(V);
std::iota(idx.begin(), idx.end(), 0);
std::partial_sort(idx.begin(), idx.begin() + K, idx.end(), [&](int a, int b) { return lg[a] > lg[b] || (lg[a] == lg[b] && a < b); });
double mx = lg[idx[0]], z = 0;
for (int v = 0; v < V; ++v) z += std::exp(static_cast<double>(lg[v]) - mx);
*lse = static_cast<float>(mx + std::log(z));
for (int i = 0; i < K; ++i) { ids[i] = idx[i]; vals[i] = lg[idx[i]]; }
}
void print_lookahead(const Ling32Engine& E, const Cfg& c, const std::string& json_path) {
const LookaheadStats& s = E.lookahead_stats();
std::ostringstream js;
js << "{\"top_k\":[8,10,16,24],\"budgets\":[16,24,32,48,64],\"layers\":[";
double tot_hit[2][4] = {}, tot_mass[2][4] = {}, tot_u[2][5] = {};
int64_t tot_tok[2] = {}, tot_b[2] = {};
bool first = true;
std::printf("lookahead coverage (Mode A: predicted vs the true top-%d of the layer; per token, mean over the run)\n", c.top_k);
std::printf(" layer | k=2 hit@8 @10 @16 @24 | mass@8 @10 @16 @24 | k=4 hit@8 @10 @16 @24 | mass@8 @10 @16 @24\n");
for (int il = c.first_k_dense; il < c.n_layers; ++il) {
std::printf(" %5d |", il);
for (int ki = 0; ki < 2; ++ki) {
const auto& cell = s.cell[static_cast<size_t>(il) * 2 + ki];
if (!cell.tokens) { std::printf(" (none) | |"); continue; }
for (int q = 0; q < 4; ++q) std::printf(" %.2f", cell.hit[q] / cell.tokens);
std::printf(" |");
for (int q = 0; q < 4; ++q) std::printf(" %.2f", cell.mass[q] / cell.tokens);
std::printf(" |");
for (int q = 0; q < 4; ++q) { tot_hit[ki][q] += cell.hit[q]; tot_mass[ki][q] += cell.mass[q]; }
for (int q = 0; q < 5; ++q) tot_u[ki][q] += cell.union_recall[q];
tot_tok[ki] += cell.tokens;
tot_b[ki] += cell.batches;
js << (first ? "" : ",") << "{\"layer\":" << il << ",\"k\":" << (ki ? 4 : 2) << ",\"tokens\":" << cell.tokens << ",\"hit\":[";
first = false;
for (int q = 0; q < 4; ++q) js << (q ? "," : "") << cell.hit[q] / cell.tokens;
js << "],\"mass\":[";
for (int q = 0; q < 4; ++q) js << (q ? "," : "") << cell.mass[q] / cell.tokens;
js << "],\"union_recall\":[";
for (int q = 0; q < 5; ++q) js << (q ? "," : "") << cell.union_recall[q] / std::max<int64_t>(1, cell.batches);
js << "]}";
}
std::printf("\n");
}
js << "],\"mean\":{";
for (int ki = 0; ki < 2; ++ki) {
if (!tot_tok[ki]) continue;
std::printf(" mean k=%d: hit@8/10/16/24 =", ki ? 4 : 2);
js << (ki ? ",\"k4\":{" : "\"k2\":{") << "\"hit\":[";
for (int q = 0; q < 4; ++q) { std::printf(" %.3f", tot_hit[ki][q] / tot_tok[ki]); js << (q ? "," : "") << tot_hit[ki][q] / tot_tok[ki]; }
std::printf(" mass =");
js << "],\"mass\":[";
for (int q = 0; q < 4; ++q) { std::printf(" %.3f", tot_mass[ki][q] / tot_tok[ki]); js << (q ? "," : "") << tot_mass[ki][q] / tot_tok[ki]; }
std::printf(" union recall@16/24/32/48/64 =");
js << "],\"union_recall\":[";
for (int q = 0; q < 5; ++q) { std::printf(" %.3f", tot_u[ki][q] / std::max<int64_t>(1, tot_b[ki])); js << (q ? "," : "") << tot_u[ki][q] / std::max<int64_t>(1, tot_b[ki]); }
std::printf("\n");
js << "]}";
}
js << "}}\n";
if (!json_path.empty()) write_text(json_path, js.str());
}
// speculative generation: first token + cycles until `gen` tokens or a stop token (tokens past the stop are dropped, like the baseline loop)
bool spec_generate(Ling32Engine& E, const RunOpts& o, const std::vector<int>& prompt, int gen, std::vector<int>& out, double& t_prefill, double& t_gen, std::string& err) {
out.clear();
std::vector<int> oracle;
std::mt19937 orng(12345);
if (!o.spec_oracle.empty()) {
std::ifstream of(o.spec_oracle);
std::stringstream ss;
ss << of.rdbuf();
oracle = parse_ids(ss.str());
E.spec_inject = [&](int n, std::vector<int>& d) {
for (int j = 0; j < n; ++j) {
const size_t at = out.size() + j; // d_j predicts output position out.size() + j
const bool bad = at >= oracle.size() || std::uniform_real_distribution<float>(0, 1)(orng) < o.spec_oracle_err;
d[j] = bad ? static_cast<int>(orng() % 400) + 10 : oracle[at];
}
};
}
const double t0 = now_s();
int first = 0;
if (!E.spec_start(prompt.data(), static_cast<int>(prompt.size()), o.chunk, first, err)) return false;
t_prefill = now_s() - t0;
const double t1 = now_s();
if (gen > 0) out.push_back(first);
bool done = gen <= 1 || is_stop(o, first);
std::vector<int> com;
while (!done) {
if (!E.spec_cycle(com, err)) return false;
for (int t : com) {
out.push_back(t);
if (is_stop(o, t) || static_cast<int>(out.size()) >= gen) { done = true; break; }
}
}
t_gen = now_s() - t1;
E.spec_inject = nullptr;
return true;
}
void print_spec_stats(const SpecStats& s, double t_gen, size_t ntok) {
std::printf("spec: %ld verify cycles, %.3f tokens / verify, acceptance %.3f (%ld of %ld drafted), %.1f tok/s over %zu tokens; accepted-length histogram:", s.cycles, s.tokens_per_verify(), s.acceptance(), s.accepted,
s.drafted, ntok / std::max(1e-9, t_gen), ntok);
for (int i = 0; i < 10; ++i) std::printf(" %ld", s.pos_hit[i]);
std::printf("\n");
}
int cmd_run(const RunOpts& o) {
if (o.serve) { // only protocol lines on stdout: keep a dup of it for them, point the process's own stdout (reports, self-check, store logs) at stderr
std::fflush(stdout);
#ifdef _WIN32
serve_detail::g_out = _fdopen(_dup(1), "w");
_dup2(2, 1);
#else
serve_detail::g_out = fdopen(dup(1), "w");
dup2(2, 1);
#endif
}
std::string err;
Ling32File f;
if (!f.open(o.model, err, false)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
if (o.selfcheck) {
const SelfcheckResult r = verify_section5_selfcheck(f);
std::printf("Section 5 self-check: %s (max relative error %.2e)\n", r.ok ? "PASS" : "FAIL", r.max_rel_err);
if (!r.ok) { std::fprintf(stderr, "strata-ling32: %s\n", r.error.c_str()); return 1; }
}
// ---- the memory tiers (P2): plan from what the card and the RAM have and from the overrides
TierPlan plan;
RankTable rt;
bool tiered = false;
bool igpu_zero_copy = false; // Windows iGPU: the RAM tier and the ring are device-visible host memory of the same RAM: read in place unless --miss says otherwise
{
cudaSetDevice(o.device);
size_t fr = 0, tot = 0;
cudaMemGetInfo(&fr, &tot);
if (!o.vis.file.empty() && (o.vis.backend == "gpu" || (o.vis.backend == "auto" && vision_default_backend(tot)[0] == 'g')))
fr = fr > (1600ull << 20) ? fr - (1600ull << 20) : 0; // the GPU picture encoder (829 MiB of weights + the activations of one picture) is not the planner's to give to experts
cudaDeviceProp prop;
const bool integrated = cudaGetDeviceProperties(&prop, o.device) == cudaSuccess && prop.integrated != 0;
const bool asked = o.tier == "hybrid" || o.tier == "nvme";
bool win_igpu = false; // Windows + HIP + integrated: plan with the probed allocation cap and the RAM floor, whatever --tier says (auto included)
#if defined(STRATA_USE_HIP) && defined(_WIN32)
win_igpu = integrated;
#endif
igpu_zero_copy = win_igpu && o.tier != "vram";
uint64_t plan_vram = fr, plan_ram = host_ram_available(), win_ram_budget = 0;
if (win_igpu && o.tier != "vram") {
constexpr uint64_t kGiBu = 1ull << 30;
const uint64_t cap = probe_gpu_alloc_cap(o.device);
const uint64_t reserve = 4 * kGiBu; // the engine's buffers beyond the planner's own "fixed" figure; hipMalloc blocks instead of failing when the pool is full
const uint64_t floor_ram = 8 * kGiBu + kGiBu * 3 / 2; // 8 GiB of Windows RAM stay free (+ the ring, staging and the process itself)
plan_vram = std::min<uint64_t>(fr, cap > reserve ? cap - reserve : 0);
plan_ram = plan_ram > floor_ram ? plan_ram - floor_ram : 0;
#if defined(_WIN32)
{ // The RAM tier is Windows memory registered with the GPU: the driver keeps GPU-visible pinned memory (this tier + the ring + the staging buffers) below half of the system RAM;
// above that the card fill stalls (measured on the Strix: 31.6 GiB of Windows RAM, 15.3 GiB pinned fine, 15.8 GiB stalls). Planner RAM budget: the RAM that is free
// minus the 8 GiB floor, at most half of the system RAM minus 0.5 GiB; it is explicit, so the planner's own 6 GiB headroom (for page cache on Linux) does not apply.
MEMORYSTATUSEX ms;
ms.dwLength = sizeof ms;
if (GlobalMemoryStatusEx(&ms)) {
const uint64_t avail = ms.ullAvailPhys;
uint64_t b = avail > 8 * kGiBu ? avail - 8 * kGiBu : 0;
b = std::min<uint64_t>(b, ms.ullTotalPhys / 2 > kGiBu / 2 ? ms.ullTotalPhys / 2 - kGiBu / 2 : 0);
win_ram_budget = b;
plan_ram = std::min<uint64_t>(std::max<uint64_t>(plan_ram, b), avail);
}
}
#endif
std::printf("Windows integrated GPU: GPU allocation cap probed %.1f GiB (device + pinned host draw from it): card budget %.1f GiB, RAM tier budget %.1f GiB (registered pages, 8 GiB of RAM stay free)\n", cap / double(kGiBu), plan_vram / double(kGiBu), plan_ram / double(kGiBu));
}
if (!o.map_experts && (!integrated || asked || (win_igpu && o.tier != "vram"))) {
std::string perr;
RunOpts plan_opts = o;
if (win_igpu && o.tier != "vram" && o.ram_budget_gib <= 0 && win_ram_budget > 0) plan_opts.ram_budget_gib = win_ram_budget / double(1ull << 30);
if (!make_plan(f, plan_opts, plan_vram, plan_ram, plan, rt, perr)) { std::fprintf(stderr, "strata-ling32: %s\n", perr.c_str()); return 1; }
std::printf("%s\n", plan.describe().c_str());
for (const auto& n : plan.notes) std::printf(" note: %s\n", n.c_str());
tiered = plan.mode != TierMode::A;
}
}
GpuModel M;
LoadOptions lo;
lo.load_lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch);
if (tiered) lo.lookahead_ks = (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1);
lo.load_experts = !tiered;
lo.verify_upload = false;
lo.map_experts = o.map_experts;
lo.lock_mapped = o.lock_mapped;
lo.device = o.device;
lo.reserve_bytes = (1ull << 30) + static_cast<uint64_t>(o.ctx) * 576 * 2 * 7 + static_cast<uint64_t>(o.chunk) * 157184 * 4 + (700ull << 20);
if (!o.vis.file.empty() && (o.vis.backend == "gpu" || (o.vis.backend == "auto" && vision_default_backend(vision_gpu_total_bytes(o.device))[0] == 'g')))
lo.reserve_bytes += 1600ull << 20; // the GPU picture encoder: ~830 MiB of weights plus the activations of one picture
const double t0 = now_s();
if (!M.load(f, lo, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::printf("%s\n", M.report().c_str());
if (!o.mtp_file.empty() && !M.load_mtp(o.mtp_file, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
if (o.spec_mtp && !M.mtp.loaded) { std::fprintf(stderr, "strata-ling32: --spec mtp needs --mtp FILE (the Ling-3.2-Air-MTP.strata sidecar)\n"); return 2; }
std::unique_ptr<ExpertStore> store;
if (tiered) {
StoreOptions so;
so.device = o.device;
so.max_tokens = o.chunk;
so.zero_copy = o.miss_explicit ? !o.miss_stage : (igpu_zero_copy ? true : !o.miss_stage);
so.adaptive_default = o.mtp_file.empty();
so.prefill_budget = o.prefill_budget;
so.turbo = o.turbo_ssd && plan.mode == TierMode::C;
so.turbo_threshold = o.turbo_threshold;
if (o.turbo_ssd && plan.mode != TierMode::C) std::printf("note: --turbo-ssd is ignored: this plan has no SSD tier (Mode %s)\n", plan.mode == TierMode::B ? "B" : "A");
so.cpu_coexec = o.cpu_coexec;
so.cpu_threads = o.cpu_threads;
if (o.cpu_coexec > 0 && (o.act_q8 || o.moe_q8)) { std::fprintf(stderr, "strata-ling32: --cpu-coexec needs float activations (no --act q8, no --moe-q8)\n"); return 2; }
store = ExpertStore::create(f, M, plan, rt, so, err);
if (!store) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
g_cached0_kb = proc_kb("/proc/meminfo", "Cached");
std::printf("tier store ready: %.2f GiB on the card, %.2f GiB pinned, start-up fill %.1f s\n%s\n", store->gpu_bytes() / kGiB, store->pinned_bytes() / kGiB, store->stats().load_s, host_mem_line().c_str());
}
Ling32Engine E;
EngineOptions eo;
eo.act_q8 = o.act_q8;
eo.clamp_after_silu = o.clamp_after;
eo.max_ctx = o.ctx;
eo.max_tokens = o.chunk;
eo.lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch);
if (tiered) { eo.lookahead_ks = (o.lookahead || o.coverage) ? 3 : (plan.lookahead_k == 4 ? 2 : 1); eo.lookahead_stats = o.lookahead; }
eo.lookahead_group_mask = !o.la_nomask;
eo.kda_chunked = !o.kda_seq;
eo.profile = o.profile;
eo.tc_min_n = o.tc_min_n;
eo.cuda_graph = o.graph;
eo.dual_stream = !o.no_dual;
eo.fuse_router = o.fuse_router;
eo.kda_par = o.kda_par;
eo.fuse_experts = o.fuse_experts;
eo.pdl = o.pdl;
eo.s8_packed = o.s8_packed;
eo.tc_mode = o.tc_mode;
eo.moe_q8 = o.moe_q8;
eo.tc_moe_min_n = o.tc_moe_min_n;
eo.capture = !o.layer_out.empty();
eo.latent_fp32 = !o.latent_f16;
eo.mla_kernel = o.mla_kernel;
eo.mla_prefill_kernel = o.mla_prefill_kernel;
eo.device = o.device;
if (!E.init(M, eo, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
if (store) {
E.set_expert_provider(store.get());
E.set_demand_sink(plan.prefetch ? static_cast<DemandSink*>(store.get()) : nullptr);
}
size_t fr = 0, tot = 0;
cudaMemGetInfo(&fr, &tot);
std::printf("ready in %.1f s; GPU memory %.2f / %.2f GiB used; activations %s, SwiGLU clamp %s silu\n", now_s() - t0, (tot - fr) / 1073741824.0, tot / 1073741824.0, o.act_q8 ? "Q8_1" : "float32",
o.clamp_after ? "after" : "before");
const int V = f.cfg().V;
Sampler S(o);
if (!o.mm_runs.empty()) {
VisionRunOpts vo = o.vis;
vo.device = o.device;
const int rc = run_mm_batch(E, o.mm_runs, vo, o.chunk, f.cfg().D, err);
if (rc) std::fprintf(stderr, "strata-ling32: %s\n", err.c_str());
return rc;
}
// the speculative parameters of a run: the command line, overridden by one entry of --spec-sweep ("tap=in,ctx=0,cut=0.3,rerank=0,block=4,label=x")
auto spec_params = [&](const std::string& entry, std::string& label) {
SpecParams sp;
sp.temp = o.temp; sp.top_p = o.top_p; sp.top_k = o.top_k; sp.seed = o.seed;
sp.block = o.spec_block; sp.adaptive = o.spec_adaptive; sp.mtp = o.spec_mtp; if (o.spec_mtp && !o.spec_block_set) sp.block = 4;
if (tiered) { sp.tier = plan.mode == TierMode::B ? 1 : 2; sp.experts_per_layer = plan.vram_ranks; sp.turbo_ssd = plan.turbo_ssd; } // the controller's tier-aware bypass
std::stringstream es(entry);
std::string kv;
label.clear();
while (std::getline(es, kv, ',')) {
const size_t eq = kv.find('=');
if (eq == std::string::npos) continue;
const std::string k = kv.substr(0, eq), v = kv.substr(eq + 1);
if (k == "block") sp.block = std::atoi(v.c_str());
else if (k == "adaptive") sp.adaptive = std::atoi(v.c_str()) != 0;
else if (k == "calibrate") sp.mtp_calibrate = std::atoi(v.c_str()) != 0;
else if (k == "temp") sp.temp = static_cast<float>(std::atof(v.c_str()));
else if (k == "label") label = v;
}
if (label.empty()) { label = entry; for (char& ch : label) if (ch == ',' || ch == '=') ch = '_'; }
return sp;
};
auto init_spec = [&](const SpecParams& sp) -> bool {
if (!E.spec_init(sp, err)) { std::fprintf(stderr, "strata-ling32: spec: %s\n", err.c_str()); return false; }
std::printf("speculative decoding: MTP (%s), K_max %d%s; greedy %s\n", M.mtp.build.c_str(), sp.block, sp.adaptive ? ", adaptive K" : ", fixed K", sp.temp <= 0 ? "yes" : "no");
return true;
};
if (o.spec && o.jobs.empty() && o.genjobs.empty()) {
std::string lbl;
if (!init_spec(spec_params("", lbl))) return 1;
}
if (o.serve) { // the line protocol of serve (Python): INFO / READY, then GEN / STOP / QUIT
ServeCfg sc;
sc.max_ctx = o.ctx;
sc.chunk = o.chunk;
sc.layers = f.cfg().n_layers;
sc.vocab = V;
sc.eos[0] = f.cfg().eos_id;
sc.eos[1] = f.cfg().pad_id;
sc.vram_ranks = f.cfg().n_exp; // Mode A: every routed expert is on the card
sc.spec_mtp = o.spec_mtp;
sc.model_base = o.model;
const size_t sl = sc.model_base.find_last_of("/\\");
if (sl != std::string::npos) sc.model_base = sc.model_base.substr(sl + 1);
for (char& ch : sc.model_base) if (ch == ' ') ch = '_';
#if __has_include("ling32_tier_store.hpp") // with the tier store (f-ling32-tier merged): the plan fills INFO, the store's counters fill STAT / DONE
if (tiered) {
sc.tier = plan.mode == TierMode::B ? "B" : "C";
sc.vram_ranks = plan.vram_ranks;
sc.ram_ranks = plan.ram_ranks;
sc.ssd_ranks = std::max(0, f.cfg().n_exp - plan.vram_ranks - plan.ram_ranks);
sc.dyn_slots = plan.dyn_slots;
sc.lookahead_k = plan.lookahead_k;
sc.prefetch = plan.prefetch;
sc.turbo_ssd = plan.turbo_ssd;
ExpertStore* st = store.get();
sc.counters = [st]() {
const TierStats s = st->stats();
ServeCounters c;
c.hits = s.hit_dyn_pf;
c.lookups = s.uniq > s.hit_vram ? s.uniq - s.hit_vram : 0;
c.h2d_bytes = static_cast<double>(s.b_h2d_prefetch + s.b_h2d_demand);
c.ssd_bytes = static_cast<double>(s.b_ssd_prefetch + s.b_ssd_demand);
return c;
};
}
#endif
std::unique_ptr<VisionRun> serve_vr; // pictures in requests (image=<path> keys): the encoder lives as long as the server (idle unload of the GPU weights)
if (!o.vis.file.empty()) {
VisionRunOpts vo = o.vis;
vo.device = o.device;
vo.images.clear();
serve_vr.reset(new VisionRun(vo));
if (!serve_vr->init(err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::fprintf(stderr, "[vision] picture encoder: %s (idle unload %.0f s)\n", serve_vr->backend().c_str(), vo.idle_s);
sc.vision = serve_vr.get();
sc.vopts = vo;
}
if (E.spec_active()) { // speculative generation through the engine's cycle loop (no prefix reuse): spec=dfly in INFO
sc.spec_run = [&E, &o](const std::vector<int>& ids, int limit, float temp, float top_p, int top_k, uint64_t seed, int resume_from, const std::function<bool(int)>& emit, ServeSpecResult& res, std::string& err) {
(void)limit;
if (!E.spec_set_sampling(temp, top_p, top_k, seed ? seed : static_cast<uint64_t>(std::random_device{}()) + 1, err)) return false;
E.spec_reset_stats();
int first = 0;
if (!E.spec_start(ids.data(), static_cast<int>(ids.size()), o.chunk, first, err, resume_from)) return false;
int shown = 1;
bool go = emit(first);
std::vector<int> com;
while (go) {
if (!E.spec_cycle(com, err)) return false;
for (int t : com) { ++shown; if (!(go = emit(t))) break; }
}
res.fed = 0;
if (o.spec_mtp) { // keep the engine state up to the last shown token (the tokens a stop token cut off are rewound): the next request of the chat resumes there
std::string e3;
if (E.spec_trim_to(static_cast<int>(ids.size()) + shown - 1, e3)) res.fed = E.pos();
}
const SpecStats& ss = E.spec_stats();
res.drafted = ss.drafted;
res.accepted = ss.accepted;
res.cycles = ss.cycles;
res.tokens_per_verify = ss.tokens_per_verify();
return true;
};
}
return ling32_serve(E, sc);
}
if (!o.hidden_jobs.empty()) { // the hidden rows of whole token sequences (MTP / drafter work); needs only the model
std::filesystem::create_directories(o.out);
std::ifstream jf(o.hidden_jobs);
std::string line2;
while (std::getline(jf, line2)) {
if (line2.find('{') == std::string::npos) continue;
const json::JVal j = json::json_parse(line2);
const std::string id = j.at("id").str();
std::vector<int> seq;
for (const auto& v : j.at("prompt_ids").a) seq.push_back(static_cast<int>(v.i()));
const size_t np = seq.size();
if (j.get("cont_ids")) for (const auto& v : j.at("cont_ids").a) seq.push_back(static_cast<int>(v.i()));
std::vector<float> hp, hf;
if (!E.debug_hidden(seq.data(), static_cast<int>(seq.size()), hp, hf, err, o.hidden_decode ? static_cast<int>(np) : -1)) { std::fprintf(stderr, "dump %s: %s\n", id.c_str(), err.c_str()); return 1; }
const std::string base2 = o.out + "/" + id;
std::ofstream(base2 + ".hpre.f32", std::ios::binary).write(reinterpret_cast<const char*>(hp.data()), static_cast<std::streamsize>(hp.size() * 4));
std::ofstream(base2 + ".hfin.f32", std::ios::binary).write(reinterpret_cast<const char*>(hf.data()), static_cast<std::streamsize>(hf.size() * 4));
std::ofstream(base2 + ".ids.i32", std::ios::binary).write(reinterpret_cast<const char*>(seq.data()), static_cast<std::streamsize>(seq.size() * 4));
std::printf("dumped %s: %zu positions (%zu prompt + %zu continuation)\n", id.c_str(), seq.size(), np, seq.size() - np);
}
return 0;
}
if (!o.genjobs.empty()) { // continuation only, spec on or off: {"id","prompt_ids","gen"} per line -> DIR/<id>.gen.json (one directory per --spec-sweep entry)
std::vector<std::string> sweep;
if (o.spec && !o.spec_sweep.empty()) { std::stringstream ss(o.spec_sweep); std::string t; while (std::getline(ss, t, ';')) if (!t.empty()) sweep.push_back(t); }
else sweep.push_back("");
for (const std::string& entry : sweep) {
std::string label;
if (entry.find("spec=off") != std::string::npos) { E.spec_shutdown(); label = "base"; } // the no-spec baseline of the same process
else if (o.spec) { if (!init_spec(spec_params(entry, label))) return 1; }
const std::string outdir = sweep.size() > 1 ? o.out + "/" + label : o.out;
if (sweep.size() > 1) std::printf("=== spec config %s\n", label.c_str());
std::filesystem::create_directories(outdir);
std::ifstream jf(o.genjobs);
std::string line;
long tot_tok = 0, tot_cyc = 0, tot_dr = 0, tot_acc = 0, tot_hist[17] = {};
if (store) store->reset_stats(); // the tier report printed after the loop covers the whole job file (prefills included, the same in every mode)
double tot_s = 0;
while (std::getline(jf, line)) {
if (line.find('{') == std::string::npos) continue;
const json::JVal j = json::json_parse(line);
const std::string id = j.at("id").str();
std::vector<int> prompt, gen_ids;
for (const auto& v : j.at("prompt_ids").a) prompt.push_back(static_cast<int>(v.i()));
const int gen = j.get("gen") ? static_cast<int>(j.at("gen").i()) : 128;
double t_pre = 0, t_gen = 0;
if (E.spec_active()) {
E.spec_reset_stats();
if (!spec_generate(E, o, prompt, gen, gen_ids, t_pre, t_gen, err)) { std::fprintf(stderr, "job %s: %s\n", id.c_str(), err.c_str()); return 1; }
} else {
E.reset();
std::vector<float> last;
const double ta = now_s();
if (!prefill(E, o, prompt, nullptr, &last, err)) { std::fprintf(stderr, "job %s: %s\n", id.c_str(), err.c_str()); return 1; }
t_pre = now_s() - ta;
const double tb = now_s();
for (int i = 0; i < gen; ++i) {
const int next = S.pick(last.data(), V);
gen_ids.push_back(next);
if (is_stop(o, next)) break;
if (i + 1 < gen && !E.forward(&next, 1, 1, &last, err)) { std::fprintf(stderr, "job %s: %s\n", id.c_str(), err.c_str()); return 1; }
}
t_gen = now_s() - tb;
}
std::ostringstream js;
const SpecStats& ss = E.spec_stats();
js << "{\"id\":\"" << id << "\",\"prompt_len\":" << prompt.size() << ",\"spec\":" << (E.spec_active() ? "true" : "false") << ",\"prefill_s\":" << t_pre << ",\"gen_s\":" << t_gen
<< ",\"decode_tok_s\":" << (gen_ids.size() > 1 ? gen_ids.size() / std::max(1e-9, t_gen) : 0.0) << ",\"cycles\":" << ss.cycles << ",\"tokens_per_verify\":" << ss.tokens_per_verify() << ",\"acceptance\":"
<< ss.acceptance() << ",\"drafted\":" << ss.drafted << ",\"accepted\":" << ss.accepted << ",\"gen_ids\":[";
for (size_t i = 0; i < gen_ids.size(); ++i) js << (i ? "," : "") << gen_ids[i];
js << "]}\n";
write_text(std::filesystem::path(outdir) / (id + ".gen.json"), js.str());
std::printf("job %-12s prompt %5zu tok: prefill %.2f s, generated %zu tokens at %.1f tok/s", id.c_str(), prompt.size(), t_pre, gen_ids.size(), gen_ids.size() / std::max(1e-9, t_gen));
if (E.spec_active()) std::printf(" | %.2f tok/verify, acceptance %.3f", ss.tokens_per_verify(), ss.acceptance());
std::printf("\n");
tot_tok += static_cast<long>(gen_ids.size());
tot_s += t_gen;
tot_cyc += ss.cycles; tot_dr += ss.drafted; tot_acc += ss.accepted; for (int hh = 0; hh < 17; ++hh) tot_hist[hh] += ss.pos_hit[hh];
}
if (E.spec_active() && tot_cyc) { // per-slot acceptance given all earlier slots accepted: P(a >= k + 1 | a >= k)
std::printf("accepted-length histogram (a = 0..8):");
for (int hh = 0; hh < 9; ++hh) std::printf(" %ld", tot_hist[hh]);
std::printf("\nper-slot conditional acceptance:");
long ge = tot_cyc;
for (int k = 0; k < 8; ++k) { long ge2 = 0; for (int hh = k + 1; hh < 17; ++hh) ge2 += tot_hist[hh]; std::printf(" %.2f", ge ? static_cast<double>(ge2) / ge : 0.0); ge = ge2; }
std::printf("\n");
}
std::printf("genjobs done: %ld tokens in %.2f s (%.1f tok/s)", tot_tok, tot_s, tot_tok / std::max(1e-9, tot_s));
if (E.spec_active()) std::printf(" | %ld verifies, %.2f tokens / verify, acceptance %.3f", tot_cyc, tot_cyc ? static_cast<double>(tot_tok) / tot_cyc : 0.0, tot_dr ? static_cast<double>(tot_acc) / tot_dr : 0.0);
std::printf("\n");
{ const std::string cr = E.mtp_controller_report(); if (!cr.empty()) std::printf("%s\n", cr.c_str()); }
if (store) std::printf("%s\n", store->report().c_str());
}
return 0;
}
auto run_jobs = [&](Ling32Engine& E, const RunOpts& o, const std::string& outdir) -> int {
std::filesystem::create_directories(outdir);
std::ifstream jf(o.jobs);
std::string line;
int n_jobs = 0;
while (std::getline(jf, line)) {
if (line.find('{') == std::string::npos) continue;
const json::JVal j = json::json_parse(line);
const std::string id = j.at("id").str();
std::vector<int> prompt, cont;
for (const auto& v : j.at("prompt_ids").a) prompt.push_back(static_cast<int>(v.i()));
if (const json::JVal* c = j.get("cont_ids")) for (const auto& v : c->a) cont.push_back(static_cast<int>(v.i()));
const int gen = j.get("gen") ? static_cast<int>(j.at("gen").i()) : 128;
const int tf = j.get("tf") ? static_cast<int>(j.at("tf").i()) : 64;
if (o.fast_jobs) { // speed / identity runs: only the last prompt position's logits, then the greedy continuation (no per-position top-K)
E.reset();
if (store) store->reset_stats();
std::vector<float> last;
const double tp = now_s();
if (!prefill(E, o, prompt, nullptr, &last, err)) { std::fprintf(stderr, "job %s: %s\n", id.c_str(), err.c_str()); return 1; }
const double t_pre = now_s() - tp;
std::vector<int> gen_ids;
std::vector<double> step_ms;
bool nan = false;
const double td = now_s();
for (int i = 0; i < gen; ++i) {
int next = 0;
float bv = last[0];
for (int v = 0; v < V; ++v) { nan = nan || !std::isfinite(last[v]); if (last[v] > bv) { bv = last[v]; next = v; } }
gen_ids.push_back(next);
if (is_stop(o, next)) break;
const double tb = now_s();
if (!E.forward(&next, 1, 1, &last, err)) { std::fprintf(stderr, "job %s: %s\n", id.c_str(), err.c_str()); return 1; }
step_ms.push_back((now_s() - tb) * 1000.0);
}
const double t_gen = now_s() - td;
std::vector<double> sm = step_ms;
std::sort(sm.begin(), sm.end());
const double med = sm.empty() ? 0.0 : sm[sm.size() / 2];
std::ostringstream js;
js << "{\"id\":\"" << id << "\",\"prompt_len\":" << prompt.size() << ",\"nan\":" << (nan ? "true" : "false") << ",\"prefill_s\":" << t_pre << ",\"decode_tok_s\":" << (gen_ids.size() > 1 ? gen_ids.size() / std::max(1e-9, t_gen) : 0.0)
<< ",\"median_step_ms\":" << med << ",\"gen_ids\":[";
for (size_t i = 0; i < gen_ids.size(); ++i) js << (i ? "," : "") << gen_ids[i];
js << "]}\n";
write_text(std::filesystem::path(outdir) / (id + ".gen.json"), js.str());
std::printf("job %-12s prompt %5zu tok: prefill %.2f s (%.1f tok/s), generated %zu tokens in %.2f s = %.2f tok/s (median step %.1f ms = %.2f tok/s)%s\n", id.c_str(), prompt.size(), t_pre,
prompt.size() / std::max(1e-9, t_pre), gen_ids.size(), t_gen, gen_ids.size() / std::max(1e-9, t_gen), med, med > 0 ? 1000.0 / med : 0.0, nan ? " NaN/Inf IN LOGITS" : "");
if (store) std::printf("%s\n%s\n", store->report().c_str(), host_mem_line().c_str());
++n_jobs;
continue;
}
// teacher-forced: the prompt (all positions), then the first `tf` continuation tokens one decode step at a time
E.reset();
if (store) store->reset_stats();
const double ta = now_s();
const int K = o.topk;
std::vector<int32_t> tid;
std::vector<float> tv, lse;
bool nan = false;
std::vector<float> last_prompt_row;
auto sink = [&](const float* rows, int n) {
for (int r = 0; r < n; ++r) {
const float* row = rows + static_cast<size_t>(r) * V;
last_prompt_row.assign(row, row + V);
for (int v = 0; v < V; ++v) nan = nan || !std::isfinite(row[v]);
const size_t at = tid.size() / K;
tid.resize((at + 1) * K);
tv.resize((at + 1) * K);
lse.resize(at + 1);
top_k_row(row, V, K, tid.data() + at * K, tv.data() + at * K, lse.data() + at);
}
};
const bool want_layers = !o.layers_for.empty() && ("," + o.layers_for + ",").find("," + id + ",") != std::string::npos;
E.opt.capture = want_layers;
if (!prefill_rows(E, o, prompt, sink, err)) { std::fprintf(stderr, "job %s: %s\n", id.c_str(), err.c_str()); return 1; }
const double t_pre = now_s() - ta;
if (o.profile) std::printf("[%s: prefill of %zu tokens]\n%s", id.c_str(), prompt.size(), E.profile_report().c_str());
if (want_layers) {
std::ofstream lf(std::filesystem::path(outdir) / (id + ".layers.f32"), std::ios::binary);
const int D = f.cfg().D;
for (int il = 0; il < f.cfg().n_layers; ++il) {
const auto& xo = E.captures()[il].x_out;
lf.write(reinterpret_cast<const char*>(xo.data() + xo.size() - D), static_cast<std::streamsize>(D * 4));
}
E.opt.capture = false;
}
const std::vector<float> after_prompt = last_prompt_row; // the distribution that starts the greedy continuation
E.checkpoint(); // state after the prompt: the teacher-forced pass below moves on, the greedy pass restarts here
const int nfed = std::min<int>(tf, static_cast<int>(cont.size()));
double t_dec = 0;
for (int i = 0; i < nfed; ++i) {
std::vector<float> lg;
const double tb = now_s();
if (!E.forward(&cont[i], 1, 1, &lg, err)) { std::fprintf(stderr, "job %s: %s\n", id.c_str(), err.c_str()); return 1; }
t_dec += now_s() - tb;
sink(lg.data(), 1);
}
if (o.profile && nfed > 0) std::printf("[%s: %d teacher-forced decode steps]\n%s", id.c_str(), nfed, E.profile_report().c_str());
const int P = static_cast<int>(lse.size());
{
std::ofstream b(std::filesystem::path(outdir) / (id + ".tf.bin"), std::ios::binary);
const int32_t hdr[2] = {P, K};
b.write(reinterpret_cast<const char*>(hdr), sizeof hdr);
b.write(reinterpret_cast<const char*>(tid.data()), static_cast<std::streamsize>(tid.size() * 4));
b.write(reinterpret_cast<const char*>(tv.data()), static_cast<std::streamsize>(tv.size() * 4));
b.write(reinterpret_cast<const char*>(lse.data()), static_cast<std::streamsize>(lse.size() * 4));
}
// greedy continuation from the prompt
std::vector<int> gen_ids;
double t_gen = 0, t_pre2 = 0;
if (gen > 0) {
E.restore();
std::vector<float> last = after_prompt;
t_pre2 = t_pre;
RunOpts g = o;
g.temp = 0;
Sampler gs(g);
const double td = now_s();
for (int i = 0; i < gen; ++i) {
const int next = gs.pick(last.data(), V);
gen_ids.push_back(next);
if (is_stop(o, next)) break;
if (!E.forward(&next, 1, 1, &last, err)) { std::fprintf(stderr, "job %s: %s\n", id.c_str(), err.c_str()); return 1; }
}
t_gen = now_s() - td;
}
std::ostringstream js;
js << "{\"id\":\"" << id << "\",\"prompt_len\":" << prompt.size() << ",\"positions\":" << P << ",\"nan\":" << (nan ? "true" : "false") << ",\"prefill_s\":" << t_pre2
<< ",\"decode_tok_s\":" << (gen_ids.size() > 1 ? gen_ids.size() / std::max(1e-9, t_gen) : 0.0) << ",\"gen_ids\":[";
for (size_t i = 0; i < gen_ids.size(); ++i) js << (i ? "," : "") << gen_ids[i];
js << "]}\n";
write_text(std::filesystem::path(outdir) / (id + ".gen.json"), js.str());
std::printf("job %-12s prompt %5zu tok: prefill %.2f s (%.0f tok/s), %d fed back %.1f tok/s, generated %zu tokens at %.1f tok/s%s\n", id.c_str(), prompt.size(), t_pre,
prompt.size() / std::max(1e-9, t_pre), nfed, nfed / std::max(1e-9, t_dec), gen_ids.size(), gen_ids.size() / std::max(1e-9, t_gen), nan ? " NaN/Inf IN LOGITS" : "");
if (o.profile) std::printf("[%s: greedy decode of %zu tokens]\n%s", id.c_str(), gen_ids.size(), E.profile_report().c_str());
if (store) std::printf("%s\n", store->report().c_str());
++n_jobs;
}
std::printf("%d jobs done\n", n_jobs);
if (o.lookahead) print_lookahead(E, f.cfg(), o.lookahead_json.empty() ? std::string() : outdir + "/lookahead.json");
return 0;
};
if (!o.jobs.empty()) {
E.destroy();
std::vector<std::string> cfgs;
{ std::stringstream cs(o.configs); std::string t; while (std::getline(cs, t, ',')) if (!t.empty()) cfgs.push_back(t); }
for (const std::string& cn : cfgs) {
EngineOptions e2 = eo;
RunOpts o2 = o;
bool pf_on = plan.prefetch;
std::stringstream ps(cn);
std::string part;
while (std::getline(ps, part, '+')) {
{ const size_t hh = part.find('#'); if (hh != std::string::npos) part.resize(hh); } // "pfon#2": a label, so repeated configs get their own output directories
if (part == "lat32") e2.latent_fp32 = true;
else if (part == "lat16") e2.latent_fp32 = false;
else if (part == "rope32") e2.rope_fp32 = true;
else if (part == "before") e2.clamp_after_silu = false;
else if (part == "lanomask") e2.lookahead_group_mask = false;
else if (part == "kdaseq") e2.kda_chunked = false;
else if (part == "q8") e2.act_q8 = true;
else if (part.size() >= 2 && part[0] == 'w' && std::isdigit(static_cast<unsigned char>(part[1]))) { if (store) store->set_prefetch_width(std::atoi(part.c_str() + 1)); } // w8: prefetch width
else if (part.size() >= 2 && (part[0] == 's' || part[0] == 'h' || part[0] == 'i' || part[0] == 'l') && std::isdigit(static_cast<unsigned char>(part[1]))) { // sN: rank cut-off, hN: residency hint ranks, iN: in-flight prefetch cap in MB
if (store) store->set_policy(part[0] == 's' ? std::atoi(part.c_str() + 1) : -1, part[0] == 'h' ? std::atoi(part.c_str() + 1) : -1, part[0] == 'i' ? std::atoi(part.c_str() + 1) : -1, part[0] == 'l' ? std::atoi(part.c_str() + 1) : -1);
}
else if (part == "k1" || part == "k2" || part == "k4" || part == "k0") { // which predictor drives the prefetch (k1: the layer own router on the entering residual); k0: the mode own
if (store) store->set_pf_k(part[1] - '0');
e2.lookahead_k1 = part == "k1";
}
else if (part.size() == 2 && part[0] == 'c' && std::isdigit(static_cast<unsigned char>(part[1]))) { if (store) store->set_cpu(part[1] - '0'); } // c4: up to 4 cold experts per decode layer on the CPU (c0: off)
else if (part == "tb0" || part == "tb1") { if (store) store->set_turbo(part == "tb1"); } // --turbo-ssd off / on for this config (needs the flag)
else if (part == "mstage" || part == "mzc") { if (store) store->set_miss_stage(part == "mstage"); }
else if (part == "pfnull") { // the lookahead predictors run, nothing is prefetched: the engine's own cost of the feature
if (!store) { std::fprintf(stderr, "strata-ling32: config 'pfnull' needs a tiered run\n"); return 2; }
pf_on = false;
e2.lookahead = true;
}
else if (part == "pfon" || part == "pfoff") { // tiers: lookahead prefetch on / off (the A/B switch, in one process, same caches)
if (!store) { std::fprintf(stderr, "strata-ling32: config '%s' needs a tiered run\n", part.c_str()); return 2; }
pf_on = part == "pfon";
if (pf_on && !plan.prefetch) { std::fprintf(stderr, "strata-ling32: pfon needs --prefetch on\n"); return 2; }
e2.lookahead = pf_on || o.lookahead;
}
else if (part.rfind("chunk", 0) == 0) { o2.chunk = std::max(1, std::atoi(part.c_str() + 5)); e2.max_tokens = o2.chunk; }
else if (part != "base") { std::fprintf(stderr, "strata-ling32: unknown config part '%s'\n", part.c_str()); return 2; }
}
e2.capture = !o.layers_for.empty();
Ling32Engine Ek;
if (!Ek.init(M, e2, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
Ek.opt.capture = false;
if (store) {
Ek.set_expert_provider(store.get());
Ek.set_demand_sink(pf_on ? static_cast<DemandSink*>(store.get()) : nullptr);
}
std::printf("=== config %s\n", cn.c_str());
const std::string outdir = (cfgs.size() == 1 && cn == "base") ? o.out : o.out + "/" + cn;
const int rc = run_jobs(Ek, o2, outdir);
if (rc) return rc;
}
return 0;
}
std::vector<int> ids = parse_ids(o.ids_csv);
if (!o.tokens_file.empty()) {
std::ifstream tf(o.tokens_file);
std::stringstream ss;
ss << tf.rdbuf();
ids = parse_ids(ss.str());
}
if (ids.empty()) { std::fprintf(stderr, "strata-ling32: no token ids (--ids or --tokens)\n"); return 2; }
const bool mm_run = !o.vis.images.empty();
std::unique_ptr<VisionRun> vrun;
MmPrompt mmp;
if (mm_run) {
if (o.invariance > 0) { std::fprintf(stderr, "strata-ling32: --invariance does not take pictures\n"); return 2; }
VisionRunOpts vo = o.vis;
vo.device = o.device;
vrun.reset(new VisionRun(vo));
if (!vrun->init(err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::printf("pictures: %zu, encoder: %s (%s)\n", vo.images.size(), vrun->backend().c_str(), vo.backend.c_str());
const double tv = now_s();
if (!build_mm_prompt(*vrun, vo, ids, f.cfg().D, mmp, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::printf("prompt with pictures: %zu tokens (%zu picture rows), rope delta %d, pictures ready in %.2f s\n", mmp.ids.size(), mmp.emb.size() / static_cast<size_t>(f.cfg().D), mmp.pos.delta, now_s() - tv);
if (!o.vision_dump.empty()) {
std::ofstream df(o.vision_dump, std::ios::binary);
df.write(reinterpret_cast<const char*>(mmp.emb.data()), static_cast<std::streamsize>(mmp.emb.size() * 4));
}
ids = mmp.ids;
}
if (o.invariance > 0) {
const int K = o.invariance, T = static_cast<int>(ids.size());
if (T <= K) { std::fprintf(stderr, "strata-ling32: --invariance K needs more than K ids\n"); return 2; }
E.reset();
std::vector<int> head(ids.begin(), ids.end() - K);
std::vector<float> l0;
if (!prefill(E, o, head, nullptr, &l0, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
E.checkpoint();
std::vector<std::vector<float>> la(K);
for (int i = 0; i < K; ++i)
if (!E.forward(&ids[T - K + i], 1, 1, &la[i], err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
E.restore();
std::vector<float> lb;
if (!E.forward(&ids[T - K], K, K, &lb, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
int same = 0;
double worst = 0;
for (int i = 0; i < K; ++i) {
const float* a = la[i].data();
const float* b = lb.data() + static_cast<size_t>(i) * V;
const bool bit = std::memcmp(a, b, static_cast<size_t>(V) * 4) == 0;
double d = 0;
for (int v = 0; v < V; ++v) d = std::max(d, static_cast<double>(std::fabs(a[v] - b[v])));
same += bit ? 1 : 0;
worst = std::max(worst, d);
std::printf(" row %2d: %s, max |dlogit| %.3e, argmax %d vs %d\n", i, bit ? "bit-identical" : "differs", d, static_cast<int>(std::max_element(a, a + V) - a), static_cast<int>(std::max_element(b, b + V) - b));
}
std::printf("invariance: %d of %d rows bit-identical (N=1 steps vs one N=%d batch), worst |dlogit| %.3e\n", same, K, K, worst);
return 0;
}
if (E.spec_active()) {
std::vector<int> out;
double t_pre = 0, t_gen = 0;
if (o.dist_n > 0) { // N sampled continuations of the prompt: histogram of the first dist_len tokens (a distribution check against the no-spec sampler)
std::vector<std::vector<int>> toks;
for (int s = 0; s < o.dist_n; ++s) {
if (!spec_generate(E, o, ids, o.dist_len, out, t_pre, t_gen, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
out.resize(o.dist_len, -1);
toks.push_back(out);
}
std::printf("DIST spec %d %d\n", o.dist_n, o.dist_len);
for (const auto& t : toks) { for (int v : t) std::printf("%d ", v); std::printf("\n"); }
print_spec_stats(E.spec_stats(), 1.0, 1);
return 0;
}
if (!spec_generate(E, o, ids, o.gen, out, t_pre, t_gen, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::printf("prefill: %zu tokens in %.2f s (%.0f tok/s)\n", ids.size(), t_pre, ids.size() / std::max(1e-9, t_pre));
std::printf("generated %zu tokens in %.2f s (%.1f tok/s)\nGEN:", out.size(), t_gen, out.size() / std::max(1e-9, t_gen));
for (int t : out) std::printf(" %d", t);
std::printf("\n");
print_spec_stats(E.spec_stats(), t_gen, out.size());
return 0;
}
if (o.dist_n > 0) { // the same histogram from the baseline sampler (one process, one seed stream)
std::vector<int> out;
std::printf("DIST base %d %d\n", o.dist_n, o.dist_len);
for (int s = 0; s < o.dist_n; ++s) {
E.reset();
std::vector<float> last;
if (!prefill(E, o, ids, nullptr, &last, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
out.clear();
for (int i = 0; i < o.dist_len; ++i) {
const int next = S.pick(last.data(), V);
out.push_back(next);
if (i + 1 < o.dist_len && !E.forward(&next, 1, 1, &last, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
}
for (int v : out) std::printf("%d ", v);
std::printf("\n");
}
return 0;
}
E.reset();
std::vector<float> last;
const double tp = now_s();
if (!(mm_run ? prefill_mm(E, o.chunk, mmp, &last, err) : prefill(E, o, ids, nullptr, &last, err))) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
const double t_pre = now_s() - tp;
std::printf("prefill: %zu tokens in %.2f s (%.0f tok/s)\n", ids.size(), t_pre, ids.size() / std::max(1e-9, t_pre));
if (!o.layer_out.empty()) { // the residual after each layer at the last prompt position (the last chunk's captures)
const int D = f.cfg().D;
std::ofstream lo_f(o.layer_out, std::ios::binary);
for (int il = 0; il < f.cfg().n_layers; ++il) {
const auto& xo = E.captures()[il].x_out;
lo_f.write(reinterpret_cast<const char*>(xo.data() + xo.size() - D), static_cast<std::streamsize>(D * 4));
}
std::printf("layer outputs at the last prompt position -> %s\n", o.layer_out.c_str());
}
std::vector<int> out;
const double td = now_s();
for (int i = 0; i < o.gen; ++i) {
const int next = S.pick(last.data(), V);
out.push_back(next);
if (is_stop(o, next)) break;
if (!E.forward(&next, 1, 1, &last, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
}
const double t_gen = now_s() - td;
if (o.profile) std::printf("%s", E.profile_report().c_str());
std::printf("generated %zu tokens in %.2f s (%.1f tok/s)\nGEN:", out.size(), t_gen, out.size() / std::max(1e-9, t_gen));
for (int t : out) std::printf(" %d", t);
std::printf("\n");
if (o.lookahead) print_lookahead(E, f.cfg(), o.lookahead_json);
if (mm_run && o.vision_hold > 0 && vrun->gpu()) { // memory behaviour of the GPU encoder: its weights are freed after the idle time
size_t f0 = 0, t0m = 0;
cudaMemGetInfo(&f0, &t0m);
std::printf("vision hold: GPU encoder %s, %.0f MiB held by it, free %.0f MiB\n", vrun->gpu()->loaded() ? "loaded" : "unloaded", vrun->gpu()->device_bytes() / 1048576.0, f0 / 1048576.0);
const double th = now_s();
while (now_s() - th < o.vision_hold && vrun->gpu()->loaded()) std::this_thread::sleep_for(std::chrono::milliseconds(500));
size_t f1 = 0;
cudaMemGetInfo(&f1, &t0m);
std::printf("vision hold: after %.1f s the GPU encoder is %s (unload count %d), free %.0f MiB (%+.0f MiB)\n", now_s() - th, vrun->gpu()->loaded() ? "still loaded" : "unloaded", vrun->gpu()->unload_count(),
f1 / 1048576.0, (static_cast<double>(f1) - static_cast<double>(f0)) / 1048576.0);
}
if (store) {
std::printf("%s\n", store->report().c_str());
size_t fr2 = 0, tot2 = 0;
cudaMemGetInfo(&fr2, &tot2);
std::printf("GPU memory in use at the end: %.2f GiB\n%s\n", (tot2 - fr2) / kGiB, host_mem_line().c_str());
}
return 0;
}
#else
int cmd_run(const RunOpts&) {
std::fprintf(stderr, "strata-ling32: this build has no CUDA (configure with -DLING32_CUDA=ON)\n");
return 1;
}
#endif
// strata-ling32 --vision-encode VISION.strata IMAGE [IMAGE ...] [--vision-device auto|cpu|gpu] [--device N] [--vision-threads N] [--out FILE] : picture -> embeddings, no language model loaded
int cmd_vision_encode(int argc, char** argv) {
VisionRunOpts vo;
vo.file = argv[2];
std::string out;
for (int i = 3; i < argc; ++i) {
const std::string a = argv[i];
auto nx = [&]() -> std::string { return i + 1 < argc ? argv[++i] : std::string(); };
if (a == "--vision-device") vo.backend = nx();
else if (a == "--device") vo.device = std::atoi(nx().c_str());
else if (a == "--vision-threads") vo.threads = std::atoi(nx().c_str());
else if (a == "--out") out = nx();
else vo.images.push_back(a);
}
std::string err;
std::ofstream of;
if (!out.empty()) of.open(out, std::ios::binary);
#ifdef LING32_HAVE_CUDA
VisionRun vr(vo);
if (!vr.init(err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::printf("encoder: %s\n", vr.backend().c_str());
const VisionCfg c = vr.cfg();
#else
if (vo.backend == "gpu") { std::fprintf(stderr, "strata-ling32: this build has no CUDA\n"); return 1; }
VisionWeights W;
if (!W.load(vo.file, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
const VisionCfg c = W.c;
std::printf("encoder: cpu\n");
#endif
for (const std::string& img : vo.images) {
PreparedImage im;
if (!vision_prepare_file(c, img, im, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
std::vector<float> e;
const double t0 = now_s();
#ifdef LING32_HAVE_CUDA
if (!vr.encode(im, e, err)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
#else
if (!vision_encode_cpu(W, im, e, err, vo.threads)) { std::fprintf(stderr, "strata-ling32: %s\n", err.c_str()); return 1; }
#endif
double ss = 0;
size_t bad = 0;
for (float v : e) { ss += static_cast<double>(v) * v; bad += !std::isfinite(v); }
std::printf("%s: %dx%d -> grid %dx%d, %d embeddings x %d, rms %.5f, non-finite %zu, %.0f ms\n", img.c_str(), im.w, im.h, im.gh, im.gw, im.tokens(), c.out_dim, std::sqrt(ss / std::max<size_t>(1, e.size())), bad,
(now_s() - t0) * 1000.0);
#ifdef LING32_HAVE_CUDA
if (vr.gpu()) std::printf(" gpu memory: weights %.0f MiB resident, activations of this picture %.0f MiB (allocated for the call, freed after it)\n", vr.gpu_stats().weight_bytes / 1048576.0, vr.gpu_stats().scratch_bytes / 1048576.0);
#endif
if (of) of.write(reinterpret_cast<const char*>(e.data()), static_cast<std::streamsize>(e.size() * 4));
}
return 0;
}
} // namespace
int main(int argc, char** argv) {
std::setvbuf(stdout, nullptr, _IONBF, 0); // unbuffered even when redirected to a file (job logs; the MSVC CRT has no line buffering and rejects _IOLBF with size 0)
if (argc >= 2 && !std::strcmp(argv[1], "--version")) { std::printf("strata-ling32 0.2.24\n"); return 0; } // no GPU, no model: the engine installer probes this
if (argc >= 4 && !std::strcmp(argv[1], "--info") && !std::strcmp(argv[3], "--kv")) return cmd_info_kv(argv[2]);
if (argc >= 2 && !std::strcmp(argv[1], "--probe-cap")) { // one line for launchers: the GPU allocation cap of this process in GiB (and what the runtime reports)
const uint64_t cap = probe_gpu_alloc_cap(0);
size_t fr = 0, tot = 0;
cudaMemGetInfo(&fr, &tot);
std::printf("gpu_alloc_cap_gib=%.1f runtime_total_gib=%.1f\n", cap / 1073741824.0, tot / 1073741824.0);
return 0;
}
if (argc >= 3 && !std::strcmp(argv[1], "--info")) return cmd_info(argv[2]);
if (argc >= 3 && !std::strcmp(argv[1], "--selfcheck")) return cmd_selfcheck(argv[2]);
if (argc >= 4 && !std::strcmp(argv[1], "--export-tokenizer")) return cmd_export_tokenizer(argv[2], argv[3]);
if (argc >= 4 && !std::strcmp(argv[1], "--vision-encode")) return cmd_vision_encode(argc, argv);
RunOpts o;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto nx = [&]() -> std::string { return i + 1 < argc ? argv[++i] : std::string(); };
if (a == "--model") o.model = nx();
else if (a == "--ids") o.ids_csv = nx();
else if (a == "--tokens") o.tokens_file = nx();
else if (a == "--jobs") o.jobs = nx();
else if (a == "--out") o.out = nx();
else if (a == "--gen") o.gen = std::atoi(nx().c_str());
else if (a == "--ctx") o.ctx = std::atoi(nx().c_str());
else if (a == "--chunk") o.chunk = std::atoi(nx().c_str());
else if (a == "--device") o.device = std::atoi(nx().c_str());
else if (a == "--topk") o.topk = std::atoi(nx().c_str());
else if (a == "--act") o.act_q8 = nx() == "q8";
else if (a == "--clamp") o.clamp_after = nx() != "before";
else if (a == "--lookahead") o.lookahead = true;
else if (a == "--serve") o.serve = true;
else if (a == "--lookahead-json") o.lookahead_json = nx();
else if (a == "--la-nomask") o.la_nomask = true;
else if (a == "--profile") o.profile = true;
else if (a == "--graph") o.graph = true;
else if (a == "--no-graph") o.graph = false;
else if (a == "--no-fuse-router") o.fuse_router = false;
else if (a == "--kda-chunk") gpu::g_kda_chunk_force = std::atoi(nx().c_str()); // 16 or 32: the chunk length of the chunk-parallel KDA (default: by the device shared memory)
else if (a == "--no-kda-par") o.kda_par = false;
else if (a == "--fuse-experts") o.fuse_experts = true;
else if (a == "--pdl") o.pdl = true;
else if (a == "--no-s8-packed") o.s8_packed = false;
else if (a == "--exact") { o.graph = false; o.tc_min_n = 0; o.tc_moe_min_n = 0; o.mla_kernel = 0; o.mla_prefill_kernel = 0; o.no_dual = true; o.tc_mode = 0; o.fuse_router = false; o.kda_par = false; o.s8_packed = false; o.fuse_experts = false; o.pdl = false; } // the reference configuration of P1: float GEMV, per-pair experts, original MLA kernel
else if (a == "--no-dual") o.no_dual = true;
else if (a == "--invariance") o.invariance = std::atoi(nx().c_str());
else if (a == "--tc-mode") o.tc_mode = std::atoi(nx().c_str());
else if (a == "--moe-q8") o.moe_q8 = true;
else if (a == "--tc") o.tc_min_n = std::atoi(nx().c_str());
else if (a == "--tc-moe") o.tc_moe_min_n = std::atoi(nx().c_str());
else if (a == "--map-experts") o.map_experts = true;
else if (a == "--lock-mapped") o.lock_mapped = true;
else if (a == "--fast-jobs") o.fast_jobs = true;
else if (a == "--cpu-coexec") o.cpu_coexec = std::atoi(nx().c_str());
else if (a == "--cpu-threads") o.cpu_threads = std::atoi(nx().c_str());
else if (a == "--coverage") o.coverage = true;
else if (a == "--tier") o.tier = nx();
else if (a == "--vram-budget-gib") o.vram_budget_gib = std::atof(nx().c_str());
else if (a == "--ram-budget-gib") o.ram_budget_gib = std::atof(nx().c_str());
else if (a == "--turbo-ssd") o.turbo_ssd = true;
else if (a == "--turbo-ssd-threshold") o.turbo_threshold = static_cast<float>(std::atof(nx().c_str()));
else if (a == "--prefetch") o.prefetch = nx() != "off";
else if (a == "--prefetch-width") o.prefetch_width = std::atoi(nx().c_str());
else if (a == "--prefill-prefetch") o.prefill_budget = std::atoi(nx().c_str());
else if (a == "--io-qd") o.io_qd = std::atoi(nx().c_str());
else if (a == "--miss") { o.miss_stage = nx() != "zc"; o.miss_explicit = true; }
else if (a == "--plan") { o.model = nx(); o.plan_only = true; }
else if (a == "--plan-table") o.plan_table = true;
else if (a == "--force-vram-ranks") o.force_vram_ranks = std::atoi(nx().c_str());
else if (a == "--force-ram-ranks") o.force_ram_ranks = std::atoi(nx().c_str());
else if (a == "--force-dyn-slots") o.force_dyn = std::atoi(nx().c_str());
else if (a == "--force-ring-slots") o.force_ring = std::atoi(nx().c_str());
else if (a == "--hw-vram-gib") o.hw_vram_gib = std::atof(nx().c_str());
else if (a == "--hw-ram-gib") o.hw_ram_gib = std::atof(nx().c_str());
else if (a == "--kda") o.kda_seq = nx() == "seq";
else if (a == "--no-selfcheck") o.selfcheck = false;
else if (a == "--vision") o.vis.file = nx();
else if (a == "--image") o.vis.images.push_back(nx());
else if (a == "--vision-device") o.vis.backend = nx();
else if (a == "--vision-idle") o.vis.idle_s = std::atof(nx().c_str());
else if (a == "--vision-threads") o.vis.threads = std::atoi(nx().c_str());
else if (a == "--newline-id") o.vis.newline_id = std::atoi(nx().c_str());
else if (a == "--vision-max-pixels") o.vis.max_pixels = std::atoll(nx().c_str());
else if (a == "--vision-hold") o.vision_hold = std::atof(nx().c_str());
else if (a == "--vision-dump") o.vision_dump = nx();
else if (a == "--mm-runs") o.mm_runs = nx();
else if (a == "--layer-out") o.layer_out = nx();
else if (a == "--configs") o.configs = nx();
else if (a == "--latent") o.latent_f16 = nx() == "f16";
else if (a == "--mla-prefill") { const std::string v = nx(); o.mla_prefill_kernel = v == "simt" ? 1 : v == "tc" ? 2 : v == "tcfast" ? 3 : 0; }
else if (a == "--mla-kernel") { const std::string v = nx(); o.mla_kernel = v == "simt" ? 1 : v == "tc" ? 2 : v == "tcfast" ? 3 : 0; }
else if (a == "--layers-for") o.layers_for = nx();
else if (a == "--spec") { const std::string v = nx(); if (v == "dfly") { std::fprintf(stderr, "strata-ling32: --spec dfly was removed: the speculative drafter is the MTP layer (--mtp Ling-3.2-Air-MTP.strata --spec mtp)\n"); return 2; } o.spec = v == "mtp"; o.spec_mtp = v == "mtp"; }
else if (a == "--mtp") o.mtp_file = nx();
else if (a == "--spec-block") { o.spec_block = std::atoi(nx().c_str()); o.spec_block_set = true; }
else if (a == "--genjobs") o.genjobs = nx();
else if (a == "--dump-hidden-jobs") o.hidden_jobs = nx();
else if (a == "--hidden-decode") o.hidden_decode = true;
else if (a == "--spec-oracle") o.spec_oracle = nx();
else if (a == "--spec-sweep") o.spec_sweep = nx();
else if (a == "--spec-adaptive") o.spec_adaptive = true;
else if (a == "--spec-oracle-err") o.spec_oracle_err = static_cast<float>(std::atof(nx().c_str()));
else if (a == "--dist-test") o.dist_n = std::atoi(nx().c_str());
else if (a == "--dist-len") o.dist_len = std::atoi(nx().c_str());
else if (a == "--temp") o.temp = static_cast<float>(std::atof(nx().c_str()));
else if (a == "--top-p") o.top_p = static_cast<float>(std::atof(nx().c_str()));
else if (a == "--top-k") o.top_k = std::atoi(nx().c_str());
else if (a == "--seed") o.seed = std::strtoull(nx().c_str(), nullptr, 10);
else if (a == "--stop") { if (o.stop.size() == 2 && o.stop[0] == 156895) o.stop.clear(); o.stop.push_back(std::atoi(nx().c_str())); }
else { std::fprintf(stderr, "strata-ling32: unknown option %s\n", a.c_str()); return 2; }
}
if (o.chunk == 0) o.chunk = default_prefill_chunk(o.device);
if (o.mla_prefill_kernel < 0) o.mla_prefill_kernel = default_mla_prefill_kernel(o.device);
if (o.plan_only) return cmd_plan(o);
if (o.tier != "auto" && o.tier != "vram" && o.tier != "hybrid" && o.tier != "nvme") { std::fprintf(stderr, "strata-ling32: --tier must be auto, vram, hybrid or nvme\n"); return 2; }
if (o.model.empty() || (o.ids_csv.empty() && o.tokens_file.empty() && o.jobs.empty() && o.genjobs.empty() && o.hidden_jobs.empty() && !o.serve && o.mm_runs.empty())) {
std::fprintf(stderr,
"usage: strata-ling32 --info FILE | --selfcheck FILE | --export-tokenizer FILE DIR\n"
" strata-ling32 --model FILE (--ids 1,2,3 | --tokens ids.txt) [--gen N] [--act f32|q8] [--clamp after|before] [--ctx N] [--chunk N] [--lookahead] [--temp T --top-p P --top-k K]\n"
" strata-ling32 --model FILE --jobs jobs.jsonl --out DIR [--topk 64] [--lookahead --lookahead-json F]\n");
return 2;
}
if (o.chunk < 1 || o.chunk > 4096) { std::fprintf(stderr, "strata-ling32: --chunk must be 1..4096\n"); return 2; }
return cmd_run(o);
}