Files
Strata/engine/src/ling32/ling32_main.cpp
T
Niko1221 03006f62ed ling32: the loader reserve counts decode_rows of scratch when a tiered run has scratch regrow on (an 8 GB card could not start at chunk 2048)
The loader refuses to start when the free card memory is below trunk + reserve_bytes, and the reserve counted the chunk's logits buffer (chunk x 157,184 x 4 B = 1.3 GiB at 2048) plus its share of the latent cache.  With scratch regrow in a tiered run only decode_rows rows of scratch stay resident (the chunk-sized set is allocated by the first prefill, the store gives pool chunks for it), so the reserve counts min(chunk, decode_rows) rows there.  Every other run (tier A, regrow off, no lazy KV) computes the same expression as before: reserve_rows = o.chunk.
2026-12-03 03:33:44 +01:00

1814 lines
119 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"
#include "ling32_latent.hpp"
#ifdef LING32_HAVE_CUDA
#include "ling32_engine.hpp"
#include "ling32_tier_store.hpp"
#include "ling32_trace.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 mtp_auto=1 images=1 tiers=A,B,C\n", f.cfg().n_layers, f.cfg().V); // mtp=1: this engine takes --mtp FILE --spec mtp; mtp_auto=1: and --mtp-auto FILE
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 (the single stream: the default of AMD with a tier store)
bool dual_force = false; // --dual: the shared expert on a second stream (the default everywhere except AMD with a tier store)
bool mla_hipx = false; // --mla-hipx [--mla-hipx-slab N]: AMD expanded-form WMMA MLA kernel for prefill chunks (the default on gfx12; --no-mla-hipx: the absorbed kernel)
bool no_hipx = false;
int mla_hipx_slab = 2048;
bool tier_grouped = false; // --tier-tc-moe (now the default; kept as a no-op flag)
bool no_tier_tc = false; // --no-tier-tc-moe: per-pair experts in the tiers (the old behaviour)
bool span = false; // --span: layer-major prefill (forward_span), the default with a tier store (--no-span: the chunk loop); --span-max N tokens per span
bool no_span = false;
int span_max = 32768;
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;
int tier_pool = -1; // --tier-pool on|off|auto: one preloaded LRU pool on the card instead of a static hot prefix + a small pool (auto: cards up to 30 GiB)
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
bool mla_expanded = false; // --mla-prefill expanded (CUDA); on by default for sm_80+ and chunks of mla_exp_min_n tokens or more (below)
bool mla_prefill_set = false; // --mla-prefill given: no default switch
int mla_exp_min_n = 0; // the smallest prefill chunk that takes the expanded form (0: every prefill chunk; the default switch sets 1024)
int mla_exp_slab = 2048; // --mla-exp-slab N
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)
bool mla_kernel_set = false; // --mla-kernel given on the command line (else a reserved context of 64K+ picks the tensor-core split kernel where it exists)
int mla_kernel = 1; // --mla-kernel old|simt|tc|tcfast (default simt: Strata's multi-head latent-attention kernel, fp32)
bool latent_set = false; // --latent given (else gfx11 / gfx12 builds default to the pre-split f16x2 cache and the WMMA kernel)
LatentFmt latent = LatentFmt::F32; // --latent f32|f16|q8 (default f32, the exact cache; q8 = int8 + fp16 block scales, 672 B per position and layer)
int age_recent = 0; // --age-mix N: the newest N positions exact, older ones rounded by --latent-emul (study)
int emul_lat = 0, emul_pe = 0; // --latent-emul lat=q8,pe=f16: study rounding of an fp32 cache (ling32_latent.hpp)
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 (loads the sidecar whatever the card)
bool mtp_auto = false; // --mtp-auto FILE: the sidecar is loaded only where it measurably pays (tier A, unified memory, tier B over a host-to-device link of 32 GB/s or more); see mtp_auto_pays
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 logits_rows_opt = -1; // --logits-rows N: rows of the engine's logits buffer (0 = a whole chunk; -1 = 32 for --serve / --genjobs, which ask for few rows, else a whole chunk: the teacher-forced modes dump every row)
int kv_init_opt = -1; // --kv-init N: lazy latent KV, initial capacity in rows (0 = reserve the whole context up front; -1 = 16384 in tier B / C, the cache then grows with the conversation and the tier store gives pool slots back); STRATA_L32_LAZY_KV=0 also switches it off
int kv_plan_rows = 0; // set by make_plan: the rows make_sizes counts for the latent cache (0 = o.ctx)
float skip_tau = -1.0f; // --skip-tau T: dynamic expert skip threshold (< 0: STRATA_L32_SKIP_TAU, default off)
int regrow_opt = -1; // --regrow on|off: scratch regrow (the activation scratch of a chunk only while a prompt is prefilled, the memory goes back to the expert pool for decode); -1 = STRATA_L32_REGROW (default off), tier B / C with lazy KV only
int decode_rows_opt = 64; // --decode-rows N: rows of the always-resident scratch set of scratch regrow
bool regrow_plan = false; // set by make_plan: make_sizes counts decode_rows_opt rows of activation scratch instead of the chunk
bool regrow() const {
if (regrow_opt >= 0) return regrow_opt > 0 && kv_init_rows() > 0 && chunk > decode_rows_opt;
const char* e = std::getenv("STRATA_L32_REGROW");
if (e && e[0]) return e[0] == '1' && kv_init_rows() > 0 && chunk > decode_rows_opt;
#if defined(STRATA_USE_HIP)
return false; // AMD: opt-in until it has run on a Radeon
#else
// default ON on NVIDIA wherever the chunk is 2048 or more: the 1.2 GiB of chunk-sized activations are given back to the pool for decode (RTX 3090, quiet host: chunk 2048 with regrow 55.1 tok/s
// against 52.3 without it and 53.3 at chunk 1024; prefill +13..15 %; ids identical; L32-SMALL's gate)
return chunk >= 2048 && kv_init_rows() > 0 && chunk > decode_rows_opt;
#endif
}
int kv_init_rows() const {
const char* e = std::getenv("STRATA_L32_LAZY_KV");
if (e && e[0] == '0') return 0;
const int n = kv_init_opt >= 0 ? kv_init_opt : 16384;
return n > 0 && n < ctx ? n : 0;
}
int logits_rows() const { return logits_rows_opt >= 0 ? logits_rows_opt : ((serve || !genjobs.empty()) ? 32 : 0); }
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, minor = 0;
cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, device);
cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, device);
cudaGetLastError();
return (major > 7 || (major == 7 && minor >= 5)) ? 2 : 1; // sm_75 (Turing: mma.sync m16n8k8 pairs) and up; Volta (sm_70) keeps the scalar kernel
#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)
// gfx12 (R9700): 2048 (the wide expert tiles of the WMMA kernels fill from about 32 pairs per expert, i.e. from 2048 tokens: 4K prefill 918 -> 1,084 tok/s, 16K 918 -> 1,095, bit-identical; the
// planner takes the 1.8 GiB of activations from the expert pool: decode -4 % in a short measurement, --chunk 1024 gives it back). Other AMD cards (gfx11 iGPUs) stay at 1024: not measured.
{
const bool g12 = std::strncmp(dp.gcnArchName, "gfx12", 5) == 0;
chunk = std::min(chunk, g12 ? 2048 : 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);
constexpr size_t kGiB = 1ull << 30;
{ // what the runtime says before anything is allocated (diagnosis of the Windows iGPU stall); STRATA_L32_GPU_CAP_GIB=N: use N GiB and skip the allocate-and-free probe
size_t fr = 0, tot = 0;
cudaMemGetInfo(&fr, &tot);
l32::trace("probe: cudaMemGetInfo before the probe: free %.2f GiB of %.2f GiB", fr / double(kGiB), tot / double(kGiB));
if (const char* ov = std::getenv("STRATA_L32_GPU_CAP_GIB")) if (std::atof(ov) > 0) return static_cast<uint64_t>(std::atof(ov) * double(kGiB));
#if defined(STRATA_USE_HIP) && defined(_WIN32)
// Windows integrated GPU (Strix Halo): DO NOT allocate and free the whole memory to find the cap. Measured on the Strix with the 96 GB carve-out (2026-12-03): the probe "succeeded" with 111 GiB,
// more than the 107.87 GiB the runtime reports (the driver overcommits into shared system memory), and after the free cudaMemGetInfo said 0.00 GiB free; the next device allocation worked but its first
// copy then stalled for good (1 thread, 14 GB working set, no events). Without the probe the same load takes 20 s. The cap is what the runtime reports before anything is allocated; a single
// allocation that fails later falls back to chunked experts (ling32_model.cu). STRATA_L32_PROBE_ALLOC=1 brings the old probe back.
cudaDeviceProp prop;
const char* pa = std::getenv("STRATA_L32_PROBE_ALLOC");
if (cudaGetDeviceProperties(&prop, device) == cudaSuccess && prop.integrated && !(pa && pa[0] == '1') && fr > 0)
return static_cast<uint64_t>(std::min(fr, tot));
#endif
}
std::vector<void*> v;
for (int i = 0; i < 512; ++i) {
void* p = nullptr;
if (cudaMalloc(&p, kGiB) != cudaSuccess) { cudaGetLastError(); break; }
v.push_back(p);
}
l32::trace("probe: %zu GiB allocated, freeing", v.size());
for (void* p : v) cudaFree(p);
{
size_t fr = 0, tot = 0;
cudaMemGetInfo(&fr, &tot);
l32::trace("probe: freed; cudaMemGetInfo free %.2f GiB of %.2f GiB", fr / double(kGiB), tot / double(kGiB));
}
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;
rq.pool = o.tier_pool;
if (!o.mtp_file.empty()) {
std::error_code ec;
const auto sz = std::filesystem::file_size(o.mtp_file, ec);
if (!ec) rq.mtp_bytes = static_cast<uint64_t>(sz);
const char* mp = std::getenv("STRATA_L32_MTP_POOL"); // =0: the sidecar's experts stay a resident block on the card
rq.mtp_in_pool = !(mp && mp[0] == '0');
strata::artifact::StrataFileReader rd;
std::string e2;
if (rq.mtp_bytes && rd.open(o.mtp_file, e2)) rq.mtp_expert_bytes = rd.header().sections[4].byte_length;
}
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;
if (o.mla_hipx) sz.trunk_bytes += 256ull * 1048576ull; // the expanded-form MLA (--mla-hipx): fp16 copies of wk_b / wv_b (7 layers) and the slab / query / state workspace
sz.lookahead_bytes = static_cast<uint64_t>(51.25 * 1048576.0);
{ // the latent cache of every MLA layer (7 in Ling-3.2-Air; the MTP layer adds one when the drafter is loaded) at the chosen precision
int n_mla = 0;
for (int il = 0; il < f.cfg().n_layers; ++il) n_mla += f.cfg().is_mla(il) ? 1 : 0;
if (o.spec_mtp || !o.mtp_file.empty()) ++n_mla;
sz.latent_bytes = static_cast<uint64_t>(n_mla) * latent_layer_bytes(o.latent, o.kv_plan_rows > 0 ? o.kv_plan_rows : o.ctx, f.cfg().kv_lora, f.cfg().rope);
}
sz.chunk = o.regrow_plan ? std::min(o.chunk, o.decode_rows_opt) : o.chunk; // scratch regrow: the plan counts the decode set only; a prompt takes pool chunks back while it is prefilled
sz.logits_rows = o.logits_rows() > 0 ? std::min(o.logits_rows(), static_cast<int>(sz.chunk)) : static_cast<int>(sz.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;
// lazy latent KV: the planner counts the initial capacity only; a plan that keeps everything on the card (tier A: CUDA graphs capture the cache) is made again with the whole context
RunOpts po = o;
po.kv_plan_rows = o.kv_init_rows();
po.regrow_plan = o.regrow();
plan = plan_tier(hw, make_request(o), rt, make_sizes(f, po));
if (plan.ok && plan.mode == TierMode::A && po.kv_plan_rows > 0) { po.kv_plan_rows = 0; po.regrow_plan = false; plan = plan_tier(hw, make_request(o), rt, make_sizes(f, po)); } // tier A keeps everything (and the CUDA graphs): no regrow
if (!plan.ok) { err = plan.error; return false; }
plan.kv_rows = po.kv_plan_rows;
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;
if (plan.mode == TierMode::A) plan.kv_rows = 0;
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; plan.dyn_big = 0; plan.slot_small = 0; }
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 %s %.0f MiB (ctx %d), chunk %d\n", sz.trunk_bytes / kGiB, latent_name(o.latent), sz.latent_bytes / 1048576.0, o.ctx, o.chunk);
for (LatentFmt lf : {LatentFmt::F32, LatentFmt::F16, LatentFmt::Q8, LatentFmt::F16X2}) { // the cache at every precision (per position of all MLA layers, and at this ctx)
RunOpts ol = o;
ol.latent = lf;
const TierSizes sl = make_sizes(f, ol);
std::printf(" latent %-3s: %6.0f B per position over all MLA layers, %8.0f MiB at ctx %d\n", latent_name(lf), static_cast<double>(sl.latent_bytes) / std::max(1, o.ctx), sl.latent_bytes / 1048576.0, o.ctx);
}
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;
if ((o.span || (E.tiered() && !o.no_span)) && !all && last) { // layer-major spans of up to span_max tokens (multiples of the chunk: the same chunk boundaries as below)
const size_t smax = std::max<size_t>(o.chunk, (static_cast<size_t>(o.span_max) / o.chunk) * o.chunk);
for (size_t t0 = 0; t0 < ids.size(); t0 += smax) {
const int n = static_cast<int>(std::min<size_t>(smax, ids.size() - t0));
const bool is_last = t0 + n >= ids.size();
std::vector<float> lg;
if (!E.forward_span(ids.data() + t0, n, is_last ? 1 : 0, is_last ? &lg : nullptr, err)) return false;
if (is_last) last->assign(lg.end() - V, lg.end());
}
return true;
}
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;
}
// like prefill_rows, but only the logits of the last `tail` prompt positions are computed and handed to the sink (long-context runs: the top-K bookkeeping of 256K rows would dominate)
bool prefill_rows_tail(Ling32Engine& E, const RunOpts& o, const std::vector<int>& ids, int tail, const std::function<void(const float*, int)>& sink, std::string& err) {
const size_t from = ids.size() > static_cast<size_t>(tail) ? ids.size() - static_cast<size_t>(tail) : 0;
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));
const size_t t1 = t0 + static_cast<size_t>(n);
const int nl = t1 <= from ? 0 : static_cast<int>(t1 - std::max(from, t0));
std::vector<float> lg;
if (!E.forward(ids.data() + t0, n, nl, nl > 0 ? &lg : nullptr, err)) return false;
if (nl > 0) sink(lg.data(), nl);
}
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");
}
// one pinned 256 MiB host-to-device copy, three repeats (after a warm-up), the median in GB/s (1e9 bytes per second); 0 when it cannot be measured
double measure_h2d_gbps(int device) {
if (const char* ov = std::getenv("STRATA_L32_H2D_GBPS")) return std::atof(ov); // test hook: the link figure by hand (ling32_mtp_auto_regress)
constexpr size_t n = 256ull << 20;
if (cudaSetDevice(device) != cudaSuccess) return 0.0;
void* h = nullptr;
void* d = nullptr;
cudaStream_t st = nullptr;
cudaEvent_t e0 = nullptr, e1 = nullptr;
double med = 0.0;
l32::trace("h2d probe: cudaMallocHost %zu MiB", n >> 20);
const bool probe_host_ok = cudaMallocHost(&h, n) == cudaSuccess;
l32::trace("h2d probe: cudaMallocHost %s; cudaMalloc %zu MiB", probe_host_ok ? "ok" : "failed", n >> 20);
if (probe_host_ok && cudaMalloc(&d, n) == cudaSuccess && cudaStreamCreate(&st) == cudaSuccess && cudaEventCreate(&e0) == cudaSuccess && cudaEventCreate(&e1) == cudaSuccess) {
l32::trace("h2d probe: memset and copies");
std::memset(h, 1, n);
cudaMemcpyAsync(d, h, n, cudaMemcpyHostToDevice, st);
cudaStreamSynchronize(st);
double v[3] = {0, 0, 0};
for (int i = 0; i < 3; ++i) {
cudaEventRecord(e0, st);
cudaMemcpyAsync(d, h, n, cudaMemcpyHostToDevice, st);
cudaEventRecord(e1, st);
cudaEventSynchronize(e1);
float ms = 0.0f;
if (cudaEventElapsedTime(&ms, e0, e1) == cudaSuccess && ms > 0.0f) v[i] = static_cast<double>(n) / (static_cast<double>(ms) * 1e6);
}
std::sort(v, v + 3);
med = v[1];
}
if (e0) cudaEventDestroy(e0);
if (e1) cudaEventDestroy(e1);
if (st) cudaStreamDestroy(st);
if (d) cudaFree(d);
if (h) cudaFreeHost(h);
(void)cudaGetLastError();
return med;
}
int cmd_run(const RunOpts& o_in) {
RunOpts o = o_in; // --mtp-auto may drop the sidecar after the plan is known
double h2d_gbps = 0.0; // the measured host-to-device link (tier B / C), 0 = not measured
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;
l32::trace("main: probing the GPU allocation cap");
const uint64_t cap = probe_gpu_alloc_cap(o.device);
l32::trace("main: allocation cap %.1f GiB", cap / 1073741824.0);
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));
}
uint64_t win_pin_cap = 0; // Windows with a discrete card: how much RAM the planner may give the pinned RAM tier
#if defined(_WIN32)
if (!win_igpu && o.tier != "vram") {
// The driver page-locks only part of the system RAM for the GPU (it stops at about half of it, and the commit limit is RAM + page file): a 34 GiB cudaHostAlloc failed with "out of memory" on a
// 63 GB PC with 43 GB free (the planner had offered all free RAM minus 6 GiB). Plan the RAM tier within the free RAM minus 8 GiB for Windows and at most half of the system RAM minus 0.5 GiB
// (the figure measured on the Strix: 15.3 GiB pinned fine of 31.6 GiB RAM, 15.8 GiB stalls); an explicit --ram-budget-gib above that is cut to it. The tier store also steps down on its own
// when the system still refuses (ling32_tier_store.cu host_region).
MEMORYSTATUSEX ms;
ms.dwLength = sizeof ms;
if (GlobalMemoryStatusEx(&ms)) {
constexpr uint64_t kGiBu = 1ull << 30;
const uint64_t freeb = ms.ullAvailPhys > 8 * kGiBu ? ms.ullAvailPhys - 8 * kGiBu : 0;
const uint64_t half = ms.ullTotalPhys / 2 > kGiBu / 2 ? ms.ullTotalPhys / 2 - kGiBu / 2 : 0;
win_pin_cap = std::min<uint64_t>(freeb, half);
}
}
#endif
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 (win_pin_cap > 0) {
const double cap_gib = win_pin_cap / double(1ull << 30);
if (plan_opts.ram_budget_gib <= 0 || plan_opts.ram_budget_gib > cap_gib) {
if (plan_opts.ram_budget_gib > cap_gib) std::printf("Windows: --ram-budget-gib %.1f is above what the GPU driver can pin here; the RAM tier is planned at %.1f GiB\n", plan_opts.ram_budget_gib, cap_gib);
else std::printf("Windows: the RAM tier is planned within %.1f GiB (free RAM minus 8 GiB, at most half of the system RAM: the GPU driver pins no more)\n", cap_gib);
plan_opts.ram_budget_gib = cap_gib;
}
}
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;
}
if (o.mtp_auto && !o.mtp_file.empty()) { // --mtp-auto: the sidecar only where it pays (tier A, unified memory, tier B over a fast link)
std::string why;
if (tiered) h2d_gbps = measure_h2d_gbps(o.device);
int min_card = kMtpAutoMinCardExperts;
if (const char* ev = std::getenv("STRATA_L32_MTP_AUTO_MIN_CARD")) if (ev[0]) min_card = std::atoi(ev); // test hook: the pool-size cut by hand (0: off; ling32_mtp_auto_regress)
const bool pays = mtp_auto_pays(tiered ? plan.mode : TierMode::A, integrated, h2d_gbps, &why, tiered ? plan.dyn_slots + plan.vram_ranks * 40 : -1, min_card); // 40 routed layers
if (tiered) std::printf("tier store: host-to-device link moved %.1f GB/s (pinned 256 MiB copies, median of 3)\n", h2d_gbps);
std::printf("MTP sidecar (--mtp-auto): %s: %s\n", pays ? "loaded" : "not loaded (--mtp FILE forces it)", why.c_str());
if (!pays) {
o.mtp_file.clear();
o.spec_mtp = false;
o.spec = false; // the speculative loop is the drafter's: a plain run follows
if (tiered) { // the plan counted the sidecar's bytes: plan again without it
RunOpts po = o;
std::string perr2;
if (make_plan(f, po, plan_vram, plan_ram, plan, rt, perr2)) { std::printf("%s\n", plan.describe().c_str()); tiered = plan.mode != TierMode::A; }
}
}
} else if (tiered && o.tier != "vram") {
h2d_gbps = measure_h2d_gbps(o.device);
std::printf("tier store: host-to-device link moved %.1f GB/s (pinned 256 MiB copies, median of 3)\n", h2d_gbps);
}
}
l32::trace("main: plan done, loading the model (%s)", tiered ? "tiered" : "tier A");
GpuModel M;
LoadOptions lo;
lo.load_lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch);
int la_ks_env = -1; // STRATA_L32_LA_KS (measurement): bit mask of the lookahead predictors to compute (1: k=2, 2: k=4, 3: both), e.g. with STRATA_L32_PF_K=2 in a tier B run
if (const char* e = std::getenv("STRATA_L32_LA_KS")) if (e[0]) la_ks_env = std::atoi(e) & 3;
if (tiered) lo.lookahead_ks = la_ks_env >= 0 ? la_ks_env : (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;
// the card must hold the trunk and this reserve; with scratch regrow in a tiered run the always-resident scratch is decode_rows rows, a prompt takes pool slots for the big chunk scratch only while it is prefilled
// (a card of 8 GB could not start at chunk 2048: the logits buffer of the chunk alone is 1.3 GiB)
const int reserve_rows = (tiered && plan.kv_rows > 0 && o.regrow()) ? std::min(o.chunk, o.decode_rows_opt) : o.chunk;
lo.reserve_bytes = (1ull << 30) + static_cast<uint64_t>(o.ctx) * 576 * 2 * 7 + static_cast<uint64_t>(reserve_rows) * 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();
l32::trace("main: M.load starts (load_experts=%d)", lo.load_experts ? 1 : 0);
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());
{ // the sidecar's experts become slots of the pool (pinned RAM -> card on demand) when the plan is a pool plan; otherwise they stay a resident block
const char* mp = std::getenv("STRATA_L32_MTP_POOL");
M.mtp_pool = tiered && plan.pool_mode && !(mp && mp[0] == '0');
}
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; }
M.drop_mtp_host(); // the store holds its own copy of the sidecar's experts
if (store->serves_mtp()) std::printf("tier store: the MTP layer's 512 experts are slots of the pool (%.2f GiB pinned in RAM)\n", M.mtp.sec4_bytes / kGiB);
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.logits_rows = o.logits_rows();
if (tiered && plan.kv_rows > 0) eo.kv_init_ctx = plan.kv_rows; // lazy latent KV (the plan counted only this)
if (o.skip_tau >= 0.0f) eo.skip_tau = o.skip_tau;
else if (const char* e = std::getenv("STRATA_L32_SKIP_TAU")) { if (e[0]) eo.skip_tau = static_cast<float>(std::atof(e)); }
if (eo.skip_tau > 0.0f) std::printf("expert skip: tau %.3f (NOT exact: routed experts below that share of a token's routing weight are dropped at decode)\n", eo.skip_tau);
if (tiered && plan.kv_rows > 0 && o.regrow()) { eo.scratch_regrow = true; eo.decode_rows = o.decode_rows_opt; } // the plan counted decode_rows rows of scratch only
eo.lookahead = o.lookahead || o.coverage || (tiered && plan.prefetch);
if (tiered) { eo.lookahead_ks = la_ks_env >= 0 ? la_ks_env : (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;
#if defined(STRATA_USE_HIP)
// AMD with a tier store: the shared expert on a second stream costs four cross-stream event operations per MoE layer (about 300 per token); on the R9700 that is 30 % of the plain decode
// step (4K prompt, pool default: 30.4 tok/s with it, 39.5 without), the overlap with the host-side prepare() wait does not pay it back. The single-stream order is also the reference arithmetic
// of --exact. --dual brings the second stream back; the Windows iGPU keeps it until measured there.
eo.dual_stream = o.dual_force || (!o.no_dual && !(tiered && !igpu_zero_copy));
#else
eo.dual_stream = !o.no_dual;
#endif
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.mla_hipx = o.mla_hipx;
eo.mla_hipx_slab = o.mla_hipx_slab;
eo.tier_grouped = !o.no_tier_tc && std::getenv("STRATA_L32_TIER_GROUPED_OFF") == nullptr; // default ON: the tiers run the same grouped tensor-core experts as a resident model (--no-tier-tc-moe: the per-pair kernels)
#if !defined(STRATA_USE_HIP)
{ // Turing (sm_75) runs the tensor-core kernels with the k16 step as two mma.sync m16n8k8 (ling32_dev.cuh), ldmatrix as is, cp.async as a register copy. Volta (sm_70) runs the trunk GEMM and
// the grouped experts on WMMA 16x16x16 (volta_group_step). Pascal has no tensor cores: every path that uses them is switched to its SIMT kernel (what --exact selects); the decode kernels are the same on every card
int ccmaj = 0, ccmin = 0;
cudaDeviceGetAttribute(&ccmaj, cudaDevAttrComputeCapabilityMajor, o.device);
cudaDeviceGetAttribute(&ccmin, cudaDevAttrComputeCapabilityMinor, o.device);
cudaGetLastError();
const bool no_mma = ccmaj > 0 && ccmaj < 7; // Pascal and below: no tensor cores (sm_70 runs the WMMA group step of the trunk GEMM and the grouped experts; its MLA stays on the scalar kernels)
if (no_mma && std::getenv("STRATA_L32_TC_FORCE") == nullptr) {
eo.tc_min_n = 0;
eo.tc_moe_min_n = 0;
eo.tier_grouped = false;
std::printf("compute capability %d.%d: no tensor cores: trunk, grouped experts and expanded MLA use the SIMT kernels\n", ccmaj, ccmin);
}
}
#endif
eo.capture = !o.layer_out.empty();
eo.latent = o.latent;
#if defined(STRATA_USE_HIP)
// AMD gfx11 / gfx12: the default MLA cache is the pre-split fp16 hi / lo planes (same bytes as fp32, fp32-class accuracy) read by the WMMA kernel: 1.8x (gfx1151) to 3x (gfx1201) faster
// attention than the scalar fp32 kernel at long context, golden-neutral (P8-LONGCTX-RESULTS.md). --latent f32 selects the scalar kernel, --exact too.
if (!o.latent_set && o.latent == LatentFmt::F32 && o.mla_kernel > 0) {
cudaDeviceProp dp{};
if (cudaGetDeviceProperties(&dp, o.device) == cudaSuccess && (std::strncmp(dp.gcnArchName, "gfx11", 5) == 0 || std::strncmp(dp.gcnArchName, "gfx12", 5) == 0)) {
eo.latent = LatentFmt::F16X2;
std::printf("MLA cache: f16x2 (pre-split fp16 planes, WMMA kernel); --latent f32 for the scalar fp32 kernel\n");
}
}
#endif
eo.emul_lat = o.emul_lat;
eo.emul_pe = o.emul_pe;
eo.age_recent = o.age_recent;
eo.mla_kernel = o.mla_kernel;
// L32-LONG: reserved contexts of 64K and more decode with the tensor-core split kernel where it exists (sm_80+): measured 1.30x faster at 256K on a PRO 6000 (f32 cache), the same accuracy class as
// the scalar kernel (golden KL / top-1 equal to the digits shown in P8-LONGCTX-RESULTS.md); below 64K, and with an explicit --mla-kernel, nothing changes.
if (!o.mla_kernel_set && o.mla_kernel == 1 && o.ctx >= 65536) eo.mla_kernel = default_mla_prefill_kernel(o.device);
eo.mla_prefill_kernel = o.mla_prefill_kernel;
eo.mla_expanded = o.mla_expanded;
eo.mla_exp_min_n = o.mla_exp_min_n;
eo.mla_exp_slab = o.mla_exp_slab;
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.h2d_gbps = h2d_gbps;
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();
if (const json::JVal* fc = j.get("fake_ctx")) { // {"id","fake_ctx":N,"gen":G}: G greedy decode steps at position N with zeroed caches, no prefill (cost only, see Ling32Engine::fake_context)
const int n = static_cast<int>(fc->i());
const int g = j.get("gen") ? static_cast<int>(j.at("gen").i()) : 32;
E.fake_context(n);
if (store) store->reset_stats();
std::vector<float> last;
int next = 1000;
std::vector<double> step_ms;
bool nan = false;
const double td = now_s();
for (int i = 0; i < g; ++i) {
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);
float bv = last[0];
next = 0;
for (int v = 0; v < V; ++v) { nan = nan || !std::isfinite(last[v]); if (last[v] > bv) { bv = last[v]; next = v; } }
}
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::printf("job %-14s fake context %7d: %d decode steps in %.2f s = %.2f tok/s (median step %.1f ms = %.2f tok/s)%s\n", id.c_str(), n, g, t_gen, g / std::max(1e-9, t_gen), med, med > 0 ? 1000.0 / med : 0.0, nan ? " NaN/Inf" : "");
if (o.profile) std::printf("%s", E.profile_report().c_str());
if (store) std::printf("%s\n", store->report().c_str());
++n_jobs;
continue;
}
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;
if (o.profile) std::printf("[%s: prefill of %zu tokens]\n%s", id.c_str(), prompt.size(), E.profile_report().c_str());
if (std::getenv("STRATA_L32_DUMP_LAST")) { // the logits of the last prompt position (bit-identity gates: compare the files)
std::ofstream lf(std::filesystem::path(outdir) / (id + ".last.f32"), std::ios::binary);
lf.write(reinterpret_cast<const char*>(last.data()), static_cast<std::streamsize>(last.size() * 4));
}
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;
const int tail = j.get("tail") ? static_cast<int>(j.at("tail").i()) : 0; // "tail": N = dump only the last N prompt positions (long prompts)
if (!(tail > 0 ? prefill_rows_tail(E, o, prompt, tail, sink, err) : 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 = LatentFmt::F32; e2.emul_lat = e2.emul_pe = 0; }
else if (part == "lat16") e2.latent = LatentFmt::F16;
else if (part == "latq8") e2.latent = LatentFmt::Q8;
else if (part == "latw") e2.latent = LatentFmt::F16X2; // pre-split fp16 hi / lo planes (AMD)
else if (part.rfind("age", 0) == 0 && part.size() > 3 && std::isdigit(static_cast<unsigned char>(part[3]))) e2.age_recent = std::atoi(part.c_str() + 3); // age512: the newest 512 positions exact, older ones through the el- / ep- rounding of the same config
else if (part == "mlasimt") e2.mla_kernel = 1; // decode / verify MLA kernel: scalar fp32 (the default) or the tensor-core split (about fp32 accuracy; a different summation order)
else if (part == "mlatc") e2.mla_kernel = 2;
else if (part.rfind("el-", 0) == 0 || part.rfind("ep-", 0) == 0) { // el-q8 / ep-f16: an fp32 cache with rounded latent / rope values (study)
int cl = 0, cp = 0;
if (!emul_parse(std::string(part[1] == 'l' ? "lat=" : "pe=") + part.substr(3), &cl, &cp)) { std::fprintf(stderr, "strata-ling32: bad config part '%s'\n", part.c_str()); return 2; }
e2.latent = LatentFmt::F32;
if (part[1] == 'l') e2.emul_lat = cl; else e2.emul_pe = cp;
}
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 == "nt2" || part == "nt4") gpu::g_w2_nt = part[2] - '0'; // AMD trunk GEMM: 32 / 64 tokens per block
else if (part == "etn1" || part == "etn2") gpu::g_w2_etn = part[3] - '0'; // AMD experts: tiles of 16 / 32 pairs
else if (part == "hx" || part == "nohx") e2.mla_hipx = part == "hx"; // expanded-form WMMA MLA on / off
else if (part == "ttc" || part == "nottc") e2.tier_grouped = part == "ttc"; // grouped tensor-core experts in the tiers on / off
else if (part == "span" || part == "nospan") { o2.span = part == "span"; o2.no_span = part == "nospan"; } // layer-major prefill on / off
else if (part == "sh0" || part == "sh1") { if (store) store->set_span_hint(part == "sh1"); } // next-layer hint of the span off / on
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
#ifndef LING32_VERSION
#error "LING32_VERSION is defined by engine/src/ling32/CMakeLists.txt (the shared engine version); there is no literal version in the sources"
#endif
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 %s\n", LING32_VERSION); 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 == "--logits-rows") o.logits_rows_opt = std::atoi(nx().c_str());
else if (a == "--kv-init") o.kv_init_opt = std::atoi(nx().c_str());
else if (a == "--regrow") { const std::string v = nx(); o.regrow_opt = (v == "on" || v == "1") ? 1 : 0; }
else if (a == "--skip-tau") o.skip_tau = static_cast<float>(std::atof(nx().c_str())); // dynamic expert skip, opt-in, NOT exact (see EngineOptions::skip_tau)
else if (a == "--decode-rows") o.decode_rows_opt = std::max(1, 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.mla_expanded = false; 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 == "--dual") o.dual_force = 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 == "--tier-tc-moe") o.tier_grouped = true;
else if (a == "--no-tier-tc-moe") o.no_tier_tc = true;
else if (a == "--mla-hipx") o.mla_hipx = true;
else if (a == "--no-mla-hipx") o.no_hipx = true;
else if (a == "--mla-hipx-slab") o.mla_hipx_slab = std::atoi(nx().c_str());
else if (a == "--span") o.span = true;
else if (a == "--no-span") o.no_span = true;
else if (a == "--span-max") o.span_max = 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 == "--tier-pool") { const std::string v = nx(); o.tier_pool = v == "on" ? 1 : v == "off" ? 0 : -1; }
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_set = true; const std::string v = nx(); if (!latent_parse(v, &o.latent)) { std::fprintf(stderr, "strata-ling32: --latent f32|f16|q8|f16x2, not '%s'\n", v.c_str()); return 2; } }
else if (a == "--age-mix") o.age_recent = std::atoi(nx().c_str());
else if (a == "--latent-emul") { const std::string v = nx(); if (!emul_parse(v, &o.emul_lat, &o.emul_pe)) { std::fprintf(stderr, "strata-ling32: --latent-emul lat=f16|q8|bf16|q10|q12|q14,pe=f16|bf16, not '%s'\n", v.c_str()); return 2; } }
else if (a == "--mla-prefill") { const std::string v = nx(); o.mla_prefill_kernel = v == "simt" ? 1 : (v == "tc" || v == "expanded") ? 2 : v == "tcfast" ? 3 : 0; o.mla_expanded = v == "expanded"; o.mla_prefill_set = true; }
else if (a == "--mla-exp-slab") o.mla_exp_slab = std::atoi(nx().c_str());
else if (a == "--mla-kernel") { o.mla_kernel_set = true; 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 == "--mtp-auto") { o.mtp_file = nx(); o.mtp_auto = true; }
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);
// a card budget below 30 GiB (--vram-budget-gib) is a small card for the planner: the 2048 chunk would take its activations out of an already small pool (R9700 capped to 10 GiB, tier C: 4K prefill
// 121 -> 84 tok/s with chunk 2048), so the chunk follows the budget as it follows the memory of a real small card
if (o.vram_budget_gib > 0 && o.vram_budget_gib < 30.0 && o.chunk > 1024) o.chunk = 1024;
}
if (o.mla_prefill_kernel < 0) o.mla_prefill_kernel = default_mla_prefill_kernel(o.device);
if (!o.mla_prefill_set && o.mla_prefill_kernel == 2 && !o.mla_expanded) { // NVIDIA sm_80+ (the tensor-core MLA is the default there): the expanded-form MLA for prefill chunks of 1024+ tokens (3.4x fewer flop; not bit-identical to the absorbed form, inside the golden bands)
const char* ev = std::getenv("STRATA_L32_MLA_EXPANDED"); // =0: back to the absorbed form without a rebuild
if (!(ev && ev[0] == '0')) { o.mla_expanded = true; o.mla_exp_min_n = 1024; }
}
#if defined(STRATA_USE_HIP)
{ // gfx12: the expanded-form WMMA MLA for prefill chunks is the default (owner decision 2026-12-02, after the R9700 goldens); gfx11 and the other AMD cards keep the absorbed kernel
cudaDeviceProp dpx{};
if (!o.no_hipx && cudaGetDeviceProperties(&dpx, o.device) == cudaSuccess && std::strncmp(dpx.gcnArchName, "gfx12", 5) == 0) o.mla_hipx = true;
cudaGetLastError();
}
#endif
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);
}