Merge int-0226 (04a8b197a1) into the community PR lane: the Loop/elastic/KV-fix/Mac merges and the standalone rdna_gr merge (the same change this branch carries)

This commit is contained in:
Niko1221 committed 2026-12-04 10:32:11 +01:00
commit 11cdd7885f
52 files changed
+2760 -153

No files matched your search

+8 -4
View File
@@ -51,8 +51,12 @@ export const QWEN4_LOOP_READY = Object.freeze({ 'strata/cuda': false, 'strata/hi
/** What the standalone strata-q4-lite engine (the .strata builds) takes today: mirrors terminal/strata_control/qwen4_family.py STRATA_BUILD_FLAG_READY (mtp, vision, loop); the GGUF build (UD-Q4_K_XL, the qwen4exp engine) has them all.
* False = "coming with the engine": the app writes no key, no flag, downloads no file for it. tests/qwen4-family.test.mjs parses the Python dict and pins this and src/lib/qwen4.ts to it. */
export const QWEN4_STRATA_READY = Object.freeze({ mtp: false, vision: false, loop: false });
export const qwen4MtpReady = (build, table = QWEN4_STRATA_READY) => String(build ?? '').toLowerCase() === 'ud-q4_k_xl' ? true : ['compact', 'balanced', 'ultra'].includes(String(build ?? '').toLowerCase()) && table.mtp === true;
export const qwen4VisionReady = (build, table = QWEN4_STRATA_READY) => String(build ?? '').toLowerCase() === 'ud-q4_k_xl' ? true : ['compact', 'balanced', 'ultra'].includes(String(build ?? '').toLowerCase()) && table.vision === true;
/** What a .strata tier takes on a Mac (Metal): converted at install and run on `strata`, so the draft layer and pictures work; Loop is coming. Mirrors qwen4_family.py STRATA_METAL_READY (the host test pins the Python, this and src/lib/qwen4.ts). */
export const QWEN4_STRATA_METAL_READY = Object.freeze({ mtp: true, vision: true, loop: false });
/** The draft layer / pictures for a build on a backend: the GGUF build yes everywhere; a .strata tier by the standalone host's table (QWEN4_STRATA_READY), or on Metal by QWEN4_STRATA_METAL_READY. */
const qwen4StrataTable = (backend, table, metalTable) => String(backend ?? '').toLowerCase() === 'metal' ? metalTable : table;
export const qwen4MtpReady = (build, table = QWEN4_STRATA_READY, backend = undefined, metalTable = QWEN4_STRATA_METAL_READY) => String(build ?? '').toLowerCase() === 'ud-q4_k_xl' ? true : ['compact', 'balanced', 'ultra'].includes(String(build ?? '').toLowerCase()) && qwen4StrataTable(backend, table, metalTable).mtp === true;
export const qwen4VisionReady = (build, table = QWEN4_STRATA_READY, backend = undefined, metalTable = QWEN4_STRATA_METAL_READY) => String(build ?? '').toLowerCase() === 'ud-q4_k_xl' ? true : ['compact', 'balanced', 'ultra'].includes(String(build ?? '').toLowerCase()) && qwen4StrataTable(backend, table, metalTable).vision === true;
export const QWEN4_STRATA_COMING_LABEL = 'Draft layer (MTP) - coming with the engine';
export const QWEN4_STRATA_COMING_NOTE = 'Coming with the engine: the draft layer (MTP) and picture reading are not in the engine for this build yet. They stay off for now.';
/** The K/V cache format (mirrors qwen4_family.py KV_CHOICES / KV_DEFAULT / KV_READY / KV_BACKENDS and src/lib/qwen4.ts; the host test pins the three): which formats a build takes and which it starts with. */
@@ -79,8 +83,8 @@ export function qwen4BuildOfConfig(config) {
/** Loop is supported for the build and backend this run config names. */
export const qwen4LoopReadyFor = (config, table = QWEN4_LOOP_READY) => qwen4LoopReady(qwen4BuildOfConfig(config), config?.backend, table);
/** The sidecar and the picture reader are supported for the build this run config names. */
export const qwen4MtpReadyFor = (config, table = QWEN4_STRATA_READY) => qwen4MtpReady(qwen4BuildOfConfig(config), table);
export const qwen4VisionReadyFor = (config, table = QWEN4_STRATA_READY) => qwen4VisionReady(qwen4BuildOfConfig(config), table);
export const qwen4MtpReadyFor = (config, table = QWEN4_STRATA_READY) => qwen4MtpReady(qwen4BuildOfConfig(config), table, config?.backend);
export const qwen4VisionReadyFor = (config, table = QWEN4_STRATA_READY) => qwen4VisionReady(qwen4BuildOfConfig(config), table, config?.backend);
export const QWEN4_LOOP_COMING_LABEL = 'Loop (2 steps) - coming soon';
export const QWEN4_LOOP_COMING_NOTE = 'Coming soon: Loop (2 steps) needs engine support that is not in this release yet. It stays off for now.';
/** The Loop choice of a saved run config as the menu says it: on when the key names a file, else off. */
+4 -4
View File
@@ -146,8 +146,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
// DFlash2 with the converted pack (the selector as Q4_0 rows) takes 175 MiB less graphics memory: the fit says the true number (Control's `selq4`, strata_control/drafting.py vram_gb).
const fitDrafter = nowDrafter === 'dflash2' && native?.capabilities?.dflash2Selq4 === true ? 'dflash2_selq4' : nowDrafter;
const draftingWords: Record<string, string> = { auto: 'Auto (recommended)', mtp: 'MTP', dflash2: 'DFlash2', off: 'Off' };
const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv: q4Kv, low_ram: lowRam, resourceProfile, ...(cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), ...(roleCards.length > 1 && roles && (customRoles || savedDiffers) ? { gpuRoles: effectiveRoles } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, cardsGpus.join(','), roles, customRoles, savedDiffers, expert, multiple]);
const downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), ...((isLingSelected || (isQ4Selected && qwen4MtpReady(selectedSize?.model))) && lingMtp !== 'auto' ? { mtp: lingMtp } : {}), ...(q4LoopReady && q4Loop === 'on' ? { loop: 'on' } : {}), ...(isLingSelected && lingSkip === 'medium' ? { ling_skip: lingSkip } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), ...(contextPicked ? { contextChosen: true } : {}) };
const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), ...(roleCards.length > 1 && roles && (customRoles || savedDiffers) ? { gpuRoles: effectiveRoles } : {}), loadAfter: true, multiple: expert && multiple, ...(q4Own ? { kv: q4Kv } : {}) }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, q4Own, q4Kv, lowRam, resourceProfile, cardsGpus.join(','), roles, customRoles, savedDiffers, expert, multiple]);
const downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), ...((isLingSelected || (isQ4Selected && qwen4MtpReady(selectedSize?.model, undefined, selectedSize?.qwen4?.backend))) && lingMtp !== 'auto' ? { mtp: lingMtp } : {}), ...(q4LoopReady && q4Loop === 'on' ? { loop: 'on' } : {}), ...(isLingSelected && lingSkip === 'medium' ? { ling_skip: lingSkip } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), ...(contextPicked ? { contextChosen: true } : {}) };
useEffect(() => { if (!native?.catalog || family)
return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const diskFamily = families.find(f => f.sizes.some(s => s.files_on_disk)); const f = loadedFamily ?? installedFamily ?? diskFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) {
setFamily(f.family);
@@ -380,7 +380,7 @@ export function NativeProgress({ job, label }: {
/** Qwen Qwen4-35B-A3B on this PC (terminal/strata_control/qwen4_fit.py through the catalog): the build and PLE table this PC gets and where the model lives, what is different about this make of card,
* the draft layer (MTP) and Loop (2 steps). Written here, never the planner's own sentences. Loop is offered for Strata's own quantization only and is off unless chosen. */
function Qwen4Plan({ selectedModel, q4, mtp, onMtp, kv, onKv, loop, onLoop, loopOffered, installedLoop, installedMtp, disabled }: { q4: NonNullable<CatalogVersion['qwen4']>; mtp: string; onMtp: (v: string) => void; kv: string; onKv: (v: string) => void; loop: string; onLoop: (v: string) => void; loopOffered: boolean; selectedModel?: string; installedLoop?: 'off' | 'on'; installedMtp?: boolean; disabled: boolean }) {
const notes = q4.notes ?? [], loopReady = qwen4LoopReady(selectedModel, q4.backend), mtpReady = qwen4MtpReady(selectedModel), kvList = q4.kv_choices?.length ? q4.kv_choices : qwen4KvChoices(selectedModel, q4.backend); // Loop (2 steps) per build and backend: qwen4_family.LOOP_READY, mirrored in lib/qwen4.ts
const notes = q4.notes ?? [], loopReady = qwen4LoopReady(selectedModel, q4.backend), mtpReady = qwen4MtpReady(selectedModel, undefined, q4.backend), kvList = q4.kv_choices?.length ? q4.kv_choices : qwen4KvChoices(selectedModel, q4.backend); // Loop (2 steps) per build and backend: qwen4_family.LOOP_READY, mirrored in lib/qwen4.ts
const has = (code: string) => notes.find(n => n.code === code);
const mtpWords: Record<string, string> = { auto: 'Auto (on when it pays)', on: 'On', off: 'Off' };
const old = has('old_nvidia'), amd = has('amd_compiled') ?? has('amd_unsupported');
@@ -393,7 +393,7 @@ function Qwen4Plan({ selectedModel, q4, mtp, onMtp, kv, onKv, loop, onLoop, loop
{has('no_card') ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("No graphics card was found. Qwen4-35B-A3B needs one.")}</p> : null}
{q4.engine_exists !== false ? <div className="native-choice__row"><div className="native-choice__col"><span className="native-choice__label">{tr(mtpReady ? "Draft layer (MTP)" : "Draft layer (MTP) - coming with the engine")}</span><Select ariaLabel={tr(mtpReady ? "Draft layer (MTP)" : "Draft layer (MTP) - coming with the engine")} value={mtpReady ? mtp : 'off'} disabled={disabled || !mtpReady} options={['auto', 'on', 'off'].map(v => ({ value: v, label: tr(mtpWords[v]) }))} onChange={v => onMtp(String(v))}/>
<small className="muted native-kv-hint">{tr(!mtpReady ? "Coming with the engine: the draft layer (MTP) and picture reading are not in the engine for this build yet. They stay off for now." : mtp === 'on' && installedMtp === false ? "The draft layer file (0.4 GB) is downloaded once, then the model loads with it." : mtp === 'auto' ? (q4.mtp_default === false ? "Auto keeps the draft layer off on this card: it is under 6 GB or it measured slower here." : "Auto turns the draft layer on for graphics cards of 6 GB or more.") : "The draft layer guesses several words ahead to answer faster. It is a 0.4 GB file.")}</small></div></div> : null}
{q4.engine_exists !== false ? <div className="native-choice__row"><div className="native-choice__col"><span className="native-choice__label">{tr("Context memory")}</span><Select ariaLabel={tr("Native KV format")} value={kv} disabled={disabled || kvList.length < 2} options={kvList.map(v => ({ value: v, label: QWEN4_KV_LABELS[v] ?? v }))} onChange={v => onKv(String(v))}/>
{q4.engine_exists !== false ? <div className="native-choice__row"><div className="native-choice__col"><span className="native-choice__label">{tr("Context memory")}</span><Select ariaLabel={tr("Context memory")} value={kv} disabled={disabled || kvList.length < 2} options={kvList.map(v => ({ value: v, label: QWEN4_KV_LABELS[v] ?? v }))} onChange={v => onKv(String(v))}/>
<small className="muted native-kv-hint">{tr(kv === 'int8' ? "int8: same quality as fp16, faster prompt reading." : kv === 'k8v4' || kv === 'q4_0' ? "k8v4 and q4_0: less memory for long context." : kv === 'fp8' ? "fp8: like int8, new, NVIDIA first." : "fp16: the reference, most memory.")}</small></div></div> : null}
{loopOffered && q4.engine_exists !== false ? <div className="native-choice__row"><div className="native-choice__col"><span className="native-choice__label">{tr(loopReady ? "Loop (2 steps)" : "Loop (2 steps) - coming soon")}</span><Select ariaLabel={tr(loopReady ? "Loop (2 steps)" : "Loop (2 steps) - coming soon")} value={loopReady ? loop : 'off'} disabled={disabled || !loopReady} options={[{ value: 'off', label: tr("Off") }, { value: 'on', label: tr("On") }]} onChange={v => onLoop(String(v))}/>
<small className="muted native-kv-hint">{tr(!loopReady ? "Coming soon: Loop (2 steps) needs engine support that is not in this release yet. It stays off for now." : loop === 'on' && installedLoop !== 'on' ? "Loop (2 steps): thinks each word twice. Slower (about 40% fewer words per second while writing, prompt reading about half as fast), a little closer to the original model. Its 147 MB file is downloaded once, then the model loads with it. It has no effect while Effort is Off." : "Loop (2 steps): thinks each word twice. Slower (about 40% fewer words per second while writing, prompt reading about half as fast), a little closer to the original model. It has no effect while Effort is Off.")}</small></div></div> : null}
+1 -1
View File
@@ -138,7 +138,7 @@ export function NativeSettings({ model }: {
const isQwen4 = family === QWEN4_FAMILY || /^qwen4-35b-a3b/i.test(model);
const ownQuant4 = isQwen4 && !(native?.catalog?.families ?? []).some(f => f.sizes.some(s => s.id === model && s.custom)); // Loop (2 steps) is for Strata's own Qwen4 quantization only
const q4Size = (native?.catalog?.families ?? []).flatMap(f => f.sizes).find(s => s.id === model);
const q4MtpReady = !isQwen4 || qwen4MtpReady(q4Size?.model); // a .strata build: the engine takes no MTP yet (qwen4_family.STRATA_BUILD_FLAG_READY)
const q4MtpReady = !isQwen4 || qwen4MtpReady(q4Size?.model, undefined, q4Size?.qwen4?.backend); // a .strata build: the engine takes no MTP yet (qwen4_family.STRATA_BUILD_FLAG_READY)
const q4LoopReady = ownQuant4 && qwen4LoopReady(q4Size?.model, q4Size?.qwen4?.backend); // Loop (2 steps) per build and backend (qwen4_family.LOOP_READY)
// Fields that belong to one family only: Ling's (thinking default, draft layer, expert skip) and Qwen4's (effort, draft layer, loop)
const ownField = (id: string) => nativeFieldShown(id, { isLing, isQwen4, ownQuant4 });
+5 -2
View File
@@ -13,8 +13,11 @@ export const qwen4LoopReady = (build?: string | null, backend?: string | null, t
};
/** What the standalone strata-q4-lite engine (the .strata builds) takes today (qwen4_family.py STRATA_BUILD_FLAG_READY; server/qwen4.mjs mirrors it too; the host test pins the three together): false = "coming with the engine". The GGUF build has them all. */
export const QWEN4_STRATA_READY: Readonly<Record<string, boolean>> = Object.freeze({ mtp: false, vision: false, loop: false });
export const qwen4MtpReady = (build?: string | null, table: Readonly<Record<string, boolean>> = QWEN4_STRATA_READY): boolean => { const b = String(build ?? '').toLowerCase(); return b === 'ud-q4_k_xl' ? true : ['compact', 'balanced', 'ultra'].includes(b) && table.mtp === true; };
export const qwen4VisionReady = (build?: string | null, table: Readonly<Record<string, boolean>> = QWEN4_STRATA_READY): boolean => { const b = String(build ?? '').toLowerCase(); return b === 'ud-q4_k_xl' ? true : ['compact', 'balanced', 'ultra'].includes(b) && table.vision === true; };
/** What a .strata tier takes on a Mac (Metal): converted at install and run on `strata`, so the draft layer and pictures work; Loop is coming (qwen4_family.py STRATA_METAL_READY; server/qwen4.mjs mirrors it too; the host test pins the three). */
export const QWEN4_STRATA_METAL_READY: Readonly<Record<string, boolean>> = Object.freeze({ mtp: true, vision: true, loop: false });
const qwen4StrataTable = (backend: string | null | undefined, table: Readonly<Record<string, boolean>>, metalTable: Readonly<Record<string, boolean>>) => String(backend ?? '').toLowerCase() === 'metal' ? metalTable : table;
export const qwen4MtpReady = (build?: string | null, table: Readonly<Record<string, boolean>> = QWEN4_STRATA_READY, backend?: string | null, metalTable: Readonly<Record<string, boolean>> = QWEN4_STRATA_METAL_READY): boolean => { const b = String(build ?? '').toLowerCase(); return b === 'ud-q4_k_xl' ? true : ['compact', 'balanced', 'ultra'].includes(b) && qwen4StrataTable(backend, table, metalTable).mtp === true; };
export const qwen4VisionReady = (build?: string | null, table: Readonly<Record<string, boolean>> = QWEN4_STRATA_READY, backend?: string | null, metalTable: Readonly<Record<string, boolean>> = QWEN4_STRATA_METAL_READY): boolean => { const b = String(build ?? '').toLowerCase(); return b === 'ud-q4_k_xl' ? true : ['compact', 'balanced', 'ultra'].includes(b) && qwen4StrataTable(backend, table, metalTable).vision === true; };
/** The K/V cache format (qwen4_family.py KV_CHOICES / KV_DEFAULT / KV_READY / KV_BACKENDS; server/qwen4.mjs mirrors it too; the host test parses the Python and pins the three together): the GGUF build (UD-Q4_K_XL) takes
* int8 (the default), fp16, k8v4, q4_0 and fp8 once it is ready (CUDA first); the .strata builds only fp16 for now. The catalog row (qwen4.kv_choices) says the same per card; this is the fallback and the pin. */
export const QWEN4_KV_CHOICES: Readonly<Record<string, readonly string[]>> = Object.freeze({ gguf: ['int8', 'fp16', 'k8v4', 'fp8', 'q4_0'], strata: ['fp16'] });
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16: die Referenz, am meisten Speicher.",
"q430": "fp8: wie int8, neu, zuerst für NVIDIA.",
"q431": "Auto schaltet die Entwurfsschicht für Grafikkarten ab 6 GB ein.",
"q432": "Auto lässt die Entwurfsschicht auf dieser Karte aus: sie hat unter 6 GB oder war hier langsamer."
"q432": "Auto lässt die Entwurfsschicht auf dieser Karte aus: sie hat unter 6 GB oder war hier langsamer.",
"q433": "Auto schaltet die Entwurfsschicht für Grafikkarten ab 6 GB ein. Ein erzwingt sie, Aus lädt sie nie. Die Datei ist 0,4 GB groß."
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16: the reference, most memory.",
"q430": "fp8: like int8, new, NVIDIA first.",
"q431": "Auto turns the draft layer on for graphics cards of 6 GB or more.",
"q432": "Auto keeps the draft layer off on this card: it is under 6 GB or it measured slower here."
"q432": "Auto keeps the draft layer off on this card: it is under 6 GB or it measured slower here.",
"q433": "Auto turns the draft layer on for graphics cards of 6 GB or more. On forces it, Off never loads it. The file is 0.4 GB."
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16: la referencia, la que más memoria usa.",
"q430": "fp8: como int8, nuevo, primero para NVIDIA.",
"q431": "Auto activa la capa de borrador en tarjetas gráficas de 6 GB o más.",
"q432": "Auto deja la capa de borrador desactivada en esta tarjeta: tiene menos de 6 GB o aquí resultó más lenta."
"q432": "Auto deja la capa de borrador desactivada en esta tarjeta: tiene menos de 6 GB o aquí resultó más lenta.",
"q433": "Auto activa la capa de borrador en tarjetas gráficas de 6 GB o más. Activado la fuerza, Desactivado nunca la carga. El archivo ocupa 0,4 GB."
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16 : la référence, la plus gourmande en mémoire.",
"q430": "fp8 : comme int8, nouveau, d’abord pour NVIDIA.",
"q431": "Auto active la couche de brouillon sur les cartes graphiques de 6 Go ou plus.",
"q432": "Auto laisse la couche de brouillon désactivée sur cette carte : elle a moins de 6 Go ou y était plus lente."
"q432": "Auto laisse la couche de brouillon désactivée sur cette carte : elle a moins de 6 Go ou y était plus lente.",
"q433": "Auto active la couche de brouillon sur les cartes graphiques de 6 Go ou plus. Activé la force, Désactivé ne la charge jamais. Le fichier fait 0,4 Go."
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16: המדד, הכי הרבה זיכרון.",
"q430": "fp8: כמו int8, חדש, קודם כל ל-NVIDIA.",
"q431": "אוטומטי: שכבת הטיוטה מופעלת בכרטיסים גרפיים של 6 GB ומעלה.",
"q432": "אוטומטי: בכרטיס הזה שכבת הטיוטה נשארת כבויה: יש בו פחות מ-6 GB או שהיא התגלתה כאן איטית יותר."
"q432": "אוטומטי: בכרטיס הזה שכבת הטיוטה נשארת כבויה: יש בו פחות מ-6 GB או שהיא התגלתה כאן איטית יותר.",
"q433": "אוטומטי: שכבת הטיוטה מופעלת בכרטיסים גרפיים של 6 GB ומעלה. מופעל כופה אותה, כבוי לא טוען אותה לעולם. הקובץ הוא 0.4 GB."
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16:基準の形式で、メモリを最も使います。",
"q430": "fp8:int8 に近く、新しい形式で、まず NVIDIA 向けです。",
"q431": "自動:6 GB 以上のグラフィックスカードでドラフトレイヤーをオンにします。",
"q432": "自動:このカードではドラフトレイヤーをオフのままにします(6 GB 未満、または実測で遅いため)。"
"q432": "自動:このカードではドラフトレイヤーをオフのままにします(6 GB 未満、または実測で遅いため)。",
"q433": "自動:6 GB 以上のグラフィックスカードでドラフトレイヤーをオンにします。オンは強制し、オフは読み込みません。ファイルは 0.4 GB です。"
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16: 기준 형식으로 메모리를 가장 많이 씁니다.",
"q430": "fp8: int8과 비슷한 새 형식으로, NVIDIA가 먼저입니다.",
"q431": "자동: 6GB 이상의 그래픽 카드에서 초안 레이어를 켭니다.",
"q432": "자동: 이 카드에서는 초안 레이어를 끈 채로 둡니다(6GB 미만이거나 실측에서 더 느렸습니다)."
"q432": "자동: 이 카드에서는 초안 레이어를 끈 채로 둡니다(6GB 미만이거나 실측에서 더 느렸습니다).",
"q433": "자동: 6GB 이상의 그래픽 카드에서 초안 레이어를 켭니다. 켬은 강제로 불러오고, 끔은 절대 불러오지 않습니다. 파일 크기는 0.4 GB입니다."
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16: a referência, a que mais usa memória.",
"q430": "fp8: como o int8, novo, primeiro para NVIDIA.",
"q431": "Auto liga a camada de rascunho em placas de vídeo de 6 GB ou mais.",
"q432": "Auto mantém a camada de rascunho desligada nesta placa: ela tem menos de 6 GB ou aqui foi mais lenta."
"q432": "Auto mantém a camada de rascunho desligada nesta placa: ela tem menos de 6 GB ou aqui foi mais lenta.",
"q433": "Auto liga a camada de rascunho em placas de vídeo de 6 GB ou mais. Ligado a força, Desligado nunca a carrega. O arquivo tem 0,4 GB."
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16: эталон, больше всего памяти.",
"q430": "fp8: как int8, новинка, сначала для NVIDIA.",
"q431": "Авто включает черновой слой на видеокартах от 6 ГБ.",
"q432": "Авто оставляет черновой слой выключенным на этой карте: у неё меньше 6 ГБ или здесь он работал медленнее."
"q432": "Авто оставляет черновой слой выключенным на этой карте: у неё меньше 6 ГБ или здесь он работал медленнее.",
"q433": "Авто включает черновой слой на видеокартах от 6 ГБ. Вкл. включает его всегда, Выкл. никогда не загружает. Файл занимает 0,4 ГБ."
}
+2 -1
View File
@@ -132,5 +132,6 @@
"q429": "fp16:基准格式,占用内存最多。",
"q430": "fp8:类似 int8,较新,优先支持 NVIDIA。",
"q431": "自动:6 GB 及以上的显卡会开启草稿层。",
"q432": "自动:此显卡上草稿层保持关闭:显存不足 6 GB,或实测更慢。"
"q432": "自动:此显卡上草稿层保持关闭:显存不足 6 GB,或实测更慢。",
"q433": "自动:6 GB 及以上的显卡会开启草稿层。开启则强制加载,关闭则从不加载。文件大小为 0.4 GB。"
}
+25 -5
View File
@@ -10,7 +10,7 @@ import { build } from 'esbuild';
import {
QWEN4_ARCH, QWEN4_FAMILY, QWEN4_COMPONENT, QWEN4_MODELS, QWEN4_EFFORTS, QWEN4_DEFAULT_EFFORT, QWEN4_EFFORT_MENU, QWEN4_LOOP_FLAGS, QWEN4_LOOP_KEY, QWEN4_LOOP_FILE, QWEN4_LOOP_STEPS, QWEN4_READY_S,
isQwen4, isQwen4Family, isQwen4Instance, qwen4VisionShard, withoutQwen4Vision, qwen4EffortWord, qwen4EffortChoice, qwen4MtpChoice, qwen4MtpPatch, qwen4LoopChoice, qwen4LoopArgs,
withoutQwen4Loop, qwen4WithLoop, qwen4LoopCoda, QWEN4_KV_CHOICES, QWEN4_KV_DEFAULT, QWEN4_KV_READY, QWEN4_KV_BACKENDS, qwen4KvChoices, qwen4KvDefault, qwen4KvPick, QWEN4_STRATA_READY, qwen4MtpReady, qwen4VisionReady, qwen4MtpReadyFor, qwen4VisionReadyFor, QWEN4_STRATA_LOOP_FLAGS, QWEN4_STRATA_COMING_LABEL, QWEN4_STRATA_COMING_NOTE, QWEN4_LOOP_READY, qwen4LoopReady, qwen4LoopSource, qwen4BuildOfConfig, qwen4LoopReadyFor, QWEN4_LOOP_COMING_LABEL, qwen4ModelArg, QWEN4_GGUF_BUILD, QWEN4_GGUF_TITLE, QWEN4_ALL_BUILDS, isQwen4GgufBuild,
withoutQwen4Loop, qwen4WithLoop, qwen4LoopCoda, QWEN4_KV_CHOICES, QWEN4_KV_DEFAULT, QWEN4_KV_READY, QWEN4_KV_BACKENDS, qwen4KvChoices, qwen4KvDefault, qwen4KvPick, QWEN4_STRATA_READY, QWEN4_STRATA_METAL_READY, qwen4MtpReady, qwen4VisionReady, qwen4MtpReadyFor, qwen4VisionReadyFor, QWEN4_STRATA_LOOP_FLAGS, QWEN4_STRATA_COMING_LABEL, QWEN4_STRATA_COMING_NOTE, QWEN4_LOOP_READY, qwen4LoopReady, qwen4LoopSource, qwen4BuildOfConfig, qwen4LoopReadyFor, QWEN4_LOOP_COMING_LABEL, qwen4ModelArg, QWEN4_GGUF_BUILD, QWEN4_GGUF_TITLE, QWEN4_ALL_BUILDS, isQwen4GgufBuild,
} from '../server/qwen4.mjs';
import { isLing32, ling32EffortWord } from '../server/ling32.mjs';
import { isNativeStrata, isNativeStrataFamily, nativeStrataVisionShard, withoutNativeStrataVision } from '../server/native-strata.mjs';
@@ -456,6 +456,25 @@ test('a .strata build: the engine takes no MTP, pictures or Loop yet: one table
assert.equal(ready('UD-Q4_K_XL'), true, 'the GGUF build has them');
assert.equal(ready('Nope'), false);
}
// a .strata tier on a Mac runs on `strata` (converted at install): the draft layer and pictures work, Loop is coming: one more table, pinned to the Python
const metalPython = /STRATA_METAL_READY = \{([^}]*)\}/.exec(family)[1];
const metalTable = Object.fromEntries([...metalPython.matchAll(/"(\w+)":\s*(True|False)/g)].map(m => [m[1], m[2] === 'True']));
assert.deepEqual({ ...QWEN4_STRATA_METAL_READY }, metalTable, 'server/qwen4.mjs mirrors the Python Mac table');
assert.deepEqual({ ...screen.QWEN4_STRATA_METAL_READY }, metalTable, 'src/lib/qwen4.ts mirrors it');
assert.deepEqual(metalTable, { mtp: true, vision: true, loop: false });
for (const ready of [qwen4MtpReady, qwen4VisionReady, screen.qwen4MtpReady, screen.qwen4VisionReady]) {
for (const b of ['Compact', 'Balanced', 'Ultra']) {
assert.equal(ready(b, undefined, 'metal'), true, `${b} on a Mac`);
assert.equal(ready(b, undefined, 'Metal'), true, 'the backend word is not case sensitive');
assert.equal(ready(b, undefined, 'cuda'), false, `${b} on NVIDIA stays coming`);
assert.equal(ready(b, undefined, 'hip'), false);
assert.equal(ready(b, undefined, undefined), false);
}
assert.equal(ready('UD-Q4_K_XL', undefined, 'metal'), true);
}
assert.equal(qwen4MtpReadyFor({ model_name: 'qwen4-35b-a3b-compact', backend: 'metal' }), true);
assert.equal(qwen4MtpReadyFor({ model_name: 'qwen4-35b-a3b-compact', backend: 'cuda' }), false);
assert.equal(qwen4VisionReadyFor({ args: ['--native', '/m/Compact.gguf', '--vision'], model_name: 'qwen4-35b-a3b-balanced', backend: 'metal' }), true);
const all = { mtp: true, vision: true, loop: true };
assert.equal(qwen4MtpReady('Compact', all), true);
assert.equal(screen.qwen4VisionReady('Ultra', all), true);
@@ -470,12 +489,12 @@ test('a .strata build: the engine takes no MTP, pictures or Loop yet: one table
assert.match(control, /isQwen4\(cfg\)&&!qwen4MtpReadyFor\(cfg\)\)\{delete cfg\.q4_mtp;delete cfg\[QWEN4_MTP_KEY\];delete cfg\[QWEN4_MTP_MODE_KEY\];\}/);
assert.match(control, /isQwen4\(cfg\)&&!qwen4VisionReadyFor\(cfg\)&&Array\.isArray\(cfg\.args\)\)cfg\.args=withoutQwen4Vision\(cfg\.args\)/);
const models = src('src/components/NativeModels.tsx');
assert.match(models, /mtpReady = qwen4MtpReady\(selectedModel\)/);
assert.match(models, /mtpReady = qwen4MtpReady\(selectedModel, undefined, q4\.backend\)/);
assert.match(models, /disabled=\{disabled \|\| !mtpReady\}/);
assert.match(models, /tr\(mtpReady \? "Draft layer \(MTP\)" : "Draft layer \(MTP\) - coming with the engine"\)/);
assert.match(models, /\(isQ4Selected && qwen4MtpReady\(selectedSize\?\.model\)\)\) && lingMtp !== 'auto'/);
assert.match(models, /\(isQ4Selected && qwen4MtpReady\(selectedSize\?\.model, undefined, selectedSize\?\.qwen4\?\.backend\)\)\) && lingMtp !== 'auto'/);
const settings = src('src/components/NativeSettings.tsx');
assert.match(settings, /q4MtpReady = !isQwen4 \|\| qwen4MtpReady\(q4Size\?\.model\)/);
assert.match(settings, /q4MtpReady = !isQwen4 \|\| qwen4MtpReady\(q4Size\?\.model, undefined, q4Size\?\.qwen4\?\.backend\)/);
assert.match(settings, /mtpReady=\{q4MtpReady\}/);
assert.match(models, new RegExp(QWEN4_STRATA_COMING_NOTE.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
// the label and the sentence, in every language
@@ -519,7 +538,8 @@ test('the K/V format: one table in the Python, the server and the screens; only
// the screens: a select with only the offered formats, next to the draft layer; Auto says what it comes to here
const models = src('src/components/NativeModels.tsx');
assert.match(models, /q4Kv = isQ4Selected \? qwen4KvPick\(selectedSize\?\.model, q4\?\.backend, kv, q4\?\.kv_choices\) : kv/);
assert.match(models, /kv: q4Kv, low_ram/);
assert.match(models, /\.\.\.\(q4Own \? \{ kv: q4Kv \} : \{\}\)/, 'a Qwen4 build sends its own format; the plain `kv,` stays for the Qwen3.8 page (kv-choice-family.test.mjs)');
assert.equal(models.split('ariaLabel={tr("Native KV format")}').length, 2, 'the Qwen3.8 select is the only one named Native KV format');
assert.match(models, /options=\{kvList\.map\(v => \(\{ value: v, label: QWEN4_KV_LABELS\[v\] \?\? v \}\)\)\}/);
assert.match(models, /q4\.mtp_default === false \? "Auto keeps the draft layer off on this card: it is under 6 GB or it measured slower here\." : "Auto turns the draft layer on for graphics cards of 6 GB or more\."/);
assert.match(src('src/lib/native.ts'), /kv_choices\?:string\[\];kv_default\?:string;mtp_default\?:boolean;mtp_available\?:boolean;/);
+3 -1
View File
@@ -103,7 +103,9 @@ add_library(q4lite_gpu STATIC
${_ling}/ling32_kernels.cu ${_ling}/ling32_layers.cu ${_ling}/ling32_moe_tc.cu ${_ling}/ling32_mla_exp.cu ${_ling}/ling32_mla_exp_hip.cu
${engine_root}/src/kernels/cuda/mla_latent_attn.cu
# Qwen4
q4_model.cu q4_glue.cu q4_gemv.cu q4_hc.cu q4_router.cu q4_moe.cu q4_engine.cu q4_mtp.cu q4_tier.cu)
q4_model.cu q4_glue.cu q4_gemv.cu q4_hc.cu q4_router.cu q4_moe.cu q4_loop.cu q4_engine.cu q4_mtp.cu q4_tier.cu
# Q4-ELASTIC: the experts and the KV pools in virtual memory (core/vmm.hpp)
q4_elastic.cu q4_kv_elastic.cu ${engine_root}/src/core/vmm.cpp)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/q4_mixers_fn.cu")
# the token mixers: Flash-Next kernels at the q4_lite geometry + q4_gdn / q4_attn (q4_mixer_sources.cmake)
include(${CMAKE_CURRENT_SOURCE_DIR}/q4_mixer_sources.cmake)
+164 -11
View File
@@ -118,6 +118,16 @@ void upload_steps(const AttnShape& s, AttnScratch& sc, int N, int pos0, cudaStre
steps_kernel<<<(N + 127) / 128, 128, 0, st>>>(sc.steps, N, pos0, s.ix_budget, s.ixb);
}
// native_qsa_rms_norm_rope launches one block per row and refuses more than 65535 rows: long prefill chunks (N * 16 query rows) go in slices
void norm_rope_rows(const float* x, int in_stride, const float* gamma, float* out, int rows, int head_dim, int n_rot, float eps, const K::RopeScaling& sc, const int32_t* pos,
cudaStream_t stream) {
constexpr int kMaxRows = 65535;
for (int r0 = 0; r0 < rows; r0 += kMaxRows) {
const int nr = std::min(kMaxRows, rows - r0);
K::native_qsa_rms_norm_rope(x + (size_t) r0 * in_stride, in_stride, gamma, out + (size_t) r0 * head_dim, nr, head_dim, n_rot, eps, sc, pos + r0, stream);
}
}
K::QsaAttnPools pools_of(const AttnState& st) {
K::QsaAttnPools p;
p.k_pool = st.k_pool;
@@ -145,27 +155,29 @@ size_t kv_pool_bytes(const AttnShape& s, size_t pages, int fmt) {
return 2 * al16(cells * s.hd * 2);
}
// KV append of N tokens (host positions: the step records of sc.steps are already uploaded) or of the one token of the device step record `d_steps`
void kv_append_fmt(const AttnShape& s, const AttnState& st, AttnScratch& sc, const float* k, const float* v, int N, const int32_t* d_steps, cudaStream_t stream) {
// KV append of N tokens whose step records (kStepCount ints each, position in kStepPos, on the device) are `steps`: N == 1 is the decode token (the *_step kernels), N > 1 a
// batch / speculative window (the *_steps kernels). Quantized formats only (fp16 has its own append kernels at the call sites).
void kv_append_fmt(const AttnShape& s, const AttnState& st, AttnScratch& sc, const float* k, const float* v, int N, const int32_t* steps, cudaStream_t stream) {
const K::QsaShapes q = qshapes(s);
const bool one = d_steps != nullptr;
const bool one = N == 1;
const int32_t* d_steps = steps;
if (st.kv_fmt == kKvInt8 || st.kv_fmt == kKvFp8) {
if (one) K::kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, d_steps, k, v, q, stream);
else K::kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, sc.steps, K::kStepCount, k, v, s.kv_width(), N, q, stream, nullptr);
else K::kv_append_q8_steps(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, steps, K::kStepCount, k, v, s.kv_width(), N, q, stream, nullptr);
} else if (st.kv_fmt == kKvQ4) { // q4_0: K and V rotated (K in place in sc.k, V into sc.v_rot), the queries are rotated by the caller
K::fwht256_cuda(k, sc.k, (int64_t) (one ? 1 : N) * s.nkv, stream);
K::fwht256_cuda(v, sc.v_rot, (int64_t) (one ? 1 : N) * s.nkv, stream);
if (one) K::kv_append_q4_step(st.k_q4, st.v_q4, st.page_table, d_steps, sc.k, sc.v_rot, q, stream);
else K::kv_append_q4_steps(st.k_q4, st.v_q4, st.page_table, sc.steps, K::kStepCount, N, sc.k, sc.v_rot, q, stream);
else K::kv_append_q4_steps(st.k_q4, st.v_q4, st.page_table, steps, K::kStepCount, N, sc.k, sc.v_rot, q, stream);
} else { // k8v4: int8 K (unrotated, so the scores stay exact; both halves of the call write K's array) + rotated q4_0 V
if (one) {
K::kv_append_q8_step(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, d_steps, k, k, q, stream);
K::fwht256_cuda(v, sc.v_rot, (int64_t) s.nkv, stream);
K::kv_append_q4_step(st.v_q4, st.v_q4, st.page_table, d_steps, sc.v_rot, sc.v_rot, q, stream);
} else {
K::kv_append_q8_steps(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, sc.steps, K::kStepCount, k, k, s.kv_width(), N, q, stream, nullptr);
K::kv_append_q8_steps(st.k_q, st.k_q, st.k_scale, st.k_scale, st.page_table, steps, K::kStepCount, k, k, s.kv_width(), N, q, stream, nullptr);
K::fwht256_cuda(v, sc.v_rot, (int64_t) N * s.nkv, stream);
K::kv_append_q4_steps(st.v_q4, st.v_q4, st.page_table, sc.steps, K::kStepCount, N, sc.v_rot, sc.v_rot, q, stream);
K::kv_append_q4_steps(st.v_q4, st.v_q4, st.page_table, steps, K::kStepCount, N, sc.v_rot, sc.v_rot, q, stream);
}
}
}
@@ -244,6 +256,49 @@ bool attn_state_assign(const AttnShape& s, int max_ctx, void* base, AttnState& o
return cudaMemcpy(o.page_table, tab.data(), pages * 4, cudaMemcpyHostToDevice) == cudaSuccess;
}
// Q4-ELASTIC: the same state with the K and V pools given from outside (virtual ranges mapped as the context grows, q4_kv_elastic.hpp); the rest is carved from base
size_t attn_state_bytes_ext(const AttnShape& s, int max_ctx) {
const size_t pages = (size_t) max_ctx / 4;
return al16(pages * 4) + al16((size_t) kTail * s.ixd * 4) + al16((size_t) s.ixd * 4) + al16((pages + 1) * s.ixd * 4) + 16;
}
int attn_kv_pool_specs(const AttnShape& s, int max_ctx, KvPoolSpec out[4]) {
const uint64_t pos = (uint64_t) max_ctx;
const uint64_t nkv = (uint64_t) s.nkv, hd = (uint64_t) s.hd;
auto put = [&](int i, uint64_t per_cell) { out[i].per_cell = per_cell; out[i].full = per_cell * pos; };
const uint64_t scale = nkv * (hd / 64) * 2, q4 = nkv * (uint64_t) K::kv_q4_bytes_per_head(s.hd);
if (g_kv_fmt == kKvFp16) { put(0, nkv * hd * 2); put(1, nkv * hd * 2); return 2; }
if (g_kv_fmt == kKvInt8 || g_kv_fmt == kKvFp8) { put(0, nkv * hd); put(1, nkv * hd); put(2, scale); put(3, scale); return 4; }
if (g_kv_fmt == kKvQ4) { put(0, q4); put(1, q4); return 2; }
put(0, nkv * hd); put(1, scale); put(2, q4); return 3; // k8v4: K int8 + its scales, V q4_0
}
bool attn_state_assign_ext(const AttnShape& s, int max_ctx, void* base, uint8_t* const* pools, int n_pools, AttnState& o) {
KvPoolSpec sp[4];
if (!base || !pools || max_ctx % 4 != 0 || max_ctx < 8 || n_pools != attn_kv_pool_specs(s, max_ctx, sp)) return false;
const size_t pg = (size_t) max_ctx / 4;
uint8_t* p = (uint8_t*) base;
o.max_ctx = max_ctx;
o.kv_fmt = g_kv_fmt;
if (g_kv_fmt == kKvFp16) {
o.k_pool = (uint16_t*) pools[0]; o.v_pool = (uint16_t*) pools[1];
} else if (g_kv_fmt == kKvInt8 || g_kv_fmt == kKvFp8) {
o.k_q = (int8_t*) pools[0]; o.v_q = (int8_t*) pools[1]; o.k_scale = (uint16_t*) pools[2]; o.v_scale = (uint16_t*) pools[3];
} else if (g_kv_fmt == kKvQ4) {
o.k_q4 = pools[0]; o.v_q4 = pools[1];
} else {
o.k_q = (int8_t*) pools[0]; o.k_scale = (uint16_t*) pools[1]; o.v_q4 = pools[2];
}
o.page_table = (int32_t*) p; p += al16(pg * 4);
o.ix_tail = (float*) p; p += al16((size_t) kTail * s.ixd * 4);
o.ix_dead = (float*) p; p += al16((size_t) s.ixd * 4);
o.ix_pooled = (float*) p; p += al16((pg + 1) * s.ixd * 4);
o.ix_block_pos = (int32_t*) p;
std::vector<int32_t> tab(pg);
for (size_t i = 0; i < pg; ++i) tab[i] = (int32_t) i;
return cudaMemcpy(o.page_table, tab.data(), pg * 4, cudaMemcpyHostToDevice) == cudaSuccess;
}
void attn_state_reset(const AttnShape& s, const AttnState& st, cudaStream_t stream) {
const size_t pages = (size_t) st.max_ctx / 4;
cudaMemsetAsync(st.ix_tail, 0, (size_t) kTail * s.ixd * 4, stream);
@@ -345,18 +400,18 @@ bool attn_run(const AttnShape& s, const AttnWeights& w, const AttnState& st, Att
try {
// 1. q / k norm + rope (q rows are the per-head [query | gate] rows of q_proj: stride 2*hd, the gate half is skipped), index split
fill_pos_kernel<<<(N * s.nh + 255) / 256, 256, 0, stream>>>(sc.pos, N * s.nh, s.nh, pos0);
K::native_qsa_rms_norm_rope(q_proj, 2 * s.hd, w.q_g, sc.q, N * s.nh, s.hd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
norm_rope_rows(q_proj, 2 * s.hd, w.q_g, sc.q, N * s.nh, s.hd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
fill_pos_kernel<<<(N * s.nkv + 255) / 256, 256, 0, stream>>>(sc.pos, N * s.nkv, s.nkv, pos0);
K::native_qsa_rms_norm_rope(k_proj, s.hd, w.k_g, sc.k, N * s.nkv, s.hd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
norm_rope_rows(k_proj, s.hd, w.k_g, sc.k, N * s.nkv, s.hd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
split_idx_kernel<<<(unsigned) (((size_t) N * (qw + s.ixd) + 255) / 256), 256, 0, stream>>>(idx_qk, sc.qi, sc.raw, N, qw, s.ixd);
fill_pos_kernel<<<(N * s.ixh + 255) / 256, 256, 0, stream>>>(sc.pos, N * s.ixh, s.ixh, pos0);
K::native_qsa_rms_norm_rope(sc.qi, s.ixd, w.ixq_g, sc.qi, N * s.ixh, s.ixd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
norm_rope_rows(sc.qi, s.ixd, w.ixq_g, sc.qi, N * s.ixh, s.ixd, s.n_rot, kEps, K::rope_scaling(), sc.pos, stream);
// 2. KV append
if (st.kv_fmt == kKvFp16) {
kv_append_batch_kernel<<<(unsigned) (((size_t) N * s.kv_width() + 255) / 256), 256, 0, stream>>>(st.k_pool, st.v_pool, sc.k, v_proj, N, pos0, s.nkv, s.hd);
} else {
upload_steps(s, sc, N, pos0, stream);
kv_append_fmt(s, st, sc, sc.k, v_proj, N, nullptr, stream);
kv_append_fmt(s, st, sc, sc.k, v_proj, N, sc.steps, stream);
}
// 3. indexer append (a window keeps what it needs to be undone)
if (vb) {
@@ -459,6 +514,104 @@ bool attn_decode_dev(const AttnShape& s, const AttnWeights& w, const AttnState&
return launch_ok(err, "attn_decode_dev");
}
// ---- graph-capturable windows
namespace {
__global__ void win_pos_kernel(const AttnShape s, int32_t* pos_q, int32_t* pos_k, int32_t* pos_i, int32_t* steps, int pos0, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < 16 * 16) pos_q[i] = pos0 + min(i / s.nh, n - 1);
if (i < 16 * 16) pos_k[i] = pos0 + min(i / s.nkv, n - 1);
if (i < 16 * 16) pos_i[i] = pos0 + min(i / s.ixh, n - 1);
if (i < n) {
const int n_kv = pos0 + i + 1;
int32_t* r = steps + (size_t) i * K::kStepCount;
r[K::kStepPos] = pos0 + i;
r[K::kStepNKv] = n_kv;
r[K::kStepNBid] = n_kv / s.ixb;
r[K::kStepWidth] = min(n_kv, s.ix_budget + n_kv % s.ixb);
}
}
// fp16 KV append of n cells at the positions of the step records
__global__ void kv_append_win_kernel(uint16_t* __restrict__ kp, uint16_t* __restrict__ vp, const float* __restrict__ k, const float* __restrict__ v, int n, int nkv, int hd,
const int32_t* __restrict__ steps) {
const size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x;
const size_t total = (size_t) n * nkv * hd;
if (i >= total) return;
const size_t t = i / ((size_t) nkv * hd);
const int r = (int) (i % ((size_t) nkv * hd));
const int h = r / hd, dd = r % hd;
const size_t cell = (size_t) steps[t * K::kStepCount + K::kStepPos];
const size_t row = ((cell / 4) * nkv + h) * 4 + (cell % 4);
kp[row * hd + dd] = K::f16_from_f32(k[i]);
vp[row * hd + dd] = K::f16_from_f32(v[i]);
}
// positions of the commit's re-append: the first *keep tokens keep their position, the others become -1 (the append skips out-of-range positions)
__global__ void commit_pos_kernel(int32_t* posc, const int32_t* steps, const int32_t* keep, int n) {
const int t = threadIdx.x;
if (t < n) posc[t] = t < *keep ? steps[t * K::kStepCount + K::kStepPos] : -1;
}
} // namespace
size_t attn_win_dev_bytes(const AttnShape&) { return 4096; }
bool attn_win_dev_assign(const AttnShape&, void* base, AttnWinDev& o) {
if (!base) return false;
uint8_t* p = (uint8_t*) base;
o.pos_q = (int32_t*) p; p += 1024;
o.pos_k = (int32_t*) p; p += 1024;
o.pos_i = (int32_t*) p; p += 1024;
o.steps = (int32_t*) p; p += 512;
o.posc = (int32_t*) p;
return true;
}
void attn_win_set_pos(const AttnShape& s, const AttnWinDev& d, int pos0, int n, cudaStream_t stream) {
win_pos_kernel<<<1, 256, 0, stream>>>(s, d.pos_q, d.pos_k, d.pos_i, d.steps, pos0, n);
}
bool attn_window_dev(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const AttnWinDev& d, const AttnVerifyBuf& vb, int n, const float* q_proj,
const float* k_proj, const float* v_proj, const float* idx_qk, float* out, cudaStream_t stream, std::string& err) {
if (!shape_ok(s, err)) return false;
if (n < 1 || n > kAttnVerifyMax || n > sc.max_n || s.nh > 16 || s.nkv > 16 || s.ixh > 16) { err = "attn_window_dev: n out of range"; return false; }
const K::QsaShapes q = qshapes(s);
const int qw = s.ixh * s.ixd;
try {
K::native_qsa_rms_norm_rope(q_proj, 2 * s.hd, w.q_g, sc.q, n * s.nh, s.hd, s.n_rot, kEps, K::rope_scaling(), d.pos_q, stream);
K::native_qsa_rms_norm_rope(k_proj, s.hd, w.k_g, sc.k, n * s.nkv, s.hd, s.n_rot, kEps, K::rope_scaling(), d.pos_k, stream);
split_idx_kernel<<<(unsigned) (((size_t) n * (qw + s.ixd) + 255) / 256), 256, 0, stream>>>(idx_qk, sc.qi, sc.raw, n, qw, s.ixd);
K::native_qsa_rms_norm_rope(sc.qi, s.ixd, w.ixq_g, sc.qi, n * s.ixh, s.ixd, s.n_rot, kEps, K::rope_scaling(), d.pos_i, stream);
if (st.kv_fmt == kKvFp16) kv_append_win_kernel<<<(unsigned) (((size_t) n * s.kv_width() + 255) / 256), 256, 0, stream>>>(st.k_pool, st.v_pool, sc.k, v_proj, n, s.nkv, s.hd, d.steps);
else kv_append_fmt(s, st, sc, sc.k, v_proj, n, d.steps, stream); // --kv int8 | fp8 | k8v4 | q4_0: the window's cells go through the format's own append (device step records)
if (st.kv_fmt == kKvQ4) K::fwht256_inplace_cuda(sc.q, (int64_t) n * s.nh, stream); // <Hq, Hk> = <q, k>
cudaMemcpyAsync(vb.tail_save, st.ix_tail, (size_t) kTail * s.ixd * 4, cudaMemcpyDeviceToDevice, stream);
cudaMemcpyAsync(vb.raw, sc.raw, (size_t) n * s.ixd * 4, cudaMemcpyDeviceToDevice, stream);
const K::QsaIndexerBuffers ib{st.ix_tail, st.ix_dead, st.ix_pooled, st.ix_block_pos};
K::native_qsa_indexer_append_steps(sc.raw, d.steps + K::kStepPos, K::kStepCount, n, 0, w.ixk_g, kEps, ib, q, st.max_ctx, K::rope_scaling(), stream);
K::qsa_block_scores(st.ix_pooled, st.ix_dead, sc.qi, d.steps, n, sc.max_blocks, q, sc.sel_scores, stream); // capacity grid (active = -1)
K::qsa_block_topk(sc.sel_scores, d.steps, n, sc.max_blocks, sc.cap, q, sc.sel_ids, stream);
K::qsa_decode_attn_batch(sc.q, pools_of(st), sc.sel_ids, d.steps, sc.cap, q, sc.attn_scratch, sc.attn, n, stream);
if (st.kv_fmt == kKvK8V4 || st.kv_fmt == kKvQ4) K::fwht256_inplace_cuda(sc.attn, (int64_t) n * s.nh, stream); // the values are stored rotated: rotate the mix back
K::native_qsa_gate_apply(sc.attn, q_proj, out, n * s.nh, s.hd, stream);
} catch (const std::exception& e) {
err = std::string("attn_window_dev: ") + e.what();
return false;
}
return launch_ok(err, "attn_window_dev");
}
bool attn_window_commit_dev(const AttnShape& s, const AttnWeights& w, const AttnState& st, const AttnWinDev& d, const AttnVerifyBuf& vb, int n, const int32_t* keep_dev,
cudaStream_t stream, std::string& err) {
if (n < 1 || n > kAttnVerifyMax) { err = "attn_window_commit_dev: n out of range"; return false; }
const K::QsaShapes q = qshapes(s);
try {
cudaMemcpyAsync(st.ix_tail, vb.tail_save, (size_t) kTail * s.ixd * 4, cudaMemcpyDeviceToDevice, stream);
commit_pos_kernel<<<1, 32, 0, stream>>>(d.posc, d.steps, keep_dev, n);
const K::QsaIndexerBuffers ib{st.ix_tail, st.ix_dead, st.ix_pooled, st.ix_block_pos};
K::native_qsa_indexer_append_steps(vb.raw, d.posc, 1, n, 0, w.ixk_g, kEps, ib, q, st.max_ctx, K::rope_scaling(), stream);
} catch (const std::exception& e) {
err = std::string("attn_window_commit_dev: ") + e.what();
return false;
}
return launch_ok(err, "attn_window_commit_dev");
}
bool attn_rollback(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, AttnVerifyBuf& vb, int n_keep, cudaStream_t stream, std::string& err,
const AttnOptions& opt) {
if (n_keep < 0 || n_keep > vb.n) { err = "attn_rollback: n_keep out of range"; return false; }
+24
View File
@@ -64,6 +64,11 @@ bool attn_parse_kv_format(const char* name, int& fmt); // fp16 | int8 | fp8 |
const char* attn_kv_format_name(int fmt);
size_t attn_state_bytes(const AttnShape& s, int max_ctx); // all of the above (16 B aligned parts)
bool attn_state_assign(const AttnShape& s, int max_ctx, void* base, AttnState& out); // carve; also fills the page table (needs a stream sync by the caller)
size_t attn_state_bytes_ext(const AttnShape& s, int max_ctx); // Q4-ELASTIC: the same without the K / V pools (given from outside: q4_kv_elastic.hpp)
// one KV array of an attention layer (the pools of the current KV format: fp16 2, int8 / fp8 4, q4_0 2, k8v4 3 arrays): bytes per position and for max_ctx positions
struct KvPoolSpec { uint64_t per_cell = 0, full = 0; };
int attn_kv_pool_specs(const AttnShape& s, int max_ctx, KvPoolSpec out[4]); // the count, in the order attn_state_assign_ext takes the pools
bool attn_state_assign_ext(const AttnShape& s, int max_ctx, void* base, uint8_t* const* pools, int n_pools, AttnState& out);
void attn_state_reset(const AttnShape& s, const AttnState& st, cudaStream_t stream);
// per-call scratch for up to max_n tokens
@@ -131,6 +136,25 @@ void attn_decode_set_pos(const AttnShape& s, const AttnDecodeDev& d, int pos, cu
bool attn_decode_dev(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const AttnDecodeDev& d, const float* q_proj, const float* k_proj,
const float* v_proj, const float* idx_qk, float* out, cudaStream_t stream, std::string& err);
// ---- graph-capturable speculative windows of n = 1..16 tokens (the same idea for several tokens): positions / step records of the window in device memory
// (attn_win_set_pos, one kernel launch outside the graph), attn_window_dev = attn_run with device positions and capacity-sized grids (n is a constant of the capture),
// attn_window_commit_dev = the rollback with the accepted count read from device memory (restores the indexer's raw tail and re-appends the kept tokens).
// Warm each n up once eagerly before capturing it.
struct AttnWinDev {
int32_t* pos_q = nullptr; // [16 * nh] rope positions of the query rows
int32_t* pos_k = nullptr; // [16 * nkv]
int32_t* pos_i = nullptr; // [16 * ixh]
int32_t* steps = nullptr; // [16][4] step records
int32_t* posc = nullptr; // [16] positions of the commit's re-append (-1 = skipped)
};
size_t attn_win_dev_bytes(const AttnShape& s);
bool attn_win_dev_assign(const AttnShape& s, void* base, AttnWinDev& out);
void attn_win_set_pos(const AttnShape& s, const AttnWinDev& d, int pos0, int n, cudaStream_t stream);
bool attn_window_dev(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const AttnWinDev& d, const AttnVerifyBuf& vb, int n, const float* q_proj,
const float* k_proj, const float* v_proj, const float* idx_qk, float* out, cudaStream_t stream, std::string& err);
bool attn_window_commit_dev(const AttnShape& s, const AttnWeights& w, const AttnState& st, const AttnWinDev& d, const AttnVerifyBuf& vb, int n, const int32_t* keep_dev,
cudaStream_t stream, std::string& err);
// the state after the first n_keep tokens of the window attn_run(..., vb) processed (0 <= n_keep <= vb.n): KV needs nothing (positions are overwritten), the indexer's
// tail is restored and the kept tokens' raw keys re-appended
bool attn_rollback(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, AttnVerifyBuf& vb, int n_keep, cudaStream_t stream,
+277
View File
@@ -0,0 +1,277 @@
// src/q4lite/q4_elastic.cu - see q4_elastic.hpp.
#include "q4_elastic.hpp"
#include "strata/core/vmm.hpp"
#include "strata/q4lite/q4_file.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
namespace strata::q4lite {
namespace {
std::string cu_msg(cudaError_t e, const char* what) { return std::string(what) + ": " + cudaGetErrorString(e); }
constexpr size_t kStage = 64ull << 20;
} // namespace
struct ElasticExperts::Impl {
GpuModel* m = nullptr;
core::VmmRange range;
uint8_t* arena = nullptr; // pinned copy of Section 4 behind the card prefix (and the bytes of experts that left the card)
const uint8_t** d_tab = nullptr; // device table [layer * n_exp + expert] -> slab address (model.d_slab_ptrs)
std::vector<const uint8_t*> h_tab;
std::vector<uint64_t> off, end; // per expert key: byte offset in the pool, offset + slab bytes
std::vector<uint64_t> starts; // the slab offsets, ascending (pool order)
// the start of the slab that contains byte pos (pos itself when it is a slab boundary): a chunk boundary can cut a slab, and the part below it moves with it
uint64_t slab_floor(uint64_t pos) const {
auto it = std::upper_bound(starts.begin(), starts.end(), pos);
return it == starts.begin() ? pos : *(it - 1);
}
uint64_t total = 0;
int64_t n_exp_total = 0;
bool quiet = false;
uint64_t prefix_bytes(int64_t mapped, uint64_t G) const { return std::min<uint64_t>(total, static_cast<uint64_t>(mapped) * G); }
// writes the table from the current prefix and uploads it
bool publish(uint64_t prefix, std::string& err) {
const uint8_t* vbase = range.base();
for (int64_t k = 0; k < n_exp_total; ++k) h_tab[static_cast<size_t>(k)] = end[static_cast<size_t>(k)] <= prefix ? vbase + off[static_cast<size_t>(k)] : arena + off[static_cast<size_t>(k)];
cudaError_t e = cudaMemcpy(d_tab, h_tab.data(), h_tab.size() * sizeof(void*), cudaMemcpyHostToDevice);
if (e != cudaSuccess) { err = cu_msg(e, "slab table upload"); return false; }
int nv = 0;
uint64_t bv = 0;
for (int64_t k = 0; k < n_exp_total; ++k) {
const bool in = end[static_cast<size_t>(k)] <= prefix;
m->expert_in_vram[static_cast<size_t>(k)] = in ? 1 : 0;
if (in) { ++nv; bv += m->experts[static_cast<size_t>(k)].body_bytes; }
}
m->experts_vram = nv;
m->experts_host = static_cast<int>(n_exp_total) - nv;
m->expert_vram_bytes = bv;
m->expert_host_bytes = total - bv;
return true;
}
int64_t resident_count(uint64_t prefix) const {
int64_t n = 0;
for (int64_t k = 0; k < n_exp_total; ++k) n += end[static_cast<size_t>(k)] <= prefix ? 1 : 0;
return n;
}
};
ElasticExperts::ElasticExperts() : p_(new Impl) {}
ElasticExperts::~ElasticExperts() { release(); delete p_; }
void ElasticExperts::release() {
if (!p_) return;
cudaDeviceSynchronize();
p_->range.release();
if (p_->arena) { cudaFreeHost(p_->arena); p_->arena = nullptr; }
if (p_->d_tab) { cudaFree(p_->d_tab); p_->d_tab = nullptr; }
if (p_->m) { p_->m->d_slab_ptrs = nullptr; p_->m->d_sec4 = nullptr; p_->m = nullptr; }
mapped_ = total_chunks_ = 0;
}
bool ElasticExperts::init(const Q4File& f, GpuModel& model, const ElasticOptions& opt, std::string& err) {
release();
Impl& I = *p_;
I.m = &model;
I.quiet = opt.quiet;
if (!core::vmm_available()) { err = "elastic experts need the driver's virtual memory API (cuMemCreate / cuMemMap): not available on this card or driver"; return false; }
gran_ = core::vmm_granularity();
const auto t0 = std::chrono::steady_clock::now();
const Q4Cfg& cfg = model.cfg;
I.total = f.section_bytes(4);
const uint64_t base = f.section_offset(4);
std::string d_err;
if (!f.validate_directory(d_err)) { err = "expert directory: " + d_err; return false; }
// ---- descriptors and slab spans (the same fields GpuModel::load fills in Mode A)
const size_t n = static_cast<size_t>(cfg.n_layers) * cfg.n_exp;
I.n_exp_total = static_cast<int64_t>(n);
model.experts.assign(n, ExpertDesc{});
model.expert_in_vram.assign(n, 0);
I.off.assign(n, 0);
I.end.assign(n, 0);
I.h_tab.assign(n, nullptr);
std::vector<uint64_t> file_off(n);
for (int il = 0; il < cfg.n_layers; ++il)
for (int eid = 0; eid < cfg.n_exp; ++eid) {
const auto& en = f.expert(il, eid);
ExpertDesc d;
d.off = en.body_offset;
d.gu_code = en.gu_code_id;
d.dn_code = en.dn_code_id;
d.dn_off = static_cast<int>(en.dn_offset);
d.body_bytes = static_cast<int>(en.body_bytes);
const size_t k = static_cast<size_t>(il) * cfg.n_exp + eid;
model.experts[k] = d;
file_off[k] = en.body_offset;
model.min_code = std::min({model.min_code, d.gu_code, d.dn_code});
model.has_code[d.gu_code & 15] = model.has_code[d.dn_code & 15] = true;
}
// ---- the pool layout: the slabs packed in HOT ORDER (opt.order, hottest first; id order when empty), the same offsets in the card range and in the pinned
// arena, so the experts on the card are always a prefix of the pool and a chunk taken from its tail moves the coldest ones
{
std::vector<uint32_t> order = opt.order;
if (order.size() != n) { order.resize(n); std::iota(order.begin(), order.end(), 0u); }
uint64_t at = 0;
I.starts.clear();
for (uint32_t k : order) {
I.starts.push_back(at);
I.off[k] = at;
at += model.experts[k].body_bytes;
I.end[k] = at;
}
if (at != I.total) { err = "expert bytes do not add up to Section 4"; return false; }
}
cudaError_t e = cudaMalloc(reinterpret_cast<void**>(&model.d_experts), n * sizeof(ExpertDesc));
if (e == cudaSuccess) e = cudaMemcpy(model.d_experts, model.experts.data(), n * sizeof(ExpertDesc), cudaMemcpyHostToDevice);
if (e == cudaSuccess) e = cudaMalloc(reinterpret_cast<void**>(&I.d_tab), n * sizeof(void*));
if (e != cudaSuccess) { err = cu_msg(e, "expert tables"); return false; }
model.expert_bytes = I.total;
// ---- the range and the card prefix
total_chunks_ = static_cast<int64_t>((I.total + gran_ - 1) / gran_);
if (!I.range.reserve(static_cast<uint64_t>(total_chunks_) * gran_)) { err = "could not reserve the expert address range"; return false; }
size_t freeb = 0, totalb = 0;
cudaMemGetInfo(&freeb, &totalb);
uint64_t avail = freeb > opt.floor_bytes ? freeb - opt.floor_bytes : 0;
if (opt.vram_cap_bytes) avail = std::min<uint64_t>(avail, opt.vram_cap_bytes);
const int64_t want = std::min<int64_t>(total_chunks_, static_cast<int64_t>(avail / gran_));
if (want > 0) I.range.map_range(0, want, [] { return 0ull; });
mapped_ = 0;
while (mapped_ < total_chunks_ && I.range.mapped(mapped_)) ++mapped_;
const uint64_t P = I.prefix_bytes(mapped_, gran_);
// ---- the pinned copy behind the prefix, then one sequential read of Section 4
e = cudaMallocHost(reinterpret_cast<void**>(&I.arena), static_cast<size_t>(I.total));
if (e != cudaSuccess) {
I.arena = nullptr;
(void) cudaGetLastError();
if (mapped_ >= total_chunks_) { // everything fits on the card: the host copy is made when the first KV chunk asks (take)
err.clear();
} else {
err = cu_msg(e, ("pinned RAM for the experts the card does not hold (" + std::to_string(I.total >> 20) + " MiB)").c_str()) +
" (the SSD tier for a RAM that cannot hold them is not wired yet)";
return false;
}
}
void* stage = nullptr;
e = cudaMallocHost(&stage, kStage);
if (e != cudaSuccess) { err = cu_msg(e, "stage buffer"); return false; }
{ // Section 4 is read in file order, in windows of up to 64 MiB; each slab goes to its place in the pool (card prefix) or the arena
std::vector<uint32_t> by_file(n);
std::iota(by_file.begin(), by_file.end(), 0u);
std::sort(by_file.begin(), by_file.end(), [&](uint32_t a, uint32_t b) { return file_off[a] < file_off[b]; });
uint8_t* st = static_cast<uint8_t*>(stage);
size_t i = 0;
while (i < n) {
const uint64_t w0 = file_off[by_file[i]];
size_t j = i;
uint64_t w1 = w0;
while (j < n && file_off[by_file[j]] == w1 && w1 + model.experts[by_file[j]].body_bytes - w0 <= kStage) { w1 += model.experts[by_file[j]].body_bytes; ++j; }
if (j == i) { err = "slab larger than the staging window"; cudaFreeHost(stage); return false; }
if (!f.reader().read_at(base + w0, st, static_cast<size_t>(w1 - w0), err)) { cudaFreeHost(stage); return false; }
for (size_t a = i; a < j; ++a) {
const uint32_t k = by_file[a];
const uint8_t* src = st + (file_off[k] - w0);
const size_t nb = static_cast<size_t>(model.experts[k].body_bytes);
if (I.end[k] <= P) {
e = cudaMemcpy(I.range.base() + I.off[k], src, nb, cudaMemcpyHostToDevice);
if (e != cudaSuccess) { err = cu_msg(e, "expert upload"); cudaFreeHost(stage); return false; }
} else {
std::memcpy(I.arena + I.off[k], src, nb);
}
}
i = j;
}
}
cudaFreeHost(stage);
if (!I.publish(P, err)) return false;
model.d_slab_ptrs = I.d_tab;
model.d_sec4 = I.range.base();
const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
if (!opt.quiet)
std::printf("q4lite tier: %lld of %lld MiB of experts on the card (%.1f %% of the experts), the rest in pinned RAM; floor %llu MiB, %.1f s\n", static_cast<long long>(P >> 20),
static_cast<long long>(I.total >> 20), 100.0 * resident_fraction(), static_cast<unsigned long long>(opt.floor_bytes >> 20), s);
return true;
}
double ElasticExperts::resident_fraction() const {
if (!p_ || p_->n_exp_total == 0) return 0.0;
return static_cast<double>(p_->resident_count(p_->prefix_bytes(mapped_, gran_))) / static_cast<double>(p_->n_exp_total);
}
// the coldest chunks of the card prefix leave: their experts are copied to the pinned arena first, the table points there, then the chunks are unmapped
bool ElasticExperts::take(int64_t n, std::vector<unsigned long long>& out) {
Impl& I = *p_;
if (n <= 0) return true;
if (n > mapped_) return false;
{
const cudaError_t se = cudaDeviceSynchronize(); // nothing may read the chunks that go
if (se != cudaSuccess) { std::fprintf(stderr, "q4lite elastic: the card reports %s before the KV takes its chunks\n", cudaGetErrorString(se)); return false; }
}
const int64_t new_mapped = mapped_ - n;
uint64_t lo = I.prefix_bytes(new_mapped, gran_);
const uint64_t hi = I.prefix_bytes(mapped_, gran_);
if (!I.arena) { // everything was on the card: the host copy is made now, of the whole prefix (one device-to-host pass)
if (cudaMallocHost(reinterpret_cast<void**>(&I.arena), static_cast<size_t>(I.total)) != cudaSuccess) { I.arena = nullptr; (void) cudaGetLastError(); return false; }
lo = 0;
}
lo = I.slab_floor(lo); // a slab cut by the chunk boundary goes whole
// a slab cut by the TOP of the card prefix is on the host already (its card part was never written): only whole slabs below it are copied
const uint64_t hi_copy = hi >= I.total ? I.total : I.slab_floor(hi);
if (hi_copy > lo) {
cudaError_t e = cudaMemcpy(I.arena + lo, I.range.base() + lo, static_cast<size_t>(hi_copy - lo), cudaMemcpyDeviceToHost);
if (e != cudaSuccess) return false;
}
lo = I.prefix_bytes(new_mapped, gran_);
std::string err;
if (!I.publish(lo, err)) return false;
for (int64_t i = mapped_ - 1; i >= new_mapped; --i) {
const unsigned long long h = I.range.unmap(i);
if (h) out.push_back(h);
}
mapped_ = new_mapped;
evicted_ += static_cast<uint64_t>(n);
return true;
}
// chunks come back (the context ended): the hottest experts of the host copy return to the card
void ElasticExperts::give(const std::vector<unsigned long long>& chunks) {
Impl& I = *p_;
cudaDeviceSynchronize();
size_t used = 0;
while (used < chunks.size() && mapped_ < total_chunks_ && I.arena) {
const unsigned long long h = chunks[used];
if (!I.range.map_range(mapped_, mapped_ + 1, [h] { return h; })) break;
const uint64_t chunk_lo = static_cast<uint64_t>(mapped_) * gran_, hi = std::min<uint64_t>(I.total, chunk_lo + gran_);
const uint64_t lo = I.slab_floor(chunk_lo); // the part of a slab cut by the boundary that lies in the chunk below was never written to the card
if (hi > lo && cudaMemcpy(I.range.base() + lo, I.arena + lo, static_cast<size_t>(hi - lo), cudaMemcpyHostToDevice) != cudaSuccess) {
I.range.unmap(mapped_);
break;
}
++mapped_;
++used;
++promoted_;
}
for (size_t i = used; i < chunks.size(); ++i) core::vmm_chunk_free(chunks[i]);
std::string err;
I.publish(I.prefix_bytes(mapped_, gran_), err);
}
std::string ElasticExperts::report() const {
char b[256];
std::snprintf(b, sizeof b, "tier: %lld of %lld chunks of experts on the card (%.1f %% of the experts), %llu chunks given to the KV, %llu taken back", static_cast<long long>(mapped_),
static_cast<long long>(total_chunks_), 100.0 * resident_fraction(), static_cast<unsigned long long>(evicted_), static_cast<unsigned long long>(promoted_));
return b;
}
} // namespace strata::q4lite
+77
View File
@@ -0,0 +1,77 @@
// src/q4lite/q4_elastic.hpp - memory elasticity of the Qwen4 .strata host (lane Q4-ELASTIC).
//
// The default build keeps every expert slab on the card (GpuModel::load, "Mode A"). With --elastic the routed experts (Section 4) live in ONE virtual range
// (core/vmm.hpp: 2 MiB chunks, the base address never moves, so every captured CUDA graph stays valid) with the slabs packed in HOT ORDER (the file's STRP
// profile, expert_hot_order in q4_tier.hpp; the same offsets in the card range and in the pinned copy). So the experts on the card are a PREFIX of the pool,
// mapped chunk by chunk; the rest is read in place from one pinned host copy (the KEXP kernels read a slab from any address and the slab table is device memory: a tier change is a table write, not a kernel change).
//
// VRAM chunks [0, mapped) slab address range_base + pool offset
// RAM everything behind them slab address pinned_arena + pool offset (zero copy over PCIe)
//
// The KV pools of the attention layers (q4_kv_elastic.hpp) are VMM ranges too. When the context grows they take 2 MiB chunks from the TAIL of the card's
// expert prefix (the coldest experts on the card): the experts of those chunks are copied to the pinned arena first (device to host), their table entries
// point at the arena, and the chunks are unmapped and mapped under the KV pools. When the context ends the KV hands the chunks back and the hottest
// experts of the host copy return to the card. Everything here runs between forward() calls on a quiet stream.
#pragma once
#include "q4_model.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace strata::q4lite {
class Q4File;
// physical 2 MiB chunks the KV pools borrow from the expert tier (and give back); a chunk is the driver's allocation handle
struct ChunkPool {
virtual ~ChunkPool() = default;
virtual uint64_t granularity() const = 0;
// n chunks (the handles are appended to out); false: not available (the tier could not free that many)
virtual bool take(int64_t n, std::vector<unsigned long long>& out) = 0;
// chunks the KV no longer needs: back to the experts (or freed)
virtual void give(const std::vector<unsigned long long>& chunks) = 0;
};
struct ElasticOptions {
uint64_t floor_bytes = 640ull << 20; // free card memory kept after the experts are placed (driver, desktop, WDDM headroom: the guard floor)
uint64_t vram_cap_bytes = 0; // 0: the whole card; else the experts use at most this much (tests: an emulated smaller card)
std::vector<uint32_t> order; // (layer * n_exp + expert), hottest first (expert_hot_order, q4_tier.hpp); empty: id order
bool quiet = false;
};
class ElasticExperts : public ChunkPool {
public:
ElasticExperts();
~ElasticExperts() override;
ElasticExperts(const ElasticExperts&) = delete;
ElasticExperts& operator=(const ElasticExperts&) = delete;
// Builds the expert tables of `model` (which must have been loaded with load_experts = false), reserves the range, maps as many chunks as the free
// card memory allows (minus floor_bytes), reads Section 4 once (the card prefix to the card, the rest into the pinned arena).
bool init(const Q4File& f, GpuModel& model, const ElasticOptions& opt, std::string& err);
void release();
uint64_t granularity() const override { return gran_; }
bool take(int64_t n, std::vector<unsigned long long>& out) override;
void give(const std::vector<unsigned long long>& chunks) override;
// chunks that are free on the card right now (not mapped under experts or KV) cannot exist here: the tier maps everything it can; this says how many
// chunks the KV can still take: mapped expert chunks (all of them can leave)
int64_t mapped_chunks() const { return mapped_; }
int64_t total_chunks() const { return total_chunks_; }
double resident_fraction() const; // experts on the card / all experts (by count)
uint64_t evicted_chunks() const { return evicted_; }
uint64_t promoted_chunks() const { return promoted_; }
std::string report() const;
private:
struct Impl;
Impl* p_ = nullptr;
uint64_t gran_ = 0;
int64_t mapped_ = 0, total_chunks_ = 0;
uint64_t evicted_ = 0, promoted_ = 0;
};
} // namespace strata::q4lite
+54 -1
View File
@@ -3,6 +3,7 @@
#include "q4_glue.hpp"
#include "q4_mixers.hpp"
#include "q4_loop.hpp"
#include "q4_hc.hpp"
#include "q4_moe.hpp"
#include "q4_router.hpp"
@@ -74,6 +75,9 @@ struct Q4Engine::Impl {
cudaStream_t s = nullptr, s2 = nullptr; // s2: the shared expert runs beside the router and the routed experts
cudaEvent_t ev_fork = nullptr, ev_join = nullptr;
std::unique_ptr<Mixers> mix;
std::unique_ptr<LoopAdapter> loop; // opt.loop_passes >= 2
bool loop_bypass = false; // set_loop_bypass: the stock single pass
float *loop_anchor = nullptr, *loop_mprev = nullptr; // [max_tokens, hc*D]: the core's input state, the previous pass's exit state
strata::kernels::PleTable* ple = nullptr;
PleHash hash;
int32_t ple_ctx[2];
@@ -211,6 +215,15 @@ bool Q4Engine::init(GpuModel& model, const EngineOptions& o, strata::kernels::Pl
I.moe.tc_min_n = opt.moe_tc_min_tokens;
I.moe.tc_mode = opt.moe_tc_mode;
I.moe.tc = opt.moe_tc > 0 && gpu::grouped_tc_available(opt.device); // the expert codes are read per call (the experts may be loaded after init)
if (opt.loop_passes >= 2) { // the owner's Loop: loaded before the mixers so that they know the core range
I.loop.reset(new LoopAdapter);
if (!I.loop->load(opt.loop_file, opt.loop_coda, opt.loop_passes, c.D, c.hc, c.n_layers, opt.max_tokens, opt.device, err)) return false;
opt.loop_core_start = I.loop->core_start();
opt.loop_core_end = I.loop->core_end();
if (!dalloc(&I.loop_anchor, M * HD, "loop anchor", err) || !dalloc(&I.loop_mprev, M * HD, "loop mprev", err)) return false;
I.graphs = false; // the decode graphs know nothing of the extra passes
std::fprintf(stderr, "q4lite: %s\n", I.loop->summary().c_str());
}
I.mix = make_mixers();
if (!I.mix || !I.mix->init(model, opt, err)) {
if (err.empty()) err = "the token mixers failed to initialise";
@@ -227,6 +240,9 @@ void Q4Engine::destroy() {
I.gexec.clear();
I.graph_ready = false;
if (I.mix) { I.mix->destroy(); I.mix.reset(); }
if (I.loop) { I.loop->destroy(); I.loop.reset(); }
if (I.loop_anchor) { cudaFree(I.loop_anchor); I.loop_anchor = nullptr; }
if (I.loop_mprev) { cudaFree(I.loop_mprev); I.loop_mprev = nullptr; }
gpu::grouped_free(I.moe.gw);
gpu::dense_release();
if (I.moe.ctr) { cudaFree(I.moe.ctr); I.moe.ctr = nullptr; }
@@ -248,6 +264,9 @@ void Q4Engine::destroy() {
m_ = nullptr;
}
void Q4Engine::set_loop_bypass(bool b) { p_->loop_bypass = b; }
bool Q4Engine::loop_loaded() const { return p_->loop != nullptr; }
void Q4Engine::reset() {
Impl& I = *p_;
pos_ = 0;
@@ -292,6 +311,7 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
const Q4Cfg& c = m_->cfg;
if (N < 1 || N > opt.max_tokens) { err = "forward: N must be 1.." + std::to_string(opt.max_tokens); return false; }
if (pos_ + N > opt.max_ctx) { err = "forward: context full (" + std::to_string(opt.max_ctx) + ")"; return false; }
if (opt.kv_elastic && !I.mix->ensure_ctx(pos_ + N, err)) return false; // Q4-ELASTIC: map the KV chunks this call needs (the expert tier gives them up)
if (n_logits > N || n_logits > opt.logits_rows) { err = "forward: n_logits too large"; return false; }
const auto t0 = std::chrono::steady_clock::now();
const int D = c.D, HD = c.hcD();
@@ -514,7 +534,9 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
f_embed(s);
capture(-1, "embed", I.x, D);
sec("embed");
for (int il = 0; il < c.n_layers; ++il) {
const bool loop_run = I.loop != nullptr && !I.loop_bypass;
int loop_pass = 0; // the core pass the layer body runs for (0 = stock; the owner's Loop adds LoRAs on the passes >= 1 and on the coda)
auto run_layer = [&](int il) -> bool {
const Layer& Ly = m_->layers[il];
if (opt.capture) capture(il, "h_in", I.h, HD);
if (Ly.ple.present && I.ple) {
@@ -527,6 +549,7 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
capture(il, "attn_x", I.x, D);
const bool okm = Ly.is_full ? I.mix->attn(il, I.x, I.xr, N, pos_, I.y, s, err) : I.mix->gdn(il, I.x, I.xr, N, pos_, I.y, s, err);
if (!okm) return false;
if (loop_run) I.loop->lora_add(0, loop_pass, il, I.x, I.y, N, s); // the owner's Loop: attn LoRA on the token mixer's output
capture(il, "mixer_y", I.y, D);
sec(Ly.is_full ? "attn" : "gdn");
f_inject(s);
@@ -535,6 +558,7 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
sec("hc_pre");
capture(il, "mlp_x", I.x, D);
f_moe(il, s);
if (loop_run) I.loop->lora_add(1, loop_pass, il, I.x, I.y, N, s); // mlp LoRA on the MoE block's output
if (opt.capture) {
capture(il, "moe_y", I.y, D);
cudaStreamSynchronize(s);
@@ -548,6 +572,35 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
}
f_inject(s);
capture(il, "h_out", I.h, HD);
return true;
};
if (!loop_run) {
for (int il = 0; il < c.n_layers; ++il)
if (!run_layer(il)) return false;
} else {
// the owner's Loop (q4_loop.hpp): the stock pass over the prelude and the core, T - 1 extra core passes from the core's input state, then the coda
LoopAdapter& LA = *I.loop;
const size_t hb = static_cast<size_t>(N) * HD * sizeof(float);
LA.set_flags(ids, N, pos_, s);
for (int il = 0; il < LA.core_end(); ++il) {
if (!run_layer(il)) return false;
if (il == LA.core_start() - 1) cudaMemcpyAsync(I.loop_anchor, I.h, hb, cudaMemcpyDeviceToDevice, s);
}
cudaMemcpyAsync(I.loop_mprev, I.h, hb, cudaMemcpyDeviceToDevice, s);
for (int p = 1; p < LA.passes(); ++p) {
loop_pass = p;
I.mix->set_pass(p);
cudaMemcpyAsync(I.h, I.loop_anchor, hb, cudaMemcpyDeviceToDevice, s);
for (int il = LA.core_start(); il < LA.core_end(); ++il) {
LA.mixer(il, I.h, I.loop_mprev, N, s);
if (!run_layer(il)) { I.mix->set_pass(0); return false; }
}
cudaMemcpyAsync(I.loop_mprev, I.h, hb, cudaMemcpyDeviceToDevice, s);
}
loop_pass = 0;
I.mix->set_pass(0);
for (int il = LA.core_end(); il < c.n_layers; ++il)
if (!run_layer(il)) return false;
}
f_final(s);
if (I.ple && I.has_ple && !I.hint.empty() && !opt.profile) {
+11
View File
@@ -21,6 +21,8 @@ namespace strata::kernels { class PleTable; }
namespace strata::q4lite {
class KvElastic; // q4_kv_elastic.hpp
struct EngineOptions {
int max_tokens = 256; // tokens per forward() call
int max_ctx = 8192; // KV rows per attention layer
@@ -29,6 +31,12 @@ struct EngineOptions {
bool capture = false; // keep named intermediates on the host (tests): captures()
int device = 0;
bool profile = false; // STRATA_Q4_PROFILE=1 or --profile: per-section GPU time (syncs between sections: relative numbers only)
KvElastic* kv_elastic = nullptr; // Q4-ELASTIC: the K / V pools are virtual ranges mapped as the context grows (owned by the caller, must outlive the engine)
int kv_init_cells = 8192; // cells mapped at start with kv_elastic
int loop_passes = 0; // the owner's Loop (q4_loop.hpp): 0 = off (today's code path), 2 / 3 = recurrent core passes; CUDA graphs are off with it
std::string loop_file; // Qwen4-35B-A3B-Loop.safetensors
std::string loop_coda = "universal"; // coda LoRA set: "compact" for the Compact tier, "universal" for Balanced / Ultra
int loop_core_start = 12, loop_core_end = 28; // set from the file when it is loaded (the mixers' extra state slots follow it)
int kv_format = 0; // --kv: 0 fp16 (default), 1 int8, 2 fp8 (E4M3), 3 k8v4, 4 q4_0 - the attention layers' K/V pools (q4_attn.hpp AttnKvFormat)
int moe_tc_min_n = 16; // routed experts of batches with at least this many tokens: grouped kernels (0 = per-pair)
int tc_min_n = -1; // dense S_K projections of batches with at least this many tokens: Ling's tensor-core GEMM (0 = the scalar GEMV; -1 = STRATA_Q4_TC_MIN_N, else the default)
@@ -52,6 +60,9 @@ public:
void destroy();
void reset(); // empty context: position 0, zero recurrent state / histories / caches
// the owner's Loop (opt.loop_passes >= 2): true = the next forward() calls run the stock single pass (--serve: a request with loop_passes=1). Change it only on an empty context (reset()).
void set_loop_bypass(bool b);
bool loop_loaded() const;
int pos() const { return pos_; }
// Runs ids[0..N) at positions pos .. pos+N-1. Logits of the LAST n_logits of them go to `logits` [n_logits][V].
// argmax_out (optional, n_logits ints): the greedy token of each returned logits row, computed on the device (logits may then be null: no logits D2H)
+12
View File
@@ -224,6 +224,18 @@ bool gdn_verify(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnS
return launch_ok(err, "gdn_verify");
}
// graph form of the commit: the window size n is a constant of the graph, the accepted count is read from DEVICE memory (0 .. n leaves nothing to do for 0)
bool gdn_commit_dev(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, const GdnVerifyBuf& vb, int n, const int32_t* keep_dev, cudaStream_t stream,
std::string& err) {
if (!shape_ok(s, err)) return false;
if (n < 1 || n > kGdnVerifyMax) return fail(err, "gdn_commit_dev: n out of range");
namespace K = strata::kernels;
const int C = s.conv_dim();
K::gdn_conv_commit(st.hist, vb.qkv, C, keep_dev, stream);
K::gdn_step_norm_multi(st.S, vb.h, C, vb.gate, vb.beta, vb.z, w.norm, kEps, sc.oc, s.hk, s.hv, n, keep_dev, stream);
return launch_ok(err, "gdn_commit_dev");
}
bool gdn_commit(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, GdnVerifyBuf& vb, int n_keep, cudaStream_t stream, std::string& err) {
if (!shape_ok(s, err)) return false;
if (n_keep < 0 || n_keep > vb.n) return fail(err, "gdn_commit: n_keep out of range");
+4
View File
@@ -87,4 +87,8 @@ bool gdn_verify(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnS
// after a gdn_verify: the state and history after the first n_keep (0..N) tokens of the window
bool gdn_commit(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, GdnVerifyBuf& vb, int n_keep, cudaStream_t stream, std::string& err);
// graph form: gdn_verify is already launch-only (capturable, window size = N of the capture); this commits the window of n tokens with the accepted count in DEVICE memory
bool gdn_commit_dev(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScratch& sc, const GdnVerifyBuf& vb, int n, const int32_t* keep_dev, cudaStream_t stream,
std::string& err);
} // namespace strata::q4lite
+60
View File
@@ -10,6 +10,7 @@
#include "ling32_dev.cuh"
#include <cstdint>
#include <cstdlib>
namespace strata::q4lite::gpu {
@@ -137,6 +138,61 @@ __global__ void __launch_bounds__(256) k_hc_up_mix(const float* __restrict__ t_a
}
}
#if defined(STRATA_USE_HIP)
// HIP: the same arithmetic as k_hc_up_mix (bit-identical), DPB output positions per block instead of 2: the silu + FWHT of the 256 down outputs is done once per block (it was repeated by every
// 2-position block, 1024 times) and the DPB / 2 row loads of a warp are issued together. grid (D / DPB, N), block 256.
template <int DPB>
__global__ void __launch_bounds__(256) k_hc_up_mix_m(const float* __restrict__ t_all, const int8_t* __restrict__ qu, const float* __restrict__ epu, const float* __restrict__ hn_all, int hc, int D,
float inv_hc, float* __restrict__ x_all) {
constexpr int IT = DPB / 2;
__shared__ float trot[256];
__shared__ float part[DPB * 4];
const int tok = blockIdx.y;
const float* t = t_all + static_cast<size_t>(tok) * 256;
const float* hn = hn_all + static_cast<size_t>(tok) * hc * D;
float* x = x_all + static_cast<size_t>(tok) * D;
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
const int c = warp & 3, pj = warp >> 2;
const int g = lane >> 3, idx0 = g * 64 + (lane & 7) * 8;
uint2 w[IT];
float eff[IT], hv[IT];
#pragma unroll
for (int it = 0; it < IT; ++it) { // the weight rows do not depend on trot: issue their loads before the FWHT
const int d = blockIdx.x * DPB + it * 2 + pj;
const int row = c * D + d;
eff[it] = epu[static_cast<size_t>(row) * 4 + g];
w[it] = *reinterpret_cast<const uint2*>(qu + static_cast<size_t>(row) * 256 + idx0);
hv[it] = hn[static_cast<size_t>(c) * D + d];
}
if (warp < 2) { // silu(t / hc) then FWHT-128 of each half
float v[4];
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] = siluf_(t[warp * 128 + lane * 4 + i] * inv_hc);
dk::fwht128_warp(v, lane);
#pragma unroll
for (int i = 0; i < 4; ++i) trot[warp * 128 + lane * 4 + i] = v[i];
}
__syncthreads();
#pragma unroll
for (int it = 0; it < IT; ++it) {
const uint32_t ww[2] = {w[it].x, w[it].y};
float s = 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) s += static_cast<float>(static_cast<int8_t>((ww[j >> 2] >> (8 * (j & 3))) & 0xFFu)) * trot[idx0 + j];
float acc = eff[it] * s;
#pragma unroll
for (int off = 16; off >= 1; off >>= 1) acc += __shfl_xor_sync(0xFFFFFFFFu, acc, off);
if (lane == 0) part[(it * 2 + pj) * 4 + c] = sigmoidf_(acc) * hv[it];
}
__syncthreads();
if (threadIdx.x < DPB) {
float sum = 0.0f;
for (int cc = 0; cc < 4; ++cc) sum += part[threadIdx.x * 4 + cc]; // fixed order over the branches (hc == 4)
x[blockIdx.x * DPB + threadIdx.x] = sum / static_cast<float>(hc);
}
}
#endif
template <int NT>
void run_split2(const int8_t* q_down, const float* e_down, int rank, const int8_t* q_inj, const float* e_inj, int hc, int K, const float* rot, float* t, float* raw, cudaStream_t s) {
if (q_inj) k_s8_split2<NT><<<rank + hc, 128, 0, s>>>(q_down, e_down, rank, q_inj, e_inj, hc, K, rot, t, raw);
@@ -157,6 +213,10 @@ void hc_read_fused(const float* h, const float* norm_w, const int8_t* q_down, co
case 3: run_split2<3>(q_down, e_down, rank, q_inj, e_inj, hc, K, rot, t, raw, s); break;
default: run_split2<4>(q_down, e_down, rank, q_inj, e_inj, hc, K, rot, t, raw, s); break;
}
#if defined(STRATA_USE_HIP)
if (D % 4 == 0) k_hc_up_mix_m<4><<<dim3(D / 4, N), 256, 0, s>>>(t, q_up, e_up, hn, hc, D, 1.0f / static_cast<float>(hc), x); // 4 positions per block: 6.4 us per call against 23.6 us for the 2-position kernel (R9700; 8 positions: 17 us, 16: 7.5 us)
else
#endif
k_hc_up_mix<<<dim3(D / 2, N), 256, 0, s>>>(t, q_up, e_up, hn, hc, D, 1.0f / static_cast<float>(hc), x);
}
+127
View File
@@ -0,0 +1,127 @@
// src/q4lite/q4_kv_elastic.cu - see q4_kv_elastic.hpp.
#include "q4_kv_elastic.hpp"
#include "strata/core/vmm.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
namespace strata::q4lite {
struct KvElastic::Impl {
struct P {
core::VmmRange range;
uint64_t per_cell = 0, full = 0;
int64_t total_chunks = 0, mapped = 0, init_chunks = 0;
int64_t chunks_for(int64_t cells, uint64_t gran) const {
const uint64_t b = static_cast<uint64_t>(std::max<int64_t>(cells, 0)) * per_cell;
return std::min<int64_t>(total_chunks, static_cast<int64_t>((b + gran - 1) / gran));
}
};
std::vector<std::unique_ptr<P>> pools;
uint64_t gran = 0;
};
KvElastic::KvElastic() : p_(new Impl) {}
KvElastic::~KvElastic() { release(); delete p_; }
void KvElastic::release() {
if (!p_) return;
cudaDeviceSynchronize();
p_->pools.clear(); // VmmRange::release frees every chunk it still holds
}
bool KvElastic::init(const std::vector<Pool>& pools, int64_t init_cells, std::string& err) {
release();
Impl& I = *p_;
if (!core::vmm_available()) { err = "elastic KV needs the driver's virtual memory API: not available"; return false; }
I.gran = core::vmm_granularity();
for (const Pool& sp : pools) {
auto q = std::make_unique<Impl::P>();
q->per_cell = sp.per_cell;
q->full = sp.full;
q->total_chunks = static_cast<int64_t>((sp.full + I.gran - 1) / I.gran);
if (!q->range.reserve(static_cast<uint64_t>(q->total_chunks) * I.gran)) { err = "could not reserve a KV address range"; I.pools.clear(); return false; }
q->init_chunks = std::max<int64_t>(1, q->chunks_for(init_cells, I.gran));
I.pools.push_back(std::move(q));
}
return ensure(init_cells, err);
}
uint8_t* KvElastic::pool(int i) const { return p_->pools[static_cast<size_t>(i)]->range.base(); }
int64_t KvElastic::cells_mapped() const {
int64_t m = INT64_MAX;
for (const auto& q : p_->pools) m = std::min<int64_t>(m, q->per_cell ? static_cast<int64_t>(static_cast<uint64_t>(q->mapped) * p_->gran / q->per_cell) : INT64_MAX);
return m == INT64_MAX ? 0 : m;
}
uint64_t KvElastic::mapped_bytes() const {
uint64_t n = 0;
for (const auto& q : p_->pools) n += static_cast<uint64_t>(q->mapped) * p_->gran;
return n;
}
uint64_t KvElastic::full_bytes_total() const {
uint64_t n = 0;
for (const auto& q : p_->pools) n += static_cast<uint64_t>(q->total_chunks) * p_->gran;
return n;
}
bool KvElastic::ensure(int64_t cells, std::string& err) {
Impl& I = *p_;
int64_t total_delta = 0;
for (const auto& q : I.pools) total_delta += std::max<int64_t>(0, q->chunks_for(cells, I.gran) - q->mapped);
if (total_delta == 0) return true;
std::vector<unsigned long long> h;
h.reserve(static_cast<size_t>(total_delta));
if (src_) {
if (!src_->take(total_delta, h)) { err = "the KV cannot grow to " + std::to_string(cells) + " cells: no expert chunk left to give (the card is too small for this context)"; return false; }
} else {
for (int64_t i = 0; i < total_delta; ++i) {
const unsigned long long c = core::vmm_chunk_new();
if (!c) { for (auto x : h) core::vmm_chunk_free(x); err = "the KV cannot grow to " + std::to_string(cells) + " cells: out of device memory"; return false; }
h.push_back(c);
}
}
size_t k = 0;
for (auto& q : I.pools) {
const int64_t need = q->chunks_for(cells, I.gran);
if (need <= q->mapped) continue;
if (!q->range.map_range(q->mapped, need, [&] { return k < h.size() ? h[k++] : 0ull; })) { err = "the KV could not map its chunks"; return false; }
q->mapped = need;
}
{
const cudaError_t se = cudaDeviceSynchronize();
if (se != cudaSuccess) { err = std::string("the card reports ") + cudaGetErrorString(se) + " after the KV mapped its chunks"; return false; }
}
if (src_) std::fprintf(stderr, "q4lite elastic: KV grows to %lld cells (%lld chunks taken from the experts)\n", static_cast<long long>(cells), static_cast<long long>(total_delta));
return true;
}
void KvElastic::shrink_to_initial() {
Impl& I = *p_;
bool any = false;
for (const auto& q : I.pools) any = any || q->mapped > q->init_chunks;
if (!any) return;
cudaDeviceSynchronize();
std::vector<unsigned long long> back;
for (auto& q : I.pools) {
for (int64_t i = q->mapped - 1; i >= q->init_chunks; --i) {
const unsigned long long h = q->range.unmap(i);
if (h) back.push_back(h);
}
q->mapped = std::min(q->mapped, q->init_chunks);
}
if (src_) src_->give(back);
else for (auto h : back) core::vmm_chunk_free(h);
}
std::string KvElastic::report() const {
char b[200];
std::snprintf(b, sizeof b, "kv: %.2f of %.2f GiB mapped under %d pools (virtual, grows with the context)", mapped_bytes() / 1073741824.0, full_bytes_total() / 1073741824.0, static_cast<int>(p_->pools.size()));
return b;
}
} // namespace strata::q4lite
+48
View File
@@ -0,0 +1,48 @@
// src/q4lite/q4_kv_elastic.hpp - the elastic KV pools of the attention layers (lane Q4-ELASTIC).
//
// Every K and V pool of the 10 QSA layers is its own virtual range (core/vmm.hpp) reserved for max_ctx cells; physical 2 MiB chunks are mapped only as far as
// the context has got (all pools together, the same number of chunks each). The addresses never move, so the captured decode graphs stay valid. Growing takes
// chunks from a ChunkPool (the expert tier: its coldest on-card experts move to pinned RAM, q4_elastic.hpp), or from the driver when there is no tier; shrinking
// (a new context) hands them back.
#pragma once
#include "q4_elastic.hpp"
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace strata::q4lite {
class KvElastic {
public:
KvElastic();
~KvElastic();
KvElastic(const KvElastic&) = delete;
KvElastic& operator=(const KvElastic&) = delete;
// one pool per entry of `pools`: bytes per position and bytes for max_ctx positions (the arrays of the KV format differ: K / V 1024 B per position in fp16,
// their scales 16 B); init_cells are mapped now. The source of the chunks may be null (the driver) and may be set later (set_source).
struct Pool { uint64_t per_cell = 0, full = 0; };
bool init(const std::vector<Pool>& pools, int64_t init_cells, std::string& err);
void release();
void set_source(ChunkPool* src) { src_ = src; }
uint8_t* pool(int i) const;
int64_t cells_mapped() const; // cells every pool can hold now (the smallest)
// every pool holds at least `cells` cells (maps chunks); false: no chunk left anywhere
bool ensure(int64_t cells, std::string& err);
// back to the initial cells: the chunks above them go back to the source
void shrink_to_initial();
uint64_t mapped_bytes() const; // physical bytes under the pools
uint64_t full_bytes_total() const;
std::string report() const;
private:
struct Impl;
Impl* p_ = nullptr;
ChunkPool* src_ = nullptr;
};
} // namespace strata::q4lite
+304
View File
@@ -0,0 +1,304 @@
// src/q4lite/q4_loop.cu - see q4_loop.hpp. Self-contained: a safetensors reader (BF16 -> fp32), the weights on the device and five small kernels.
#include "q4_loop.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
namespace strata::q4lite {
namespace {
constexpr int kThinkEnd = 248069; // </think>
constexpr float kLoraScale = 0.25f;
constexpr int kMaxRank = 128;
constexpr int kTG = 256;
#define LP_CK(x, err) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { (err) = std::string(#x) + ": " + cudaGetErrorString(e_); return false; } } while (0)
// ---- a minimal safetensors header reader: {"name": {"dtype": "BF16", "shape": [..], "data_offsets": [a, b]}, "__metadata__": {...}}
struct TInfo { std::string dtype; std::vector<int64_t> shape; uint64_t a = 0, b = 0; };
struct Js {
const std::string& s;
size_t i = 0;
bool ok = true;
explicit Js(const std::string& t) : s(t) {}
void ws() { while (i < s.size() && (s[i] == ' ' || s[i] == '\n' || s[i] == '\r' || s[i] == '\t')) ++i; }
bool lit(char c) { ws(); if (i < s.size() && s[i] == c) { ++i; return true; } return false; }
std::string str() {
std::string r;
ws();
if (i >= s.size() || s[i] != '"') { ok = false; return r; }
++i;
while (i < s.size() && s[i] != '"') { if (s[i] == '\\' && i + 1 < s.size()) ++i; r += s[i++]; }
++i;
return r;
}
double num() { ws(); char* e = nullptr; const double v = std::strtod(s.c_str() + i, &e); if (e == s.c_str() + i) ok = false; i = e - s.c_str(); return v; }
void skip() { // any value
ws();
if (i >= s.size()) { ok = false; return; }
if (s[i] == '"') { str(); return; }
if (s[i] == '{' || s[i] == '[') {
const char open = s[i], close = open == '{' ? '}' : ']';
++i;
if (lit(close)) return;
do { if (open == '{') { str(); lit(':'); } skip(); } while (ok && lit(','));
lit(close);
return;
}
while (i < s.size() && s[i] != ',' && s[i] != '}' && s[i] != ']') ++i;
}
};
bool read_header(std::ifstream& f, std::map<std::string, TInfo>& out, std::map<std::string, std::string>& meta, uint64_t& data_start, std::string& err) {
uint64_t n = 0;
f.read(reinterpret_cast<char*>(&n), 8);
if (!f || n == 0 || n > (64u << 20)) { err = "loop file: bad safetensors header length"; return false; }
std::string h(n, '\0');
f.read(&h[0], static_cast<std::streamsize>(n));
if (!f) { err = "loop file: truncated header"; return false; }
data_start = 8 + n;
Js j(h);
if (!j.lit('{')) { err = "loop file: header is not a JSON object"; return false; }
if (j.lit('}')) return true;
do {
const std::string name = j.str();
j.lit(':');
if (name == "__metadata__") {
j.lit('{');
if (!j.lit('}')) do { const std::string k = j.str(); j.lit(':'); meta[k] = j.str(); } while (j.ok && j.lit(','));
j.lit('}');
continue;
}
TInfo t;
j.lit('{');
do {
const std::string k = j.str();
j.lit(':');
if (k == "dtype") t.dtype = j.str();
else if (k == "shape") { j.lit('['); if (!j.lit(']')) do { t.shape.push_back(static_cast<int64_t>(j.num())); } while (j.ok && j.lit(',')); j.lit(']'); }
else if (k == "data_offsets") { j.lit('['); t.a = static_cast<uint64_t>(j.num()); j.lit(','); t.b = static_cast<uint64_t>(j.num()); j.lit(']'); }
else j.skip();
} while (j.ok && j.lit(','));
j.lit('}');
out[name] = t;
} while (j.ok && j.lit(','));
if (!j.ok) { err = "loop file: header parse error"; return false; }
return true;
}
// ---- kernels
__device__ __forceinline__ float block_sum(float v, float* sm) {
for (int o = 16; o > 0; o >>= 1) v += __shfl_down_sync(0xffffffffu, v, o);
const int lane = threadIdx.x & 31, w = threadIdx.x >> 5;
if (lane == 0) sm[w] = v;
__syncthreads();
float t = lane < (blockDim.x >> 5) ? sm[lane] : 0.0f;
for (int o = 16; o > 0; o >>= 1) t += __shfl_down_sync(0xffffffffu, t, o);
t = __shfl_sync(0xffffffffu, t, 0);
__syncthreads();
return t;
}
// dn[t, k] = (m[t, k] - x[t, k]) * rsqrt(mean_k (m - x)^2 + eps) * w1[k] grid (N)
__global__ void k_dual_norm(const float* __restrict__ x, const float* __restrict__ m, const float* __restrict__ w1, float* __restrict__ dn, int hd, float eps) {
__shared__ float sm[8];
const size_t base = static_cast<size_t>(blockIdx.x) * hd;
float s = 0.0f;
for (int k = threadIdx.x; k < hd; k += blockDim.x) { const float d = m[base + k] - x[base + k]; s += d * d; }
s = block_sum(s, sm);
const float inv = rsqrtf(s / static_cast<float>(hd) + eps);
for (int k = threadIdx.x; k < hd; k += blockDim.x) dn[base + k] = (m[base + k] - x[base + k]) * inv * w1[k];
}
// tmp[t, r] = sum_k x[t, k] * A[r, k] grid (rank, N)
__global__ void k_proj_a(const float* __restrict__ x, const float* __restrict__ a, float* __restrict__ tmp, int in_dim, int rank) {
__shared__ float sm[8];
const int r = blockIdx.x, t = blockIdx.y;
const float* xr = x + static_cast<size_t>(t) * in_dim;
const float* ar = a + static_cast<size_t>(r) * in_dim;
float s = 0.0f;
for (int k = threadIdx.x; k < in_dim; k += blockDim.x) s += xr[k] * ar[k];
s = block_sum(s, sm);
if (threadIdx.x == 0) tmp[static_cast<size_t>(t) * rank + r] = s;
}
__global__ void k_silu(float* __restrict__ v, int n) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) { const float a = v[i]; v[i] = a / (1.0f + expf(-a)); }
}
// tmp[t, :] *= cd where flag[t] > 0.5 (the coda LoRA after </think>; the LoRA is linear in tmp)
__global__ void k_scale_flag(float* __restrict__ tmp, int rank, int rows, const float* __restrict__ flag, float cd) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < rows * rank && flag[i / rank] > 0.5f) tmp[i] *= cd;
}
// y[t, o] += sum_r tmp[t, r] * B[o, r] grid (ceil(out / 256), N)
__global__ void k_proj_b_add(const float* __restrict__ tmp, const float* __restrict__ b, float* __restrict__ y, int out_dim, int rank) {
const int o = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y;
if (o >= out_dim) return;
const float* tr = tmp + static_cast<size_t>(t) * rank;
const float* br = b + static_cast<size_t>(o) * rank;
float acc = 0.0f;
for (int r = 0; r < rank; ++r) acc += tr[r] * br[r];
y[static_cast<size_t>(t) * out_dim + o] += acc;
}
// h[t, j] += g[j] * sum_r tmp[t, r] * B[j, r] grid (ceil(hd / 256), N)
__global__ void k_mix_add(const float* __restrict__ tmp, const float* __restrict__ b, const float* __restrict__ g, float* __restrict__ h, int hd, int rank) {
const int j = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y;
if (j >= hd) return;
const float* tr = tmp + static_cast<size_t>(t) * rank;
const float* br = b + static_cast<size_t>(j) * rank;
float acc = 0.0f;
for (int r = 0; r < rank; ++r) acc += tr[r] * br[r];
h[static_cast<size_t>(t) * hd + j] += g[j] * acc;
}
} // namespace
float* LoopAdapter::up(const std::vector<float>& v, std::string& err) {
float* p = nullptr;
if (cudaMalloc(reinterpret_cast<void**>(&p), v.size() * sizeof(float)) != cudaSuccess) { err = "loop: cudaMalloc failed"; return nullptr; }
allocs_.push_back(p);
if (cudaMemcpy(p, v.data(), v.size() * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) { err = "loop: cudaMemcpy failed"; return nullptr; }
return p;
}
void LoopAdapter::destroy() {
for (void* p : allocs_) cudaFree(p);
allocs_.clear();
mix_.clear();
core_.clear();
coda_.clear();
cd_.clear();
d_ns_ = d_tmp_ = d_flag_ = nullptr;
passes_ = 0;
}
bool LoopAdapter::load(const std::string& path, const std::string& coda, int passes, int D, int hc, int n_layers, int max_tokens, int device, std::string& err) {
destroy();
if (passes < 2 || passes > 3) { err = "loop: --loop must be 2 or 3 (the file holds core_lora.pass_1 and pass_2)"; return false; }
if (coda != "universal" && coda != "compact") { err = "loop: --loop-coda must be universal or compact"; return false; }
std::ifstream f(path, std::ios::binary);
if (!f) { err = "loop: cannot open " + path; return false; }
std::map<std::string, TInfo> T;
std::map<std::string, std::string> meta;
uint64_t data0 = 0;
if (!read_header(f, T, meta, data0, err)) return false;
if (meta.count("format") == 0 || meta["format"] != "strata_dual_coda_loop_v1") { err = "loop: " + path + " is not a strata_dual_coda_loop_v1 file"; return false; }
int c0 = 0, c1 = 0, d0 = 0, d1 = 0;
if (std::sscanf(meta["core_layers"].c_str(), "%d..%d", &c0, &c1) != 2 || std::sscanf(meta["coda_layers"].c_str(), "%d..%d", &d0, &d1) != 2 || d0 != c1 + 1) {
err = "loop: the file's core_layers / coda_layers are missing or not adjacent";
return false;
}
core_start_ = c0; core_end_ = c1 + 1; coda_n_ = d1 - d0 + 1;
if (core_end_ + coda_n_ != n_layers) { err = "loop: the file's layer ranges do not fit this model's " + std::to_string(n_layers) + " layers"; return false; }
passes_ = passes; D_ = D; hc_ = hc; n_layers_ = n_layers; max_tokens_ = max_tokens; device_ = device;
LP_CK(cudaSetDevice(device), err);
const int hd = hc * D;
auto get = [&](const std::string& name, std::vector<float>& out, std::vector<int64_t>* shape = nullptr) -> bool {
auto it = T.find(name);
if (it == T.end()) { err = "loop: missing tensor " + name; return false; }
const TInfo& t = it->second;
uint64_t n = 1;
for (int64_t d : t.shape) n *= static_cast<uint64_t>(d);
if (t.dtype != "BF16" || t.b - t.a != n * 2) { err = "loop: tensor " + name + " is not BF16 of the expected size"; return false; }
std::vector<uint16_t> raw(n);
f.seekg(static_cast<std::streamoff>(data0 + t.a));
f.read(reinterpret_cast<char*>(raw.data()), static_cast<std::streamsize>(n * 2));
if (!f) { err = "loop: truncated data for " + name; return false; }
out.resize(n);
for (uint64_t i = 0; i < n; ++i) { const uint32_t w = static_cast<uint32_t>(raw[i]) << 16; std::memcpy(&out[i], &w, 4); }
if (shape) *shape = t.shape;
return true;
};
const int core_len = core_end_ - core_start_;
mix_.resize(core_len);
for (int i = 0; i < core_len; ++i) {
const std::string p = "mixers." + std::to_string(core_start_ + i) + ".";
std::vector<float> w1, a, b, g;
std::vector<int64_t> sa;
if (!get(p + "norm.weight", w1) || !get(p + "mix_a.weight", a, &sa) || !get(p + "mix_b.weight", b) || !get(p + "gate.weight", g)) return false;
if (static_cast<int>(w1.size()) != hd || sa.size() != 2 || sa[1] != hd || static_cast<int>(g.size()) != hd) { err = "loop: mixer shape mismatch at layer " + std::to_string(core_start_ + i); return false; }
rank_mix_ = static_cast<int>(sa[0]);
if (rank_mix_ > kMaxRank) { err = "loop: mixer rank too large"; return false; }
for (float& v : w1) v += 1.0f; // rms_norm_f32(delta, 1 + norm)
for (float& v : g) v = 1.0f / (1.0f + std::exp(-v)); // g = sigmoid(gate)
mix_[i].norm1 = up(w1, err); mix_[i].a = up(a, err); mix_[i].b = up(b, err); mix_[i].gate = up(g, err);
if (!mix_[i].norm1 || !mix_[i].a || !mix_[i].b || !mix_[i].gate) return false;
}
auto pair = [&](const std::string& base, Lora& dst) -> bool {
std::vector<float> a, b;
std::vector<int64_t> sa, sb;
if (!get(base + "_a.weight", a, &sa) || !get(base + "_b.weight", b, &sb)) return false;
if (sa.size() != 2 || sb.size() != 2 || sa[0] != sb[1] || sa[0] > kMaxRank || sa[1] != D || sb[0] != D) { err = "loop: bad LoRA shapes for " + base; return false; }
for (float& v : b) v *= kLoraScale;
dst.a = up(a, err); dst.b = up(b, err);
dst.in = static_cast<int>(sa[1]); dst.out = static_cast<int>(sb[0]); dst.rank = static_cast<int>(sa[0]);
return dst.a && dst.b;
};
const char* kinds[2] = {"attn", "mlp"};
core_.resize(static_cast<size_t>(passes - 1) * core_len * 2);
for (int p = 1; p < passes; ++p)
for (int i = 0; i < core_len; ++i)
for (int k = 0; k < 2; ++k)
if (!pair("core_lora.pass_" + std::to_string(p) + "." + std::to_string(core_start_ + i) + "." + kinds[k], core_[(static_cast<size_t>(p - 1) * core_len + i) * 2 + k])) return false;
coda_.resize(static_cast<size_t>(coda_n_) * 2);
for (int j = 0; j < coda_n_; ++j)
for (int k = 0; k < 2; ++k)
if (!pair("coda_lora." + coda + "." + std::to_string(core_end_ + j) + "." + kinds[k], coda_[static_cast<size_t>(j) * 2 + k])) return false;
if (!get("meta.cd_omega", cd_)) return false;
if (static_cast<int>(cd_.size()) < coda_n_) { err = "loop: meta.cd_omega is shorter than the coda"; return false; }
for (float& v : cd_) v = std::min(1.0f, std::max(0.0f, v));
LP_CK(cudaMalloc(reinterpret_cast<void**>(&d_ns_), static_cast<size_t>(max_tokens) * hd * sizeof(float)), err);
allocs_.push_back(d_ns_);
LP_CK(cudaMalloc(reinterpret_cast<void**>(&d_tmp_), static_cast<size_t>(max_tokens) * kMaxRank * sizeof(float)), err);
allocs_.push_back(d_tmp_);
LP_CK(cudaMalloc(reinterpret_cast<void**>(&d_flag_), static_cast<size_t>(max_tokens) * sizeof(float)), err);
allocs_.push_back(d_flag_);
LP_CK(cudaMemset(d_flag_, 0, static_cast<size_t>(max_tokens) * sizeof(float)), err);
h_flag_.assign(max_tokens, 0.0f);
char b[200];
std::snprintf(b, sizeof b, "loop T=%d core=[%d,%d) coda=%d (%s) mixer rank %d, %zu LoRA pairs", passes, core_start_, core_end_, coda_n_, coda.c_str(), rank_mix_, core_.size() / 2 + coda_.size() / 2);
summary_ = b;
return true;
}
void LoopAdapter::set_flags(const int* ids, int N, int pos0, cudaStream_t s) {
if (pos0 == 0 || pos0 <= close_pos_) close_pos_ = INT64_MAX; // a new sequence, or a rewind to / before the first </think>
for (int t = 0; t < N; ++t) {
if (close_pos_ == INT64_MAX && ids[t] == kThinkEnd) close_pos_ = static_cast<int64_t>(pos0) + t;
h_flag_[t] = static_cast<int64_t>(pos0) + t >= close_pos_ ? 1.0f : 0.0f;
}
cudaMemcpyAsync(d_flag_, h_flag_.data(), static_cast<size_t>(N) * sizeof(float), cudaMemcpyHostToDevice, s);
cudaStreamSynchronize(s); // h_flag_ is reused by the next call
}
void LoopAdapter::mixer(int il, float* h, const float* mprev, int N, cudaStream_t s) {
const Mix& m = mix_[il - core_start_];
const int hd = hc_ * D_;
k_dual_norm<<<N, kTG, 0, s>>>(h, mprev, m.norm1, d_ns_, hd, 1e-6f);
k_proj_a<<<dim3(rank_mix_, N), kTG, 0, s>>>(d_ns_, m.a, d_tmp_, hd, rank_mix_);
k_silu<<<(N * rank_mix_ + 255) / 256, 256, 0, s>>>(d_tmp_, N * rank_mix_);
k_mix_add<<<dim3((hd + 255) / 256, N), 256, 0, s>>>(d_tmp_, m.b, m.gate, h, hd, rank_mix_);
}
void LoopAdapter::lora_add(int kind, int pass, int il, const float* x, float* y, int N, cudaStream_t s) {
const Lora* l = nullptr;
float cd = 1.0f;
bool coda = false;
if (pass >= 1 && is_core(il)) l = &core_[(static_cast<size_t>(pass - 1) * (core_end_ - core_start_) + (il - core_start_)) * 2 + kind];
else if (pass == 0 && il >= core_end_ && il < core_end_ + coda_n_) { l = &coda_[static_cast<size_t>(il - core_end_) * 2 + kind]; coda = true; cd = cd_[il - core_end_]; }
if (!l || !l->a) return;
k_proj_a<<<dim3(l->rank, N), kTG, 0, s>>>(x, l->a, d_tmp_, l->in, l->rank);
if (coda && cd != 1.0f) k_scale_flag<<<(N * l->rank + 255) / 256, 256, 0, s>>>(d_tmp_, l->rank, N, d_flag_, cd);
k_proj_b_add<<<dim3((l->out + 255) / 256, N), 256, 0, s>>>(d_tmp_, l->b, y, l->out, l->rank);
}
} // namespace strata::q4lite
+59
View File
@@ -0,0 +1,59 @@
// src/q4lite/q4_loop.hpp - the owner's Loop adapter (Qwen4-35B-A3B-Loop.safetensors, format strata_dual_coda_loop_v1) for strata-q4-lite.
//
// Math (the owner's trainer 03_train_dual_coda_loop.py, forward_looped):
// pass 0 runs the stock layers 0..core_end-1; the anchor is the residual entering the core (layer 12), m_prev the residual after the core's last layer.
// Extra pass p = 1 .. T-1: h = anchor; for every core layer il (12..27):
// h = h + sigmoid(gate_il) * up_il( silu( down_il( rms(m_prev - h) * (1 + norm_il) ) ) ) (ONE rms over the whole hc*D vector, eps 1e-6)
// the layer il runs with core_lora.pass_p.il on both sub-layers; m_prev = h after the pass.
// LoRA: y += 0.25 * B (A x), x = the hyper-connection-mixed input of the sub-layer, y = the sub-layer's output before the inject; "attn" on the
// token mixer, "mlp" on the MoE block. The coda layers (28..39) carry coda_lora.<universal|compact>.il (T >= 2 only), their delta times
// cd_omega[il - 28] on the tokens from the first </think> (248069) on.
// Off (loop_passes < 2) the engine never constructs this class.
#pragma once
#include <cuda_runtime.h>
#include <cstdint>
#include <string>
#include <vector>
namespace strata::q4lite {
class LoopAdapter {
public:
~LoopAdapter() { destroy(); }
// coda: "universal" | "compact"; max_tokens: the engine's widest forward()
bool load(const std::string& path, const std::string& coda, int passes, int D, int hc, int n_layers, int max_tokens, int device, std::string& err);
void destroy();
int passes() const { return passes_; }
int core_start() const { return core_start_; }
int core_end() const { return core_end_; }
bool is_core(int il) const { return il >= core_start_ && il < core_end_; }
const std::string& summary() const { return summary_; }
// the after-</think> flags of the N tokens at positions pos0 ..: call once per forward() (before the layers)
void set_flags(const int* ids, int N, int pos0, cudaStream_t s);
// h [N, hc*D] += sigmoid(gate) * up(silu(down(rms(m_prev - h) * (1 + norm)))) of core layer il
void mixer(int il, float* h, const float* mprev, int N, cudaStream_t s);
// y [N, D] += 0.25 * B(A x) of the (pass, il, kind) LoRA when there is one; kind 0 = attn (token mixer), 1 = mlp (MoE)
void lora_add(int kind, int pass, int il, const float* x, float* y, int N, cudaStream_t s);
private:
struct Lora { float *a = nullptr, *b = nullptr; int in = 0, out = 0, rank = 0; };
struct Mix { float *norm1 = nullptr, *a = nullptr, *b = nullptr, *gate = nullptr; };
std::vector<void*> allocs_;
std::vector<Mix> mix_; // [core layer]
std::vector<Lora> core_; // [(pass - 1) * core_len + core layer][2]
std::vector<Lora> coda_; // [coda layer][2]
std::vector<float> cd_; // cd_omega per coda layer
float *d_ns_ = nullptr, *d_tmp_ = nullptr, *d_flag_ = nullptr;
std::vector<float> h_flag_;
int passes_ = 0, D_ = 0, hc_ = 0, n_layers_ = 0, max_tokens_ = 0, device_ = 0, rank_mix_ = 0;
int core_start_ = 12, core_end_ = 28, coda_n_ = 12;
int64_t close_pos_ = INT64_MAX; // position of the first </think> token of the sequence (INT64_MAX: none yet)
std::string summary_;
float* up(const std::vector<float>& v, std::string& err);
};
} // namespace strata::q4lite
+53 -1
View File
@@ -18,6 +18,9 @@
#include "q4_serve.hpp"
#include "q4_tier.hpp"
#include "q4_mtp.hpp"
#include "q4_elastic.hpp"
#include "strata/core/vmm.hpp"
#include "q4_kv_elastic.hpp"
#include "strata/kernels/ngram.hpp"
#ifdef _WIN32
@@ -28,6 +31,7 @@
#include <algorithm>
#include <chrono>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
@@ -47,6 +51,8 @@ using namespace strata::q4lite;
namespace {
struct Opts {
std::string model, ple, ids_csv, ids_file, jobs, out, capture_dir, mtp, prompts;
std::string loop_file, loop_coda = "auto"; // the owner's Loop (--loop N --loop-file PATH [--loop-coda auto|universal|compact]); auto: compact on the Compact tier, universal otherwise
int loop_passes = 0;
#if defined(STRATA_USE_HIP)
int gen = 0, max_tokens = 1024, max_ctx = 8192, device = 0, top = 256, spec = 2, kv_format = 0; // HIP: 1024-token prompt chunks (R9700 Compact: 4K prefill 4.7 s at 256, 3.6 s at 1024)
#else
@@ -63,6 +69,10 @@ struct Opts {
uint64_t vram_reserve_mb = 640; // --vram-reserve MB
int embed_host = -1; // --embed-host on|off|auto
std::string expert_order = "strp"; // --expert-order strp|id
// Q4-ELASTIC (q4_elastic.hpp): experts in a virtual range (the card holds a prefix, the rest is pinned RAM) and KV pools that grow from the coldest experts' chunks
int elastic = -1; // --elastic on|kv|off|auto (default auto: on when the driver has virtual memory; kv: only the KV pools are elastic, chunks from the driver)
int vram_cap_mib = 0; // --vram-cap-mib N: tests: an emulated card of N MiB (a ballast holds the rest)
int kv_init_cells = 8192; // --kv-init-cells N: KV cells mapped at start with --elastic
};
// flags the app / Control pass that this build does not use yet: value = how many arguments follow (Q4-APP's table ENGINE_FILE_FLAGS and the generic server flags)
@@ -107,6 +117,9 @@ bool parse_args(int argc, char** argv, Opts& o) {
else if (a == "--vram-reserve") o.vram_reserve_mb = static_cast<uint64_t>(std::atoll(next()));
else if (a == "--embed-host") { const std::string v = next(); o.embed_host = v == "on" ? 1 : v == "off" ? 0 : -1; }
else if (a == "--expert-order") o.expert_order = next();
else if (a == "--elastic") { const std::string v = next(); o.elastic = (v == "on" || v == "1") ? 1 : (v == "kv" ? 2 : (v == "off" || v == "0") ? 0 : -1); }
else if (a == "--vram-cap-mib") o.vram_cap_mib = std::atoi(next());
else if (a == "--kv-init-cells") o.kv_init_cells = std::atoi(next());
else if (a == "--ids") o.ids_csv = next();
else if (a == "--ids-file") o.ids_file = next();
else if (a == "--gen") o.gen = std::atoi(next());
@@ -128,6 +141,9 @@ bool parse_args(int argc, char** argv, Opts& o) {
else if (a == "--info") o.info = true;
else if (a == "--profile") o.profile = true;
else if (a == "--version") o.version = true;
else if (a == "--loop" || a == "--loop-passes") o.loop_passes = std::atoi(next()); // (--loop-passes / --loop-adapter: the names the other engines and the app use)
else if (a == "--loop-file" || a == "--loop-adapter") o.loop_file = next();
else if (a == "--loop-coda") o.loop_coda = next();
else if (const int ar = ignored_flag_arity(a); ar >= 0) {
std::string w = a;
if (ar > 0) { w += " "; w += next(); }
@@ -209,6 +225,14 @@ int main(int argc, char** argv) {
cudaSetDevice(o.device);
bool integrated = false;
free0 = q4_free_device_bytes(o.device, &total0, &integrated);
const int el_mode = o.elastic >= 0 ? o.elastic : ((!integrated && strata::core::vmm_available()) ? 1 : 0); // auto: the elastic tier wherever the driver can map virtual memory
void* ballast = nullptr; // --vram-cap-mib: the card looks like N MiB (everything below sees the real free memory)
if (o.vram_cap_mib > 0 && free0 > (static_cast<uint64_t>(o.vram_cap_mib) << 20)) {
const uint64_t hold = free0 - (static_cast<uint64_t>(o.vram_cap_mib) << 20);
if (cudaMalloc(&ballast, static_cast<size_t>(hold)) != cudaSuccess) { std::fprintf(stderr, "vram cap: cannot hold %llu MiB back\n", static_cast<unsigned long long>(hold >> 20)); return 1; }
total0 = static_cast<uint64_t>(o.vram_cap_mib) << 20;
std::printf("vram cap: the card is held to %d MiB (ballast %llu MiB)\n", o.vram_cap_mib, static_cast<unsigned long long>(hold >> 20));
}
lo.embed_on_host = o.embed_host == 1 || (o.embed_host < 0 && total0 < (20ull << 30)); // 12 GB cards: the 520 MB embedding table stays in pinned host memory (one row copy per token)
if (!model.load(f, lo, err)) { std::fprintf(stderr, "load: %s\n", err.c_str()); return 1; }
@@ -226,9 +250,36 @@ int main(int argc, char** argv) {
eo.capture = o.capture;
if (o.serve) eo.logits_rows = 16; // the serve loop asks for the last row only
eo.profile = o.profile || std::getenv("STRATA_Q4_PROFILE") != nullptr;
KvElastic kv_el;
if (el_mode) { eo.kv_elastic = &kv_el; eo.kv_init_cells = o.kv_init_cells; }
if (!o.loop_file.empty() && o.loop_passes == 0) o.loop_passes = 2; // --loop-adapter FILE alone: the default 2 steps
if (o.loop_passes >= 2) { // the owner's Loop; CUDA graphs and MTP are off while it runs
if (o.loop_file.empty()) { std::fprintf(stderr, "--loop %d needs --loop-file Qwen4-35B-A3B-Loop.safetensors\n", o.loop_passes); return 2; }
std::string tier = man.tier;
for (char& ch : tier) ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
if (!o.mtp.empty()) { std::fprintf(stderr, "q4lite: --loop: the MTP drafter is off while the Loop runs\n"); o.mtp.clear(); }
eo.loop_passes = o.loop_passes;
eo.loop_file = o.loop_file;
eo.loop_coda = o.loop_coda == "auto" ? (tier.find("compact") != std::string::npos ? "compact" : "universal") : o.loop_coda;
}
Q4Engine eng;
if (!eng.init(model, eo, o.ple.empty() ? nullptr : &ple, err)) { std::fprintf(stderr, "engine: %s\n", err.c_str()); return 1; }
{
ElasticExperts el_experts;
if (el_mode == 1) {
const uint64_t freeb = q4_free_device_bytes(o.device);
ElasticOptions eopt;
eopt.floor_bytes = o.vram_reserve_mb * (1ull << 20);
if (o.vram_budget_gb >= 0.0) eopt.vram_cap_bytes = static_cast<uint64_t>(o.vram_budget_gb * 1073741824.0);
std::string how = "expert id order";
if (o.expert_order != "id" && !expert_hot_order(f, eopt.order, how)) { std::fprintf(stderr, "expert order: %s\n", how.c_str()); return 1; }
if (!el_experts.init(f, model, eopt, err)) { std::fprintf(stderr, "elastic experts: %s\n", err.c_str()); return 1; }
kv_el.set_source(&el_experts);
std::printf("experts: %d in VRAM (%.2f GiB), %d in pinned host memory (%.2f GiB), ranked by %s; card free before %.2f GiB (elastic)\n", model.experts_vram, model.expert_vram_bytes / 1073741824.0,
model.experts_host, model.expert_host_bytes / 1073741824.0, how.c_str(), freeb / 1073741824.0);
std::printf("%s\n%s\n", kv_el.report().c_str(), el_experts.report().c_str());
if (!std::getenv("STRATA_Q4_NO_PACK") && model.experts_host == 0 && !model.build_packed_s8(eopt.floor_bytes, err)) { std::fprintf(stderr, "pack: %s\n", err.c_str()); return 1; }
std::printf("%s, packed S8 copies %.2f GiB%s\n", model.report().c_str(), model.packed_bytes / 1073741824.0, model.h_embed ? ", embed_tokens on the host" : "");
} else {
const uint64_t freeb = q4_free_device_bytes(o.device);
const uint64_t reserve = o.vram_reserve_mb * (1ull << 20); // CUDA graphs, driver workspace, fragmentation (and the desktop on a display card)
ExpertPlan plan;
@@ -248,6 +299,7 @@ int main(int argc, char** argv) {
if (o.serve) {
ServeCfg sc;
sc.max_ctx = o.max_ctx;
sc.loop_passes = eo.loop_passes;
sc.chunk = o.max_tokens;
sc.layers = model.cfg.n_layers;
sc.vocab = V;
+17
View File
@@ -22,6 +22,7 @@ public:
// allocate state for `opt.max_ctx` positions and scratch for `opt.max_tokens` tokens; may use the model's weights
virtual bool init(const GpuModel& m, const EngineOptions& opt, std::string& err) = 0;
virtual void destroy() = 0;
virtual void set_pass(int p) { (void)p; } // the owner's Loop: the core pass the next gdn() / attn() calls belong to (0 = the stock state)
virtual void reset() = 0; // position 0: zero recurrent state / histories / KV
virtual bool gdn(int il, const float* x, const float* xr, int N, int pos0, float* y, cudaStream_t s, std::string& err) = 0;
virtual bool attn(int il, const float* x, const float* xr, int N, int pos0, float* y, cudaStream_t s, std::string& err) = 0;
@@ -29,6 +30,8 @@ public:
virtual void checkpoint() {} // snapshot of the state before a verify batch
virtual bool rollback(int pos0, int n_keep, std::string&) { (void)pos0; (void)n_keep; return false; }
virtual size_t state_bytes() const { return 0; }
// Q4-ELASTIC: the KV pools hold at least cells positions (elastic pools map more chunks, taken from the expert tier); call between forward() calls, nothing in flight
virtual bool ensure_ctx(int cells, std::string& err) { (void)cells; (void)err; return true; }
// after a run of CUDA-graph decode steps (the GDN layers were not called on the host): bring the GDN layers' host position counters to `pos`
virtual void sync_gdn_pos(int pos) { (void)pos; }
// CUDA-graph decode (N = 1): decode_graph_ok() says the attention layers can be captured. Before EVERY graph launch (also the first) call set_decode_pos(pos, s) on the
@@ -38,6 +41,20 @@ public:
virtual bool decode_graph_ok() const { return false; }
virtual bool set_decode_pos(int pos, cudaStream_t s, std::string& err) { (void)pos; (void)s; err = "decode graphs are not supported by these mixers"; return false; }
virtual bool attn_decode(int il, const float* x, const float* xr, float* y, cudaStream_t s, std::string& err) { (void)il; (void)x; (void)xr; (void)y; (void)s; err = "attn_decode: not supported"; return false; }
// CUDA-graph speculative windows of n = 1..16 tokens (verify without state change + commit with a DEVICE keep count). Per window:
// set_window_pos(pos, n, s) before EVERY launch of a window graph (one kernel: positions / step records of the n tokens in device memory)
// gdn_window / attn_window (il, x, xr, n, y, s, err) inside the capture of the window: like gdn()/attn() in verify mode at the device position (the GDN state, the conv history
// and the indexer's raw tail are NOT advanced; the inputs of a commit are kept), launch-only with constant grids (n is a constant of the capture)
// commit_window(n, keep_dev, s, err) after acceptance: all GDN layers (conv history + recurrent state of the first *keep_dev tokens) and all attention layers (indexer tail restored,
// kept tokens re-appended); keep_dev = DEVICE int32 in [0, n]; launch-only, capturable as one graph per n
// window_committed(pos0, n_keep) host bookkeeping after the engine has read the accepted count (position trackers)
// Each n needs one eager warm-up (Mixers::init does n = 2, 3, 4). window_graph_ok(n) is false when the warm-up failed.
virtual bool window_graph_ok(int n) const { (void)n; return false; }
virtual bool set_window_pos(int pos, int n, cudaStream_t s, std::string& err) { (void)pos; (void)n; (void)s; err = "windows: not supported"; return false; }
virtual bool gdn_window(int il, const float* x, const float* xr, int n, float* y, cudaStream_t s, std::string& err) { (void)il; (void)x; (void)xr; (void)n; (void)y; (void)s; err = "windows: not supported"; return false; }
virtual bool attn_window(int il, const float* x, const float* xr, int n, float* y, cudaStream_t s, std::string& err) { (void)il; (void)x; (void)xr; (void)n; (void)y; (void)s; err = "windows: not supported"; return false; }
virtual bool commit_window(int n, const int32_t* keep_dev, cudaStream_t s, std::string& err) { (void)n; (void)keep_dev; (void)s; err = "windows: not supported"; return false; }
virtual void window_committed(int pos0, int n_keep) { (void)pos0; (void)n_keep; }
};
// Defined by the implementation (q4_mixers_fn.cu): a new instance of the production mixers
+142 -10
View File
@@ -8,6 +8,7 @@
#include "q4_gdn.hpp"
#include "q4_mixers.hpp"
#include "q4_router.hpp"
#include "q4_kv_elastic.hpp"
#include "ling32_kernels.hpp"
@@ -40,9 +41,13 @@ public:
if (!attn_global_init(as_, max_ctx_, err)) return false;
global_ = true;
const int nl = c.n_layers;
gdn_.assign(nl, {});
attn_.assign(nl, {});
pos_.assign(nl, 0);
// the owner's Loop (opt.loop_passes >= 2): the core layers get T - 1 extra state slots, slot = il + pass * n_layers (set_pass picks the pass)
T_ = std::max(1, opt.loop_passes);
nl_ = nl;
pass_ = 0;
gdn_.assign(nl * T_, {});
attn_.assign(nl * T_, {});
pos_.assign(nl * T_, 0);
// arena
size_t total = 0;
auto al = [](size_t x) { return (x + 255) & ~size_t(255); };
@@ -51,10 +56,14 @@ public:
al(M * as_.ix_width() * 4) + al(M * c.q_dim() * 4) + al(M * c.val_dim() * 4);
const size_t gsc = al(gdn_scratch_bytes(gs_, maxn_)), asc = al(attn_scratch_bytes(as_, maxn_, max_ctx_));
size_t per_gdn = al(gdn_state_bytes(gs_)) + al(gdn_hist_bytes(gs_)) + al((size_t) gs_.hv * 4) + al(gdn_verify_bytes(gs_));
size_t per_attn = al(attn_state_bytes(as_, max_ctx_)) + al((size_t) (2 * as_.hd + 2 * as_.ixd) * 4) + al(attn_verify_bytes(as_));
ke_ = opt.kv_elastic;
size_t per_attn = al(ke_ ? attn_state_bytes_ext(as_, max_ctx_) : attn_state_bytes(as_, max_ctx_)) + al((size_t) (2 * as_.hd + 2 * as_.ixd) * 4) + al(attn_verify_bytes(as_));
int n_g = 0, n_a = 0;
for (int il = 0; il < nl; ++il) (c.is_full[il] ? n_a : n_g)++;
total = proj + gsc + asc + al(attn_decode_dev_bytes()) + per_gdn * n_g + per_attn * n_a;
int x_g = 0, x_a = 0; // the Loop's extra slots
for (int p = 1; p < T_; ++p)
for (int il = opt.loop_core_start; il < opt.loop_core_end; ++il) (c.is_full[il] ? x_a : x_g)++;
total = proj + gsc + asc + al(attn_decode_dev_bytes()) + al(attn_win_dev_bytes(as_)) + per_gdn * (n_g + x_g) + per_attn * (n_a + x_a);
MX_CK(cudaMalloc(&arena_, total), err);
arena_bytes_ = total;
uint8_t* p = (uint8_t*) arena_;
@@ -73,6 +82,16 @@ public:
gdn_assign_scratch(take(gsc));
if (!attn_scratch_assign(as_, maxn_, max_ctx_, take(asc), asc_)) { err = "attn scratch"; return false; }
if (!attn_decode_dev_assign(take(attn_decode_dev_bytes()), dec_)) { err = "attn decode buffers"; return false; }
if (!attn_win_dev_assign(as_, take(attn_win_dev_bytes(as_)), win_)) { err = "attn window buffers"; return false; }
int n_attn_seen = 0, np = 0;
if (ke_) { // Q4-ELASTIC: 2 virtual pools (K, V) per attention layer, the first kv_init_cells mapped now
KvPoolSpec sp[4];
np = attn_kv_pool_specs(as_, max_ctx_, sp);
std::vector<KvElastic::Pool> pools;
for (int a = 0; a < n_a + x_a; ++a) // the Loop's extra attention slots are elastic too
for (int j = 0; j < np; ++j) pools.push_back({sp[j].per_cell, sp[j].full});
if (!ke_->init(pools, std::min(opt.kv_init_cells, max_ctx_), err)) return false;
}
for (int il = 0; il < nl; ++il) {
if (!c.is_full[il]) {
G& g = gdn_[il];
@@ -85,7 +104,12 @@ public:
if (!gdn_verify_assign(gs_, take(gdn_verify_bytes(gs_)), g.vb)) { err = "gdn verify"; return false; }
} else {
A& a = attn_[il];
if (!attn_state_assign(as_, max_ctx_, take(attn_state_bytes(as_, max_ctx_)), a.st)) { err = "attn state"; return false; }
if (ke_) {
uint8_t* pl[4];
for (int j = 0; j < np; ++j) pl[j] = ke_->pool(n_attn_seen * np + j);
if (!attn_state_assign_ext(as_, max_ctx_, take(attn_state_bytes_ext(as_, max_ctx_)), pl, np, a.st)) { err = "attn state"; return false; }
++n_attn_seen;
} else if (!attn_state_assign(as_, max_ctx_, take(attn_state_bytes(as_, max_ctx_)), a.st)) { err = "attn state"; return false; }
float* gam = (float*) take((size_t) (2 * as_.hd + 2 * as_.ixd) * 4);
const AttnLayer& L = m.layers[il].attn;
attn_gamma_1pw(L.q_norm, gam, as_.hd, 0);
@@ -96,6 +120,27 @@ public:
if (!attn_verify_assign(as_, take(attn_verify_bytes(as_)), a.vb)) { err = "attn verify"; return false; }
}
}
for (int p = 1; p < T_; ++p)
for (int il = opt.loop_core_start; il < opt.loop_core_end; ++il) {
const int sl = il + p * nl;
if (!c.is_full[il]) {
G& g = gdn_[sl];
g.st.S = (float*) take(gdn_state_bytes(gs_));
g.st.hist = (float*) take(gdn_hist_bytes(gs_));
g.w = gdn_[il].w;
if (!gdn_verify_assign(gs_, take(gdn_verify_bytes(gs_)), g.vb)) { err = "gdn verify"; return false; }
} else {
A& a = attn_[sl];
if (ke_) {
uint8_t* pl[4];
for (int j = 0; j < np; ++j) pl[j] = ke_->pool(n_attn_seen * np + j);
if (!attn_state_assign_ext(as_, max_ctx_, take(attn_state_bytes_ext(as_, max_ctx_)), pl, np, a.st)) { err = "attn state"; return false; }
++n_attn_seen;
} else if (!attn_state_assign(as_, max_ctx_, take(attn_state_bytes(as_, max_ctx_)), a.st)) { err = "attn state"; return false; }
a.w = attn_[il].w;
if (!attn_verify_assign(as_, take(attn_verify_bytes(as_)), a.vb)) { err = "attn verify"; return false; }
}
}
MX_CK(cudaDeviceSynchronize(), err);
// warm-up of the graph-capturable decode kernels (lazy attributes / statics must not first run inside a stream capture)
{
@@ -113,6 +158,29 @@ public:
} else {
MX_CK(cudaDeviceSynchronize(), err);
}
// the window kernels (n = 2..4), eagerly once: verify + commit of one GDN and one attention layer
int gfirst = -1;
for (int il = 0; il < nl && gfirst < 0; ++il) if (!c.is_full[il]) gfirst = il;
const int32_t one = 1;
cudaMemcpy(gsc_.keep, &one, 4, cudaMemcpyHostToDevice);
cudaMemset(pj_qkv_, 0, (size_t) 4 * c.conv_dim() * 4); cudaMemset(pj_z_, 0, (size_t) 4 * c.val_dim() * 4);
cudaMemset(pj_a_, 0, (size_t) 4 * gs_.hv * 4); cudaMemset(pj_b_, 0, (size_t) 4 * gs_.hv * 4);
for (int n = 2; n <= 4 && win_ok_; ++n) {
std::string e2;
attn_win_set_pos(as_, win_, 8, n, own_);
bool ok = attn_window_dev(as_, attn_[first].w, attn_[first].st, asc_, win_, attn_[first].vb, n, pj_q_, pj_k_, pj_v_, pj_ix_, pj_o_, own_, e2);
if (ok && gfirst >= 0) {
G& g = gdn_[gfirst];
ok = gdn_verify(gs_, g.w, g.st, gsc_, g.vb, pj_qkv_, pj_z_, pj_a_, pj_b_, n, pj_y_, own_, e2) &&
gdn_commit_dev(gs_, g.w, g.st, gsc_, g.vb, n, gsc_.keep, own_, e2);
}
if (ok) ok = attn_window_commit_dev(as_, attn_[first].w, attn_[first].st, win_, attn_[first].vb, n, gsc_.keep, own_, e2);
cudaDeviceSynchronize();
if (!ok || cudaGetLastError() != cudaSuccess) {
std::fprintf(stderr, "q4lite: graph-capturable verify windows unavailable (%s)\n", e2.c_str());
win_ok_ = false;
}
}
}
}
reset();
@@ -121,6 +189,7 @@ public:
}
bool dec_ok_ = true; // the device-position decode attention passed its warm-up
bool win_ok_ = true; // the window kernels (n = 2..4) passed their warm-up
void destroy() override {
if (arena_) { cudaDeviceSynchronize(); cudaFree(arena_); arena_ = nullptr; }
if (own_) { cudaStreamDestroy(own_); own_ = nullptr; }
@@ -136,10 +205,12 @@ public:
}
cudaDeviceSynchronize();
verify_mode_ = false;
if (ke_) ke_->shrink_to_initial(); // a new context: the KV chunks above the first cells go back to the experts
}
bool gdn(int il, const float* x, const float* xr, int N, int pos0, float* y, cudaStream_t s, std::string& err) override {
namespace L = strata::ling32::gpu;
il += pass_ * nl_; // the state slot of the current Loop pass (pass 0: the layer itself)
G& g = gdn_[il];
if (!g.st.S) { err = "gdn: layer " + std::to_string(il) + " is not a GDN layer"; return false; }
if (g.pending) { // an earlier window that was not rolled back: all of it was accepted
@@ -149,7 +220,7 @@ public:
}
// (no position check for GDN layers: graph decode replays them without the host)
if (N < 1 || N > maxn_) { err = "gdn: N out of range"; return false; }
const GdnLayer& W = m_->layers[il].gdn;
const GdnLayer& W = m_->layers[il % nl_].gdn;
const Q4Cfg& c = m_->cfg;
gemv_dense(W.qkv, xr, N, pj_qkv_, c.conv_dim(), s);
gemv_dense(W.z, xr, N, pj_z_, c.val_dim(), s);
@@ -174,12 +245,13 @@ public:
bool attn(int il, const float* x, const float* xr, int N, int pos0, float* y, cudaStream_t s, std::string& err) override {
namespace L = strata::ling32::gpu;
il += pass_ * nl_;
A& a = attn_[il];
if (!attn_state_present(a.st)) { err = "attn: layer " + std::to_string(il) + " is not an attention layer"; return false; }
if (a.pending) { a.pending = false; pos_[il] += pending_n_[il]; } // previous window accepted in full
if (pos0 != pos_[il]) { err = "attn: position " + std::to_string(pos0) + " does not continue layer " + std::to_string(il) + " at " + std::to_string(pos_[il]) + " (after graph decode steps call set_decode_pos for each token)"; return false; }
if (N < 1 || N > maxn_) { err = "attn: N out of range"; return false; }
const AttnLayer& W = m_->layers[il].attn;
const AttnLayer& W = m_->layers[il % nl_].attn;
const Q4Cfg& c = m_->cfg;
gemv_dense(W.q, xr, N, pj_q_, 2 * c.q_dim(), s);
gemv_dense(W.k, xr, N, pj_k_, c.kv_dim(), s);
@@ -209,7 +281,7 @@ public:
namespace L = strata::ling32::gpu;
A& a = attn_[il];
if (!attn_state_present(a.st)) { err = "attn_decode: layer " + std::to_string(il) + " is not an attention layer"; return false; }
const AttnLayer& W = m_->layers[il].attn;
const AttnLayer& W = m_->layers[il % nl_].attn;
const Q4Cfg& c = m_->cfg;
(void) x;
gemv_dense(W.q, xr, 1, pj_q_, 2 * c.q_dim(), s);
@@ -222,6 +294,62 @@ public:
return true;
}
void set_pass(int p) override { pass_ = p; }
// ---- graph-capturable speculative windows (see q4_mixers.hpp)
bool window_graph_ok(int n) const override { return m_ != nullptr && win_ok_ && n >= 1 && n <= kGdnVerifyMax; }
bool set_window_pos(int pos, int n, cudaStream_t s, std::string& err) override {
if (!m_ || n < 1 || n > kGdnVerifyMax || pos < 0 || pos + n > max_ctx_) { err = "set_window_pos: out of range"; return false; }
attn_win_set_pos(as_, win_, pos, n, s);
return true;
}
bool gdn_window(int il, const float* x, const float* xr, int n, float* y, cudaStream_t s, std::string& err) override {
namespace L = strata::ling32::gpu;
G& g = gdn_[il];
if (!g.st.S) { err = "gdn_window: layer " + std::to_string(il) + " is not a GDN layer"; return false; }
const GdnLayer& W = m_->layers[il].gdn;
const Q4Cfg& c = m_->cfg;
gemv_dense(W.qkv, xr, n, pj_qkv_, c.conv_dim(), s);
gemv_dense(W.z, xr, n, pj_z_, c.val_dim(), s);
L::gemv_f32(W.a, gs_.hv, D_, x, n, pj_a_, s);
L::gemv_f32(W.b, gs_.hv, D_, x, n, pj_b_, s);
if (!gdn_verify(gs_, g.w, g.st, gsc_, g.vb, pj_qkv_, pj_z_, pj_a_, pj_b_, n, pj_y_, s, err)) return false;
L::fwht128(pj_y_, pj_r_, n, c.val_dim(), s);
gemv_dense(W.out, pj_r_, n, y, D_, s);
return true;
}
bool attn_window(int il, const float* x, const float* xr, int n, float* y, cudaStream_t s, std::string& err) override {
namespace L = strata::ling32::gpu;
A& a = attn_[il];
if (!attn_state_present(a.st)) { err = "attn_window: layer " + std::to_string(il) + " is not an attention layer"; return false; }
const AttnLayer& W = m_->layers[il].attn;
const Q4Cfg& c = m_->cfg;
(void) x;
gemv_dense(W.q, xr, n, pj_q_, 2 * c.q_dim(), s);
gemv_dense(W.k, xr, n, pj_k_, c.kv_dim(), s);
gemv_dense(W.v, xr, n, pj_v_, c.kv_dim(), s);
gemv_dense(W.ix_qk, xr, n, pj_ix_, as_.ix_width(), s);
if (!attn_window_dev(as_, a.w, a.st, asc_, win_, a.vb, n, pj_q_, pj_k_, pj_v_, pj_ix_, pj_o_, s, err)) return false;
L::fwht128(pj_o_, pj_r_, n, c.q_dim(), s);
gemv_dense(W.o, pj_r_, n, y, D_, s);
return true;
}
bool commit_window(int n, const int32_t* keep_dev, cudaStream_t s, std::string& err) override {
for (size_t il = 0; il < gdn_.size(); ++il) {
if (gdn_[il].st.S) { if (!gdn_commit_dev(gs_, gdn_[il].w, gdn_[il].st, gsc_, gdn_[il].vb, n, keep_dev, s, err)) return false; }
else if (attn_state_present(attn_[il].st)) { if (!attn_window_commit_dev(as_, attn_[il].w, attn_[il].st, win_, attn_[il].vb, n, keep_dev, s, err)) return false; }
}
return true;
}
void window_committed(int pos0, int n_keep) override {
for (size_t il = 0; il < pos_.size(); ++il) { pos_[il] = pos0 + n_keep; gdn_[il].pending = false; attn_[il].pending = false; }
}
void sync_gdn_pos(int pos) override {
for (size_t il = 0; il < gdn_.size(); ++il)
if (gdn_[il].st.S) { pos_[il] = pos; gdn_[il].pending = false; }
@@ -253,6 +381,7 @@ public:
}
size_t state_bytes() const override { return arena_bytes_; }
bool ensure_ctx(int cells, std::string& err) override { return !ke_ || ke_->ensure(cells, err); }
private:
struct G { GdnWeights w; GdnState st; GdnVerifyBuf vb; bool pending = false; };
@@ -274,13 +403,16 @@ private:
GdnScratch gsc_;
AttnScratch asc_;
AttnDecodeDev dec_;
AttnWinDev win_;
std::vector<G> gdn_;
std::vector<A> attn_;
std::vector<int> pos_;
int pending_n_[64] = {};
int pending_n_[160] = {};
int pass_ = 0, T_ = 1, nl_ = 40;
int maxn_ = 0, max_ctx_ = 0, D_ = 0;
bool verify_mode_ = false, global_ = false;
cudaStream_t own_ = nullptr; // the native Flash-Next kernels refuse the legacy default stream: warm-up and rollback use this one
KvElastic* ke_ = nullptr;
void* arena_ = nullptr;
size_t arena_bytes_ = 0;
float *pj_qkv_ = nullptr, *pj_z_ = nullptr, *pj_a_ = nullptr, *pj_b_ = nullptr, *pj_y_ = nullptr, *pj_q_ = nullptr, *pj_k_ = nullptr, *pj_v_ = nullptr, *pj_ix_ = nullptr,
+15 -2
View File
@@ -45,6 +45,7 @@ namespace strata::q4lite {
struct ServeCfg {
int max_ctx = 8192, chunk = 256;
std::string model_base, tier = "A", extra_info; // extra_info: more key=value words for the INFO line
int loop_passes = 0; // the owner's Loop: T when it is loaded (INFO loop_passes=T; a request's loop_passes=1 runs the stock single pass), 0 = not loaded
int layers = 40, vocab = 248320;
std::vector<int> eos = {248046, 248044}; // <|im_end|>, <|endoftext|> (generation_config.json)
int vram_ranks = 0, host_ranks = 0;
@@ -122,6 +123,7 @@ struct GenReq {
float pen_repeat = 1.0f, pen_freq = 0.0f, pen_present = 0.0f;
int pen_last_n = 64, pen_from = -1;
bool has_image = false;
int loop_passes = 0; // GEN loop_passes=N (0: not given)
std::vector<int> ids;
bool has_penalty() const { return pen_repeat != 1.0f || pen_freq != 0.0f || pen_present != 0.0f; }
};
@@ -167,6 +169,8 @@ inline bool parse_gen(const std::string& line, GenReq& r, std::string& err) {
else if (key == "penalty_present") r.pen_present = static_cast<float>(d);
else if (key == "penalty_last_n") r.pen_last_n = static_cast<int>(d);
else if (key == "pen_from") r.pen_from = static_cast<int>(d);
else if (key == "loop_passes") r.loop_passes = static_cast<int>(d);
else if (key == "loop_cd_omega" || key == "loop_cd_thinking") continue; // the owner's Loop has its own </think> gate: nothing to set per request
else if (key == "thinking" || key == "pcie_frac" || key == "spec_min_p" || key == "prefill_pipe") continue; // not ours (the template is Python-side) / tuning keys of other engines
else {
err = "unsupported key " + key;
@@ -256,13 +260,15 @@ inline int pick(const float* lg, int V, const GenReq& q, std::mt19937_64& rng) {
inline int q4_serve(Q4Engine& E, const ServeCfg& cfg) {
using namespace serve_detail;
const int V = cfg.vocab, max_ctx = cfg.max_ctx;
proto("INFO engine=strata-q4-lite-serve-0 arch=qwen4exp_q4_lite backend=cuda model=%s layers=%d vocab=%d chunk=%d session_reuse=1 tier=%s vram_ranks=%d host_ranks=%d spec=off images=0 loop=0%s",
cfg.model_base.c_str(), cfg.layers, V, cfg.chunk, cfg.tier.c_str(), cfg.vram_ranks, cfg.host_ranks, cfg.extra_info.c_str());
proto("INFO engine=strata-q4-lite-serve-0 arch=qwen4exp_q4_lite backend=cuda model=%s layers=%d vocab=%d chunk=%d session_reuse=1 tier=%s vram_ranks=%d host_ranks=%d spec=off images=0 loop=%d%s%s",
cfg.model_base.c_str(), cfg.layers, V, cfg.chunk, cfg.tier.c_str(), cfg.vram_ranks, cfg.host_ranks, cfg.loop_passes >= 2 ? 1 : 0,
cfg.loop_passes >= 2 ? (" loop_passes=" + std::to_string(cfg.loop_passes)).c_str() : "", cfg.extra_info.c_str());
proto("READY %d stop", max_ctx);
LineInput in;
in.start();
std::string line, err;
bool res_bypass = false; // the Loop mode the resident state was built in (a request of the other mode reads its prompt again)
std::vector<int> tok; // the tokens of the resident state (the last request's prompt and what it generated)
int fed = 0; // positions of tok whose KV / state is resident (== E.pos() when valid)
std::vector<float> lg;
@@ -279,6 +285,11 @@ inline int q4_serve(Q4Engine& E, const ServeCfg& cfg) {
}
in.stop.store(false);
if (q.has_image) { proto("ERR image: this engine has no picture reader yet (--vision is not built)"); continue; }
bool bypass = false; // the owner's Loop: loop_passes=1 = the stock single pass, loop_passes=T (or none) = the loop
if (q.loop_passes != 0) {
if (q.loop_passes == 1) bypass = cfg.loop_passes >= 2;
else if (q.loop_passes != cfg.loop_passes) { proto("ERR loop_passes: 1 or %d (the loaded --loop), got %d", cfg.loop_passes >= 2 ? cfg.loop_passes : 1, q.loop_passes); continue; }
}
const int T0 = static_cast<int>(q.ids.size());
if (T0 == 0) { proto("ERR empty prompt"); continue; }
if (T0 >= max_ctx) { proto("ERR prompt exceeds context (%d of %d)", T0, max_ctx); continue; }
@@ -298,10 +309,12 @@ inline int q4_serve(Q4Engine& E, const ServeCfg& cfg) {
}
int start = 0;
if (fed > 0 && E.pos() == fed && common >= fed && fed < T0) start = fed; // the resident state is a prefix of this prompt
if (start > 0 && bypass != res_bypass) start = 0;
if (start == 0) {
E.reset();
fed = 0;
}
if (cfg.loop_passes >= 2) { E.set_loop_bypass(bypass); res_bypass = bypass; }
tok.assign(q.ids.begin(), q.ids.end());
if (start > 0) proto("RESUME %d", start);
+2 -1
View File
@@ -332,7 +332,7 @@ def gen(args):
man["total"] = total
else:
total = args.ctx
ops = make_ops(total, ("chunks", 1000) if total > 1100 else ("first", min(256, total - 80)))
ops = make_ops(total, ("chunks", args.chunk or 1000) if (total > 1100 or args.chunk) else ("first", min(256, total - 80)))
qw = (0.1 * rng.standard_normal(HD)).astype(f32)
kw = (0.1 * rng.standard_normal(HD)).astype(f32)
iqw = (0.1 * rng.standard_normal(IXD)).astype(f32)
@@ -499,6 +499,7 @@ def main():
g.add_argument("--ctx", type=int, default=300)
g.add_argument("--out", required=True)
g.add_argument("--seed", type=int, default=1)
g.add_argument("--chunk", type=int, default=0, help="attn: prefill chunk size (default 1000 for long contexts)")
c = sub.add_parser("cmp")
c.add_argument("--dir", required=True)
sub.add_parser("selftest")
+119 -4
View File
@@ -11,6 +11,7 @@
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
@@ -102,16 +103,53 @@ static bool graph_step(const AttnShape& s, const AttnWeights& w, const AttnState
return true;
}
// --graphwin: verify windows through captured graphs (one verify graph and one commit graph per window size n; the accepted count goes in as a device int, the position
// through attn_win_set_pos), replayed for every window of that size
struct WinGraphs { cudaGraphExec_t v = nullptr, c = nullptr; };
static std::map<int, WinGraphs> g_wg;
static int32_t* g_keep = nullptr;
static AttnWinDev g_win;
static float *gw_q = nullptr, *gw_k = nullptr, *gw_v = nullptr, *gw_ix = nullptr; // attention window inputs (fixed addresses)
static float *gw_qkv = nullptr, *gw_z = nullptr, *gw_a = nullptr, *gw_b = nullptr; // GDN window inputs
static void win_set_keep(int keep, cudaStream_t st) { CK(cudaMemcpyAsync(g_keep, &keep, 4, cudaMemcpyHostToDevice, st)); CK(cudaStreamSynchronize(st)); }
template <class FV, class FC>
static bool win_graphs(int n, cudaStream_t st, FV fv, FC fc, std::string& err) {
if (g_wg.count(n)) return true;
// warm-up (eager): verify, then commit nothing (keep 0) so the state is as before
win_set_keep(0, st);
if (!fv(err) || !fc(err)) return false;
CK(cudaStreamSynchronize(st));
WinGraphs g;
for (int which = 0; which < 2; ++which) {
CK(cudaStreamBeginCapture(st, cudaStreamCaptureModeThreadLocal));
const bool ok = which == 0 ? fv(err) : fc(err);
cudaGraph_t gr = nullptr;
CK(cudaStreamEndCapture(st, &gr));
if (!ok) return false;
CK(cudaGraphInstantiate(which == 0 ? &g.v : &g.c, gr, 0));
cudaGraphDestroy(gr);
}
g_wg[n] = g;
std::printf("window graphs captured for n=%d\n", n);
return true;
}
int main(int argc, char** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: q4_attn_test DIR [--no-tc] [--fp32-indexer] [--time]\n"); return 2; }
DIR = argv[1];
bool no_tc = false, fp32_ix = false, do_time = false, use_graph = false;
bool no_tc = false, fp32_ix = false, do_time = false, use_graph = false, use_gw = false;
int arg_maxn = 0, arg_maxctx = 0, bigrun = 0;
int bench_ctx = 0;
for (int i = 2; i < argc; ++i) {
if (!std::strcmp(argv[i], "--no-tc")) no_tc = true;
else if (!std::strcmp(argv[i], "--fp32-indexer")) fp32_ix = true;
else if (!std::strcmp(argv[i], "--time")) do_time = true;
else if (!std::strcmp(argv[i], "--graph")) use_graph = true;
else if (!std::strcmp(argv[i], "--graphwin")) use_gw = true;
else if (!std::strcmp(argv[i], "--maxn") && i + 1 < argc) arg_maxn = std::atoi(argv[++i]);
else if (!std::strcmp(argv[i], "--bigrun") && i + 1 < argc) bigrun = std::atoi(argv[++i]);
else if (!std::strcmp(argv[i], "--maxctx") && i + 1 < argc) arg_maxctx = std::atoi(argv[++i]);
else if (!std::strcmp(argv[i], "--bench") && i + 1 < argc) bench_ctx = std::atoi(argv[++i]);
}
MKDIR((DIR + "/gpu").c_str());
@@ -159,7 +197,25 @@ int main(int argc, char** argv) {
float* b = upload("op" + std::to_string(i) + ".b.f32");
bool ok;
if (o.kind == "run") ok = gdn_run(s, w, state, sc, qkv, z, a, b, o.n, y, st, err);
else {
else if (use_gw) {
if (!g_keep) {
CK(cudaMalloc(&g_keep, 16));
CK(cudaMalloc(&gw_qkv, (size_t) 16 * s.conv_dim() * 4)); CK(cudaMalloc(&gw_z, (size_t) 16 * s.val_dim() * 4));
CK(cudaMalloc(&gw_a, 16 * s.hv * 4)); CK(cudaMalloc(&gw_b, 16 * s.hv * 4));
}
auto fv = [&](std::string& e) { return gdn_verify(s, w, state, sc, vb, gw_qkv, gw_z, gw_a, gw_b, o.n, y, st, e); };
auto fc = [&](std::string& e) { return gdn_commit_dev(s, w, state, sc, vb, o.n, g_keep, st, e); };
CK(cudaMemcpyAsync(gw_qkv, qkv, (size_t) o.n * s.conv_dim() * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(gw_z, z, (size_t) o.n * s.val_dim() * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(gw_a, a, (size_t) o.n * s.hv * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(gw_b, b, (size_t) o.n * s.hv * 4, cudaMemcpyDeviceToDevice, st));
ok = win_graphs(o.n, st, fv, fc, err);
if (ok) {
CK(cudaGraphLaunch(g_wg[o.n].v, st));
win_set_keep(o.keep, st);
CK(cudaGraphLaunch(g_wg[o.n].c, st));
}
} else {
ok = gdn_verify(s, w, state, sc, vb, qkv, z, a, b, o.n, y, st, err);
if (ok) ok = gdn_commit(s, w, state, sc, vb, o.keep, st, err);
}
@@ -182,7 +238,7 @@ int main(int argc, char** argv) {
}
} else {
AttnShape s;
const int max_n = 1024, max_ctx = 8192;
const int max_n = arg_maxn ? arg_maxn : 1024, max_ctx = arg_maxctx ? arg_maxctx : 8192;
std::string e2;
if (!attn_global_init(s, max_ctx, e2)) { std::fprintf(stderr, "%s\n", e2.c_str()); return 2; }
float *qw = upload("w.q_norm.f32"), *kw = upload("w.k_norm.f32"), *iqw = upload("w.ix_q_ln.f32"), *ikw = upload("w.ix_k_ln.f32");
@@ -220,7 +276,30 @@ int main(int argc, char** argv) {
bool ok;
if (o.kind == "run" && o.n == 1 && use_graph) ok = graph_step(s, w, state, sc, q, k, v, ix, pos, out, st, err);
else if (o.kind == "run") ok = attn_run(s, w, state, sc, q, k, v, ix, o.n, pos, out, st, err, opt);
else {
else if (use_gw) {
if (!g_keep) {
CK(cudaMalloc(&g_keep, 16));
void* wm = nullptr;
CK(cudaMalloc(&wm, attn_win_dev_bytes(s)));
attn_win_dev_assign(s, wm, g_win);
CK(cudaMalloc(&gw_q, (size_t) 16 * s.nh * 2 * s.hd * 4)); CK(cudaMalloc(&gw_k, (size_t) 16 * s.kv_width() * 4));
CK(cudaMalloc(&gw_v, (size_t) 16 * s.kv_width() * 4)); CK(cudaMalloc(&gw_ix, (size_t) 16 * s.ix_width() * 4));
}
auto fv = [&](std::string& e) { return attn_window_dev(s, w, state, sc, g_win, vb, o.n, gw_q, gw_k, gw_v, gw_ix, out, st, e); };
auto fc = [&](std::string& e) { return attn_window_commit_dev(s, w, state, g_win, vb, o.n, g_keep, st, e); };
CK(cudaMemcpyAsync(gw_q, q, (size_t) o.n * s.nh * 2 * s.hd * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(gw_k, k, (size_t) o.n * s.kv_width() * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(gw_v, v, (size_t) o.n * s.kv_width() * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(gw_ix, ix, (size_t) o.n * s.ix_width() * 4, cudaMemcpyDeviceToDevice, st));
attn_win_set_pos(s, g_win, pos, o.n, st);
ok = win_graphs(o.n, st, fv, fc, err); // warm-up + capture use the positions just set (eager verify writes the window, the keep-0 commit restores the tail)
if (ok) {
attn_win_set_pos(s, g_win, pos, o.n, st);
CK(cudaGraphLaunch(g_wg[o.n].v, st));
win_set_keep(o.keep, st);
CK(cudaGraphLaunch(g_wg[o.n].c, st));
}
} else {
ok = attn_run(s, w, state, sc, q, k, v, ix, o.n, pos, out, st, err, opt, &vb);
if (ok) ok = attn_rollback(s, w, state, sc, vb, o.keep, st, err, opt);
}
@@ -242,6 +321,42 @@ int main(int argc, char** argv) {
float ms; cudaEventElapsedTime(&ms, e0, e1);
std::printf("TIME attention decode step at ctx %d (norm+rope, kv, indexer, select, attn, gate; 1 layer): %.1f us\n", ctx, ms * 1000.0f / 100);
}
if (bigrun > 0 && !bad) { // one attn_run of `bigrun` tokens (op0's inputs tiled): the long-chunk limits; checks only that it runs and the output is finite
const int mc = (bigrun + 64 + 3) / 4 * 4;
attn_global_init(s, mc, e2);
void* stm2 = nullptr; void* scm2 = nullptr;
CK(cudaMalloc(&stm2, attn_state_bytes(s, mc)));
CK(cudaMalloc(&scm2, attn_scratch_bytes(s, bigrun, mc)));
AttnState st2; AttnScratch sc2;
attn_state_assign(s, mc, stm2, st2);
attn_state_reset(s, st2, st);
attn_scratch_assign(s, bigrun, mc, scm2, sc2);
const int n0 = ops[0].n;
size_t c0 = 0;
float* q0 = upload("op0.q.f32", &c0); float* k0 = upload("op0.k.f32"); float* v0 = upload("op0.v.f32"); float* ix0 = upload("op0.idx.f32");
float *q = nullptr, *k = nullptr, *v = nullptr, *ix = nullptr, *o2 = nullptr;
const size_t wq = (size_t) s.nh * 2 * s.hd, wk = (size_t) s.kv_width(), wi = (size_t) s.ix_width();
CK(cudaMalloc(&q, (size_t) bigrun * wq * 4)); CK(cudaMalloc(&k, (size_t) bigrun * wk * 4)); CK(cudaMalloc(&v, (size_t) bigrun * wk * 4));
CK(cudaMalloc(&ix, (size_t) bigrun * wi * 4)); CK(cudaMalloc(&o2, (size_t) bigrun * s.q_width() * 4));
for (int t = 0; t < bigrun; ++t) {
const int r = t % n0;
CK(cudaMemcpyAsync(q + (size_t) t * wq, q0 + (size_t) r * wq, wq * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(k + (size_t) t * wk, k0 + (size_t) r * wk, wk * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(v + (size_t) t * wk, v0 + (size_t) r * wk, wk * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(ix + (size_t) t * wi, ix0 + (size_t) r * wi, wi * 4, cudaMemcpyDeviceToDevice, st));
}
CK(cudaStreamSynchronize(st));
auto t0 = std::chrono::steady_clock::now();
const bool ok = attn_run(s, w, st2, sc2, q, k, v, ix, bigrun, 0, o2, st, err, opt);
CK(cudaStreamSynchronize(st));
const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
std::vector<float> h((size_t) bigrun * s.q_width());
CK(cudaMemcpy(h.data(), o2, h.size() * 4, cudaMemcpyDeviceToHost));
size_t nonfinite = 0;
for (float f : h) if (!(f == f) || f > 1e30f || f < -1e30f) ++nonfinite;
std::printf("BIGRUN N=%d: %s %s, %.1f ms (%.0f tokens/s per layer), %zu non-finite outputs\n", bigrun, ok ? "ok" : "FAILED", ok ? "" : err.c_str(), ms, bigrun / (ms / 1000.0), nonfinite);
if (!ok || nonfinite) bad = 1;
}
if (bench_ctx > 0 && !bad) { // timing only: fill a long context with the first op's inputs repeated (random data), then time decode steps at its end
const int mc = (bench_ctx + 64 + 3) / 4 * 4;
attn_global_init(s, mc, e2);
+8 -6
View File
@@ -104,12 +104,14 @@ def extra_args(cfg: dict, base_args: list, exe: str | None = None, *, announce:
args = list(base_args)
info = probe(exe, args, cfg) if exe and ("--vision" in args or cfg.get(qwen4_family.MTP_CONFIG_KEY)) else None
build = qwen4_family.build_of_model_name(cfg.get("model_name"))
if "--vision" in args and (not qwen4_family.vision_ready(build) or (info or {}).get("images") != "1"): # a .strata build: the engine takes no --vision yet (it would exit 2)
be = str(cfg.get("backend") or "cuda").lower()
metal = qwen4_family.uses_metal_converter(build, be) # a .strata tier on a Mac: the converted GGUF on `strata` (--mtp <rt> with the --spec 2 already in the arguments)
if "--vision" in args and (not qwen4_family.vision_ready(build, be) or (info or {}).get("images") != "1"): # a .strata build: the engine takes no --vision yet (it would exit 2)
args = _without(args, ("--vision", "--vision-device", "--vision-max-pixels"))
if announce:
print(f"[strata] {NO_IMAGES_NOTE}", flush=True)
mtp = cfg.get(qwen4_family.MTP_CONFIG_KEY)
if mtp and not qwen4_family.mtp_ready(build): # a .strata build: the engine takes no --mtp yet (it would exit 2): the key is ignored
if mtp and not qwen4_family.mtp_ready(build, be): # a .strata build on the standalone host: the engine takes no --mtp yet (it would exit 2): the key is ignored
if announce:
print(f"[strata] Qwen4-35B-A3B: {qwen4_family.STRATA_COMING_NOTE}", flush=True)
mtp = None
@@ -119,10 +121,10 @@ def extra_args(cfg: dict, base_args: list, exe: str | None = None, *, announce:
print(f"[strata] {NO_MTP_NOTE}", flush=True)
else:
gguf = qwen4_family.is_gguf_build(qwen4_family.build_of_model_name(cfg.get("model_name")))
if gguf: # the plain start has --spec 2 (a native pack needs >= 2); with the drafter it is --spec 4 --spec-min-p 0.5
if gguf: # the plain start has --spec 2 (a native pack needs >= 2); with the drafter it is --spec K --spec-min-p 0.5
args = _without(args, ("--spec", "--spec-min-p"))
spec_k = cfg.get(qwen4_family.MTP_SPEC_CONFIG_KEY) # the K the launcher / setup chose for this card (default 3)
args += qwen4_family.mtp_engine_args(mtp, cfg.get(qwen4_family.MTP_MODE_KEY) or "auto", gguf=gguf, spec_k=spec_k if isinstance(spec_k, int) and not isinstance(spec_k, bool) else None)
args += qwen4_family.mtp_engine_args(mtp, cfg.get(qwen4_family.MTP_MODE_KEY) or "auto", gguf=gguf, spec_k=spec_k if isinstance(spec_k, int) and not isinstance(spec_k, bool) else None, metal=metal)
loop = cfg.get(qwen4_family.LOOP_CONFIG_KEY)
backend = cfg.get("backend") or "cuda"
if not qwen4_family.loop_ready(build, backend): # Loop is coming for this build on this backend: an old config's key and flags are ignored
@@ -156,7 +158,7 @@ def is_strata_build(cfg: dict | None) -> bool:
return False
from strata_control import qwen4_family
build = qwen4_family.build_of_model_name(cfg.get("model_name")) or qwen4_family.build_of_file(qwen4_family.model_arg(cfg.get("args")))
return build in qwen4_family.BUILDS
return qwen4_family.uses_standalone_host(build, cfg.get("backend")) if build in qwen4_family.BUILDS else False
def strata_engine_args(cfg: dict, exe: str | None = None, *, announce: bool = True) -> list[str]:
@@ -210,7 +212,7 @@ def engine_serves(cfg: dict, exe: str | None = None) -> bool:
build = qwen4_family.build_of_model_name((cfg or {}).get("model_name"))
if build is None: # an unknown model (a custom file): the generic start decides
return True
if qwen4_family.is_gguf_build(build):
if qwen4_family.is_gguf_build(build) or not qwen4_family.uses_standalone_host(build, (cfg or {}).get("backend")): # the GGUF build and every Mac build run on `strata`, which serves
return True
if qwen4_family.strata_serve_ready():
return True
+238 -35
View File
@@ -11261,35 +11261,9 @@ def qwen4_tokenizer_dir(model: Path, out: Path, engine: Path | None, folder: Pat
if (out / "vocab.json").is_file() and (out / qwen4_family.CHAT_TEMPLATE_FILE).is_file():
return out
raw = out.parent / (qwen4_family.TOKENIZER_DIR + "-hf") # the four files as published: the conversion writes tokenizer/ beside it (its tokenizer.json is another file)
near = [d for d in (raw, Path(model).parent / qwen4_family.TOKENIZER_DIR if model else None, Path(model).parent if model else None,
Path(folder) / qwen4_family.TOKENIZER_DIR if folder else None, Path(data) / "models" / qwen4_family.FAMILY / qwen4_family.TOKENIZER_DIR if data else None) if d is not None]
shipped = ROOT / "tests" / "data" / "qwen4"
got: dict = {}
for name in qwen4_family.TOKENIZER_FILES:
p = qwen4_tokenizer_find(name, near)
if p is None and not own:
for src in qwen4_family.sources():
listed = (src.get("files") or {}).get(name)
urls = ([listed] if isinstance(listed, str) else list(listed)) if listed else ([f"{src['base']}/{qwen4_family.TOKENIZER_DIR}/{name}"] if src.get("base") else [])
for url in urls:
try:
raw.mkdir(parents=True, exist_ok=True)
download(url, raw / name, name)
size, sha = qwen4_family.TOKENIZER_FILES[name]
verify_sha256(raw / name, size, sha)
p = raw / name
break
except SystemExit:
warn(f"{name}: that source did not work")
if p is not None:
break
if p is None and name != qwen4_family.TOKENIZER_FILE:
p = (shipped / name) if (shipped / name).is_file() else None # the three small files ship with Strata (its own vendored copies, not checked against the pins)
if p is not None:
say(f" {name}: using the copy that ships with Strata")
if p is None:
return None
got[name] = p
got = qwen4_tokenizer_raw(model, out, folder, data, own)
if got is None:
return None
raw.mkdir(parents=True, exist_ok=True)
for name, p in got.items():
if p.parent != raw:
@@ -11548,7 +11522,7 @@ def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *,
warn(f"the picture reader program ({VEXE}) is not in the engine package yet: pictures are off for now")
mmproj = None
spec_k = qwen4_fit.mtp_spec_k((gpu or {}).get("name")) # K = 3 on every card (Q4-SMALL's matrix), a per-card override in qwen4_fit.MTP_SPEC_BY_CARD
args = qwen4_family.gguf_engine_args(trunk, shard2, pack=pack, profile=profile, vision=mmproj, loop=loop_path, ctx=ctx, kv=kv) # the MTP runtime is a config key, turned into --mtp <rt> --spec 4 --spec-min-p 0.5 (in place of --spec 2) at the start
args = qwen4_family.gguf_engine_args(trunk, shard2, pack=pack, profile=profile, vision=mmproj, loop=loop_path, ctx=ctx, kv=kv, vram_gb=None if unified else vram_gib, ram_gb=ram_gib, unified=unified) # the MTP runtime is a config key, turned into --mtp <rt> --spec 4 --spec-min-p 0.5 (in place of --spec 2) at the start
cfg = {"exe": engine_exe(eng), "args": args, "cwd": str(ROOT), "tokenizer": str(tokdir), "model_name": qwen4_family.model_key(model), "arch": fam["arch"],
"log": str(home() / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port, "drafting": "off",
qwen4_family.EFFORT_CONFIG_KEY: effort, "thinking": "off" if effort == "off" else "on"}
@@ -11654,6 +11628,232 @@ def qwen4_pick_engine(a, gpu, hip, backend: str) -> None:
warn(pick["words"])
def qwen4_tokenizer_raw(model: Path | None, out: Path, folder: Path | None = None, data: Path | None = None, own: bool = False) -> dict | None:
"""The four Hugging Face tokenizer files (qwen4_family.TOKENIZER_FILES) as {name: path}, each taken only at its pinned size and SHA-256: 1) beside the model, in the model folder's tokenizer/ folder, in
<packs>/tokenizer-hf or in the data folder's family folder, 2) downloaded from a configured source (<base>/tokenizer/<name>; never for the person's own files), 3) for the three small ones, the copies
Strata ships (tests/data/qwen4). None when one is nowhere (tokenizer.json has no copy of its own). Shared by the tokenizer step of every Qwen4 install and the Mac install's converter."""
out = Path(out)
raw = out.parent / (qwen4_family.TOKENIZER_DIR + "-hf") # the four files as published: the conversion writes tokenizer/ beside it (its tokenizer.json is another file)
near = [d for d in (raw, Path(model).parent / qwen4_family.TOKENIZER_DIR if model else None, Path(model).parent if model else None,
Path(folder) / qwen4_family.TOKENIZER_DIR if folder else None, Path(data) / "models" / qwen4_family.FAMILY / qwen4_family.TOKENIZER_DIR if data else None) if d is not None]
shipped = ROOT / "tests" / "data" / "qwen4"
got: dict = {}
for name in qwen4_family.TOKENIZER_FILES:
p = qwen4_tokenizer_find(name, near)
if p is None and not own:
for src in qwen4_family.sources():
listed = (src.get("files") or {}).get(name)
urls = ([listed] if isinstance(listed, str) else list(listed)) if listed else ([f"{src['base']}/{qwen4_family.TOKENIZER_DIR}/{name}"] if src.get("base") else [])
for url in urls:
try:
raw.mkdir(parents=True, exist_ok=True)
download(url, raw / name, name)
size, sha = qwen4_family.TOKENIZER_FILES[name]
verify_sha256(raw / name, size, sha)
p = raw / name
break
except SystemExit:
warn(f"{name}: that source did not work")
if p is not None:
break
if p is None and name != qwen4_family.TOKENIZER_FILE:
p = (shipped / name) if (shipped / name).is_file() else None # the three small files ship with Strata (its own vendored copies, not checked against the pins)
if p is not None:
say(f" {name}: using the copy that ships with Strata")
if p is None:
return None
got[name] = p
return got
def qwen4_ensure_zstd() -> None:
"""The Mac converter reads the .strata's manifest (zstd): `zstandard` is installed into setup's Python when it is not there (the Mac setup Python has none)."""
try:
import zstandard # noqa: F401
except ImportError:
pip_install(["zstandard"], "zstandard (reads the manifest of the .strata file)")
def qwen4_metal_tool(key: str, what: str) -> Path:
"""One of the Mac conversion tools (qwen4_family.METAL_TOOLS): its path, or one plain sentence and a stop when this Strata does not have it."""
rel = qwen4_family.METAL_TOOLS[key]
p = ROOT / rel
if not p.is_file():
fail(f"the tool that {what} ({rel}) is not in this Strata, so the Mac install of the Qwen4-35B-A3B builds cannot go on", "update Strata and run this again")
return p
def qwen4_fresh(out: Path, *inputs) -> bool:
"""Is `out` there, not empty and not older than every input (an input that is missing counts as old)?"""
try:
if not out.is_file() or out.stat().st_size == 0:
return False
t = out.stat().st_mtime
return all(Path(i).stat().st_mtime <= t for i in inputs if i is not None and Path(i).exists())
except OSError:
return False
def qwen4_metal_vision(paths: dict, vision_strata: Path | None) -> bool:
"""The picture reader of a .strata tier on a Mac: qwen4_vision_strata_to_gguf.py writes the mmproj GGUF from Vision.strata (about 1 s, 0.9 GB; tensor-identical to Unsloth's mmproj-BF16.gguf, so the existing
picture reader takes it). Optional: a missing tool or any failure is one warning and False (pictures off), never a failed install."""
if vision_strata is None:
return False
tool = ROOT / qwen4_family.METAL_TOOLS["vision_to_gguf"]
if not tool.is_file():
warn(qwen4_family.METAL_COMING_NOTE)
return False
try:
if not qwen4_fresh(paths["mmproj"], vision_strata):
paths["vision_dir"].mkdir(parents=True, exist_ok=True)
say(" Converting the picture reader ...")
run([sys.executable, str(tool), "--strata", str(vision_strata), "--out", str(paths["mmproj"])])
except (SystemExit, subprocess.SubprocessError, OSError) as e:
warn(f"the picture reader could not be prepared ({e}): pictures are off for this build")
return False
return paths["mmproj"].is_file()
def qwen4_metal_prepare(paths: dict, strata: Path, ple: Path, tok: dict, mtp_strata: Path | None) -> bool:
"""Step 6 of a .strata tier on a Mac (Q4-METAL's chain, once per model, each step skipped when its output is newer than its inputs):
1) the HF directory the converter reads (tokenizer-compat/ and generation_config.json from the flat tokenizer files),
2) qwen4_strata_to_gguf.py: the dense half as a qwen4exp GGUF (the experts stay in the .strata: its path is in the GGUF),
3) iq_pack.py --compat-bf16 and qwen4_strata_pack_fix.py: the engine pack, then the layout fix for the placeholder expert tensors,
4) the neutral expert profile,
5) the draft layer: qwen4_mtp_strata_to_gguf.py and the empty rt folder (optional: any failure is one warning and False, MTP off).
A failing required step stops with one plain sentence. Returns whether the draft layer is ready."""
d = paths["dir"]
d.mkdir(parents=True, exist_ok=True)
qwen4_ensure_zstd()
qwen4_family.build_hf_dir(tok, paths["hf"])
gguf = paths["gguf"]
if not qwen4_fresh(gguf, strata, ple):
say(" Converting the model for the Mac engine (about 30 seconds, one time) ...")
run([sys.executable, str(qwen4_metal_tool("to_gguf", "converts the model")), "--strata", str(strata), "--hf-dir", str(paths["hf"]), "--ple-gguf", str(ple), "--out", str(gguf)])
pack, mark = paths["pack"], paths["pack"] / ".strata-pack-fixed"
if not (qwen4_fresh(mark, gguf) and (pack / "native_experts.txt").is_file() and (pack / "tokenizer" / "vocab.json").is_file()):
say(" Making the engine pack ...")
run([sys.executable, str(qwen4_metal_tool("iq_pack", "makes the engine pack")), "--gguf", str(gguf), "--out", str(pack), "--compat-bf16"])
run([sys.executable, str(qwen4_metal_tool("pack_fix", "fixes the engine pack")), str(pack)])
mark.write_text("fixed after the conversion of " + gguf.name + "\n", encoding="utf-8")
if not paths["profile"].is_file():
qwen4_family.write_uniform_profile(paths["profile"]) # the neutral 40 x 256 profile: the same bytes as qwen4_neutral_profile.py
if mtp_strata is None:
return False
try:
if not qwen4_fresh(paths["mtp_gguf"], mtp_strata):
paths["mtp_dir"].mkdir(parents=True, exist_ok=True)
say(" Converting the draft layer ...")
run([sys.executable, str(qwen4_metal_tool("mtp_to_gguf", "converts the draft layer")), "--strata", str(mtp_strata), "--out", str(paths["mtp_gguf"])])
paths["mtp_rt"].mkdir(parents=True, exist_ok=True)
except (SystemExit, subprocess.SubprocessError, OSError) as e:
warn(f"the draft layer could not be prepared ({e}): MTP is off for this build")
return False
return paths["mtp_gguf"].is_file()
def install_qwen4_metal(a, family, fam, gpu, port, adopted, *, model, ctx, tag, folder, own, vram_gib, ram_gib, unified, mtp_mode, effort, ple_asked, kv, vision=False):
"""Steps 2-7 for a .strata tier (Compact / Balanced / Ultra) on a Mac (Metal): the files from the configured source or the folder, the tier's dense half converted to a qwen4exp GGUF beside the
.strata (strata_control/qwen4_family.py METAL_*, Q4-METAL's chain), and the run config for the Metal engine `strata` of the component strata-q4-lite (the .strata experts are read in place, so the file
stays where it is). The draft layer (MTP) is on by default (`--spec 2 --mtp <rt>`); pictures are on by default too (Vision.strata converted to the mmproj, the "vision" section of the config);
Loop is coming."""
adv = qwen4_fit.advise(None, ram_gib, unified=True, ctx=ctx, build=model, ple=ple_asked, vision=False, mtp=mtp_mode != "off", loop=False, backend="metal", kv=kv)
ple = ple_asked or adv["ple"]
say()
say(f" Memory plan for this Mac: {adv['mode_words']}; the PLE table is {ple} (read from the disk)")
say(f" about {adv['vram_need_gib']:.1f} GiB of the Mac's memory for the model and its cache, {adv['ram_need_gib']:.1f} GiB with what the system keeps")
for w in adv["warnings"]:
warn(w)
local_native = None
if own and Path(a.gguf_dir).is_file() and Path(a.gguf_dir).suffix.lower() == ".strata" and Path(a.gguf_dir).name not in qwen4_family.FILES:
local_native = Path(a.gguf_dir) # the person's own .strata (a fine-tune or another build): used as it is, never hash-checked
own_strata_check(local_native)
model_name = qwen4_family.build_file(model)
files = [n for n in (model_name, qwen4_family.ple_file(ple)) if not (local_native is not None and n == model_name)]
want = list(files) + ([qwen4_family.MTP_FILE] if mtp_mode != "off" and not own else []) + ([qwen4_family.VISION_FILE] if vision and not own else [])
left = 0.0
for n in want:
p = folder / n
if not qwen4_have(a, p) and not (n in (qwen4_family.MTP_FILE, qwen4_family.VISION_FILE) and qwen4_family.find_file(n, None, [folder])):
part = p.with_name(p.name + ".part")
left += (qwen4_family.FILES[n][0] - (part.stat().st_size if part.is_file() else 0)) / 1e9
left += sum(qwen4_family.TOKENIZER_FILES[n][0] for n in qwen4_family.TOKENIZER_FILES) / 1e9 + qwen4_fit.METAL_STRATA_DISK_EXTRA_GB[model] + 1.0 # the tokenizer files, the converted dense GGUF, the pack and the draft layer
free = free_gb(folder) if folder.exists() or folder.parent.exists() else None
if left and free is not None and free < left:
fail(f"not enough free disk space in {folder}: need ~{left:.0f} GB, {free:.0f} GB free", ("use --data-dir on a bigger drive (strata launch --data-dir)" if CONTROL else "use --models-dir on a bigger drive"))
if left and free is not None and free < left + 1:
warn(f"little free disk space in {folder}: {free:.1f} GB free for about {left:.1f} GB. Setup goes on and should fit")
step(3, "Python packages")
pip_install(runtime_packages(), "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil, textual (the screens)")
qwen4_ensure_zstd()
step(4, "the Qwen4-35B-A3B engine")
SHAPE_ENGINE.clear()
SHAPE_ENGINE["shape"], SHAPE_ENGINE["title"] = qwen4_family.SHAPE, fam["title"] # the Mac runs the .strata tiers on `strata` (no program suffix: qwen4_family.program_for)
llama, eng, meta, lib_dirs, gpu, _vision = engine_step(a, gpu, False, False, None, "none")
if meta.get("component") != "missing":
ok(f"engine: {Path(eng) / qwen4_family.EXE}")
step(5, f"downloading {fam['title']} {model}")
paths_dl = {n: qwen4_fetch(a, n, folder, own) for n in files}
strata = local_native if local_native is not None else paths_dl[model_name]
ple_path = paths_dl[qwen4_family.ple_file(ple)]
ok(f"model file: {strata}")
data, _ = data_folder_for(a)
mtp_strata = qwen4_optional(a, qwen4_family.MTP_FILE, folder, own, strata, [data / "models" / qwen4_family.FAMILY], "MTP") if mtp_mode != "off" else None
vision_strata = qwen4_optional(a, qwen4_family.VISION_FILE, folder, own, strata, [data / "models" / qwen4_family.FAMILY], "pictures") if vision else None
step(6, "preparing the model for the Mac engine")
mp = qwen4_family.metal_paths(folder, model)
tok = qwen4_tokenizer_raw(strata, data / "packs" / tag.lower() / "tokenizer", folder, data, own)
if tok is None:
fail("the tokenizer files (tokenizer.json and three small ones) were not found beside the model and no source could give them", f"put them in {folder / qwen4_family.TOKENIZER_DIR} (or set {qwen4_family.SOURCE_ENV} to a base URL that holds them) and run this again")
mtp_ok = qwen4_metal_prepare(mp, strata, ple_path, tok, mtp_strata)
vision_ok = qwen4_metal_vision(mp, vision_strata)
reader = Path(eng) / VEXE
if vision_ok and not reader.is_file():
warn(f"the picture reader program ({VEXE}) is not in the engine package yet: pictures are off for now")
vision_ok = False
ok(f"model prepared: {mp['gguf']}")
ok(f"tokenizer: {mp['pack'] / 'tokenizer'}")
step(7, "writing the start script")
ok(f"MTP: {'on' if mtp_mode == 'on' else 'auto (the engine decides at start whether it pays here)'}" if mtp_ok else "MTP: off")
ok("pictures: " + (f"on ({mp['mmproj'].name})" if vision_ok else "off"))
ok(f"Loop: off. {qwen4_family.LOOP_WORDS} (Coming soon.)")
if getattr(a, "kv", None):
warn("--kv is not used on a Mac: its engine keeps the K/V cache in int8 whatever is asked")
cfg = {"exe": engine_exe(eng), "args": qwen4_family.metal_engine_args(mp, ple_path, ctx, vision_ok), "cwd": str(ROOT), "tokenizer": str(mp["pack"] / "tokenizer"), "model_name": qwen4_family.model_key(model),
"arch": fam["arch"], "log": str(home() / f"strata-{tag.lower()}.log"), "lib_dirs": lib_dirs, "port": port, "drafting": "off", "backend": "metal", "env": dict(qwen4_family.METAL_ENV),
qwen4_family.EFFORT_CONFIG_KEY: effort, "thinking": "off" if effort == "off" else "on"}
if mtp_ok:
cfg[qwen4_family.MTP_CONFIG_KEY] = str(mp["mtp_rt"])
cfg[qwen4_family.MTP_MODE_KEY] = "on" if mtp_mode == "on" else "auto"
cfg[qwen4_family.MTP_SPEC_CONFIG_KEY] = qwen4_fit.mtp_spec_k((gpu or {}).get("name"), model, "metal")
if vision_ok: # pictures: strata-vision reads the converted mmproj with the Metal tower (the server adds --vision handling)
cfg["vision"] = qwen4_family.metal_vision_section(reader, mp, vision_tokens(getattr(a, "vision_tokens", None), "gpu", None))
if a.host:
cfg["host"] = a.host
if a.api_key:
cfg["api_key"] = a.api_key
if a.browser is not None:
cfg["open_browser"] = a.browser
cfg_path = home() / f"strata-{tag.lower()}.json"
write_setup_config(cfg_path, cfg, adopted if adopted is not None and adopted.name == cfg_path.name else None, explicit_args(a))
script = write_run_script(tag, cfg_path, port, cfg.get("open_browser") is not False)
ok(f"start script: {script.name}")
say()
say("All set.")
say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: {qwen4_family.FAMILY})")
say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages")
say(f" Effort: {qwen4_family.EFFORT_WORDS[effort]} by default (how much it thinks; a request can ask the other way); change it with --effort off|low|high|xhigh")
say(f" Next time: just run ./setup.sh (or {script.name}) - it starts right away")
if a.no_start:
return 0
return start(cfg_path, port)
def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
"""Steps 2-7 for Qwen Qwen4-35B-A3B (QWEN4_FAMILIES): the build (recommended by strata_control/qwen4_fit.py for this PC's video memory and RAM, any build can be chosen), the PLE table
(Q4, or Q8_0 when the RAM allows; --ple), the context, the engine of the shape q4_lite (component strata-q4-lite, fetched through the signed feed like a model shape's), the files
@@ -11670,7 +11870,7 @@ def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
mtp_mode = qwen4_mtp_mode(a)
effort = qwen4_effort(a)
ple_asked = qwen4_ple_choice(a)
rec = qwen4_fit.recommend(vram_gib, ram_gib, unified=unified)
rec = qwen4_fit.recommend(vram_gib, ram_gib, unified=unified, backend=backend)
model = a.model
if model and model not in qwen4_family.ALL_BUILDS:
fail(f"{fam['title']} has no {a.model} model file", "choose: " + ", ".join(qwen4_family.ALL_BUILDS))
@@ -11680,7 +11880,7 @@ def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
else:
say()
say(" Builds (the PLE table and the other small files come with every one):")
for i, r in enumerate(qwen4_fit.rows(vram_gib, ram_gib, unified=unified), 1):
for i, r in enumerate(qwen4_fit.rows(vram_gib, ram_gib, unified=unified, backend=backend), 1):
say(f" {i}) {r['build']:9s} {qwen4_family.BUILD_ABOUT[r['build']]}; download {r['download_gb']:.0f} GB <- {qwen4_fit.MODE_WORDS[r['mode']]}"
+ (" (recommended)" if r["recommended"] else ""))
for i, g in enumerate(qwen4_family.GGUF_BUILDS, len(qwen4_family.BUILDS) + 1): # the fourth build is offered, never recommended
@@ -11694,10 +11894,10 @@ def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
if mtp_mode == "auto" and not qwen4_fit.mtp_auto_on(vram_gib, unified, model, (gpu or {}).get("name")): # MTP Auto: on for a card of 6 GB or more and a unified pool, off below (qwen4_fit.MTP_AUTO_*)
mtp_mode = "off"
say(" " + qwen4_fit.mtp_auto_note(vram_gib, (gpu or {}).get("name")))
if model in qwen4_family.BUILDS and (vision or mtp_mode != "off") and not (qwen4_family.vision_ready(model) and qwen4_family.mtp_ready(model)):
if not qwen4_family.vision_ready(model): # a .strata build: the engine takes neither --vision nor --mtp yet (it would exit 2): no flag, no key, no file
if model in qwen4_family.BUILDS and (vision or mtp_mode != "off") and not (qwen4_family.vision_ready(model, backend) and qwen4_family.mtp_ready(model, backend)):
if not qwen4_family.vision_ready(model, backend): # a .strata build on the standalone host: the engine takes neither --vision nor --mtp yet (it would exit 2): no flag, no key, no file
vision = False
if not qwen4_family.mtp_ready(model):
if not qwen4_family.mtp_ready(model, backend):
mtp_mode = "off"
say(" " + qwen4_family.STRATA_COMING_NOTE)
ctx = a.context or qwen4_family.DEFAULT_CONTEXT
@@ -11717,6 +11917,9 @@ def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
if qwen4_family.is_gguf_build(model): # the fourth build: Unsloth's GGUF, prepared at install (its own steps 2-7 below)
return install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, model=model, ctx=ctx, tag=tag, folder=folder, own=own, backend=backend, vram_gib=vram_gib, ram_gib=ram_gib,
unified=unified, vision=vision, mtp_mode=mtp_mode, effort=effort, loop_on=loop_on, ple_asked=ple_asked, kv=kv)
if qwen4_family.uses_metal_converter(model, backend): # a .strata tier on a Mac: converted at install, runs on `strata` (Q4-METAL's flow: install_qwen4_metal)
return install_qwen4_metal(a, family, fam, gpu, port, adopted, model=model, ctx=ctx, tag=tag, folder=folder, own=own, vram_gib=vram_gib, ram_gib=ram_gib, unified=unified, mtp_mode=mtp_mode,
effort=effort, ple_asked=ple_asked, kv=kv, vision=vision)
local_native = None
if own and Path(a.gguf_dir).is_file() and Path(a.gguf_dir).suffix.lower() == ".strata" and Path(a.gguf_dir).name not in qwen4_family.FILES:
local_native = Path(a.gguf_dir) # the person's own .strata (a fine-tune or another build): used as it is, never hash-checked
+34 -1
View File
@@ -142,6 +142,37 @@ def model_files(folder: Path, family: str, family_def: dict | None = None) -> li
return find_shards(folder) or (find_single(folder) if (family_def or {}).get("feed") else [])
def _qwen4_metal_plan(folder: Path, build: str, model_name: str, context: int, kv: str | None, log: Path, src: Path, data_dir: Path, ple: str | None, backend: str | None) -> tuple[dict | None, list[str]]:
"""(config, problems) for a .strata tier on a Mac: the files the Mac install made under <models>/qwen4-35b-a3b/metal/<tier>/ (the converted GGUF, the pack, the neutral profile, the MTP runtime when
there is one), the PLE table beside the .strata, the engine arguments of qwen4_family.metal_engine_args, the environment the recipe wants. No pictures, no Loop (coming)."""
from strata_control import qwen4_family
paths = qwen4_family.metal_paths(folder, build)
places = [folder, Path(data_dir) / "models" / qwen4_family.FAMILY]
problems: list[str] = []
for key, what in (("gguf", "the converted model"), ("profile", "the expert profile")):
if not paths[key].is_file():
problems.append(f"{paths[key].name} ({what}) is not in {paths['dir']}: setup makes it from the .strata file")
if not (paths["pack"] / "native_experts.txt").is_file():
problems.append(f"the pack {paths['pack']} is not made yet: setup makes it from the converted model")
tokenizer = paths["pack"] / "tokenizer"
if not any((tokenizer / n).is_file() for n in ("vocab.json", "tokenizer.json", "tiktoken.model")):
problems.append(f"the tokenizer {tokenizer} is missing")
ple_kind = "Q8" if str(ple or "").upper() == "Q8" else "Q4"
ple_path = next((p for p in (qwen4_family.find_file(qwen4_family.PLE_FILES[k], None, places) for k in ((ple_kind, "Q4") if ple_kind == "Q8" else ("Q4", "Q8"))) if p is not None), None)
if ple_path is None:
problems.append(f"the PLE table ({qwen4_family.PLE_FILES['Q4']}) is not beside the model in {folder}")
if problems:
return None, problems
cfg = {"exe": qwen4_family.exe_reference(build, backend), "args": qwen4_family.metal_engine_args(paths, ple_path, context), "cwd": str(src), "tokenizer": str(tokenizer),
"model_name": model_name, "arch": qwen4_family.ARCH, "log": str(log), "lib_dirs": [], "port": 8080, "drafting": "off", "backend": "metal",
"env": dict(qwen4_family.METAL_ENV), qwen4_family.EFFORT_CONFIG_KEY: qwen4_family.DEFAULT_EFFORT, "thinking": "off" if qwen4_family.DEFAULT_EFFORT == "off" else "on"}
if (paths["mtp_rt"] / "dense.bin").is_file() or paths["mtp_gguf"].is_file(): # the drafter (Auto / On / Off decide at the start; serve adds --mtp <rt>)
cfg[qwen4_family.MTP_CONFIG_KEY] = str(paths["mtp_rt"])
cfg[qwen4_family.MTP_MODE_KEY] = qwen4_family.DEFAULT_MTP_MODE
cfg[qwen4_family.MTP_SPEC_CONFIG_KEY] = int(qwen4_family.METAL_SPEC_ARGS[1])
return cfg, []
def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path, context: int, kv: str | None, model_name: str, family_def: dict,
log: Path, backend: str | None, vram_gb: float = 0.0, notes: list | None = None, pack_name: str | None = None,
drafting: str | None = None, platform: str | None = None, ram_gb: float = 0.0, pin_half: bool | None = None, ple: str | None = None, loop: str | None = None) -> tuple[dict | None, list[str]]:
@@ -303,7 +334,7 @@ def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path,
except OSError:
profile = None
# pictures need the strata-vision program of the engine package, which only setup places in the config (its "vision" section): a re-adopted config starts without them
args = qwen4_family.gguf_engine_args(trunk, shard2, pack=pack if pack.is_dir() else None, profile=profile, mtp_rt=None, vision=None, ctx=context)
args = qwen4_family.gguf_engine_args(trunk, shard2, pack=pack if pack.is_dir() else None, profile=profile, mtp_rt=None, vision=None, ctx=context, vram_gb=vram_gb or None, ram_gb=ram_gb or None)
cfg = {"exe": qwen4_family.exe_reference(qwen4_family.GGUF_BUILD), "args": args, "cwd": str(src), "tokenizer": str(tokenizer),
"model_name": model_name, "arch": qwen4_family.ARCH, "log": str(log), "lib_dirs": [], "port": 8080,
"drafting": "off", qwen4_family.EFFORT_CONFIG_KEY: qwen4_family.DEFAULT_EFFORT, "thinking": "off" if qwen4_family.DEFAULT_EFFORT == "off" else "on"}
@@ -328,6 +359,8 @@ def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path,
native = shards[0]
build = qwen4_family.build_of_file(native) or (model if model in qwen4_family.MODEL_FILES else qwen4_family.DEFAULT_BUILD)
folder = native.parent
if qwen4_family.uses_metal_converter(build, backend): # a .strata tier on a Mac: the converted GGUF, the pack and the neutral profile setup made beside the files (strata_control/qwen4_family.py METAL_*)
return _qwen4_metal_plan(folder, build, model_name, context, kv, log, src, data_dir, ple, backend)
tag = (pack_name or (qwen4_family.TAG + build)).lower()
tokenizer = Path(data_dir) / "packs" / tag / "tokenizer"
if not any((tokenizer / n).is_file() for n in ("vocab.json", "tokenizer.json", "tiktoken.model")):
+1 -1
View File
@@ -163,7 +163,7 @@ def assess(catalog, family: str | None, model: str | None, *, vision: str = "off
mtp = mtp_choice(mtp, drafting)
if family == "qwen4-35b-a3b": # a .strata build: the engine takes no MTP yet (qwen4_family.mtp_ready), so no sidecar is a part of it
from strata_control import qwen4_family as _q4
if model in _q4.BUILDS and not _q4.mtp_ready(model):
if model in _q4.BUILDS and not _q4.mtp_ready(model, backend):
mtp = "off"
pool = (rows if rows is not None else catalog.rows()) if (family and model) else []
row = (next((r for r in pool if custom_id and getattr(r, "custom", False) and r.id == custom_id), None)
+2 -2
View File
@@ -918,7 +918,7 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str]
cfg["thinking"] = "off" if effort == "off" else "on" # the plain switch beside it (an older serve reads only this one)
cfg.pop("mtp", None)
q4_build = qwen4_family.build_of_model_name(cfg.get("model_name")) or qwen4_family.build_of_file(qwen4_family.model_arg(cfg.get("args")))
mtp_word = s.mtp if qwen4_family.mtp_ready(q4_build) else "off" # a .strata build: the engine takes no MTP yet, so no key (STRATA_BUILD_FLAG_READY)
mtp_word = s.mtp if qwen4_family.mtp_ready(q4_build, cfg.get("backend")) else "off" # a .strata build on the standalone host: the engine takes no MTP yet, so no key (STRATA_BUILD_FLAG_READY); on a Mac it does
if mtp_word == "off":
cfg.pop(qwen4_family.MTP_CONFIG_KEY, None)
cfg.pop(qwen4_family.MTP_MODE_KEY, None)
@@ -941,7 +941,7 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str]
found_loop = qwen4_family.find_file(qwen4_family.LOOP_FILE, qwen4_family.model_arg(cfg.get("args")))
if found_loop is not None:
cfg[qwen4_family.LOOP_CONFIG_KEY] = str(found_loop)
if isinstance(cfg.get("args"), list) and (s.vision in ("off", "no") or not qwen4_family.vision_ready(q4_build)): # pictures: off (or a .strata build, whose engine reads none yet) takes the Vision flag out of this start
if isinstance(cfg.get("args"), list) and (s.vision in ("off", "no") or not qwen4_family.vision_ready(q4_build, cfg.get("backend"))): # pictures: off (or a .strata build, whose engine reads none yet) takes the Vision flag out of this start
cargs = [str(a) for a in cfg["args"]]
vflag = qwen4_family.ENGINE_FILE_FLAGS["vision"]
while vflag in cargs:
+7 -4
View File
@@ -555,10 +555,13 @@ def check_qwen4(s: LaunchSettings, *, vram_gb: float | None, ram_gb: float | Non
if (s.mtp in (None, "auto")) and not qwen4_fit.mtp_auto_on(vram_gb, bool(unified), adv.get("build"), ((cards or [{}])[0] or {}).get("name")): # MTP Auto resolves to off here
out.append(Notice("warn", qwen4_fit.mtp_auto_note(vram_gb, ((cards or [{}])[0] or {}).get("name")), ""))
if adv.get("build") in qwen4_family.BUILDS: # a .strata build: the engine has no MTP, pictures or server mode yet (qwen4_family.STRATA_BUILD_FLAG_READY)
if not (qwen4_family.mtp_ready(adv["build"]) and qwen4_family.vision_ready(adv["build"])):
out.append(Notice("warn", qwen4_family.STRATA_COMING_NOTE, ""))
if not qwen4_family.strata_serve_ready():
out.append(Notice("warn", qwen4_family.STRATA_SERVE_NOTE, ""))
if qwen4_family.uses_metal_converter(adv["build"], backend): # a Mac: the draft layer and pictures work (the conversions run at install)
pass
else:
if not (qwen4_family.mtp_ready(adv["build"], backend) and qwen4_family.vision_ready(adv["build"])):
out.append(Notice("warn", qwen4_family.STRATA_COMING_NOTE, ""))
if qwen4_family.uses_standalone_host(adv["build"], backend) and not qwen4_family.strata_serve_ready():
out.append(Notice("warn", qwen4_family.STRATA_SERVE_NOTE, ""))
if s.loop == "on":
from strata_control import qwen4_family
if s.custom_id or s.model_path and qwen4_family.build_of_file(s.model_path) is None:
+128 -12
View File
@@ -45,11 +45,34 @@ EXE = program_file(GGUF_PROGRAM) # the GGUF build's
STRATA_EXE = program_file(STRATA_PROGRAM)
def exe_reference(build=None) -> str:
"""The run config's `exe` of a build: "component:strata-q4-lite" for the GGUF build (the component's own program, `strata`: byte-identical to what setup wrote before),
"component:strata-q4-lite/strata-q4-lite" for the .strata builds (the same folder, the standalone host)."""
#: THE program table: which program of the component a build runs on, by (source, backend). The GGUF build and every Mac build run on `strata` (the qwen4exp engine at q4_lite: on a Mac the
#: .strata tiers are converted to a dense GGUF plus the .strata experts, see METAL_* below); the .strata tiers on NVIDIA and AMD run on the standalone host `strata-q4-lite`.
PROGRAM_BY_SOURCE_BACKEND = {("strata", "cuda"): STRATA_PROGRAM, ("strata", "hip"): STRATA_PROGRAM, ("strata", "metal"): GGUF_PROGRAM,
("gguf", "cuda"): GGUF_PROGRAM, ("gguf", "hip"): GGUF_PROGRAM, ("gguf", "metal"): GGUF_PROGRAM}
def program_for(build=None, backend=None) -> str:
"""The program of the component this build runs on for this backend (no backend means cuda; an unknown build is the GGUF build's `strata`)."""
src = "strata" if build in BUILDS else "gguf"
return PROGRAM_BY_SOURCE_BACKEND.get((src, str(backend or "cuda").lower()), GGUF_PROGRAM)
def uses_standalone_host(build=None, backend=None) -> bool:
"""Does this build run on the standalone `strata-q4-lite` (a .strata tier on NVIDIA or AMD)? False for the GGUF build and for every build on a Mac."""
return program_for(build, backend) == STRATA_PROGRAM
def uses_metal_converter(build=None, backend=None) -> bool:
"""Is this build a .strata tier on a Mac (converted at install: METAL_* below, runs on `strata`)?"""
return build in BUILDS and str(backend or "").lower() == "metal"
def exe_reference(build=None, backend=None) -> str:
"""The run config's `exe` of a build: "component:strata-q4-lite" for a build that runs on the component's own program `strata` (the GGUF build, and every build on a Mac: byte-identical to what
setup wrote before), "component:strata-q4-lite/strata-q4-lite" for a .strata tier on NVIDIA or AMD (the same folder, the standalone host)."""
from strata_control import engine_component as ec
return ec.program_reference(COMPONENT, "" if is_gguf_build(build) or build not in BUILDS else STRATA_PROGRAM)
program = program_for(build, backend)
return ec.program_reference(COMPONENT, "" if program == GGUF_PROGRAM else program)
def program_of(exe) -> str:
@@ -211,6 +234,9 @@ STRATA_BUILD_FLAGS = {"model": "--model", "ple": "--ple-gguf", "ctx": "--max-ctx
#: which flags the strata-q4-lite engine takes today (CORE-API.md section 0): flip each to True when CORE-API.md / `strata-q4-lite --version` says it is there. mtp (+ --spec K): the MTP worker, ETA
#: 11:30; vision: after text + Loop; loop: Q4-LOOP's strata spelling `--loop 2 --loop-file PATH`; serve: the engine's `--serve` (SHIP worker), without which a strata build cannot be started by Strata.
STRATA_BUILD_FLAG_READY = {"model": True, "ple": True, "ctx": True, "device": True, "mtp": False, "vision": False, "loop": False, "serve": True}
#: what a .strata tier takes on a Mac (Metal): converted at install and run on `strata` (qwen4exp), so the draft layer (`--mtp <rt> --spec 2`) and pictures (Vision.strata converted to the mmproj, the Metal
#: tower) work today; Loop is coming (LOOP_READY). ONE table, mirrored in app/host/server/qwen4.mjs and src/lib/qwen4.ts (the host test parses this dict and pins the three).
STRATA_METAL_READY = {"mtp": True, "vision": True, "loop": False}
STRATA_SPEC_ARGS = ["--spec", "4"] # with --mtp PATH on a strata build (K is the engine's to confirm; only written when STRATA_BUILD_FLAG_READY["mtp"])
STRATA_LOOP_PASSES = "2" # `--loop 2`
STRATA_LOOP_FLAGS = (STRATA_BUILD_FLAGS["loop"], STRATA_BUILD_FLAGS["loop_file"])
@@ -226,15 +252,22 @@ STRATA_GEN_KEYS = ("temperature", "top_p", "top_k", "min_p", "seed", "penalty_re
STRATA_TOP_K_CAP = 64
STRATA_COMING_NOTE = "Coming with the engine: the draft layer (MTP) and picture reading are not in the engine for this build yet. They stay off for now."
STRATA_SERVE_NOTE = "The engine's server mode is not in this build yet: this build starts when the engine for it is updated."
METAL_COMING_NOTE = "Picture reading is off for this build on this Mac: the tool that prepares it is not in this Strata, or it did not finish. Everything else works."
def mtp_ready(build) -> bool:
"""Does the engine take the MTP sidecar for this build? The GGUF build: yes (its drafter runtime); a .strata build: STRATA_BUILD_FLAG_READY["mtp"] (not yet)."""
def mtp_ready(build, backend=None) -> bool:
"""Does the engine take the MTP sidecar for this build? The GGUF build: yes (its drafter runtime); a .strata tier on a Mac: yes (the Metal drafter, `--mtp <rt> --spec 2`, Q4-METAL); a .strata
tier on the standalone host: STRATA_BUILD_FLAG_READY["mtp"] (not yet)."""
if uses_metal_converter(build, backend):
return bool(STRATA_METAL_READY["mtp"])
return True if build in GGUF_BUILDS else bool(STRATA_BUILD_FLAG_READY["mtp"]) if build in BUILDS else False
def vision_ready(build) -> bool:
"""Does the engine read pictures for this build? The GGUF build: yes (strata-vision with the mmproj); a .strata build: STRATA_BUILD_FLAG_READY["vision"] (not yet)."""
def vision_ready(build, backend=None) -> bool:
"""Does the engine read pictures for this build? The GGUF build: yes (strata-vision with the mmproj); a .strata tier on a Mac: yes (Vision.strata converted to the mmproj, the Metal tower);
a .strata tier on the standalone host: STRATA_BUILD_FLAG_READY["vision"] (not yet)."""
if uses_metal_converter(build, backend):
return bool(STRATA_METAL_READY["vision"])
return True if build in GGUF_BUILDS else bool(STRATA_BUILD_FLAG_READY["vision"]) if build in BUILDS else False
@@ -320,6 +353,69 @@ def gguf_spec_args(k=None) -> list[str]:
GGUF_ABOUT = "Unsloth's UD-Q4_K_XL GGUF of the model, community-supported (the same engine reads it); setup prepares it for the engine, which takes a few minutes"
# ---- the Mac install of the .strata tiers (Q4-METAL, INT #36): the tier's dense half is converted to a qwen4exp GGUF, the routed experts stay in the .strata (read through the key qwen4exp.strata_experts),
#: and the engine is `strata` (Metal). Everything is made once, under the tier's own folder D = <models>/qwen4-35b-a3b/metal/<tier>/:
#: D/<Tier>.gguf qwen4_strata_to_gguf.py --strata <Tier>.strata --hf-dir D/hf --ple-gguf <PLE> --out D/<Tier>.gguf (the .strata must stay where it is: its path is in the GGUF)
#: D/mtp/mtp-q2_0.gguf qwen4_mtp_strata_to_gguf.py --strata MTP.strata --out D/mtp/mtp-q2_0.gguf and the folder D/mtp/rt (the engine reads the GGUF next to the rt folder it is given)
#: D/pack/ iq_pack.py --gguf D/<Tier>.gguf --out D/pack --compat-bf16, then qwen4_strata_pack_fix.py D/pack
#: D/profile.bin the neutral 40 x 256 expert profile (the same STRP bytes as write_uniform_profile)
#: D/hf/ the layout the converter reads: tokenizer-compat/{tokenizer.json, tokenizer_config.json, chat_template.jinja} and generation_config.json
#: D/vision/mmproj-Qwen4-35B-A3B-Vision.gguf qwen4_vision_strata_to_gguf.py --strata Qwen4-35B-A3B-Vision.strata --out <that file> (about 1 s, 0.9 GB, tensor-identical to Unsloth's mmproj-BF16.gguf, so the
#: existing picture reader takes it: the config's "vision" section {exe: strata-vision, mmproj, model: D/<Tier>.gguf, gpu: true} and a bare --vision in the engine args)
METAL_TOOLS = {"to_gguf": "tools/qwen4_strata_to_gguf.py", "mtp_to_gguf": "tools/qwen4_mtp_strata_to_gguf.py", "pack_fix": "tools/qwen4_strata_pack_fix.py", "iq_pack": "tools/iq_pack.py",
"vision_to_gguf": "tools/qwen4_vision_strata_to_gguf.py"}
METAL_VISION_GGUF = "mmproj-Qwen4-35B-A3B-Vision.gguf"
METAL_SUBDIR = "metal" # <models>/qwen4-35b-a3b/metal/<tier>/
METAL_MTP_GGUF = "mtp-q2_0.gguf"
METAL_PROFILE_FILE = "profile.bin"
#: the engine's start line on a Mac (Q4-METAL): strata --pack D/pack --native D/<Tier>.gguf --native-dense-gguf D/<Tier>.gguf --ple-gguf <PLE> --expert-profile D/profile.bin --expert-cache 64
#: --mmap-experts --prefill auto --spec 2 [--mtp D/mtp/rt] --max-context N; the environment below is part of the recipe (measured on an M5 Max).
METAL_RUN_ARGS = ["--expert-cache", "64", "--mmap-experts", "--prefill", "auto"]
METAL_SPEC_ARGS = ["--spec", "2"]
METAL_ENV = {"STRATA_METAL_STREAM": "0", "STRATA_HC_Q8": "0", "STRATA_PREFILL_CPU_SHARE": "0"}
#: the tokenizer files the converter reads, by name, and where each sits in its HF directory (the repo's tokenizer/ folder is flat, the converter wants tokenizer-compat/ for three of them)
HF_DIR_LAYOUT = {"tokenizer.json": "tokenizer-compat/tokenizer.json", "tokenizer_config.json": "tokenizer-compat/tokenizer_config.json",
"chat_template.jinja": "tokenizer-compat/chat_template.jinja", "generation_config.json": "generation_config.json"}
def metal_paths(models_folder, build: str) -> dict:
"""Every file of the Mac install of one tier, as paths: {"dir", "gguf", "pack", "profile", "mtp_dir", "mtp_gguf", "mtp_rt", "hf"}."""
d = Path(models_folder) / METAL_SUBDIR / build.lower()
return {"dir": d, "gguf": d / (build + ".gguf"), "pack": d / "pack", "profile": d / METAL_PROFILE_FILE, "mtp_dir": d / "mtp", "mtp_gguf": d / "mtp" / METAL_MTP_GGUF,
"mtp_rt": d / "mtp" / "rt", "hf": d / "hf", "vision_dir": d / "vision", "mmproj": d / "vision" / METAL_VISION_GGUF}
def metal_engine_args(paths: dict, ple, ctx=None, vision: bool = False) -> list[str]:
"""The engine's arguments of a .strata tier on a Mac: the converted GGUF as trunk and dense half, the pack, the PLE table, the neutral profile, `--spec 2`. The MTP runtime is NOT here: it is the run
config's `qwen4_mtp` key (serve adds `--mtp <rt>` at the start, so Auto / On / Off decide). NEVER a `--kv`: the Metal window keeps the K/V cache in int8 only and ignores the flag (Q4-METAL).
`vision`: the bare `--vision` (the picture reader itself is the config's "vision" section, metal_vision_section), like the GGUF build and Flash-Next."""
out = ["--pack", str(paths["pack"]), "--native", str(paths["gguf"]), "--native-dense-gguf", str(paths["gguf"]), "--ple-gguf", str(ple), "--expert-profile", str(paths["profile"]), *METAL_RUN_ARGS,
*METAL_SPEC_ARGS]
if vision:
out += ["--vision"]
if ctx:
out += ["--max-context", str(int(ctx))]
return out
def metal_vision_section(reader, paths: dict, max_tokens: int) -> dict:
"""The run config's "vision" section of a Mac tier: the picture reader program `strata-vision` of the engine package, the mmproj converted from Vision.strata, the converted model (opened vocab-only)
and the Metal tower on (`gpu`: true is the Mac build's default)."""
return {"exe": str(reader), "mmproj": str(paths["mmproj"]), "model": str(paths["gguf"]), "gpu": True, "max_tokens": int(max_tokens)}
def build_hf_dir(found: dict, hf) -> Path:
"""The directory the converter reads, made from the flat tokenizer files: `found` is {file name: path}; each is copied to its place in HF_DIR_LAYOUT under `hf` (a copy already there is kept)."""
import shutil
hf = Path(hf)
for name, rel in HF_DIR_LAYOUT.items():
dst = hf / rel
if not dst.is_file():
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(found[name], dst)
return hf
# ---- the K/V cache format (owner 2026-12-04; Q4-KV's measurements on UD-Q4_K_XL, A6000, 36 probes, KL against fp16: int8 0.0070, k8v4 0.0101, q4_0 0.0113; int8 prefill at 32K 3604 tok/s against 2841) ----
#: ONE table per source: the formats the engine takes for the GGUF build (qwen4exp engine) and for the .strata builds (the standalone strata-q4-lite host allocates fp16 for --max-ctx: no flag). The
#: .strata list gains a word when Q4-KV reports a --kv-style flag. k8v8 is not offered. The memory per format is qwen4_fit.KV_BYTES_PER_TOKEN.
@@ -385,8 +481,24 @@ def write_uniform_profile(path, n_layer: int = 40, n_expert: int = 256) -> None:
f.write(struct.pack("<%di" % n_expert, *table[l]))
def gguf_engine_args(trunk, ple_shard, *, pack=None, profile=None, mtp_rt=None, vision=None, loop=None, ctx=None, kv=None, spec_k=None) -> list[str]:
"""The engine's arguments of the GGUF build: --native trunk40.gguf --native-dense-gguf trunk40.gguf --ple-gguf <shard 2>, plus --mtp <rt> --spec 4 when the sidecar is on."""
#: Qwen4's KV is small (10 attention layers, 2 KV heads: 0.67 GiB at 32K in fp16, 2.7 GiB at 128K), so streaming it to RAM does not pay below 64K: measured on an A6000 held to a 12 GB budget,
#: UD-Q4_K_XL at 32K, --kv-resident 16384 gave 160 more expert slots (3,660 to 3,820) but cost 17 % of the prefill speed (2,719 to 2,243 tok/s, fp16 K/V). The Unsloth rule applies from 64K up.
KV_RESIDENT_MIN_CTX = 65536
def kv_resident_args(vram_gb, ram_gb, ctx, *, unified: bool = False, kv: str = "fp16") -> list[str]:
"""Q4-ELASTIC: the elastic KV of the Unsloth quants (#6354, gpu_fit.unsloth_kv_resident_default): on a discrete card with at least 16 GB of RAM the older KV pages of a long context
stream to pinned RAM (`--kv-resident N`), so the card's memory stays with the expert cache. Nothing when the card or the RAM is unknown, on a unified-memory PC, or below 64K."""
if not vram_gb or not ram_gb or not ctx or int(ctx) < KV_RESIDENT_MIN_CTX:
return []
from strata_control import gpu_fit
n = gpu_fit.unsloth_kv_resident_default(float(vram_gb), float(ram_gb), int(ctx), kv=kv, uma=bool(unified))
return ["--kv-resident", str(int(n))] if n else []
def gguf_engine_args(trunk, ple_shard, *, pack=None, profile=None, mtp_rt=None, vision=None, loop=None, ctx=None, kv=None, spec_k=None, vram_gb=None, ram_gb=None, unified: bool = False) -> list[str]:
"""The engine's arguments of the GGUF build: --native trunk40.gguf --native-dense-gguf trunk40.gguf --ple-gguf <shard 2>, plus --mtp <rt> --spec 4 when the sidecar is on,
and --kv-resident N (the elastic KV) when the card and the RAM are given and the context is 64K or more (kv_resident_args)."""
out = (["--pack", str(pack)] if pack else []) + ["--native", str(trunk), "--native-dense-gguf", str(trunk), "--ple-gguf", str(ple_shard)]
if profile:
out += ["--expert-profile", str(profile)]
@@ -398,6 +510,7 @@ def gguf_engine_args(trunk, ple_shard, *, pack=None, profile=None, mtp_rt=None,
out += (([ENGINE_FILE_FLAGS["mtp"], str(mtp_rt)] + gguf_spec_args(spec_k)) if mtp_rt else GGUF_PLAIN_SPEC)
if ctx:
out += ["--max-context", str(int(ctx))]
out += kv_resident_args(vram_gb, ram_gb, ctx, unified=unified, kv=kv if kv in KV_CHOICES["gguf"] else KV_DEFAULT["gguf"])
return out
#: every file the family knows (any build, the PLE tables, the sidecar, the Vision shard, the Loop file)
@@ -495,10 +608,13 @@ def engine_args(model: str | os.PathLike, *, ple: str | os.PathLike | None = Non
return out
def mtp_engine_args(mtp: str | os.PathLike | None, mode: str | None = "auto", gguf: bool = False, spec_k=None) -> list[str]:
"""The sidecar's flags for a start: nothing for off or no file; `--mtp FILE` for auto and on (the engine's own rule decides in auto, as for the other speculative sidecars). PROVISIONAL (see ENGINE_FILE_FLAGS)."""
def mtp_engine_args(mtp: str | os.PathLike | None, mode: str | None = "auto", gguf: bool = False, spec_k=None, metal: bool = False) -> list[str]:
"""The sidecar's flags for a start: nothing for off or no file; `--mtp FILE` for auto and on (the engine's own rule decides in auto, as for the other speculative sidecars). PROVISIONAL (see ENGINE_FILE_FLAGS).
On a Mac (`metal`, a .strata tier): `--mtp <rt>` only, the depth stays the `--spec 2` already in the arguments (Q4-METAL's measurements)."""
if not mtp or str(mode or "auto").lower() == "off":
return []
if metal:
return [ENGINE_FILE_FLAGS["mtp"], str(mtp)]
if not gguf: # a .strata build: the engine's own spelling, only when it takes it (STRATA_BUILD_FLAG_READY["mtp"])
return [STRATA_BUILD_FLAGS["mtp"], str(mtp), *STRATA_SPEC_ARGS] if STRATA_BUILD_FLAG_READY["mtp"] else []
return [ENGINE_FILE_FLAGS["mtp"], str(mtp)] + gguf_spec_args(spec_k)
+55 -25
View File
@@ -144,19 +144,35 @@ def build_for_vram(vram_gib: float | None) -> str:
return best
def build_for_pool(pool_gib: float | None, ctx: int | None = None) -> str:
"""The build of a unified-memory pool (Mac, DGX Spark): the largest whose model plus its PLE table (Q4) plus the work and K/V memory fit what the pool keeps after UMA_RESERVE_GIB."""
#: ---- a .strata tier on a Mac (Q4-METAL): the tier's dense half is converted to a GGUF (Q8_0: 3.6 GB for Compact and Balanced, BF16: 5.7 GB for Ultra), the routed experts are read from the .strata
#: itself (about 8 GB for Compact: the file less its trunk, mapped) and the PLE table is read from the disk, so it does not count in the pool. ESTIMATE for Balanced and Ultra (Q4-METAL gave Compact).
STRATA_TRUNK_BYTES = int(2.6 * GIB) # the dense trunk inside a .strata (CORE-API.md: 2.6 GiB), replaced on a Mac by the converted dense GGUF
METAL_DENSE_BYTES = {"Compact": 3_600_000_000, "Balanced": 3_600_000_000, "Ultra": 5_700_000_000}
METAL_STRATA_DISK_EXTRA_GB = {"Compact": 3.6, "Balanced": 3.6, "Ultra": 5.7} # the converted dense GGUF written beside the download (plus the small MTP GGUF and the pack: under 1 GB)
def metal_pool_gib(build: str, ctx: int | None = None, mtp: bool = False, kv: str | None = None) -> float:
"""What a .strata tier keeps in the Mac's one memory pool (GiB): the experts of the .strata (its file less its trunk), the converted dense GGUF, the MTP sidecar when on, the K/V memory of `ctx` and the work memory."""
n = BUILD_BYTES[build] - STRATA_TRUNK_BYTES + METAL_DENSE_BYTES[build] + (MTP_BYTES if mtp else 0)
return n / GIB + kv_gib(ctx, kv=kv) + WORK_GIB
def build_for_pool(pool_gib: float | None, ctx: int | None = None, metal: bool = False) -> str:
"""The build of a unified-memory pool (Mac, DGX Spark): the largest whose model plus its PLE table (Q4) plus the work and K/V memory fit what the pool keeps after UMA_RESERVE_GIB. `metal`: the Mac's
.strata tiers (metal_pool_gib: the PLE table is read from the disk)."""
free = float(pool_gib or 0.0) - UMA_RESERVE_GIB
best = "Compact"
for b in ORDER:
if weights_gib(b) + ple_gib("Q4") + WORK_GIB + kv_gib(ctx) <= free:
if (metal_pool_gib(b, ctx) if metal else weights_gib(b) + ple_gib("Q4") + WORK_GIB + kv_gib(ctx)) <= free:
best = b
return best
def ple_for(build: str, ram_gib: float | None, vram_gib: float | None = None, *, unified: bool = False, pool_gib: float | None = None, ctx: int | None = None) -> str:
def ple_for(build: str, ram_gib: float | None, vram_gib: float | None = None, *, unified: bool = False, pool_gib: float | None = None, ctx: int | None = None, metal: bool = False) -> str:
"""The PLE table: Q4 unless the memory also holds Q8_0. A discrete card: the RAM must hold the Q8_0 table, the experts that spill (none when the build fits the card) and the system, with
PLE_Q8_RAM_EXTRA_GIB over. A unified pool: the pool must hold the model, Q8_0, the work and K/V memory, and UMA_RESERVE_GIB."""
PLE_Q8_RAM_EXTRA_GIB over. A unified pool: the pool must hold the model, Q8_0, the work and K/V memory, and UMA_RESERVE_GIB. A .strata tier on a Mac reads the table from the disk: Q4 (the smaller download)."""
if metal:
return "Q4"
if unified:
free = float(pool_gib or ram_gib or 0.0) - UMA_RESERVE_GIB
return "Q8" if weights_gib(build) + ple_gib("Q8") + WORK_GIB + kv_gib(ctx) <= free else "Q4"
@@ -165,8 +181,11 @@ def ple_for(build: str, ram_gib: float | None, vram_gib: float | None = None, *,
return "Q8" if ram >= ple_gib("Q8") + spill + OS_RESERVE_GIB + PLE_Q8_RAM_EXTRA_GIB else "Q4"
def mode_of(build: str, vram_gib: float | None, ram_gib: float, ple: str = "Q4", *, unified: bool = False, ctx: int | None = None, vision: bool = False, mtp: bool = False, loop: bool = False, kv: str | None = None) -> str:
def mode_of(build: str, vram_gib: float | None, ram_gib: float, ple: str = "Q4", *, unified: bool = False, ctx: int | None = None, vision: bool = False, mtp: bool = False, loop: bool = False, kv: str | None = None,
metal: bool = False) -> str:
""""resident" / "hybrid" / "unified" / "short": where the build lives on this PC."""
if metal: # a .strata tier on a Mac: one pool, the PLE table read from the disk (metal_pool_gib)
return "unified" if metal_pool_gib(build, ctx, mtp, kv) <= float(vram_gib or ram_gib or 0.0) - UMA_RESERVE_GIB else "short"
if strata_below_floor(build, vram_gib, unified): # the standalone engine holds the whole build on the card today
return "short"
need = vram_need_gib(build, ctx, vision, mtp, loop, kv)
@@ -178,12 +197,13 @@ def mode_of(build: str, vram_gib: float | None, ram_gib: float, ple: str = "Q4",
return "hybrid" if float(ram_gib or 0.0) - OS_RESERVE_GIB >= ple_gib(ple) + spill else "short"
def recommend(vram_gib: float | None, ram_gib: float, *, unified: bool = False, ctx: int | None = None) -> dict:
"""{"build", "ple"}: what this PC gets by default (the rule above)."""
def recommend(vram_gib: float | None, ram_gib: float, *, unified: bool = False, ctx: int | None = None, backend: str | None = None) -> dict:
"""{"build", "ple"}: what this PC gets by default (the rule above). `backend` "metal": the Mac's .strata tiers (metal_pool_gib)."""
if unified:
pool = float(vram_gib or ram_gib or 0.0)
build = build_for_pool(pool, ctx)
return {"build": build, "ple": ple_for(build, ram_gib, vram_gib, unified=True, pool_gib=pool, ctx=ctx)}
metal = backend == "metal"
build = build_for_pool(pool, ctx, metal)
return {"build": build, "ple": ple_for(build, ram_gib, vram_gib, unified=True, pool_gib=pool, ctx=ctx, metal=metal)}
build = build_for_vram(vram_gib)
return {"build": build, "ple": ple_for(build, ram_gib, vram_gib, ctx=ctx)}
@@ -192,13 +212,16 @@ def advise(vram_gib: float | None, ram_gib: float, *, unified: bool = False, ctx
ple: str | None = None, vision: bool = True, mtp: bool = True, loop: bool = False, backend: str | None = None, kv: str | None = None) -> dict:
"""The whole answer for one PC: the chosen build and PLE table (the person's word wins over the rule), where it lives (`mode`), the files and the download, and the warnings.
{"build", "ple", "mode", "mode_words", "vram_need_gib", "ram_need_gib", "download_gb", "files", "warnings", "recommended": {"build", "ple"}}."""
rec = recommend(vram_gib, ram_gib, unified=unified, ctx=ctx)
metal = backend == "metal" and unified # a .strata tier on a Mac: converted at install, one pool, the PLE table read from the disk
rec = recommend(vram_gib, ram_gib, unified=unified, ctx=ctx, backend=backend)
b = build if build in BUILD_BYTES else rec["build"]
p = ple if ple in PLE_BYTES else (rec["ple"] if not build or b == rec["build"] else ple_for(b, ram_gib, vram_gib, unified=unified, pool_gib=vram_gib if unified else None, ctx=ctx))
mode = mode_of(b, vram_gib, ram_gib, p, unified=unified, ctx=ctx, vision=False, mtp=mtp, loop=loop, kv=kv)
need = vram_need_gib(b, ctx, False, mtp, loop, kv)
p = ple if ple in PLE_BYTES else (rec["ple"] if not build or b == rec["build"] else ple_for(b, ram_gib, vram_gib, unified=unified, pool_gib=vram_gib if unified else None, ctx=ctx, metal=metal))
mode = mode_of(b, vram_gib, ram_gib, p, unified=unified, ctx=ctx, vision=False, mtp=mtp, loop=loop, kv=kv, metal=metal)
need = metal_pool_gib(b, ctx, mtp, kv) if metal else vram_need_gib(b, ctx, False, mtp, loop, kv)
warnings: list[str] = []
if unified:
if metal:
ram_need = need + UMA_RESERVE_GIB
elif unified:
ram_need = need + ple_gib(p) + UMA_RESERVE_GIB
else:
spill = max(0.0, need - float(vram_gib or 0.0)) if vram_gib else need
@@ -214,7 +237,7 @@ def advise(vram_gib: float | None, ram_gib: float, *, unified: bool = False, ctx
if p == "Q8" and ple not in PLE_BYTES and mode == "short":
p = "Q4"
files = [model_file_of(b), ple_file_of(p)] + (["Qwen4-35B-A3B-Vision.strata"] if vision else []) + (["Qwen4-35B-A3B-MTP.strata"] if mtp else []) + (["Qwen4-35B-A3B-Loop.safetensors"] if loop else [])
dl = disk_gb(b, p, vision, mtp, loop)
dl = disk_gb(b, p, vision, mtp, loop) + (METAL_STRATA_DISK_EXTRA_GB[b] if metal else 0.0) # (a Mac also writes the converted dense GGUF)
if disk_free_gb is not None and disk_free_gb < dl + DISK_MARGIN_GB:
warnings.append(f"The download is {dl:.1f} GB and the disk has {disk_free_gb:.1f} GB free; free some space first.")
return {"build": b, "ple": p, "mode": mode, "mode_words": MODE_WORDS[mode], "vram_need_gib": round(need, 2), "ram_need_gib": round(ram_need, 2), "download_gb": round(dl, 2),
@@ -229,14 +252,16 @@ def ple_file_of(ple: str) -> str:
return {"Q4": "Qwen4-35B-A3B-PLE-Q4.gguf", "Q8": "Qwen4-35B-A3B-PLE-Q8_0.gguf"}[ple]
def rows(vram_gib: float | None, ram_gib: float, *, unified: bool = False, ctx: int | None = None) -> list[dict]:
"""One row per build for the menus: {"build", "ple", "mode", "fits", "recommended"}, smallest first."""
rec = recommend(vram_gib, ram_gib, unified=unified, ctx=ctx)
def rows(vram_gib: float | None, ram_gib: float, *, unified: bool = False, ctx: int | None = None, backend: str | None = None) -> list[dict]:
"""One row per build for the menus: {"build", "ple", "mode", "fits", "recommended"}, smallest first. `backend` "metal": the Mac's .strata tiers (one pool, the PLE table read from the disk)."""
metal = backend == "metal" and unified
rec = recommend(vram_gib, ram_gib, unified=unified, ctx=ctx, backend=backend)
out = []
for b in ORDER:
p = rec["ple"] if b == rec["build"] else ple_for(b, ram_gib, vram_gib, unified=unified, pool_gib=vram_gib if unified else None, ctx=ctx)
m = mode_of(b, vram_gib, ram_gib, p, unified=unified, ctx=ctx)
out.append({"build": b, "ple": p, "mode": m, "fits": m != "short", "recommended": b == rec["build"], "download_gb": round(disk_gb(b, p), 2)})
p = rec["ple"] if b == rec["build"] else ple_for(b, ram_gib, vram_gib, unified=unified, pool_gib=vram_gib if unified else None, ctx=ctx, metal=metal)
m = mode_of(b, vram_gib, ram_gib, p, unified=unified, ctx=ctx, metal=metal)
out.append({"build": b, "ple": p, "mode": m, "fits": m != "short", "recommended": b == rec["build"],
"download_gb": round(disk_gb(b, p) + (METAL_STRATA_DISK_EXTRA_GB[b] if metal else 0.0), 2)})
return out
@@ -368,13 +393,18 @@ MTP_SPEC_BY_CARD: dict = {}
MTP_SPEC_MIN_P = 0.5
def mtp_spec_k(card_name: str | None = None) -> int:
"""The K of `--spec K` for this card: a per-card override first, else MTP_SPEC_DEFAULT (3)."""
#: K by (source, backend) where it is not MTP_SPEC_DEFAULT: a .strata tier on a Mac keeps `--spec 2` with the drafter (Q4-METAL's measurements: Compact 81-86 tok/s without MTP, 124-137 with)
MTP_SPEC_BY_SOURCE_BACKEND = {("strata", "metal"): 2}
def mtp_spec_k(card_name: str | None = None, build: str | None = None, backend: str | None = None) -> int:
"""The K of `--spec K` for this card: a per-card override first, then the (source, backend) table (a .strata tier on a Mac: 2), else MTP_SPEC_DEFAULT (3)."""
low = str(card_name or "").lower()
for word, k in MTP_SPEC_BY_CARD.items():
if str(word).lower() in low:
return int(k)
return MTP_SPEC_DEFAULT
src = "strata" if build in BUILD_BYTES else "gguf"
return int(MTP_SPEC_BY_SOURCE_BACKEND.get((src, str(backend or "cuda").lower()), MTP_SPEC_DEFAULT))
# ---- the engine's "needs a newer engine" words (Inkling's and Ling's pattern): an engine that is installed but too old for this family ----
+12
View File
@@ -370,6 +370,18 @@ class MtpSpecK(unittest.TestCase):
self.assertEqual(QF.mtp_spec_k("NVIDIA GeForce RTX 3060"), 2)
self.assertEqual(QF.mtp_spec_k("NVIDIA GeForce RTX 4060 Ti"), 3)
def test_the_elastic_kv_of_the_gguf_build(self):
# Q4-ELASTIC: --kv-resident (the Unsloth rule, gpu_fit.unsloth_kv_resident_default) when the card and the RAM are known and the context is 64K or more
g = F.gguf_engine_args("/t/trunk", "/t/s2", ctx=131072, vram_gb=12, ram_gb=32)
self.assertEqual(g[g.index("--kv-resident") + 1], "16384")
self.assertEqual(F.kv_resident_args(24, 64, 131072), ["--kv-resident", "32768"])
self.assertEqual(F.kv_resident_args(12, 32, 8192), []) # a short context stays on the card
self.assertEqual(F.kv_resident_args(12, 32, 32768), []) # 32K: the KV is 0.67 GiB, streaming it cost 17 % of the prefill (measured)
self.assertEqual(F.kv_resident_args(12, 8, 131072), []) # no room in RAM
self.assertEqual(F.kv_resident_args(12, 32, 131072, unified=True), []) # one pool: nothing to gain
self.assertEqual(F.kv_resident_args(None, 32, 131072), [])
self.assertNotIn("--kv-resident", F.gguf_engine_args("/t/trunk", "/t/s2", ctx=131072))
def test_the_arguments(self):
self.assertEqual(F.gguf_spec_args(), ["--spec", "3", "--spec-min-p", "0.5"])
self.assertEqual(F.gguf_spec_args(2), ["--spec", "2", "--spec-min-p", "0.5"])
@@ -7,6 +7,12 @@ file) become F32 as the loader expects. The routed experts (S2_E8P gate/up, S3_
usage: qwen4_mtp_strata_to_gguf.py --strata Qwen4-35B-A3B-MTP.strata --out mtp-q2_0.gguf [--manifest manifest.json] [--gguf-py DIR]
(the engine reads the file as <dir>/mtp-q2_0.gguf next to the rt folder given to --mtp)
"""
import sys
if sys.platform == "win32":
# CPython 3.12's WMI helper (_wmi, behind platform.system() / uname()) takes an access violation in a worker thread when WMI refuses the
# account (0x80041003) and the caller has already gone (DIAG-WINHOST-0216). Without _wmi, platform uses the registry and the environment.
sys.modules["_wmi"] = None
import argparse, os, sys
import numpy as np
+4
View File
@@ -6,6 +6,10 @@ the compiled shape (Q4_K gate/up/down, 2048 x 512: 1,769,472 B) and wants the la
the GGUF stay as written (nothing reads them: check_experts_gguf accepts a GGUF with the key qwen4exp.strata_experts).
"""
import sys
if sys.platform == "win32":
# CPython 3.12's WMI helper (_wmi, behind platform.system() / uname()) takes an access violation in a worker thread when WMI refuses the
# account (0x80041003) and the caller has already gone (DIAG-WINHOST-0216). Without _wmi, platform uses the registry and the environment.
sys.modules["_wmi"] = None
BLOB = 3 * 512 * (2048 // 256) * 144 # gate + up + down, Q4_K, 512 rows of 2048 values (down: 2048 rows of 512 values: the same bytes)
path = sys.argv[1].rstrip("/\\") + "/native_experts.txt"
+6
View File
@@ -11,6 +11,12 @@ the Hugging Face repo's tokenizer-compat files and the PLE GGUF: no Unsloth file
[--layers N] [--alignment 16384] [--manifest manifest.json] (the manifest is read from the file with zstandard, or from this JSON)
HFDIR holds tokenizer-compat/{tokenizer.json, tokenizer_config.json, chat_template.jinja} and generation_config.json of Qwen/Qwen4-35B-A3B.
"""
import sys
if sys.platform == "win32":
# CPython 3.12's WMI helper (_wmi, behind platform.system() / uname()) takes an access violation in a worker thread when WMI refuses the
# account (0x80041003) and the caller has already gone (DIAG-WINHOST-0216). Without _wmi, platform uses the registry and the environment.
sys.modules["_wmi"] = None
import argparse, os, sys, time
import numpy as np
@@ -0,0 +1,186 @@
"""qwen4_vision_strata_to_gguf.py - Qwen4-35B-A3B-Vision.strata (the owner's 27-layer vision tower, plain BF16 tensors with Hugging Face names) -> the mmproj
GGUF (qwen3vl_merger layout: v.blk.N.*, v.patch_embd.weight(.1), v.position_embd.weight, v.post_ln.*, mm.0.*, mm.2.*) that `strata-vision --mmproj` reads on every
backend, Metal included. No Unsloth file is needed.
python qwen4_vision_strata_to_gguf.py --strata Qwen4-35B-A3B-Vision.strata --out mmproj-Qwen4-35B-A3B-Vision.gguf
[--manifest manifest.json] (zstandard is read when installed; else the manifest's JSON)
[--check-template mmproj-BF16.gguf] compare keys, tensor names / shapes / types and tensor bytes with another mmproj and report
The Vision.strata has the tensors un-rotated (no FWHT domain) in the file's section 3, offsets in the manifest relative to it.
"""
import sys
if sys.platform == "win32":
# CPython 3.12's WMI helper (_wmi, behind platform.system() / uname()) takes an access violation in a worker thread when WMI refuses the
# account (0x80041003) and the caller has already gone (DIAG-WINHOST-0216). Without _wmi, platform uses the registry and the environment.
sys.modules["_wmi"] = None
import argparse, json, mmap, os, struct
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--strata", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--manifest")
ap.add_argument("--check-template")
ap.add_argument("--gguf-py")
A = ap.parse_args()
if A.gguf_py:
sys.path.insert(0, A.gguf_py)
else:
from _paths import add_gguf_py
add_gguf_py()
import gguf
gguf.GGUFWriter.ggml_pad = staticmethod(lambda x, n: ((int(x) + n - 1) // n) * n) # numpy uint32 sizes wrapped tensor offsets at 4 GiB
f = open(A.strata, "rb")
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if mm[:8] != b"STRATA\x00\x01":
sys.exit("not a .strata file")
sec = {}
for i in range(6):
fo, bl, _sha, sid, _fl, _rs = struct.unpack_from("<QQ32sIIQ", mm, 0x20 + i * 64)
sec[sid] = (fo, bl)
if A.manifest:
man = json.load(open(A.manifest))
else:
import zstandard
fo, bl = sec[0]
man = json.loads(zstandard.ZstdDecompressor().decompressobj().decompress(mm[fo:fo + bl]))
vc = man["vision_config"]
if man.get("shard_role") != "vision_encoder" or int(vc["depth"]) != 27:
sys.exit("not the Qwen4 vision tower")
base = sec[3][0]
T = {t["name"]: t for t in man["tensors"]}
def raw_bf16(name):
t = T[name]
assert t["dtype"] == "BF16"
n = int(np.prod(t["shape"]))
return np.frombuffer(mm, dtype=np.uint16, count=n, offset=base + int(t["offset"])).reshape(t["shape"])
def f32(name):
return (raw_bf16(name).astype(np.uint32) << 16).view(np.float32)
W, H = int(vc["hidden_size"]), int(vc["num_heads"])
FF, OUT, PATCH, MERGE = int(vc["intermediate_size"]), int(vc["out_hidden_size"]), int(vc["patch_size"]), int(vc["spatial_merge_size"])
IMG = int(round(np.sqrt(int(vc["num_position_embeddings"])))) * PATCH
V = gguf.GGUFValueType
w = gguf.GGUFWriter(A.out, arch="clip")
ents = [
("general.type", "mmproj", V.STRING, None),
("general.sampling.top_k", 20, V.INT32, None),
("general.sampling.top_p", float(np.float32(0.95)), V.FLOAT32, None),
("general.sampling.temp", 1.0, V.FLOAT32, None),
("general.name", "Qwen4-35B-A3B-Vision", V.STRING, None),
("general.size_label", "447M", V.STRING, None),
("general.license", "apache-2.0", V.STRING, None),
("general.file_type", 32, V.UINT32, None),
("clip.has_vision_encoder", True, V.BOOL, None),
("clip.vision.projection_dim", OUT, V.UINT32, None),
("clip.vision.image_size", IMG, V.UINT32, None),
("clip.vision.patch_size", PATCH, V.UINT32, None),
("clip.vision.embedding_length", W, V.UINT32, None),
("clip.vision.feed_forward_length", FF, V.UINT32, None),
("clip.vision.block_count", int(vc["depth"]), V.UINT32, None),
("clip.vision.attention.head_count", H, V.UINT32, None),
("clip.vision.image_mean", [0.5, 0.5, 0.5], V.ARRAY, V.FLOAT32), # the Qwen vision preprocessor: (x / 255 - 0.5) / 0.5
("clip.vision.image_std", [0.5, 0.5, 0.5], V.ARRAY, V.FLOAT32),
("clip.projector_type", "qwen3vl_merger", V.STRING, None),
("clip.use_gelu", True, V.BOOL, None), # hidden_act gelu_pytorch_tanh
("clip.vision.spatial_merge_size", MERGE, V.UINT32, None),
("clip.vision.attention.layer_norm_epsilon", float(np.float32(1e-6)), V.FLOAT32, None),
("clip.vision.is_deepstack_layers", [i in set(vc.get("deepstack_visual_indexes", [])) for i in range(int(vc["depth"]))], V.ARRAY, V.BOOL),
("general.quantization_version", 2, V.UINT32, None),
]
for k, v, t, sub in ents:
w.add_key_value(k, v, t, sub)
keep = []
def put_bf16(name, a):
raw = np.ascontiguousarray(a).view(np.uint8).reshape(a.shape[:-1] + (a.shape[-1] * 2,))
keep.append(raw)
w.add_tensor(name, raw, raw_dtype=gguf.GGMLQuantizationType.BF16)
def put_f32(name, a):
a = np.ascontiguousarray(a, dtype=np.float32)
keep.append(a)
w.add_tensor(name, a)
V0 = "model.visual."
pe = f32(V0 + "patch_embed.proj.weight") # [W, 3, 2, 16, 16]
put_f32("v.patch_embd.weight", pe[:, :, 0])
put_f32("v.patch_embd.weight.1", pe[:, :, 1])
put_f32("v.patch_embd.bias", f32(V0 + "patch_embed.proj.bias"))
put_f32("v.position_embd.weight", f32(V0 + "pos_embed.weight"))
for i in range(int(vc["depth"])):
p, q = "%sblocks.%d." % (V0, i), "v.blk.%d." % i
for a, b in (("norm1", "ln1"), ("norm2", "ln2")):
put_f32(q + b + ".weight", f32(p + a + ".weight"))
put_f32(q + b + ".bias", f32(p + a + ".bias"))
for a, b in (("attn.qkv", "attn_qkv"), ("attn.proj", "attn_out"), ("mlp.linear_fc1", "ffn_up"), ("mlp.linear_fc2", "ffn_down")):
put_bf16(q + b + ".weight", raw_bf16(p + a + ".weight"))
put_f32(q + b + ".bias", f32(p + a + ".bias"))
put_f32("v.post_ln.weight", f32(V0 + "merger.norm.weight"))
put_f32("v.post_ln.bias", f32(V0 + "merger.norm.bias"))
for a, b in (("linear_fc1", "mm.0"), ("linear_fc2", "mm.2")):
put_bf16(b + ".weight", raw_bf16(V0 + "merger." + a + ".weight"))
put_f32(b + ".bias", f32(V0 + "merger." + a + ".bias"))
w.write_header_to_file()
w.write_kv_data_to_file()
w.write_tensors_to_file(progress=False)
w.close()
print("wrote %s: %d tensors" % (A.out, len(keep)))
if A.check_template:
r1 = gguf.GGUFReader(A.out)
r2 = gguf.GGUFReader(A.check_template)
bad = []
skip = ("general.quantized_by", "general.repo_url")
for k, fd in r2.fields.items():
if k.startswith("GGUF.") or k in skip:
continue
g = r1.fields.get(k)
if g is None:
bad.append("%s: missing" % k)
continue
a, b = g.contents(), fd.contents()
a = a.tolist() if hasattr(a, "tolist") else a
b = b.tolist() if hasattr(b, "tolist") else b
if [t.name for t in g.types] != [t.name for t in fd.types]:
bad.append("%s: type %s vs %s" % (k, [t.name for t in g.types], [t.name for t in fd.types]))
if a != b and not (isinstance(a, float) and abs(a - b) < 1e-9):
bad.append("%s: %r vs %r" % (k, a, b))
for k in r1.fields:
if not k.startswith("GGUF.") and k not in r2.fields:
bad.append("%s: written, not in the template" % k)
t1 = {t.name: t for t in r1.tensors}
t2 = {t.name: t for t in r2.tensors}
n_eq = 0
for n, b in t2.items():
a = t1.get(n)
if a is None:
bad.append("tensor %s: missing" % n)
continue
if a.tensor_type != b.tensor_type or [int(x) for x in a.shape] != [int(x) for x in b.shape]:
bad.append("tensor %s: %s %s vs %s %s" % (n, a.tensor_type.name, list(a.shape), b.tensor_type.name, list(b.shape)))
continue
if np.array_equal(np.asarray(a.data).view(np.uint8), np.asarray(b.data).view(np.uint8)):
n_eq += 1
else:
bad.append("tensor %s: bytes differ" % n)
for n in t1:
if n not in t2:
bad.append("tensor %s: written, not in the template" % n)
for line in bad[:40]:
print("DIFFERENCE:", line)
print("check: %d of %d tensors byte-identical, %d differences" % (n_eq, len(t2), len(bad)))
+5 -5
View File
@@ -848,12 +848,12 @@ class Strata:
"context_fit": None, "ling32": True, "footprint_gb": foot}
@staticmethod
def qwen4_program_row(build) -> dict:
def qwen4_program_row(build, backend=None) -> dict:
"""{"engine_has_program": bool} on the size row of a Qwen4 .strata build: does the installed q4_lite engine folder hold `strata-q4-lite` (the host those builds run on)? False makes the
app say "needs a newer engine" and offer the update (app/host/server/engine-version.mjs markEngine). Nothing for the GGUF build, and nothing when no engine is installed yet (the install fetches it)."""
try:
from strata_control import qwen4_family
if build in qwen4_family.BUILDS:
if build in qwen4_family.BUILDS and qwen4_family.uses_standalone_host(build, backend): # a Mac runs the .strata tiers on `strata`: no second program needed
has = qwen4_family.engine_has_program()
if has is not None:
return {"engine_has_program": has}
@@ -898,7 +898,7 @@ class Strata:
# the app's panel (app/host/src/lib/native.ts NativeSize.qwen4): the same facts in its own words
"expert_slots": qwen4_fit.gguf_expert_slots(None if unified else vram_gib) if qwen4_family.is_gguf_build(build) else None, "expert_slots_total": qwen4_fit.GGUF_EXPERT_SLOTS_TOTAL if qwen4_family.is_gguf_build(build) else None,
"strata_floor_gib": qwen4_fit.STRATA_MIN_VRAM_GIB.get(build), "kv": kv_eff, "kv_choices": qwen4_family.kv_choices(build, backend), "kv_default": qwen4_family.kv_default(build), "kv_words": {k: qwen4_family.KV_WORDS[k] for k in qwen4_family.kv_choices(build, backend)},
"mtp_default": qwen4_fit.mtp_auto_on(None if unified else vram_gib, unified, build, (card or {}).get("name")), "mtp_available": qwen4_family.mtp_ready(build),
"mtp_default": qwen4_fit.mtp_auto_on(None if unified else vram_gib, unified, build, (card or {}).get("name")), "mtp_available": qwen4_family.mtp_ready(build, backend),
"recommended_ple": adv["recommended"]["ple"], "vram_need_gib": adv["vram_need_gib"], "ram_need_gib": adv["ram_need_gib"], "loop_available": qwen4_family.loop_ready(build, backend),
"notes": self._qwen4_notes(cards, backend, pick)}
@@ -1851,7 +1851,7 @@ class Strata:
q4 = self.qwen4_fit_row(m, ram if ram else None, usable)
on_disk, rem_gb = (False, None) if tag in have else self._local_build_status(S, f, m, d, fd)
sizes.append({"model": m, "about": d["about"], "download_gb": d["download_gb"],
**({"qwen4": q4} if q4 else {}), **self.qwen4_program_row(m),
**({"qwen4": q4} if q4 else {}), **self.qwen4_program_row(m, (q4 or {}).get("backend")),
**({"files_on_disk": True, "remaining_download_gb": rem_gb} if on_disk else {}),
"experimental": False, "images": True,
"ram_needed_gb": d["ram_gb"], "experts_gb": d.get("arena_gb"), "mem_total": False,
@@ -2022,7 +2022,7 @@ class Strata:
**({"hy4": hy4} if hy4 else {}),
**({"inkling": ink} if ink else {}),
**({"ling32": ling} if ling else {}),
**({"qwen4": q4} if q4 else {}), **self.qwen4_program_row(m),
**({"qwen4": q4} if q4 else {}), **self.qwen4_program_row(m, (q4 or {}).get("backend")),
**({"format": d["format"]} if d.get("format") else {}),
**({"gpu_vendor": d["gpu_vendor"], "label": d["label"]} if d.get("gpu_vendor") else {}),
**({"offered": False} if d.get("offered") is False else {}),
+2 -4
View File
@@ -355,9 +355,7 @@ class Install(unittest.TestCase):
_, w, says, _, _ = self.run_install(backend="hip", arch="gfx1100", vram_gb=24.0)
self.assertEqual(w["cfg"]["backend"], "hip")
self.assertTrue(any(s.startswith("warn") and "RDNA 3" in s for s in says), says)
_, w, says, _, _ = self.run_install(backend="metal", arch="apple-gpu", ram=64, vram_gb=0.0)
self.assertEqual(w["cfg"]["backend"], "metal")
self.assertTrue(any("one memory pool" in s for s in says), says)
# (a Mac: the .strata tiers are converted at install and run on `strata`: tools/test_setup_qwen4_mac.py)
self.assertNotIn("backend", self.run_install()[1]["cfg"]) # NVIDIA: nothing extra
def test_a_pc_that_cannot_hold_the_build_is_told_not_refused(self):
@@ -536,7 +534,7 @@ class GgufBuild(unittest.TestCase):
shard2 = folder / qwen4_family.GGUF_FILES["shard2"][0]
mmproj = folder / qwen4_family.GGUF_FILES["mmproj"][0]
pack = root / "data" / "packs" / "qwen4-35b-a3b-ud-q4_k_xl"
self.assertEqual(cfg["args"], qwen4_family.gguf_engine_args(trunk, shard2, pack=pack, profile=folder / qwen4_family.GGUF_PROFILE_FILE, vision=mmproj, ctx=65536))
self.assertEqual(cfg["args"], qwen4_family.gguf_engine_args(trunk, shard2, pack=pack, profile=folder / qwen4_family.GGUF_PROFILE_FILE, vision=mmproj, ctx=65536, vram_gb=24.0, ram_gb=64)) # the elastic KV: a 24 GB card at 64K keeps 32768 cells
self.assertEqual(cfg["vision"]["mmproj"], str(mmproj))
self.assertEqual(cfg["vision"]["model"], str(trunk))
self.assertEqual(cfg["model_name"], "qwen4-35b-a3b-ud-q4_k_xl")
+430
View File
@@ -0,0 +1,430 @@
"""A .strata tier (Compact / Balanced / Ultra) of Qwen Qwen4-35B-A3B on a Mac: Q4-METAL's converter chain run by setup (the HF directory, the dense GGUF, the pack and its fix, the neutral profile, the draft
layer), the run config for the Metal engine `strata`, the program table by backend, serve's start of such a config, the fit rows of the one memory pool and the launcher's adopt. The outside world
(downloads, pip, the tools themselves) is replaced: no engine, no Mac, nothing real is converted.
python -m pytest tools/test_setup_qwen4_mac.py
"""
from __future__ import annotations
import os
import sys
import tempfile
import time
import unittest
from pathlib import Path
from unittest import mock
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(1, str(HERE.parent))
import setup # noqa: E402
import strata_mcp as M # noqa: E402
from strata_control import qwen4_family as F, qwen4_fit # noqa: E402
from strata_cli.launch import adopt # noqa: E402
from serve import qwen4_kind as K # noqa: E402
from test_setup_qwen4 import BLOB, TINY, ns # noqa: E402
def fake_tools(ran: list, fail: str | None = None):
"""A `run` that records each tool's command line and writes what the real tool would: the dense GGUF, the pack folder, the draft layer's GGUF. `fail`: the tool file name that stops."""
def run(cmd, *a, **k):
cmd = [str(c) for c in cmd]
ran.append(cmd)
tool = Path(cmd[1]).name
if tool == fail:
raise SystemExit(1)
if tool in ("qwen4_strata_to_gguf.py", "qwen4_mtp_strata_to_gguf.py", "qwen4_vision_strata_to_gguf.py"):
out = Path(cmd[cmd.index("--out") + 1])
out.parent.mkdir(parents=True, exist_ok=True)
out.write_bytes(b"gguf")
elif tool == "iq_pack.py":
out = Path(cmd[cmd.index("--out") + 1])
(out / "tokenizer").mkdir(parents=True, exist_ok=True)
(out / "tokenizer" / "vocab.json").write_text("{}", encoding="utf-8")
(out / "native_experts.txt").write_text("0 1 2 3 4\n", encoding="utf-8")
return run
def tok_files(root: Path) -> dict:
d = root / "tok"
d.mkdir(parents=True, exist_ok=True)
out = {}
for n in F.TOKENIZER_FILES:
(d / n).write_text(n, encoding="utf-8")
out[n] = d / n
return out
class Programs(unittest.TestCase):
def test_the_program_table_by_source_and_backend(self):
for b in F.BUILDS:
self.assertEqual(F.program_for(b, "cuda"), "strata-q4-lite")
self.assertEqual(F.program_for(b), "strata-q4-lite") # no backend: cuda
self.assertEqual(F.program_for(b, "hip"), "strata-q4-lite")
self.assertEqual(F.program_for(b, "metal"), "strata")
for be in ("cuda", "hip", "metal"):
self.assertEqual(F.program_for(F.GGUF_BUILD, be), "strata")
self.assertEqual(F.exe_reference("Compact"), "component:strata-q4-lite/strata-q4-lite")
self.assertEqual(F.exe_reference("Compact", "metal"), "component:strata-q4-lite") # the same folder's own program: byte-identical to the GGUF build's reference
self.assertEqual(F.exe_reference(F.GGUF_BUILD, "metal"), "component:strata-q4-lite")
self.assertTrue(F.uses_metal_converter("Ultra", "metal"))
self.assertFalse(F.uses_metal_converter("Ultra", "cuda"))
self.assertFalse(F.uses_metal_converter(F.GGUF_BUILD, "metal"))
self.assertFalse(F.uses_standalone_host("Ultra", "metal"))
def test_the_draft_layer_is_ready_on_a_mac_only(self):
self.assertTrue(F.mtp_ready("Compact", "metal"))
self.assertFalse(F.mtp_ready("Compact", "cuda"))
self.assertFalse(F.mtp_ready("Compact"))
self.assertTrue(F.mtp_ready(F.GGUF_BUILD, "cuda"))
self.assertFalse(F.vision_ready("Compact")) # the standalone host reads no pictures yet
self.assertTrue(F.vision_ready("Compact", "metal")) # a Mac tier: Vision.strata converted to the mmproj
self.assertTrue(F.vision_ready(F.GGUF_BUILD))
self.assertFalse(F.loop_ready("Compact", "metal"))
def test_the_hf_directory_layout_and_the_args(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
hf = F.build_hf_dir(tok_files(root), root / "hf")
for name, rel in F.HF_DIR_LAYOUT.items():
self.assertEqual((hf / rel).read_text(encoding="utf-8"), name)
self.assertTrue((hf / "tokenizer-compat" / "chat_template.jinja").is_file())
self.assertTrue((hf / "generation_config.json").is_file())
self.assertFalse((hf / "tokenizer.json").exists()) # tokenizer.json lives in tokenizer-compat/ only
paths = F.metal_paths(root / "models", "Compact")
self.assertEqual(paths["dir"], root / "models" / "metal" / "compact")
self.assertEqual(paths["gguf"], root / "models" / "metal" / "compact" / "Compact.gguf")
args = F.metal_engine_args(paths, "/m/PLE.gguf", 65536)
self.assertEqual(args, ["--pack", str(paths["pack"]), "--native", str(paths["gguf"]), "--native-dense-gguf", str(paths["gguf"]), "--ple-gguf", "/m/PLE.gguf",
"--expert-profile", str(paths["profile"]), "--expert-cache", "64", "--mmap-experts", "--prefill", "auto", "--spec", "2", "--max-context", "65536"])
with_pics = F.metal_engine_args(paths, "/m/PLE.gguf", 8192, True)
self.assertEqual(with_pics[with_pics.index("--vision"):][:2], ["--vision", "--max-context"])
self.assertNotIn("--kv", with_pics) # the Metal window keeps the K/V cache in int8 only and ignores --kv
class Chain(unittest.TestCase):
def inputs(self, root: Path):
strata, ple, mtp = root / "Compact.strata", root / "PLE.gguf", root / "MTP.strata"
for p in (strata, ple, mtp):
p.write_bytes(b"x")
os.utime(p, (time.time() - 100, time.time() - 100))
return strata, ple, mtp
def test_the_steps_run_in_order_with_the_right_flags(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
strata, ple, mtp = self.inputs(root)
paths = F.metal_paths(root, "Compact")
ran: list = []
with mock.patch.multiple(setup, run=fake_tools(ran), qwen4_ensure_zstd=lambda: None, say=lambda *x, **y: None):
mtp_ok = setup.qwen4_metal_prepare(paths, strata, ple, tok_files(root), mtp)
self.assertTrue(mtp_ok)
self.assertEqual([Path(c[1]).name for c in ran], ["qwen4_strata_to_gguf.py", "iq_pack.py", "qwen4_strata_pack_fix.py", "qwen4_mtp_strata_to_gguf.py"])
self.assertEqual(ran[0][2:], ["--strata", str(strata), "--hf-dir", str(paths["hf"]), "--ple-gguf", str(ple), "--out", str(paths["gguf"])])
self.assertEqual(ran[1][2:], ["--gguf", str(paths["gguf"]), "--out", str(paths["pack"]), "--compat-bf16"])
self.assertEqual(ran[2][2:], [str(paths["pack"])])
self.assertEqual(ran[3][2:], ["--strata", str(mtp), "--out", str(paths["mtp_gguf"])])
self.assertTrue((paths["hf"] / "tokenizer-compat" / "tokenizer.json").is_file()) # the HF directory the converter reads
self.assertTrue((paths["mtp_dir"] / "rt").is_dir()) # the engine reads mtp-q2_0.gguf next to the rt folder it is given
self.assertEqual(paths["profile"].stat().st_size, 81944) # the neutral 40 x 256 profile
self.assertEqual(paths["profile"].read_bytes()[:4], b"STRP")
def test_a_second_run_skips_every_step_whose_output_is_fresh(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
strata, ple, mtp = self.inputs(root)
paths = F.metal_paths(root, "Balanced")
ran: list = []
with mock.patch.multiple(setup, run=fake_tools(ran), qwen4_ensure_zstd=lambda: None, say=lambda *x, **y: None):
setup.qwen4_metal_prepare(paths, strata, ple, tok_files(root), mtp)
first = len(ran)
self.assertEqual(setup.qwen4_metal_prepare(paths, strata, ple, tok_files(root), mtp), True)
self.assertEqual((first, len(ran)), (4, 4)) # nothing ran the second time
with mock.patch.multiple(setup, run=fake_tools(ran), qwen4_ensure_zstd=lambda: None, say=lambda *x, **y: None):
os.utime(strata, None) # a newer .strata: the conversion and what depends on it run again, not the draft layer
setup.qwen4_metal_prepare(paths, strata, ple, tok_files(root), mtp)
self.assertEqual([Path(c[1]).name for c in ran[4:]], ["qwen4_strata_to_gguf.py", "iq_pack.py", "qwen4_strata_pack_fix.py"])
def test_a_failing_draft_layer_step_is_one_warning_and_mtp_off(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
strata, ple, mtp = self.inputs(root)
paths = F.metal_paths(root, "Compact")
warned: list = []
with mock.patch.multiple(setup, run=fake_tools([], fail="qwen4_mtp_strata_to_gguf.py"), qwen4_ensure_zstd=lambda: None, say=lambda *x, **y: None, warn=lambda t="", *x: warned.append(t)):
self.assertFalse(setup.qwen4_metal_prepare(paths, strata, ple, tok_files(root), mtp))
self.assertEqual(len(warned), 1)
self.assertIn("MTP is off", warned[0])
self.assertTrue(paths["gguf"].is_file()) # the model itself is there
def test_no_draft_layer_file_means_no_draft_layer_step(self):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
strata, ple, _mtp = self.inputs(root)
ran: list = []
with mock.patch.multiple(setup, run=fake_tools(ran), qwen4_ensure_zstd=lambda: None, say=lambda *x, **y: None):
self.assertFalse(setup.qwen4_metal_prepare(F.metal_paths(root, "Compact"), strata, ple, tok_files(root), None))
self.assertNotIn("qwen4_mtp_strata_to_gguf.py", [Path(c[1]).name for c in ran])
def test_a_failing_required_step_stops(self):
for tool in ("qwen4_strata_to_gguf.py", "iq_pack.py", "qwen4_strata_pack_fix.py"):
with self.subTest(tool=tool), tempfile.TemporaryDirectory() as d:
root = Path(d)
strata, ple, mtp = self.inputs(root)
with mock.patch.multiple(setup, run=fake_tools([], fail=tool), qwen4_ensure_zstd=lambda: None, say=lambda *x, **y: None):
with self.assertRaises(SystemExit):
setup.qwen4_metal_prepare(F.metal_paths(root, "Compact"), strata, ple, tok_files(root), mtp)
def test_a_missing_tool_is_one_plain_sentence(self):
with mock.patch.object(setup, "ROOT", Path(tempfile.gettempdir()) / "no-such-strata-tree"), mock.patch.object(setup, "fail", side_effect=SystemExit(1)) as fail:
with self.assertRaises(SystemExit):
setup.qwen4_metal_tool("to_gguf", "converts the model")
self.assertIn("tools/qwen4_strata_to_gguf.py", fail.call_args[0][0])
class Install(unittest.TestCase):
"""install_qwen4 for a .strata tier with the Mac backend, end to end with the outside world replaced."""
def run_install(self, *, fail=None, mtp_file=True, reader=True, **kw):
with tempfile.TemporaryDirectory() as d, mock.patch.dict(F.FILES, TINY):
root = Path(d)
ram = kw.pop("ram", 64)
written, says, fetched, ran = {}, [], [], []
gpu = {"index": 0, "name": "Apple M5 Max", "vendor": "apple", "vram_gb": 0.0, "unified_gb": float(ram), "uma": True, "count": 1}
a = ns(context=kw.pop("context", 65536), models_dir=str(root / "models"), rope_scaling=None, rope_scale=None, kv=kw.pop("kv", None), resident_budget_gib=None, low_ram=None,
backend=None, gpu=None, host=None, api_key=None, browser=None, no_start=True, **kw)
eng = root / "engine"
eng.mkdir()
if reader:
(eng / setup.VEXE).write_bytes(b"strata-vision") # the picture reader program of the engine package
(root / "models" / "qwen4-35b-a3b").mkdir(parents=True)
toks = tok_files(root)
def fake_fetch(a_, name, folder, own):
fetched.append(name)
p = Path(folder) / name
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(BLOB)
return p
def fake_optional(a_, name, folder, own, model, extra=(), what=""):
return fake_fetch(a_, name, folder, own) if mtp_file else None
patches = dict(say=lambda *x, **y: says.append(" ".join(map(str, x))), ok=lambda t="": says.append("ok " + t), warn=lambda t="", *x: says.append("warn " + t), step=lambda *x: None,
pip_install=lambda *x, **y: None, runtime_packages=lambda: [], own_strata_check=lambda p: None, qwen4_ensure_zstd=lambda: None,
engine_step=lambda *x, **y: (None, eng, {"version": "9"}, [], gpu, "none"), data_folder_for=lambda a: (root / "data", False), home=lambda: root,
write_setup_config=lambda path, cfg, *x, **y: written.update(path=path, cfg=cfg), write_run_script=lambda *x, **y: Path("run.sh"),
engine_exe=lambda e: "component:strata-q4-lite", run_tag=lambda a, family, fam, model: fam["tag"] + model.lower(),
qwen4_fetch=fake_fetch, qwen4_optional=fake_optional, qwen4_tokenizer_raw=lambda *x, **y: toks, qwen4_backend=lambda *x, **y: "metal",
hy4_pc=lambda g, r: (None, float(r), True), explicit_args=lambda a: [], run=fake_tools(ran, fail))
with mock.patch.multiple(setup, **patches):
rc = setup.install_qwen4(a, "qwen4-35b-a3b", gpu, False, [], None, False, 8080, ram, None)
return rc, written, says, fetched, ran, root
def test_the_config_the_mac_install_writes(self):
rc, w, says, fetched, ran, root = self.run_install(model="Compact")
self.assertEqual(rc, 0)
cfg = w["cfg"]
folder = root / "models" / "qwen4-35b-a3b"
paths = F.metal_paths(folder, "Compact")
self.assertEqual(sorted(fetched), sorted([F.build_file("Compact"), F.ple_file("Q4"), F.MTP_FILE, F.VISION_FILE])) # the tier, the PLE table (Q4: it is read from the disk), the drafter's and the picture reader's files
self.assertEqual(cfg["exe"], F.exe_reference("Compact", "metal")) # the component's own program `strata`
self.assertEqual((cfg["arch"], cfg["model_name"], cfg["backend"], cfg["drafting"]), (F.ARCH, "qwen4-35b-a3b-compact", "metal", "off"))
self.assertEqual(cfg["args"], F.metal_engine_args(paths, folder / F.ple_file("Q4"), 65536, True))
self.assertEqual(cfg["env"], {"STRATA_METAL_STREAM": "0", "STRATA_HC_Q8": "0", "STRATA_PREFILL_CPU_SHARE": "0"})
self.assertEqual(cfg["tokenizer"], str(paths["pack"] / "tokenizer"))
self.assertEqual(cfg[F.MTP_CONFIG_KEY], str(paths["mtp_rt"]))
self.assertEqual((cfg[F.MTP_MODE_KEY], cfg[F.MTP_SPEC_CONFIG_KEY]), ("auto", 2)) # on by default; the depth stays 2 on this path
self.assertEqual(cfg[F.EFFORT_CONFIG_KEY], F.DEFAULT_EFFORT)
self.assertEqual(cfg["args"].count("--vision"), 1) # a bare flag: the reader is the "vision" section
self.assertEqual(cfg["args"][cfg["args"].index("--vision") + 1].startswith("--"), True)
self.assertEqual(cfg["vision"], {"exe": str(root / "engine" / setup.VEXE), "mmproj": str(paths["mmproj"]), "model": str(paths["gguf"]), "gpu": True,
"max_tokens": setup.vision_tokens(None, "gpu", None)})
self.assertNotIn(F.LOOP_CONFIG_KEY, cfg)
for flag in F.ALL_LOOP_FLAGS:
self.assertNotIn(flag, cfg["args"])
for f in ("--model", "--max-ctx", "--mtp"): # the standalone host's spellings are not here
self.assertNotIn(f, cfg["args"])
self.assertEqual([Path(c[1]).name for c in ran], ["qwen4_strata_to_gguf.py", "iq_pack.py", "qwen4_strata_pack_fix.py", "qwen4_mtp_strata_to_gguf.py", "qwen4_vision_strata_to_gguf.py"])
self.assertEqual(ran[-1][2:], ["--strata", str(folder / F.VISION_FILE), "--out", str(paths["mmproj"])])
self.assertTrue(any("Memory plan for this Mac" in s for s in says), says)
def test_mtp_off_leaves_the_drafter_out(self):
rc, w, says, fetched, ran, root = self.run_install(model="Balanced", mtp="off")
cfg = w["cfg"]
self.assertNotIn(F.MTP_FILE, fetched)
self.assertNotIn(F.MTP_CONFIG_KEY, cfg)
self.assertNotIn("qwen4_mtp_strata_to_gguf.py", [Path(c[1]).name for c in ran])
self.assertEqual(cfg["exe"], "component:strata-q4-lite")
def test_a_failing_draft_layer_still_installs(self):
rc, w, says, fetched, ran, root = self.run_install(model="Compact", fail="qwen4_mtp_strata_to_gguf.py")
self.assertEqual(rc, 0)
self.assertNotIn(F.MTP_CONFIG_KEY, w["cfg"])
self.assertTrue(any(s.startswith("warn") and "MTP is off" in s for s in says), says)
def test_pictures_off_leaves_the_reader_out(self):
rc, w, says, fetched, ran, root = self.run_install(model="Compact", vision="no")
cfg = w["cfg"]
self.assertNotIn(F.VISION_FILE, fetched)
self.assertNotIn("--vision", cfg["args"])
self.assertNotIn("vision", cfg)
self.assertNotIn("qwen4_vision_strata_to_gguf.py", [Path(c[1]).name for c in ran])
def test_a_failing_picture_conversion_is_one_warning_and_pictures_off(self):
rc, w, says, fetched, ran, root = self.run_install(model="Compact", fail="qwen4_vision_strata_to_gguf.py")
self.assertEqual(rc, 0)
self.assertNotIn("vision", w["cfg"])
self.assertNotIn("--vision", w["cfg"]["args"])
self.assertEqual(len([s for s in says if s.startswith("warn") and "picture reader" in s]), 1, says)
self.assertIn(F.MTP_CONFIG_KEY, w["cfg"]) # the draft layer is not touched by it
def test_a_missing_picture_tool_is_one_sentence_and_pictures_off(self):
real_root = setup.ROOT
with tempfile.TemporaryDirectory() as d:
fake_root = Path(d)
for rel in F.METAL_TOOLS.values():
if "vision" not in rel:
(fake_root / rel).parent.mkdir(parents=True, exist_ok=True)
(fake_root / rel).write_text("# fake", encoding="utf-8")
(fake_root / "tests" / "data").mkdir(parents=True)
with mock.patch.object(setup, "ROOT", fake_root):
rc, w, says, fetched, ran, root = self.run_install(model="Compact")
self.assertEqual(rc, 0)
self.assertNotIn("vision", w["cfg"])
self.assertTrue(any(s == "warn " + F.METAL_COMING_NOTE for s in says), says)
self.assertEqual(real_root, setup.ROOT)
def test_no_reader_program_in_the_engine_package_means_pictures_off(self):
rc, w, says, fetched, ran, root = self.run_install(model="Compact", reader=False)
self.assertNotIn("vision", w["cfg"])
self.assertNotIn("--vision", w["cfg"]["args"])
self.assertTrue(any(s.startswith("warn") and setup.VEXE in s for s in says), says)
def test_a_failing_conversion_stops_before_a_config_is_written(self):
with self.assertRaises(SystemExit):
self.run_install(model="Compact", fail="qwen4_strata_to_gguf.py")
def test_no_kv_flag_is_ever_written_on_a_mac(self):
for word in (None, "fp16", "int8", "q4_0"):
with self.subTest(kv=word):
rc, w, says, *_ = self.run_install(model="Compact", kv=word)
self.assertNotIn("--kv", w["cfg"]["args"])
self.assertEqual(any(s.startswith("warn") and "--kv is not used on a Mac" in s for s in says), word is not None)
def test_the_menu_default_for_a_mac_follows_the_pool(self):
rc, w, says, fetched, ran, root = self.run_install(model=None, ram=36)
self.assertEqual(w["cfg"]["model_name"], "qwen4-35b-a3b-balanced") # a 36 GB Mac: the largest tier whose experts, dense half and cache fit what the pool keeps
class Fit(unittest.TestCase):
def test_a_mac_tier_is_one_pool_with_the_ple_table_on_the_disk(self):
rows = {r["build"]: r for r in qwen4_fit.rows(None, 36, unified=True, backend="metal")}
self.assertEqual({b: r["mode"] for b, r in rows.items()}, {"Compact": "unified", "Balanced": "unified", "Ultra": "short"})
self.assertTrue(all(r["ple"] == "Q4" for r in rows.values()))
self.assertEqual([b for b, r in rows.items() if r["recommended"]], ["Balanced"])
c, u = qwen4_fit.metal_pool_gib("Compact"), qwen4_fit.metal_pool_gib("Ultra")
self.assertLess(c, u)
self.assertGreater(c, 11.0) # about 8 GB of experts + 3.6 GB dense (Q4-METAL) + the cache and the work memory
adv = qwen4_fit.advise(None, 16, unified=True, build="Compact", backend="metal")
self.assertEqual(adv["mode"], "short")
self.assertEqual(qwen4_fit.advise(None, 64, unified=True, build="Ultra", backend="metal")["mode"], "unified")
self.assertEqual(qwen4_fit.advise(None, 64, unified=True, build="Compact", backend="metal")["ram_need_gib"], round(qwen4_fit.metal_pool_gib("Compact", None, True) + qwen4_fit.UMA_RESERVE_GIB, 2))
def test_the_other_backends_are_not_touched(self):
self.assertEqual(qwen4_fit.rows(24.0, 64), qwen4_fit.rows(24.0, 64, backend="cuda"))
self.assertEqual(qwen4_fit.recommend(None, 64, unified=True), qwen4_fit.recommend(None, 64, unified=True, backend="cuda"))
def test_the_draft_depth_is_two_on_a_mac_tier_and_three_elsewhere(self):
self.assertEqual(qwen4_fit.mtp_spec_k("Apple M5 Max", "Compact", "metal"), 2)
self.assertEqual(qwen4_fit.mtp_spec_k("RTX 3060", F.GGUF_BUILD, "cuda"), 3)
self.assertEqual(qwen4_fit.mtp_spec_k("RTX 3060"), 3)
self.assertEqual(qwen4_fit.mtp_spec_k(None, F.GGUF_BUILD, "metal"), 3)
class Serve(unittest.TestCase):
CFG = {"exe": "component:strata-q4-lite", "arch": F.ARCH, "model_name": "qwen4-35b-a3b-compact", "drafting": "off", "backend": "metal",
"args": ["--pack", "/d/pack", "--native", "/d/Compact.gguf", "--native-dense-gguf", "/d/Compact.gguf", "--ple-gguf", "/m/PLE.gguf", "--expert-profile", "/d/profile.bin",
"--expert-cache", "64", "--mmap-experts", "--prefill", "auto", "--spec", "2", "--max-context", "65536"]}
def test_a_mac_tier_is_not_the_standalone_host(self):
self.assertFalse(K.is_strata_build(self.CFG))
self.assertTrue(K.is_strata_build({**self.CFG, "backend": "cuda"}))
self.assertTrue(K.is_strata_build({k: v for k, v in self.CFG.items() if k != "backend"}))
self.assertTrue(K.engine_serves(self.CFG, None))
self.assertIsNone(K.serve_blocked(self.CFG, None))
def test_the_draft_layer_is_added_without_touching_the_spec_depth(self):
with tempfile.TemporaryDirectory() as d:
rt = Path(d) / "rt"
rt.mkdir()
cfg = {**self.CFG, F.MTP_CONFIG_KEY: str(rt), F.MTP_MODE_KEY: "auto", F.MTP_SPEC_CONFIG_KEY: 2}
args = K.extra_args(cfg, cfg["args"], None, announce=False)
self.assertEqual(args[args.index("--mtp") + 1], str(rt))
self.assertEqual(args[args.index("--spec") + 1], "2") # not --spec 3, not --spec-min-p
self.assertNotIn("--spec-min-p", args)
self.assertEqual(args.count("--spec"), 1)
off = {**cfg, F.MTP_MODE_KEY: "off"}
self.assertNotIn("--mtp", K.extra_args(off, off["args"], None, announce=False))
def test_the_mac_tier_keeps_pictures_where_the_engine_reads_them_and_loop_off(self):
cfg = {**self.CFG, "args": [*self.CFG["args"], "--vision"]}
with mock.patch.object(K, "probe", return_value={"images": "1"}):
args = K.extra_args(cfg, cfg["args"], "/e/strata", announce=False)
self.assertIn("--vision", args) # the engine says images=1: kept
with mock.patch.object(K, "probe", return_value={"images": "0"}):
args = K.extra_args(cfg, cfg["args"], "/e/strata", announce=False)
self.assertNotIn("--vision", args) # an engine that reads none starts without
self.assertEqual(args[args.index("--spec") + 1], "2")
class Adopt(unittest.TestCase):
def test_adopt_writes_the_same_config_setup_does(self):
with tempfile.TemporaryDirectory() as d, mock.patch.dict(F.FILES, TINY):
td = Path(d)
folder = td / "models" / "qwen4-35b-a3b"
folder.mkdir(parents=True)
(folder / F.build_file("Compact")).write_bytes(b"x")
(folder / F.ple_file("Q4")).write_bytes(BLOB)
paths = F.metal_paths(folder, "Compact")
paths["gguf"].parent.mkdir(parents=True)
paths["gguf"].write_bytes(b"x")
paths["profile"].write_bytes(b"x")
(paths["pack"] / "tokenizer").mkdir(parents=True)
(paths["pack"] / "native_experts.txt").write_text("x", encoding="utf-8")
(paths["pack"] / "tokenizer" / "vocab.json").write_text("{}", encoding="utf-8")
(paths["mtp_rt"]).mkdir(parents=True)
(paths["mtp_rt"] / "dense.bin").write_bytes(b"x")
cfg, problems = adopt.plan(family="qwen4-35b-a3b", model="Compact", model_dir=folder, data_dir=td, src=td, context=65536, kv=None, model_name="qwen4-35b-a3b-compact",
family_def={}, log=td / "x.log", backend="metal")
self.assertEqual(problems, [])
self.assertEqual(cfg["exe"], F.exe_reference("Compact", "metal"))
self.assertEqual(cfg["args"], F.metal_engine_args(paths, folder / F.ple_file("Q4"), 65536))
self.assertNotIn("--kv", cfg["args"])
self.assertEqual(cfg["env"], F.METAL_ENV)
self.assertEqual(cfg[F.MTP_CONFIG_KEY], str(paths["mtp_rt"]))
self.assertEqual(cfg[F.MTP_SPEC_CONFIG_KEY], 2)
self.assertEqual(cfg["backend"], "metal")
def test_adopt_says_what_is_missing(self):
with tempfile.TemporaryDirectory() as d:
td = Path(d)
folder = td / "models" / "qwen4-35b-a3b"
folder.mkdir(parents=True)
(folder / F.build_file("Compact")).write_bytes(b"x")
cfg, problems = adopt.plan(family="qwen4-35b-a3b", model="Compact", model_dir=folder, data_dir=td, src=td, context=65536, kv=None, model_name="qwen4-35b-a3b-compact",
family_def={}, log=td / "x.log", backend="metal")
self.assertIsNone(cfg)
self.assertTrue(any("setup makes" in p for p in problems), problems)
class Catalog(unittest.TestCase):
def test_a_mac_tier_needs_no_second_program(self):
self.assertEqual(M.Strata.qwen4_program_row("Compact", "metal"), {})
self.assertEqual(M.Strata.qwen4_program_row(F.GGUF_BUILD, "cuda"), {})
with mock.patch.object(F, "engine_has_program", return_value=False):
self.assertEqual(M.Strata.qwen4_program_row("Compact", "cuda"), {"engine_has_program": False})
self.assertEqual(M.Strata.qwen4_program_row("Compact", "metal"), {})
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -131,7 +131,7 @@ INSTALLER_TOOLS = ("strata_mcp", "iq_pack", "strata_pack", "pack_index", "mtp_fe
#: tools run BY PATH (`python tools/.../x.py`) by setup.py, strata_cli or strata_control: no import names them, so setup_tool_imports() cannot find
#: them. setup.py's by-path tools (nvfp4_local_pack, strata_bench, strata_inspect) were missing from the bundle once.
#: tests/terminal/test_bundle_tools_paths.py reads the by-path references out of the source and fails when one is missing from the bundle.
INSTALLER_SCRIPTS = ("nvfp4_local_pack", "strata_bench", "strata_inspect", "qwen4_split_gguf", "mtp_qwen4_rt") # the last two: Qwen4-35B-A3B's UD-Q4_K_XL preparation (strata_control/qwen4_family.py runs them by path)
INSTALLER_SCRIPTS = ("nvfp4_local_pack", "strata_bench", "strata_inspect", "qwen4_split_gguf", "mtp_qwen4_rt", "qwen4_strata_to_gguf", "qwen4_mtp_strata_to_gguf", "qwen4_strata_pack_fix", "qwen4_vision_strata_to_gguf") # the last two: Qwen4-35B-A3B's UD-Q4_K_XL preparation (strata_control/qwen4_family.py runs them by path)
INSTALLER_DATA = "data" # draft vocabularies, expert profiles: 2 MB
#: gguf-py and llama.cpp's HF converter at the llama.cpp pin (third_party/strata-gguf-py, 1.8 MB, MIT): the preparation tools import them, so
#: no llama.cpp download is needed to prepare a model (before 0.2.15 the installed Terminal fetched the 170 MB zip for this)