const MIN_GAIN = 0.005;
const DEFAULT_GUARD_MAX_DROP = 0.015;
const FILLER =
"alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega ";
const PARITY_TEXT = "parity check: " + FILLER;
let measureNonce = 0;
function isSyntheticKey(name) {
return /^(engine|gpu|plan):/.test(name);
}
function kernelFamily(name) {
const idx = name.indexOf(" ");
return idx >= 0 ? name.slice(0, idx) : name;
}
function collectSpills(spent) {
const byFamily = {};
const details = new Map();
for (const [name, row] of Object.entries(spent || {})) {
if (isSyntheticKey(name) || !row || !row.attrs || !(row.attrs.local > 0)) continue;
const fam = kernelFamily(name);
const local = row.attrs.local;
if (!byFamily[fam] || local > byFamily[fam]) byFamily[fam] = local;
const cur = details.get(fam) || {
name: fam,
local: 0,
regs: 0,
shared: 0,
ctas: 0,
sites: 0,
ms: 0,
};
cur.sites += 1;
cur.ms += (row.seconds || 0) * 1000;
if (local >= cur.local) {
cur.local = local;
cur.regs = row.attrs.regs || 0;
cur.shared = row.attrs.shared || 0;
cur.ctas = row.attrs.ctas || 0;
}
details.set(fam, cur);
}
const list = Array.from(details.values()).sort((a, b) => b.local - a.local || b.ms - a.ms);
return { byFamily, list };
}
function hasNewSpills(baseMap, candMap) {
for (const [fam, local] of Object.entries(candMap || {})) {
if (local > (baseMap[fam] || 0)) return true;
}
return false;
}
function parseMetric(m) {
const streams = m.streams || [];
let decodeTokens = 0;
let decodeSecs = 0;
let firstSum = 0;
let firstCount = 0;
let cachedTokens = 0;
for (const s of streams) {
cachedTokens += s.cached || 0;
if (s.first != null) {
firstSum += s.first;
firstCount += 1;
}
if (s.tokens > 1 && s.first != null && s.last != null && s.last > s.first) {
decodeTokens += s.tokens - 1;
decodeSecs += s.last - s.first;
}
}
const totalSecs = m.seconds > 0 ? m.seconds : 1e-9;
const decodeTps = decodeSecs > 0 ? decodeTokens / decodeSecs : m.tokens / totalSecs;
const ttftMs = firstCount > 0 ? (firstSum / firstCount) * 1000 : 0;
const prefillTps = ttftMs > 0 ? m.prompt_tokens / (ttftMs / 1000) : 0;
const spent = m.spent || {};
const spills = collectSpills(spent);
return {
decode_tps: decodeTps,
prefill_tps: prefillTps,
ttft_ms: ttftMs,
seconds: m.seconds,
tokens: m.tokens,
prompt_tokens: m.prompt_tokens,
cached_tokens: cachedTokens,
launches: m.launches,
spill_kernels: spills.list.reduce((acc, r) => acc + r.sites, 0),
spills_by_family: spills.byFamily,
spills_list: spills.list,
spent,
};
}
function rankSpent(spent, limit) {
const byFamily = new Map();
for (const [name, s] of Object.entries(spent || {})) {
if (isSyntheticKey(name) || !s) continue;
const fam = kernelFamily(name);
const cur = byFamily.get(fam) || {
name: fam,
seconds: 0,
count: 0,
sites: 0,
attrs: null,
};
cur.seconds += s.seconds || 0;
cur.count += s.count || 0;
cur.sites += 1;
if (s.attrs) {
if (!cur.attrs || (s.attrs.local || 0) > (cur.attrs.local || 0)) {
cur.attrs = s.attrs;
}
}
byFamily.set(fam, cur);
}
const rows = Array.from(byFamily.values());
rows.sort((a, b) => b.seconds - a.seconds);
const total = rows.reduce((acc, r) => acc + r.seconds, 0) || 1e-9;
return rows.slice(0, limit).map((r) => ({
name: r.name,
ms: r.seconds * 1000,
pct: (r.seconds / total) * 100,
count: r.count,
sites: r.sites,
attrs: r.attrs,
}));
}
function formatAttrs(a) {
if (!a) return "";
const spill = a.local > 0 ? ` lmem=${a.local} SPILL` : "";
return ` [regs=${a.regs} smem=${a.shared} ctas=${a.ctas}${spill}]`;
}
function knobKey(kernel, name) {
return `${kernel}:${name}`;
}
function targetReports(explained, target, streams) {
const reports = [];
if (!explained) return reports;
if (target === "prefill") {
if (explained.prefill) reports.push(explained.prefill);
return reports;
}
if (explained.decode) {
const all = Array.isArray(explained.decode) ? explained.decode : [explained.decode];
const primary = all.filter((r) => r && r.target && r.target.rows === streams);
reports.push(...(primary.length > 0 ? primary : all));
}
if (reports.length === 0 && explained.prefill) reports.push(explained.prefill);
return reports;
}
function activeKnobs(schema, explained, filters, target, streams) {
const byKey = new Map();
for (const k of schema.knobs || []) {
byKey.set(knobKey(k.kernel, k.name), k);
}
const found = new Map();
for (const rep of targetReports(explained, target, streams)) {
for (const v of rep.values || []) {
if (v.chosen === false) continue;
const key = knobKey(v.kernel, v.name);
const meta = byKey.get(key);
if (!meta || found.has(key)) continue;
if (filters && filters.length > 0) {
const matched = filters.some((f) => key === f || key.startsWith(`${f}:`) || v.kernel === f);
if (!matched) continue;
}
found.set(key, {
key,
kernel: v.kernel,
name: v.name,
rule: v.rule || "",
current: v.value,
from: v.from || "default",
least: meta.least,
most: meta.most,
default: meta.default != null ? meta.default : meta.base,
entries: meta.entries || [],
});
}
}
return Array.from(found.values());
}
function knobPriority(knob, ranked) {
let score = 0;
for (const r of ranked) {
if (r.name.includes(knob.kernel) || (knob.rule && r.name.includes(knob.rule))) {
score += r.ms;
}
}
return score;
}
function candidateValues(knob) {
const vals = new Set();
const span = knob.most - knob.least;
if (span <= 6) {
for (let v = knob.least; v <= knob.most; v++) vals.add(v);
} else {
vals.add(knob.least);
vals.add(knob.most);
for (let p = 1; p <= knob.most; p *= 2) {
if (p >= knob.least) vals.add(p);
if ((p * 3) / 2 <= knob.most && (p * 3) / 2 >= knob.least && Number.isInteger((p * 3) / 2)) {
vals.add((p * 3) / 2);
}
}
for (const e of knob.entries || []) {
if (e.value >= knob.least && e.value <= knob.most) vals.add(e.value);
}
if (typeof knob.current === "number") {
for (const mult of [0.5, 0.75, 1.25, 1.5, 2]) {
const v = Math.round(knob.current * mult);
if (v >= knob.least && v <= knob.most) vals.add(v);
}
}
}
if (typeof knob.current === "number") vals.delete(knob.current);
return Array.from(vals).sort((a, b) => a - b);
}
function spotKey(key, config) {
if (!config.scope_rows) return key;
const rows = config.target === "prefill" ? config.prompt_tokens : config.streams;
return `${key},rows=${rows}..${rows}`;
}
function withKnob(shape, spot, value) {
const next = shape.filter(([k]) => k !== spot);
next.push([spot, value]);
return next;
}
function planSignature(explained) {
const strip = (rep) => ({
fallbacks: rep ? Boolean(rep.fallbacks) : false,
kernels: rep ? rep.kernels : null,
values: rep ? rep.values : null,
});
const dec = Array.isArray(explained.decode)
? explained.decode.map(strip)
: strip(explained.decode);
return JSON.stringify({ decode: dec, prefill: strip(explained.prefill) });
}
function fallbackInfo(explained) {
const items = [];
let count = 0;
const add = (rep) => {
if (!rep) return;
if (Array.isArray(rep.findings) && rep.findings.length > 0) {
for (const f of rep.findings) {
const c = f.count || 1;
count += c;
items.push({
rule: f.rule,
kernel: f.kernel,
count: c,
ms: f.ms || 0,
site: f.site || "",
rejections: Array.isArray(f.rejections) ? f.rejections : [],
});
}
} else if (rep.fallbacks) {
count += 1;
}
};
if (explained) {
if (Array.isArray(explained.decode)) explained.decode.forEach(add);
else add(explained.decode);
add(explained.prefill);
}
return { count, items };
}
function rejectedRules(explained) {
const byRule = new Map();
const fb = fallbackInfo(explained);
for (const item of fb.items) {
for (const rej of item.rejections || []) {
if (!rej || !rej.rule) continue;
if (!byRule.has(rej.rule)) {
byRule.set(rej.rule, {
rule: rej.rule,
fallback_rule: item.rule,
fallback_kernel: item.kernel,
count: item.count,
reason: rej.reason || "",
});
}
}
}
return Array.from(byRule.values());
}
function makeWorkloadAsk(w, reuse, tokensOverride) {
const ask = {
prompt_tokens: w.prompt_tokens,
tokens: tokensOverride != null ? tokensOverride : w.tokens,
streams: w.streams,
};
if (!reuse) {
measureNonce += 1;
ask.text = `t${measureNonce} ${FILLER}`;
}
return ask;
}
function makeMeasureAsk(config, tokensOverride) {
const reuse = Boolean(config.args && config.args.reuse_prefix);
return makeWorkloadAsk(config, reuse, tokensOverride);
}
function guardLabel(g) {
return `${g.prompt_tokens}x${g.tokens}x${g.streams}:${g.target}`;
}
function parityIds(config) {
const ask = {
prompt_tokens: Math.min(32, config.prompt_tokens),
tokens: Math.min(16, config.tokens),
streams: 1,
text: PARITY_TEXT,
};
const res = host("measure", ask);
const s = res && res.streams && res.streams[0];
if (!s || !Array.isArray(s.token_ids) || s.token_ids.length === 0) return null;
return s.token_ids;
}
function idsEqual(a, b) {
if (!a || !b || a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
function scoreOf(metrics, target) {
return target === "prefill" ? metrics.prefill_tps : metrics.decode_tps;
}
function trialRecord(knob, value, status, candScore, refScore, metrics) {
const gain = refScore > 0 ? (candScore - refScore) / refScore : 0;
return {
knob,
value,
status,
score: candScore,
decode_tps: metrics.decode_tps,
prefill_tps: metrics.prefill_tps,
ref_tps: refScore,
gain_pct: gain * 100,
};
}
function explainRows(config) {
const rows = new Set([config.streams]);
for (const g of config.guards || []) rows.add(g.streams);
return Array.from(rows).sort((a, b) => a - b);
}
function explainPrefillRows(config) {
let maxP = config.prompt_tokens;
for (const g of config.guards || []) {
if (g.prompt_tokens > maxP) maxP = g.prompt_tokens;
}
return maxP;
}
function applyRecipeAndWarm(recipe, config, extra) {
const ask = Object.assign({ recipe }, extra || {});
const applied = host("apply", ask);
if (applied && applied.error) return applied;
host("measure", makeMeasureAsk(config, Math.min(2, config.tokens)));
return applied;
}
function applyAndWarm(shape, config, extra) {
return applyRecipeAndWarm({ shape }, config, extra);
}
function measureGuards(guards, config) {
const reuse = Boolean(config.args && config.args.reuse_prefix);
const out = [];
for (const g of guards || []) {
host("measure", makeWorkloadAsk(g, reuse, Math.min(2, g.tokens)));
const m = parseMetric(host("measure", makeWorkloadAsk(g, reuse)));
out.push({
label: guardLabel(g),
target: g.target,
score: scoreOf(m, g.target),
decode_tps: m.decode_tps,
prefill_tps: m.prefill_tps,
ttft_ms: m.ttft_ms,
});
}
return out;
}
function checkGuards(guards, baseGuards, config, maxDrop) {
if (!guards || guards.length === 0) return { ok: true, results: [], worst_drop: 0 };
const got = measureGuards(guards, config);
let worstDrop = 0;
let failed = null;
for (let i = 0; i < got.length; i++) {
const ref = baseGuards[i].score;
const drop = ref > 0 ? (ref - got[i].score) / ref : 0;
got[i].ref_score = ref;
got[i].delta_pct = -drop * 100;
if (drop > worstDrop) worstDrop = drop;
if (drop > maxDrop && !failed) failed = got[i];
}
return { ok: !failed, failed, results: got, worst_drop: worstDrop };
}
function probeRejectedRules(baseExplain, baseMetrics, baseShape, config, target) {
const candidates = rejectedRules(baseExplain);
const probes = [];
const baseScore = scoreOf(baseMetrics, target);
const extra = { rows: explainRows(config), prefill_rows: explainPrefillRows(config) };
for (const c of candidates) {
let applied;
try {
applied = applyRecipeAndWarm({ shape: baseShape, favor: c.rule }, config, extra);
} catch (e) {
probes.push({ rule: c.rule, status: "invalid", error: e.message, fallback: c.fallback_kernel });
continue;
}
if (applied && applied.error) {
probes.push({ rule: c.rule, status: "error", error: applied.error, fallback: c.fallback_kernel });
continue;
}
const m = parseMetric(host("measure", makeMeasureAsk(config)));
const score = scoreOf(m, target);
const gainPct = baseScore > 0 ? ((score - baseScore) / baseScore) * 100 : 0;
probes.push({
rule: c.rule,
status: "ok",
fallback_rule: c.fallback_rule,
fallback_kernel: c.fallback_kernel,
fallback_count: c.count,
reason: c.reason,
score,
ref_score: baseScore,
gain_pct: gainPct,
});
}
if (candidates.length > 0) {
applyRecipeAndWarm({ shape: baseShape, favor: null }, config, extra);
}
return probes;
}
function emitProfile(schema, metrics, explained, knobs, guardBase, ruleProbes, config) {
if (config.json) return;
const top = rankSpent(metrics.spent, 15);
const fb = fallbackInfo(explained);
host("say", `Model: ${schema.model} (${schema.device})\n`);
host(
"say",
`Measure: ${metrics.decode_tps.toFixed(1)} tok/s decode, ` +
`${metrics.prefill_tps.toFixed(1)} tok/s prefill, ` +
`TTFT ${metrics.ttft_ms.toFixed(1)} ms ` +
`(${metrics.launches} launches, ${metrics.cached_tokens} cached, ${metrics.spill_kernels} spilling)\n`,
);
if (guardBase.length > 0) {
host("say", "Guard baselines:\n");
for (const g of guardBase) {
host("say", ` ${g.label}: ${g.score.toFixed(1)} tok/s ${g.target} (TTFT ${g.ttft_ms.toFixed(1)} ms)\n`);
}
}
if (top.length > 0) {
host("say", "Top kernel families:\n");
for (const r of top) {
host(
"say",
` ${r.pct.toFixed(1).padStart(5)}% ${r.ms.toFixed(2).padStart(8)} ms x${String(r.count).padEnd(5)} (${String(r.sites).padStart(3)} sites) ${r.name}${formatAttrs(r.attrs)}\n`,
);
}
}
if (metrics.spills_list.length > 0) {
host("say", `Spilling kernel families (${metrics.spills_list.length}):\n`);
for (const s of metrics.spills_list.slice(0, 10)) {
host(
"say",
` lmem=${s.local} regs=${s.regs} smem=${s.shared} ctas=${s.ctas} (${s.sites} sites, ${s.ms.toFixed(2)} ms) ${s.name}\n`,
);
}
}
if (fb.items.length > 0) {
host("say", `Lowering fallbacks (${fb.count} sites):\n`);
for (const f of fb.items.slice(0, 10)) {
host("say", ` ${f.count}x ${f.rule}/${f.kernel} (${f.ms.toFixed(2)} ms) ${f.site}\n`);
}
}
if (ruleProbes.length > 0) {
host("say", `Rule probes (${ruleProbes.length}):\n`);
for (const p of ruleProbes) {
if (p.status === "ok") {
const sign = p.gain_pct >= 0 ? "+" : "";
host(
"say",
` favor=${p.rule}: ${p.ref_score.toFixed(1)} -> ${p.score.toFixed(1)} tok/s (${sign}${p.gain_pct.toFixed(2)}%) [${p.fallback_count}x ${p.fallback_rule}/${p.fallback_kernel}: ${p.reason}]\n`,
);
} else {
host("say", ` favor=${p.rule}: ${p.status} (${p.error || ""})\n`);
}
}
}
if (knobs.length > 0) {
host("say", `Active chosen knobs (${knobs.length}):\n`);
for (const k of knobs) {
host("say", ` ${k.key} = ${k.current} (${k.from}, range ${k.least}..=${k.most})\n`);
}
}
}
function pickNextKnob(schema, explained, metrics, filters, target, streams, tried) {
const active = activeKnobs(schema, explained, filters, target, streams).filter((k) => !tried.has(k.key));
if (active.length === 0) return null;
const ranked = rankSpent(metrics.spent, 40);
active.sort((a, b) => knobPriority(b, ranked) - knobPriority(a, ranked));
return active[0];
}
export function run(config) {
const target = config.target || "decode";
const guards = config.guards || [];
const guardMaxDrop =
config.args && typeof config.args.guard_max_drop === "number"
? config.args.guard_max_drop
: DEFAULT_GUARD_MAX_DROP;
const schema = host("schema", null);
const current = host("recipe", null);
const baseShape = ((current && current.recipe && current.recipe.shape) || []).map((e) => [e[0], e[1]]);
const rowsList = explainRows(config);
const prefillRows = explainPrefillRows(config);
const explainAsk = { recipe: {}, rows: rowsList, prefill_rows: prefillRows };
const baseExplain = host("explain", explainAsk);
const filters = config.knobs || [];
const initialKnobs = activeKnobs(schema, baseExplain, filters, target, config.streams);
host("measure", makeMeasureAsk(config, Math.min(2, config.tokens)));
const baseMetrics = parseMetric(host("measure", makeMeasureAsk(config)));
const ranked = rankSpent(baseMetrics.spent, 40);
initialKnobs.sort((a, b) => knobPriority(b, ranked) - knobPriority(a, ranked));
const guardBaselines = measureGuards(guards, config);
const ruleProbes = config.probe_rules
? probeRejectedRules(baseExplain, baseMetrics, baseShape, config, target)
: [];
emitProfile(schema, baseMetrics, baseExplain, initialKnobs, guardBaselines, ruleProbes, config);
if (config.profile_only) {
return {
mode: "profile",
target,
model: schema.model,
device: schema.device,
metrics: {
decode_tps: baseMetrics.decode_tps,
prefill_tps: baseMetrics.prefill_tps,
ttft_ms: baseMetrics.ttft_ms,
seconds: baseMetrics.seconds,
cached_tokens: baseMetrics.cached_tokens,
launches: baseMetrics.launches,
spill_kernels: baseMetrics.spill_kernels,
},
guards: guardBaselines,
rule_probes: ruleProbes,
top_kernels: rankSpent(baseMetrics.spent, 20),
spills: baseMetrics.spills_list,
fallbacks: fallbackInfo(baseExplain),
knobs: initialKnobs,
};
}
let baseParity = parityIds(config);
if (baseParity != null && !idsEqual(baseParity, parityIds(config))) {
baseParity = null;
if (!config.json) {
host("note", "baseline greedy token_ids are non-deterministic; skipping parity guard");
}
}
let bestShape = baseShape.slice();
let bestExplain = baseExplain;
let bestSig = planSignature(baseExplain);
let bestMetrics = baseMetrics;
let bestGuards = guardBaselines;
let bestFallbacks = fallbackInfo(baseExplain).count;
const baseSpills = baseMetrics.spills_by_family;
const trials = [];
const accepted = [];
const triedKnobs = new Set();
let evaluated = 0;
const maxTrials = config.max_trials;
const unit = target === "prefill" ? "tok/s prefill" : "tok/s decode";
const applyExtra = { rows: rowsList, prefill_rows: prefillRows };
while (maxTrials == null || evaluated < maxTrials) {
const knob = pickNextKnob(schema, bestExplain, bestMetrics, filters, target, config.streams, triedKnobs);
if (!knob) break;
triedKnobs.add(knob.key);
const candidates = candidateValues(knob);
const spot = spotKey(knob.key, config);
let currentVal = knob.current;
for (const val of candidates) {
if (maxTrials != null && evaluated >= maxTrials) break;
if (val === currentVal) continue;
const shape = withKnob(bestShape, spot, val);
let explained;
try {
explained = host("explain", { recipe: { shape }, rows: rowsList, prefill_rows: prefillRows });
} catch (e) {
trials.push({ knob: spot, value: val, status: "invalid", error: e.message });
continue;
}
const candFallbacks = fallbackInfo(explained).count;
if (candFallbacks > bestFallbacks) {
trials.push({ knob: spot, value: val, status: "fallback" });
continue;
}
const sig = planSignature(explained);
if (sig === bestSig) {
trials.push({ knob: spot, value: val, status: "noop" });
continue;
}
evaluated += 1;
const applied = applyAndWarm(shape, config, applyExtra);
if (applied && applied.error) {
trials.push({ knob: spot, value: val, status: "error", error: applied.error });
continue;
}
const b1 = parseMetric(host("measure", makeMeasureAsk(config)));
if (hasNewSpills(baseSpills, b1.spills_by_family)) {
applyAndWarm(bestShape, config, applyExtra);
trials.push({ knob: spot, value: val, status: "spill", spill_kernels: b1.spill_kernels });
if (!config.json) host("note", `rejected ${spot}=${val}: new register spill`);
continue;
}
let candScore = scoreOf(b1, target);
let refScore = scoreOf(bestMetrics, target);
let kept = false;
let status = "rejected";
let guardCheck = null;
if (candScore > refScore * (1 + MIN_GAIN)) {
if (baseParity != null && !idsEqual(baseParity, parityIds(config))) {
applyAndWarm(bestShape, config, applyExtra);
const record = trialRecord(spot, val, "parity", candScore, refScore, b1);
trials.push(record);
if (!config.json) {
host("record", record);
host(
"note",
`rejected ${spot}=${val}: greedy token_ids mismatch (${refScore.toFixed(1)} -> ${candScore.toFixed(1)} ${unit}, +${record.gain_pct.toFixed(2)}%)`,
);
}
continue;
}
guardCheck = checkGuards(guards, bestGuards, config, guardMaxDrop);
if (!guardCheck.ok) {
applyAndWarm(bestShape, config, applyExtra);
trials.push({
knob: spot,
value: val,
status: "regression",
score: candScore,
ref_tps: refScore,
guards: guardCheck.results,
});
if (!config.json) {
host(
"note",
`rejected ${spot}=${val}: guard ${guardCheck.failed.label} regressed ${guardCheck.failed.delta_pct.toFixed(2)}%`,
);
}
continue;
}
if (config.abba) {
const b2 = parseMetric(host("measure", makeMeasureAsk(config)));
applyAndWarm(bestShape, config, applyExtra);
const a2 = parseMetric(host("measure", makeMeasureAsk(config)));
candScore = (scoreOf(b1, target) + scoreOf(b2, target)) / 2;
refScore = (scoreOf(bestMetrics, target) + scoreOf(a2, target)) / 2;
kept = candScore > refScore * (1 + MIN_GAIN);
if (kept) {
applyAndWarm(shape, config, applyExtra);
bestMetrics = b2;
} else {
bestMetrics = a2;
}
} else {
kept = true;
bestMetrics = b1;
}
} else {
applyAndWarm(bestShape, config, applyExtra);
}
if (kept) status = "accepted";
const record = trialRecord(spot, val, status, candScore, refScore, b1);
trials.push(record);
if (!config.json) host("record", record);
if (kept) {
bestShape = shape;
bestExplain = explained;
bestSig = sig;
bestFallbacks = candFallbacks;
if (guardCheck && guardCheck.results.length > 0) bestGuards = guardCheck.results;
currentVal = val;
accepted.push({ knob: spot, value: val, gain_pct: record.gain_pct });
if (!config.json) {
host(
"note",
`accepted ${spot}=${val}: ${refScore.toFixed(1)} -> ${candScore.toFixed(1)} ${unit} (+${record.gain_pct.toFixed(2)}%)`,
);
}
}
}
}
const saved = host("save", { shape: bestShape });
const baseScore = scoreOf(baseMetrics, target);
const bestScore = scoreOf(bestMetrics, target);
const totalGain = baseScore > 0 ? ((bestScore - baseScore) / baseScore) * 100 : 0;
if (!config.json) {
host(
"say",
`\nSummary (${target}): ${baseScore.toFixed(1)} -> ${bestScore.toFixed(1)} ${unit} (${totalGain >= 0 ? "+" : ""}${totalGain.toFixed(2)}%), ${accepted.length} accepted of ${evaluated} measured\n`,
);
if (guardBaselines.length > 0) {
host("say", "Guards:\n");
for (let i = 0; i < guardBaselines.length; i++) {
const b = guardBaselines[i];
const e = bestGuards[i];
const pct = b.score > 0 ? ((e.score - b.score) / b.score) * 100 : 0;
host(
"say",
` ${b.label}: ${b.score.toFixed(1)} -> ${e.score.toFixed(1)} tok/s (${pct >= 0 ? "+" : ""}${pct.toFixed(2)}%)\n`,
);
}
}
if (bestShape.length > 0 && saved && saved.text) host("say", `\n${saved.text}`);
if (saved && saved.path) host("note", `saved overlay to ${saved.path}`);
}
return {
mode: "tune",
target,
scope_rows: Boolean(config.scope_rows),
model: schema.model,
device: schema.device,
baseline: {
decode_tps: baseMetrics.decode_tps,
prefill_tps: baseMetrics.prefill_tps,
ttft_ms: baseMetrics.ttft_ms,
},
best: {
decode_tps: bestMetrics.decode_tps,
prefill_tps: bestMetrics.prefill_tps,
ttft_ms: bestMetrics.ttft_ms,
gain_pct: totalGain,
},
guards: bestGuards,
rule_probes: ruleProbes,
shape: bestShape,
accepted,
trials,
saved: saved ? saved.path : null,
toml: saved ? saved.text : null,
top_kernels: rankSpent(bestMetrics.spent, 20),
spills: bestMetrics.spills_list,
fallbacks: fallbackInfo(bestExplain).count > 0,
};
}