okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0212-df2choice (final 181b668e5) into f-0212-int081edf2d9

main
12.3 KiB166 linesraw
1/**
2 * Several requests at once (the engine's batch slots) for the installed app.
3 *
4 * The app is for people who run a chat, a helper agent and a second chat side by side, so a model loads with
5 * 4 request slots by default instead of making them queue. Two engine facts decide how far that can go:
6 *
7 *   - Every slot keeps its OWN conversation state in graphics memory at the model's full context
8 *     (docs/BATCHING.md, "What a slot costs"): the context is per slot, so 4 slots cost 4 times one slot.
9 *   - Without `--batch-mtp` the slots decode WITHOUT the draft layer. With it, each slot verifies one draft per window
10 *     (docs/BATCHING.md), at the price of a little more memory per slot. A request that runs alone still takes the
11 *     engine's solo path, so a single chat is not slower for having slots.
12 *
13 * Recommend, never force: a number the person sets (Expert mode, or a value already in the model's saved settings)
14 * is kept exactly. The default only fills in what nobody chose. If the card has no room for 4 it is fewer, and the
15 * person is told in plain words; a load that fails with several slots is tried again with one before it is reported.
16 *
17 * The engine does the final fitting itself ("it never refuses a count it cannot run": it logs what it could do).
18 * This module keeps the request realistic so the expert cache is not squeezed for a count that could not run.
19 */
20
21export const DEFAULT_SLOTS = 4;
22/** What the person is told when DFlash2 is chosen and nobody picked a number of requests (strata_control/drafting.py ONE_REQUEST_NOTE). */
23export const DFLASH2_NOTE = 'DFlash2 answers one request at a time, so Strata set this model to one request at a time.';
24/** The most the engine's batch window holds without grouped MTP. */
25export const MAX_SLOTS = 8;
26/**
27 * THE one-line policy.
28 *   'fit'   the default aims for 4 and takes fewer where the slots would eat more than CACHE_LOSS_SHARE of the expert cache
29 *           the card would otherwise have (the owner's choice: "fit to the card")
30 *   'fixed' the default is always DEFAULT_SLOTS, whatever the card (the engine still fits what it can)
31 *
32 * Why a cache budget: on a 12 GB RTX 3060 (IQ3_XXS, 32K) the slots' sessions come out of the expert cache. Measured, one request
33 * alone: no slots 61 tok/s (cache 5.1 GiB); 2 slots 41 (cache 3.25 GiB); 4 slots 38 (cache 1.4 GiB). Several requests together
34 * were SLOWER in total than queueing them (52-57 tok/s total queued, against 33-42 in slots). Slots start everyone at once;
35 * they pay off when the cache stays mostly intact.
36 */
37export const PARALLEL_POLICY = 'fit';
38/** The share of the solo expert cache the slots' sessions may take together under the 'fit' policy. */
39export const CACHE_LOSS_SHARE = 0.2;
40/**
41 * The expert cache a card has with one request at a time is what remains of its memory after the dense weights, the draft layer,
42 * one session, the safety reserve and the prompt path (measured: a 12 GB card ends with 5.1 GiB of cache and 0.35 GiB free, so
43 * about 6.9 GiB goes to everything else; a second card in a layer split about 2 GiB).
44 */
45export const FIRST_CARD_OTHER_GB = 6.9;
46/**
47 * The draft layer (MTP) is part of that 6.9: about 1 GB of graphics memory (786 MiB of files and the draft head's ~218 MiB,
48 * phaseA-tests/notes-021-settings.md). With "Draft layer (MTP)" off in Expert settings (`"mtp": false`) the engine does not load it, so
49 * the card has that much more cache and the slots may use it.
50 */
51export const MTP_VRAM_GB = 1.08;
52/** Graphics memory of DFlash2 alone, with the MTP layer not loaded beside it (RESULTS-DF2MEM.md: 890 MiB; the MTP layer 1082 MiB). Fit, plan and slot estimates use the drafter that is chosen. */
53export const DFLASH2_VRAM_GB = 0.89;
54/** The same with the converted pack (the selector's codebooks as Q4_0 rows, 715 MiB; strata_control/drafting.py DRAFTER_MIB "dflash2_selq4"): `capabilities.dflash2Selq4` says it is the one in use. */
55export const DFLASH2_SELQ4_VRAM_GB = 0.72;
56export const NEXT_CARD_OTHER_GB = 2.0;
57/**
58 * `--batch-mtp` lets each slot verify draft tokens. Where it pays and where it does not (all measured):
59 *   - RTX PRO 5000 72 GB, 32K (FP4-Local): 1 stream 140 tok/s either way; 2 streams 129 -> 160 (+24%) with it; 4 streams 177 either way;
60 *     the text is exactly the batch text.
61 *   - 12 GB RTX 3060: a lone chat 35.6 tok/s with it against 37.8 without, 2 chats 37.2 against 33.8, 4 chats 42.5 against 38.4, and
62 *     400 MiB less expert cache: not worth it on a small card.
63 *   - 2 cards in a layer split with all experts in VRAM: -22% (docs/BATCHING.md): never on a layer split.
64 * 'auto' turns it on for one card of at least BATCH_MTP_MIN_VRAM_GB with a draft layer, 2 or more slots, and room for the slot drafters
65 * with a margin. 'off' never adds it. Expert mode decides either way: `--batch-mtp` in the engine arguments, or "batchMtp": true / false
66 * in the model's settings (or the load's values).
67 */
68export const BATCH_MTP_POLICY = 'auto';
69export const BATCH_MTP_MIN_VRAM_GB = 24;
70/** Memory the slot drafters need per slot (their K/V ring and buffers; measured about 0.1 GiB, rounded up) and the cache that must remain after them. */
71export const BATCH_MTP_DRAFTER_GB = 0.25;
72export const BATCH_MTP_MARGIN_GB = 2;
73
74const argValue = (args, flag) => { const at = args.indexOf(flag); return at >= 0 ? args[at + 1] : undefined; };
75
76/** Graphics memory (GB) one slot's session takes at `context` tokens. Flash-Next: 12 attention layers; Qwen3.6: 45 KB per token. */
77export function slotGb({ context, kv = 'int8', family = 'flash' }) {
78  const ctx = Number(context) > 0 ? Number(context) : 32768;
79  if (family === 'q36') return (ctx * 45_000) / 1e9 + 0.07;
80  return (ctx * 12 * (kv === 'q4_0' ? 1150 : 2100)) / 1e9 + 0.17; // measured on the 0.1.45 engine: 0.92 GiB per slot at 32K
81}
82
83/** What the saved settings say about the engine, read from the config (never from the screen). */
84export function engineFacts(config = {}) {
85  const args = Array.isArray(config.args) ? config.args.map(String) : [];
86  const context = Number(argValue(args, '--max-context') ?? argValue(args, '--context') ?? config.max_context ?? config.context) || null;
87  const kv = /q4/i.test(argValue(args, '--kv') ?? argValue(args, '--kv-type') ?? '') ? 'q4_0' : 'int8';
88  const family = /qwen3\.6|qwen36|35b-a3b/i.test(`${config.model_name ?? ''} ${args.join(' ')}`) ? 'q36' : 'flash';
89  const gpus = Array.isArray(config.gpu) ? config.gpu : config.gpu === undefined || config.gpu === null ? [0] : [config.gpu];
90  return {
91    args, context, kv, family, gpus,
92    mtp: args.includes('--mtp') && config.mtp !== false,
93    batchMtp: args.includes('--batch-mtp'),
94    explicitBatch: args.includes('--batch') || args.includes('--slots'),
95  };
96}
97
98/**
99 * @param {object} input
100 * @param {object} input.config            the model's saved settings (args, gpu, parallel, ...)
101 * @param {object} [input.values]          what the person set for this load (Expert mode's "Concurrent requests")
102 * @param {object} [input.hardware]        the host's hardware read (`gpus[{index, vram_gb}]`)
103 * @param {number} [input.requested]       the default to aim for
104 * @param {string} [input.drafter]         the drafter this load runs (resolveDrafter): with dflash2 the app fills in one request at a time unless the person chose a number
105 * @returns {{slots:number, batchMtp:boolean, explicit:boolean, requested:number, note:string|null, slotGb:number}}
106 */
107export function chooseParallel({ config = {}, values = {}, hardware = null, requested = DEFAULT_SLOTS, drafter = null }) {
108  const facts = engineFacts(config);
109  const slot = slotGb({ context: facts.context, kv: facts.kv, family: facts.family });
110  const chosen = values.parallel !== undefined && values.parallel !== null ? Number(values.parallel)
111    : config.parallel !== undefined && config.parallel !== null ? Number(config.parallel) : null;
112  // A number someone chose (including 1) is the person's decision, and so is an explicit --batch in the engine arguments.
113  if (facts.explicitBatch || (chosen !== null && Number.isFinite(chosen))) {
114    const slots = facts.explicitBatch ? null : Math.max(1, Math.min(1024, Math.trunc(chosen)));
115    // DFlash2 chosen by name with a number of requests (owner, 2026-11-03: the person's own choice wins) runs DFlash2 with that many requests, a drafter per request
116    // (strata_control/drafting.py blocked_by `named`). Expert mode's batch-mtp wish is still added here as in 0.2.10: the server knows the backend and the engine, takes
117    // --batch-mtp out when DFlash2 runs, and keeps it when the MTP runs instead (Metal, which has no per-request drafters).
118    const wantMtp = (values.batchMtp ?? config.batchMtp) === true && !facts.batchMtp && facts.mtp && facts.gpus.length === 1 && (slots ?? 0) > 1;
119    return { slots: slots ?? 0, batchMtp: wantMtp, explicit: true, requested, note: null, slotGb: slot };
120  }
121  // DFlash2 (named, or Auto where the engine has it) and nobody chose a number of requests: one at a time, the app does not fill in slots beside it. (A number the person chose is kept
122  // above: DFlash2 named runs it with that many requests; Auto keeps the MTP for several.)
123  if ((drafter ?? ((values.drafting ?? config.drafting) === 'dflash2' ? 'dflash2' : null)) === 'dflash2') return { slots: 1, batchMtp: false, explicit: false, requested, note: DFLASH2_NOTE, slotGb: slot };
124  const cards = (hardware?.gpus ?? []).filter(g => facts.gpus.includes(g.index)).map(g => Number(g.vram_gb)).filter(n => Number.isFinite(n) && n > 0);
125  // Without a hardware read nothing can be sized: one at a time is the safe default (a number can still be chosen).
126  if (!cards.length) return { slots: PARALLEL_POLICY === 'fixed' ? requested : 1, batchMtp: false, explicit: false, requested, note: null, slotGb: slot };
127  const total = cards.reduce((a, b) => a + b, 0);
128  const oneCard = facts.gpus.length === 1 && cards.length === 1;
129  const soloCache = Math.max(0, total - (FIRST_CARD_OTHER_GB - MTP_VRAM_GB + (facts.mtp ? MTP_VRAM_GB : 0)) - NEXT_CARD_OTHER_GB * (cards.length - 1));
130  let slots = requested;
131  if (PARALLEL_POLICY === 'fit') while (slots > 1 && slots * slot > CACHE_LOSS_SHARE * soloCache) slots -= 1;
132  const note = slots >= requested ? null
133    : slots > 1 ? `Your graphics card has room for ${slots} requests at once with this context size, so Strata set that. A smaller context size leaves room for more.`
134      : 'Strata set this model to one request at a time: your graphics card is best used that way, because more at once would make every answer slower. Helper agents and a second chat take their turn instead. A smaller context size leaves room for more at once.';
135  const wish = values.batchMtp ?? config.batchMtp;   // Expert mode: true adds it by hand, false keeps it off
136  const roomLeft = soloCache - slots * (slot + BATCH_MTP_DRAFTER_GB);
137  const auto = BATCH_MTP_POLICY === 'auto' && oneCard && cards[0] >= BATCH_MTP_MIN_VRAM_GB && roomLeft >= BATCH_MTP_MARGIN_GB;
138  const batchMtp = slots > 1 && facts.mtp && !facts.batchMtp && wish !== false && (wish === true ? oneCard : auto);
139  return { slots, batchMtp, explicit: false, requested, note, slotGb: slot };
140}
141
142/**
143 * Apply a choice to the run configuration that is about to be saved. Never touches a number the person chose.
144 * Returns the configuration and the plain-words note (or null).
145 */
146export function applyParallel(cfg, choice) {
147  // `batchMtp` is the app's own setting (Expert mode); the engine's config does not know it, the argument is what it reads.
148  const { batchMtp: _wish, ...clean } = cfg;
149  if (choice.explicit && !choice.batchMtp) return { cfg: 'batchMtp' in cfg ? clean : cfg, note: null };
150  if (choice.explicit) return { cfg: { ...clean, args: [...(clean.args ?? []), '--batch-mtp'] }, note: null };
151  const next = { ...clean };
152  if (choice.slots > 1) next.parallel = choice.slots; else delete next.parallel;
153  if (choice.batchMtp) next.args = [...(next.args ?? []), '--batch-mtp'];
154  return { cfg: next, note: choice.note };
155}
156
157/** The same configuration with one request at a time, for the second try after a load that failed with several. */
158export function withoutParallel(cfg) {
159  const next = { ...cfg };
160  delete next.parallel;
161  next.args = (next.args ?? []).filter(a => a !== '--batch-mtp');
162  return next;
163}
164
165/** What to say when the second try worked. */
166export const FALLBACK_NOTE = 'The model could not start with several requests at once on this PC, so Strata loaded it for one request at a time. Everything still works; helper agents and a second chat wait their turn.';