qwen4: KV cache choice, the BF16-route MTP drafter for the GGUF build, MTP Auto on the app side, and the real fit facts

- KV: per-format bytes from Q4-KV (fp16 20480, int8 and fp8 10560, k8v4 8160, q4_0 5760 per token); GGUF default int8, .strata builds fp16; KV_CHOICES, KV_DEFAULT, KV_READY (fp8 not ready), KV_BACKENDS; setup, launcher, catalog and the app panel ("Context memory" select, strings q427 to q430).
- MTP: the GGUF build builds the 923 MiB BF16-route drafter at install (mtp_fetch at the pinned Qwen revision, mtp_pack q8_0, mtp_rt); any failed step is MTP off with one warning; Unsloth's 1.95 GB sidecar is out of the download set; --spec 3 --spec-min-p 0.5 on every card (Q4-SMALL measurements), qwen4_mtp_spec; MTP Auto on for 6 GB and up with an empty per-card fallback table; app Auto help lines (q431, q432).
- fit facts: .strata floors (Compact 13, Balanced 22, Ultra 29 GiB: below it the build shows as short until the engine's memory tiering lands), the GGUF build needs about 64 GB of RAM, informational expert slot counts per card size.
- the model host name stays in setup.py only.
This commit is contained in:
Niko1221 committed 2026-12-04 09:09:19 +01:00
1 parent 80851089b4
commit bc049a5aea
30 files changed
+633 -100

No files matched your search

+14
View File
@@ -293,11 +293,25 @@ const strataComing = {
ko: ['엔진과 함께 제공 예정', '엔진과 함께 제공 예정: 이 빌드의 엔진은 초안 레이어(MTP)과 이미지 읽기를 아직 지원하지 않습니다. 당분간 꺼진 상태로 유지됩니다.'],
he: ['יגיע עם המנוע', 'יגיע עם המנוע: שכבת הטיוטה (MTP) וקריאת תמונות עדיין אינן במנוע עבור הגרסה הזו. בינתיים הן נשארות כבויות.'],
};
// the K/V format lines (q427 to q430) and the Auto help of the draft layer (q431 on, q432 off): qwen4_family.KV_WORDS, qwen4_fit.AUTO_HELP.
const kvAuto = {
en: ['int8: same quality as fp16, faster prompt reading.', 'k8v4 and q4_0: less memory for long context.', 'fp16: the reference, most memory.', 'fp8: like int8, new, NVIDIA first.', 'Auto turns the draft layer on for graphics cards of 6 GB or more.', 'Auto keeps the draft layer off on this card: it is under 6 GB or it measured slower here.'],
de: ['int8: gleiche Qualität wie fp16, schnelleres Lesen des Prompts.', 'k8v4 und q4_0: weniger Speicher bei langem Kontext.', 'fp16: die Referenz, am meisten Speicher.', 'fp8: wie int8, neu, zuerst für NVIDIA.', 'Auto schaltet die Entwurfsschicht für Grafikkarten ab 6 GB ein.', 'Auto lässt die Entwurfsschicht auf dieser Karte aus: sie hat unter 6 GB oder war hier langsamer.'],
es: ['int8: la misma calidad que fp16, lectura del prompt más rápida.', 'k8v4 y q4_0: menos memoria con contexto largo.', 'fp16: la referencia, la que más memoria usa.', 'fp8: como int8, nuevo, primero para NVIDIA.', 'Auto activa la capa de borrador en tarjetas gráficas de 6 GB o más.', 'Auto deja la capa de borrador desactivada en esta tarjeta: tiene menos de 6 GB o aquí resultó más lenta.'],
fr: ['int8 : même qualité que fp16, lecture de l’invite plus rapide.', 'k8v4 et q4_0 : moins de mémoire pour un long contexte.', 'fp16 : la référence, la plus gourmande en mémoire.', 'fp8 : comme int8, nouveau, d’abord pour NVIDIA.', 'Auto active la couche de brouillon sur les cartes graphiques de 6 Go ou plus.', 'Auto laisse la couche de brouillon désactivée sur cette carte : elle a moins de 6 Go ou y était plus lente.'],
pt: ['int8: a mesma qualidade do fp16, leitura do prompt mais rápida.', 'k8v4 e q4_0: menos memória com contexto longo.', 'fp16: a referência, a que mais usa memória.', 'fp8: como o int8, novo, primeiro para NVIDIA.', 'Auto liga a camada de rascunho em placas de vídeo de 6 GB ou mais.', 'Auto mantém a camada de rascunho desligada nesta placa: ela tem menos de 6 GB ou aqui foi mais lenta.'],
ru: ['int8: то же качество, что у fp16, быстрее чтение запроса.', 'k8v4 и q4_0: меньше памяти при длинном контексте.', 'fp16: эталон, больше всего памяти.', 'fp8: как int8, новинка, сначала для NVIDIA.', 'Авто включает черновой слой на видеокартах от 6 ГБ.', 'Авто оставляет черновой слой выключенным на этой карте: у неё меньше 6 ГБ или здесь он работал медленнее.'],
zh: ['int8:质量与 fp16 相同,读取提示更快。', 'k8v4 和 q4_0:长上下文占用更少内存。', 'fp16:基准格式,占用内存最多。', 'fp8:类似 int8,较新,优先支持 NVIDIA。', '自动:6 GB 及以上的显卡会开启草稿层。', '自动:此显卡上草稿层保持关闭:显存不足 6 GB,或实测更慢。'],
ja: ['int8:fp16 と同じ品質で、プロンプトの読み込みが速くなります。', 'k8v4 と q4_0:長いコンテキストでメモリを節約します。', 'fp16:基準の形式で、メモリを最も使います。', 'fp8:int8 に近く、新しい形式で、まず NVIDIA 向けです。', '自動:6 GB 以上のグラフィックスカードでドラフトレイヤーをオンにします。', '自動:このカードではドラフトレイヤーをオフのままにします(6 GB 未満、または実測で遅いため)。'],
ko: ['int8: fp16과 같은 품질에 프롬프트 읽기가 더 빠릅니다.', 'k8v4와 q4_0: 긴 컨텍스트에서 메모리를 덜 씁니다.', 'fp16: 기준 형식으로 메모리를 가장 많이 씁니다.', 'fp8: int8과 비슷한 새 형식으로, NVIDIA가 먼저입니다.', '자동: 6GB 이상의 그래픽 카드에서 초안 레이어를 켭니다.', '자동: 이 카드에서는 초안 레이어를 끈 채로 둡니다(6GB 미만이거나 실측에서 더 느렸습니다).'],
he: ['int8: אותה איכות כמו fp16, קריאת ההנחיה מהירה יותר.', 'k8v4 ו-q4_0: פחות זיכרון בהקשר ארוך.', 'fp16: המדד, הכי הרבה זיכרון.', 'fp8: כמו int8, חדש, קודם כל ל-NVIDIA.', 'אוטומטי: שכבת הטיוטה מופעלת בכרטיסים גרפיים של 6 GB ומעלה.', 'אוטומטי: בכרטיס הזה שכבת הטיוטה נשארת כבויה: יש בו פחות מ-6 GB או שהיא התגלתה כאן איטית יותר.'],
};
for (const [lang, strings] of Object.entries(add)) {
const file = join(dir, `gtui-${lang}.json`);
const data = JSON.parse(readFileSync(file, 'utf8'));
// French: a no-break space before ; : ? ! (tests/french-typography-all.test.mjs)
for (const [k, v] of Object.entries(strings)) if (!(k in data)) data[k] = lang === 'fr' ? v.replace(/(?<=\S) ([;:?!])/g, '\u00a0$1') : v;
kvAuto[lang].forEach((text, i) => { const k = `q${427 + i}`; if (!(k in data)) data[k] = lang === 'fr' ? text.replace(/(?<=\S) ([;:?!])/g, '\u00a0$1') : text; });
const [suffix, sentence] = strataComing[lang];
const guicEn = JSON.parse(readFileSync(join(dir, 'guic-en.json'), 'utf8')); // the language's own "Draft layer (MTP)" is in the guic catalog
const guic = JSON.parse(readFileSync(join(dir, `guic-${lang}.json`), 'utf8'));
+1 -1
View File
@@ -14,7 +14,7 @@ export const NATIVE_FIELDS=[
{id:'mtp',label:'Draft layer (MTP)',group:'Serving',type:'boolean',hint:'The draft layer guesses several words ahead, which makes answers faster, and costs about 1 GB of graphics memory and some RAM. Turn it off if the model stops while it starts, or the card is small: the expert cache gets that memory back and answers are slower. Default is on.'},
{id:'ling_mtp',label:'Draft layer (MTP)',group:'Serving',type:'enum',choices:['auto','on','off'],hint:'Auto: the engine loads the MTP draft layer only where it speeds answers up on this card (it measures the link when it starts). On forces it, Off never loads it. The file is 1 GB.'},
{id:'effort',label:'Effort by default',group:'Responses',type:'enum',choices:['off','low','high','xhigh'],hint:'How hard Qwen4-35B-A3B thinks when a request says nothing (the Reasoning menu of a chat does). Off answers straight away; Low, High and X-High think first, longer each step: slower, better on hard questions.'},
{id:'q4_mtp',label:'Draft layer (MTP)',group:'Serving',type:'enum',choices:['auto','on','off'],hint:'Auto: the engine loads the MTP draft layer only where it speeds answers up on this PC (it checks when it starts). On forces it, Off never loads it. The file is 0.4 GB.'},
{id:'q4_mtp',label:'Draft layer (MTP)',group:'Serving',type:'enum',choices:['auto','on','off'],hint:'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.'},
{id:'q4_loop',label:'Loop (2 steps)',group:'Serving',type:'enum',choices:['off','on'],hint:'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. Off by default. Needs a 147 MB file that the Download step fetches when Loop is on. It has no effect while Effort is Off.'},
{id:'ling_skip',label:'Expert skip',group:'Serving',type:'enum',choices:['off','medium','custom'],hint:'Faster answers with a small cost in accuracy. Off (the default) gives the exact answers. Medium lets the engine skip the experts that matter least for each word it writes: about 1 word in 60 differs. Applies the next time the model loads.'},
{id:'thinking',label:'Thinking by default',group:'Responses',type:'enum',choices:['off','on'],hint:'Ling-3.2-Air thinks only when a request asks for it (the Thinking menu of a chat does). On makes every request that says nothing think first: slower, better on hard questions.'},
+9
View File
@@ -55,6 +55,15 @@ export const qwen4MtpReady = (build, table = QWEN4_STRATA_READY) => String(build
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;
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. */
export const QWEN4_KV_CHOICES = Object.freeze({ gguf: Object.freeze(['int8', 'fp16', 'k8v4', 'fp8', 'q4_0']), strata: Object.freeze(['fp16']) });
export const QWEN4_KV_DEFAULT = Object.freeze({ gguf: 'int8', strata: 'fp16' });
export const QWEN4_KV_READY = Object.freeze({ 'gguf/fp8': false });
export const QWEN4_KV_BACKENDS = Object.freeze({ fp8: Object.freeze(['cuda']) });
const kvSource = build => String(build ?? '').toLowerCase() === 'ud-q4_k_xl' ? 'gguf' : 'strata';
export const qwen4KvChoices = (build, backend) => { const src = kvSource(build), be = String(backend || 'cuda').toLowerCase(); return QWEN4_KV_CHOICES[src].filter(k => QWEN4_KV_READY[`${src}/${k}`] !== false && (QWEN4_KV_BACKENDS[k] ?? [be]).includes(be)); };
export const qwen4KvDefault = build => QWEN4_KV_DEFAULT[kvSource(build)];
export const qwen4KvPick = (build, backend, kv) => kv && qwen4KvChoices(build, backend).includes(kv) ? kv : qwen4KvDefault(build);
/** The Loop table's source of a build name: gguf for UD-Q4_K_XL, strata for the others. */
export const qwen4LoopSource = build => String(build ?? '').toLowerCase() === 'ud-q4_k_xl' ? 'gguf' : 'strata';
/** Does the engine support Loop for this build on this backend (no backend means cuda; an unknown build or backend is false)? */
+9 -7
View File
@@ -35,7 +35,7 @@ import { NativeTune } from './NativeTune';
import { NativeTuneBadge } from './NativeTuneBadge';
import { commitWarning } from '../lib/commit-warning';
import { nativeCatalogModels, catalogVersionLabel, type CatalogVersion, fetchesPictures, hasKvChoice, HY4_FAMILY, LING_FAMILY, isNativeStrataFamily } from '../lib/native-catalog';
import { QWEN4_FAMILY, qwen4LoopReady, qwen4MtpReady, isQwen4GgufBuild } from '../lib/qwen4';
import { QWEN4_FAMILY, qwen4LoopReady, qwen4MtpReady, qwen4KvPick, qwen4KvChoices, QWEN4_KV_LABELS, isQwen4GgufBuild } from '../lib/qwen4';
export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }: {
onOtherModels: () => void;
onImport?: () => void;
@@ -57,7 +57,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
const selectedFamily = families.find(f => f.family === family || f.sizes.some(size => size.sourceFamily === family)) ?? families[0], selectedSize = selectedFamily?.sizes.find(s => s.id === size) ?? selectedFamily?.sizes[0];
const isHy4Selected = isNativeStrataFamily(selectedFamily?.family); // Hy4-Flash, Inkling-2-Mini or Ling-3.2-Air: a native program, none of the Flash-Next options
const isLingSelected = selectedFamily?.family === LING_FAMILY, ling = isLingSelected ? selectedSize?.ling32 ?? null : null;
const isQ4Selected = selectedFamily?.family === QWEN4_FAMILY, q4 = isQ4Selected ? selectedSize?.qwen4 ?? null : null, q4Own = isQ4Selected && !selectedSize?.custom, q4LoopReady = q4Own && qwen4LoopReady(selectedSize?.model, q4?.backend); // Qwen4-35B-A3B: Loop (2 steps) is for Strata's own quantization only
const isQ4Selected = selectedFamily?.family === QWEN4_FAMILY, q4 = isQ4Selected ? selectedSize?.qwen4 ?? null : null, q4Own = isQ4Selected && !selectedSize?.custom, q4LoopReady = q4Own && qwen4LoopReady(selectedSize?.model, q4?.backend), q4Kv = isQ4Selected ? qwen4KvPick(selectedSize?.model, q4?.backend, kv, q4?.kv_choices) : kv; // Qwen4-35B-A3B: Loop (2 steps) is for Strata's own quantization only
const q4NoEngine = !!q4 && q4.engine_exists === false;
const lingNoEngine = !!ling && ling.engine_exists === false; // this make of card has no Ling engine yet (Intel until SYCL exists): the download would be for nothing
const isGgufSelected = selectedFamily?.family === HY4_FAMILY && selectedSize?.format === 'gguf'; // AngelSlim's Hy4-Flash GGUF build (NVIDIA): its own Context-memory choice (INT8 or FP16)
@@ -146,7 +146,7 @@ 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, 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 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 } : {}) };
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) {
@@ -261,7 +261,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
return; presetPending.current = true; setFamily(f.family); setSize(f.sizes.find(s => s.model === v.model && (s.sourceFamily === v.family || f.family === v.family))?.id ?? ''); setContext(v.context ?? 32768); setVision(v.vision ?? 'no'); setKv(v.kv ?? 'int8'); setLowRam(v.low_ram ?? 'auto'); }}/> : null}<Btn icon="models" size="sm" variant="ghost" onClick={() => setManage(true)}>{tr("Manage models")}</Btn></span></div>
<div className="native-version"><VersionPicker pick={native?.catalog?.recommendation} versions={selectedFamily?.sizes ?? []} details={expert} selectedId={selectedSize.id} hardware={labelHardware} cache={{ context, kv, drafter: fitDrafter }} downloaded={readyIds} onSelect={id => { const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); setLoadedError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/></div>
{tr(fitState === 'ssd' ? <p className="small muted native-spill-note"><Icon name="disk" size={16}/>{tr("may run slower")}</p> : null)}
{tr(q4 ? <Qwen4Plan selectedModel={selectedSize?.model} q4={q4} mtp={lingMtp} onMtp={setLingMtp} loop={q4Loop} onLoop={setQ4Loop} loopOffered={q4Own} installedLoop={installed?.q4Loop} installedMtp={installed?.draftLayer} disabled={!!active}/> : null)}
{tr(q4 ? <Qwen4Plan selectedModel={selectedSize?.model} q4={q4} mtp={lingMtp} onMtp={setLingMtp} kv={q4Kv} onKv={setKv as (v: string) => void} loop={q4Loop} onLoop={setQ4Loop} loopOffered={q4Own} installedLoop={installed?.q4Loop} installedMtp={installed?.draftLayer} disabled={!!active}/> : null)}
{tr(ling ? <LingPlan ling={ling} mtp={lingMtp} onMtp={setLingMtp} skip={lingSkip} onSkip={setLingSkip} installedMtp={installed?.draftLayer} live={loadedSelected?.metrics?.engine?.ling32} disabled={!!active}/> : null)}
{tr(isGgufSelected && selectedSize?.hy4?.fit?.level === 'tight' ? <p className="small muted native-spill-note"><Icon name="warning" size={16}/>{tr("This build wants about {0} GB of RAM and this PC has {1} GB: the experts that do not fit are read from the SSD, which is much slower.", [selectedSize.hy4.ram_need_gb, Math.round(pcRam ?? 0)])}{tr(selectedSize.hy4.fit.suggest ? <> {tr("The less-RAM build needs about {0} GB.", [selectedFamily?.sizes.find(s => s.model === selectedSize.hy4!.fit!.suggest)?.ram_needed_gb])}</> : null)}</p> : null)}
<div className="native-choice__row">
@@ -379,8 +379,8 @@ 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, loop, onLoop, loopOffered, installedLoop, installedMtp, disabled }: { q4: NonNullable<CatalogVersion['qwen4']>; mtp: string; onMtp: (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); // Loop (2 steps) per build and backend: qwen4_family.LOOP_READY, mirrored in lib/qwen4.ts
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 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');
@@ -392,7 +392,9 @@ function Qwen4Plan({ selectedModel, q4, mtp, onMtp, loop, onLoop, loopOffered, i
{old ? <p className="small muted native-spill-note"><Icon name="info" size={16}/>{tr("This NVIDIA card has no tensor cores for this engine, so Qwen4-35B-A3B runs on plain kernels, slower than on an RTX 20 series or newer.")}</p> : null}
{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' ? "Auto: the draft layer is used only where it speeds answers up on this PC; the engine checks when it starts. The file is 0.4 GB." : "The draft layer guesses several words ahead to answer faster. It is a 0.4 GB file.")}</small></div></div> : null}
<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))}/>
<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}
</div>;
+1 -1
View File
@@ -3,7 +3,7 @@ import { api } from './client';
import type { Hardware, RuntimeModels } from './types';
export interface GpuChoiceOption {key:string;cards:number[];label:string;verdict:'fits'|'tight'|'spills'|'unknown';words:string;notes:string[];recommended:boolean}
export interface GpuChoice {options:GpuChoiceOption[];recommended:string|null;ignored:{name?:string;why_ignored:string}[];cards:number}
export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;/** The files without the lookup table (the download minus the n-gram / PLE / Engram file): what the fit label and the "Needs" figure use. */fit_gb?:number|null;format?:string;/** The make of card a build runs on (a Hy4-Flash GGUF build: "nvidia"), and its short name in the version list. */gpu_vendor?:string;label?:string;/** Qwen3.6: its own context rule (strata_control/own_path_fit.py via the catalog, #5715). */context_fit?:import('./native-fit').ContextFit|null;/** Tencent Hy4-Flash: where the build's experts go on this PC (strata_control/hy4_fit.py via the catalog). */hy4?:{placement?:{vram_gb:number;ram_gb:number;ssd_gb:number};mode:'ram_vram_zero_ssd'|'near_resident_ssd'|'cross_tier_ssd';recommended:boolean;unified:boolean;engram_gb?:number;/** A GGUF build (AngelSlim's, NVIDIA): the RAM it wants against this PC's, in words (strata_control/hy4_gguf.py fit_words). */gguf?:boolean;ram_need_gb?:number;fit?:{level:'ok'|'tight'|'unknown';text:string;suggest:string|null};context?:number}|null;/** Inkling-2-Mini: hardware placement & auto-selection (strata_control/inkling_fit.py via the catalog). */inkling?:{placement:{vram_gb:number;ram_gb:number;ssd_gb:number;full_vram?:boolean};mode:'full_vram'|'ram_vram_zero_ssd'|'near_resident_ssd'|'cross_tier_ssd';recommended:boolean;unified:boolean;context:number;kv_gb:number;parallel_choices?:number[]}|null;/** inclusionAI Ling-3.2-Air: the memory tier this PC gets (terminal/strata_control/ling32_fit.py via the catalog) and what is different about this make of card (codes in notes; no speed figure). */ling32?:{tier:'A'|'B'|'C'|null;placement:{vram_gb:number;ram_gb:number;ssd_gb:number};mode:'ram_vram_zero_ssd'|'cross_tier_ssd';recommended:boolean;unified:boolean;context:number;feasible:boolean;backend?:'cuda'|'hip'|'metal'|'sycl';engine_exists?:boolean;mac?:boolean;mac_advice?:string|null;mtp_default?:boolean;notes?:{code:string;card?:string;cards?:string[];ram_gb?:number;below?:boolean;advice?:string}[]}|null;/** Qwen4-35B-A3B (strata_control/qwen4_fit.py through the catalog): the build and PLE table this PC gets, where the model lives (mode), the memory it needs, the engine row of this card and whether the engine reads pictures. */qwen4?:{build:'Compact'|'Balanced'|'Ultra'|'UD-Q4_K_XL';ple:'Q4'|'Q8'|null;recommended_ple?:'Q4'|'Q8';mode:'resident'|'hybrid'|'unified'|'short';recommended?:boolean;unified?:boolean;vram_need_gib?:number;ram_need_gib?:number;download_gb?:number;backend?:'cuda'|'hip'|'metal';engine_exists?:boolean;engine_images?:boolean;loop_available?:boolean;notes?:{code:string;card?:string;cards?:string[];ram_gb?:number;advice?:string}[]}|null;installed:boolean;/** Model files are already present on disk in the models folder even before a run config is created (#7216 / SQv2-20). */files_on_disk?:boolean;/** Path to the discovered local .strata/.gguf weight file on disk when unregistered. */local_files_path?:string;/** Remaining download size in GB when primary model files are already on disk. */remaining_download_gb?:number;/** Inkling-2-Mini: false for a quant 0.2.23 no longer offers (listed only while it is installed; never recommended, never downloaded). */offered?:boolean;/** The line of credit shown with the version (GSQ-RCO: GSQ + RCO by IST Austria DASLab, Apache-2.0). */credit?:string;/** Installed, but the file is an older one than the one offered now (SQ-20 of 0.2.22): the list says so; the old file keeps working and is never deleted. */update_available?:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean;/** A custom build (the person's own .strata or .gguf, used in place): its id is its own run config; `model` is the closest official build. */custom?:boolean;displayName?:string;customBytes?:number;}
export interface NativeSize {/** The first engine that reads this size's files (the catalog), and whether the installed engine is older: the screen then says "needs a newer engine" and offers the update. */engine_min?:string|null;needsNewerEngine?:boolean;id:string;model:string;about:string;download_gb:number;ram_needed_gb:number;experts_gb:number;on_this_pc:string|null;/** The files without the lookup table (the download minus the n-gram / PLE / Engram file): what the fit label and the "Needs" figure use. */fit_gb?:number|null;format?:string;/** The make of card a build runs on (a Hy4-Flash GGUF build: "nvidia"), and its short name in the version list. */gpu_vendor?:string;label?:string;/** Qwen3.6: its own context rule (strata_control/own_path_fit.py via the catalog, #5715). */context_fit?:import('./native-fit').ContextFit|null;/** Tencent Hy4-Flash: where the build's experts go on this PC (strata_control/hy4_fit.py via the catalog). */hy4?:{placement?:{vram_gb:number;ram_gb:number;ssd_gb:number};mode:'ram_vram_zero_ssd'|'near_resident_ssd'|'cross_tier_ssd';recommended:boolean;unified:boolean;engram_gb?:number;/** A GGUF build (AngelSlim's, NVIDIA): the RAM it wants against this PC's, in words (strata_control/hy4_gguf.py fit_words). */gguf?:boolean;ram_need_gb?:number;fit?:{level:'ok'|'tight'|'unknown';text:string;suggest:string|null};context?:number}|null;/** Inkling-2-Mini: hardware placement & auto-selection (strata_control/inkling_fit.py via the catalog). */inkling?:{placement:{vram_gb:number;ram_gb:number;ssd_gb:number;full_vram?:boolean};mode:'full_vram'|'ram_vram_zero_ssd'|'near_resident_ssd'|'cross_tier_ssd';recommended:boolean;unified:boolean;context:number;kv_gb:number;parallel_choices?:number[]}|null;/** inclusionAI Ling-3.2-Air: the memory tier this PC gets (terminal/strata_control/ling32_fit.py via the catalog) and what is different about this make of card (codes in notes; no speed figure). */ling32?:{tier:'A'|'B'|'C'|null;placement:{vram_gb:number;ram_gb:number;ssd_gb:number};mode:'ram_vram_zero_ssd'|'cross_tier_ssd';recommended:boolean;unified:boolean;context:number;feasible:boolean;backend?:'cuda'|'hip'|'metal'|'sycl';engine_exists?:boolean;mac?:boolean;mac_advice?:string|null;mtp_default?:boolean;notes?:{code:string;card?:string;cards?:string[];ram_gb?:number;below?:boolean;advice?:string}[]}|null;/** Qwen4-35B-A3B (strata_control/qwen4_fit.py through the catalog): the build and PLE table this PC gets, where the model lives (mode), the memory it needs, the engine row of this card and whether the engine reads pictures. */qwen4?:{build:'Compact'|'Balanced'|'Ultra'|'UD-Q4_K_XL';ple:'Q4'|'Q8'|null;recommended_ple?:'Q4'|'Q8';mode:'resident'|'hybrid'|'unified'|'short';recommended?:boolean;unified?:boolean;vram_need_gib?:number;ram_need_gib?:number;download_gb?:number;backend?:'cuda'|'hip'|'metal';engine_exists?:boolean;engine_images?:boolean;loop_available?:boolean;/** The K/V formats this build takes on this card (qwen4_family.kv_choices), the one it starts with, and what Auto does with the draft layer here. */kv?:string;kv_choices?:string[];kv_default?:string;mtp_default?:boolean;mtp_available?:boolean;notes?:{code:string;card?:string;cards?:string[];ram_gb?:number;advice?:string}[]}|null;installed:boolean;/** Model files are already present on disk in the models folder even before a run config is created (#7216 / SQv2-20). */files_on_disk?:boolean;/** Path to the discovered local .strata/.gguf weight file on disk when unregistered. */local_files_path?:string;/** Remaining download size in GB when primary model files are already on disk. */remaining_download_gb?:number;/** Inkling-2-Mini: false for a quant 0.2.23 no longer offers (listed only while it is installed; never recommended, never downloaded). */offered?:boolean;/** The line of credit shown with the version (GSQ-RCO: GSQ + RCO by IST Austria DASLab, Apache-2.0). */credit?:string;/** Installed, but the file is an older one than the one offered now (SQ-20 of 0.2.22): the list says so; the old file keeps working and is never deleted. */update_available?:boolean;gpu_options?:GpuChoice|null;images?:boolean;imagesCapable?:boolean;/** A custom build (the person's own .strata or .gguf, used in place): its id is its own run config; `model` is the closest official build. */custom?:boolean;displayName?:string;customBytes?:number;}
export interface NativeFamily {family:string;title:string;about:string;experimental:boolean;images:boolean;sizes:NativeSize[];/** A model of the signed update feed (shown after the built-in ones); `available:false` = this engine does not run it, `unavailable_reason` says so in plain words. */feed?:boolean;available?:boolean;unavailable_reason?:string}
export interface NativeField {id:string;label:string;group:string;type:'number'|'boolean'|'string'|'enum'|'array';min?:number;max?:number;choices?:string[];hint?:string;supported?:boolean}
export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string;family?:string;state:'running'|'done'|'error'|'cancelled';startedAt:string;summary:string;error:string|null;details?:string;result:Record<string,any>|null;progress?:Record<string,any>|null;/** An engine or Strata update beside a loaded model: which step it is on and the models it concerns (the app words these itself). */step?:'downloading'|'applying'|'getting-ready'|'stopping'|'stopped';models?:string[]}
+14
View File
@@ -15,6 +15,20 @@ export const qwen4LoopReady = (build?: string | null, backend?: string | null, t
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; };
/** 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'] });
export const QWEN4_KV_DEFAULT: Readonly<Record<string, string>> = Object.freeze({ gguf: 'int8', strata: 'fp16' });
export const QWEN4_KV_READY: Readonly<Record<string, boolean>> = Object.freeze({ 'gguf/fp8': false });
export const QWEN4_KV_BACKENDS: Readonly<Record<string, readonly string[]>> = Object.freeze({ fp8: ['cuda'] });
const kvSource = (build?: string | null) => String(build ?? '').toLowerCase() === 'ud-q4_k_xl' ? 'gguf' : 'strata';
export const qwen4KvChoices = (build?: string | null, backend?: string | null): string[] => { const src = kvSource(build), be = String(backend || 'cuda').toLowerCase(); return QWEN4_KV_CHOICES[src].filter(k => QWEN4_KV_READY[`${src}/${k}`] !== false && (QWEN4_KV_BACKENDS[k] ?? [be]).includes(be)); };
export const qwen4KvDefault = (build?: string | null): string => QWEN4_KV_DEFAULT[kvSource(build)];
/** The format a start uses: the person's word when this build takes it, else the build's default. */
export const qwen4KvPick = (build?: string | null, backend?: string | null, kv?: string | null, offered?: readonly string[] | null): string => { const list = offered?.length ? offered : qwen4KvChoices(build, backend); return kv && list.includes(kv) ? kv : qwen4KvDefault(build); };
export const QWEN4_KV_LABELS: Readonly<Record<string, string>> = Object.freeze({ int8: 'INT8', fp16: 'FP16', k8v4: 'K8 / V4', q4_0: 'Q4', fp8: 'FP8' });
/** What each format is for, in one line (qwen4_family.KV_WORDS): the strings q427 to q430. */
export const QWEN4_KV_HINTS: Readonly<Record<string, string>> = Object.freeze({ int8: 'int8: same quality as fp16, faster prompt reading.', k8v4: 'k8v4 and q4_0: less memory for long context.', q4_0: 'k8v4 and q4_0: less memory for long context.', fp16: 'fp16: the reference, most memory.', fp8: 'fp8: like int8, new, NVIDIA first.' });
export const QWEN4_BUILDS = ['Compact', 'Balanced', 'Ultra'] as const;
export type Qwen4Build = typeof QWEN4_BUILDS[number];
/** The fourth build, Unsloth's UD-Q4_K_XL GGUF (qwen4_family.GGUF_BUILD): listed after the three, never recommended, no PLE choice of its own. */
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop (2 Schritte) - bald verfügbar",
"q424": "Bald verfügbar: Loop (2 Schritte) braucht Engine-Unterstützung, die in dieser Version noch nicht enthalten ist. Es bleibt vorerst aus.",
"q425": "Entwurfsschicht (MTP) - kommt mit der Engine",
"q426": "Kommt mit der Engine: Die Entwurfsschicht (MTP) und das Lesen von Bildern sind in der Engine für diese Variante noch nicht enthalten. Sie bleiben vorerst aus."
"q426": "Kommt mit der Engine: Die Entwurfsschicht (MTP) und das Lesen von Bildern sind in der Engine für diese Variante noch nicht enthalten. Sie bleiben vorerst aus.",
"q427": "int8: gleiche Qualität wie fp16, schnelleres Lesen des Prompts.",
"q428": "k8v4 und q4_0: weniger Speicher bei langem Kontext.",
"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."
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop (2 steps) - coming soon",
"q424": "Coming soon: Loop (2 steps) needs engine support that is not in this release yet. It stays off for now.",
"q425": "Draft layer (MTP) - coming with the engine",
"q426": "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."
"q426": "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.",
"q427": "int8: same quality as fp16, faster prompt reading.",
"q428": "k8v4 and q4_0: less memory for long context.",
"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."
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop (2 pasos) - próximamente",
"q424": "Próximamente: Loop (2 pasos) necesita compatibilidad del motor que aún no está en esta versión. Por ahora sigue desactivado.",
"q425": "Capa de borrador (MTP) - llegará con el motor",
"q426": "Llegará con el motor: la capa de borrador (MTP) y la lectura de imágenes aún no están en el motor para esta variante. Por ahora siguen desactivadas."
"q426": "Llegará con el motor: la capa de borrador (MTP) y la lectura de imágenes aún no están en el motor para esta variante. Por ahora siguen desactivadas.",
"q427": "int8: la misma calidad que fp16, lectura del prompt más rápida.",
"q428": "k8v4 y q4_0: menos memoria con contexto largo.",
"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."
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop (2 étapes) - bientôt disponible",
"q424": "Bientôt disponible : Loop (2 étapes) a besoin d’une prise en charge du moteur qui n’est pas encore dans cette version. Il reste désactivé pour l’instant.",
"q425": "Couche de brouillon (MTP) - arrive avec le moteur",
"q426": "Arrive avec le moteur : la couche de brouillon (MTP) et la lecture des images ne sont pas encore dans le moteur pour cette version. Elles restent désactivées pour l’instant."
"q426": "Arrive avec le moteur : la couche de brouillon (MTP) et la lecture des images ne sont pas encore dans le moteur pour cette version. Elles restent désactivées pour l’instant.",
"q427": "int8 : même qualité que fp16, lecture de l’invite plus rapide.",
"q428": "k8v4 et q4_0 : moins de mémoire pour un long contexte.",
"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."
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop (2 צעדים) - בקרוב",
"q424": "בקרוב: ל-Loop (2 צעדים) דרושה תמיכה במנוע שעדיין אינה בגרסה הזו. בינתיים הוא נשאר כבוי.",
"q425": "שכבת טיוטה (MTP) - יגיע עם המנוע",
"q426": "יגיע עם המנוע: שכבת הטיוטה (MTP) וקריאת תמונות עדיין אינן במנוע עבור הגרסה הזו. בינתיים הן נשארות כבויות."
"q426": "יגיע עם המנוע: שכבת הטיוטה (MTP) וקריאת תמונות עדיין אינן במנוע עבור הגרסה הזו. בינתיים הן נשארות כבויות.",
"q427": "int8: אותה איכות כמו fp16, קריאת ההנחיה מהירה יותר.",
"q428": "k8v4 ו-q4_0: פחות זיכרון בהקשר ארוך.",
"q429": "fp16: המדד, הכי הרבה זיכרון.",
"q430": "fp8: כמו int8, חדש, קודם כל ל-NVIDIA.",
"q431": "אוטומטי: שכבת הטיוטה מופעלת בכרטיסים גרפיים של 6 GB ומעלה.",
"q432": "אוטומטי: בכרטיס הזה שכבת הטיוטה נשארת כבויה: יש בו פחות מ-6 GB או שהיא התגלתה כאן איטית יותר."
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop(2 ステップ)- 近日対応",
"q424": "近日対応:Loop(2 ステップ)にはエンジン側の対応が必要で、このリリースにはまだ含まれていません。当面はオフのままです。",
"q425": "ドラフトレイヤー(MTP) - エンジン対応待ち",
"q426": "エンジン対応待ち:このビルドでは、ドラフトレイヤー(MTP)と画像の読み取りにエンジン側がまだ対応していません。当面はオフのままです。"
"q426": "エンジン対応待ち:このビルドでは、ドラフトレイヤー(MTP)と画像の読み取りにエンジン側がまだ対応していません。当面はオフのままです。",
"q427": "int8:fp16 と同じ品質で、プロンプトの読み込みが速くなります。",
"q428": "k8v4 と q4_0:長いコンテキストでメモリを節約します。",
"q429": "fp16:基準の形式で、メモリを最も使います。",
"q430": "fp8:int8 に近く、新しい形式で、まず NVIDIA 向けです。",
"q431": "自動:6 GB 以上のグラフィックスカードでドラフトレイヤーをオンにします。",
"q432": "自動:このカードではドラフトレイヤーをオフのままにします(6 GB 未満、または実測で遅いため)。"
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop(2단계) - 곧 제공",
"q424": "곧 제공: Loop(2단계)에는 엔진 지원이 필요하며 이번 릴리스에는 아직 없습니다. 당분간 꺼진 상태로 유지됩니다.",
"q425": "초안 레이어(MTP) - 엔진과 함께 제공 예정",
"q426": "엔진과 함께 제공 예정: 이 빌드의 엔진은 초안 레이어(MTP)과 이미지 읽기를 아직 지원하지 않습니다. 당분간 꺼진 상태로 유지됩니다."
"q426": "엔진과 함께 제공 예정: 이 빌드의 엔진은 초안 레이어(MTP)과 이미지 읽기를 아직 지원하지 않습니다. 당분간 꺼진 상태로 유지됩니다.",
"q427": "int8: fp16과 같은 품질에 프롬프트 읽기가 더 빠릅니다.",
"q428": "k8v4와 q4_0: 긴 컨텍스트에서 메모리를 덜 씁니다.",
"q429": "fp16: 기준 형식으로 메모리를 가장 많이 씁니다.",
"q430": "fp8: int8과 비슷한 새 형식으로, NVIDIA가 먼저입니다.",
"q431": "자동: 6GB 이상의 그래픽 카드에서 초안 레이어를 켭니다.",
"q432": "자동: 이 카드에서는 초안 레이어를 끈 채로 둡니다(6GB 미만이거나 실측에서 더 느렸습니다)."
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop (2 passos) - em breve",
"q424": "Em breve: o Loop (2 passos) precisa de suporte do motor que ainda não está nesta versão. Por enquanto fica desligado.",
"q425": "Camada de rascunho (MTP) - chega com o motor",
"q426": "Chega com o motor: a camada de rascunho (MTP) e a leitura de imagens ainda não estão no motor para esta versão. Por enquanto ficam desligadas."
"q426": "Chega com o motor: a camada de rascunho (MTP) e a leitura de imagens ainda não estão no motor para esta versão. Por enquanto ficam desligadas.",
"q427": "int8: a mesma qualidade do fp16, leitura do prompt mais rápida.",
"q428": "k8v4 e q4_0: menos memória com contexto longo.",
"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."
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop (2 шага) - скоро",
"q424": "Скоро: для Loop (2 шага) нужна поддержка в движке, которой пока нет в этой версии. Пока он остаётся выключенным.",
"q425": "Черновой слой (MTP) - появится вместе с движком",
"q426": "Появится вместе с движком: черновой слой (MTP) и чтение изображений пока не поддерживаются движком для этой сборки. Пока они остаются выключенными."
"q426": "Появится вместе с движком: черновой слой (MTP) и чтение изображений пока не поддерживаются движком для этой сборки. Пока они остаются выключенными.",
"q427": "int8: то же качество, что у fp16, быстрее чтение запроса.",
"q428": "k8v4 и q4_0: меньше памяти при длинном контексте.",
"q429": "fp16: эталон, больше всего памяти.",
"q430": "fp8: как int8, новинка, сначала для NVIDIA.",
"q431": "Авто включает черновой слой на видеокартах от 6 ГБ.",
"q432": "Авто оставляет черновой слой выключенным на этой карте: у неё меньше 6 ГБ или здесь он работал медленнее."
}
+7 -1
View File
@@ -126,5 +126,11 @@
"q423": "Loop(2 步)- 即将推出",
"q424": "即将推出:Loop(2 步)需要引擎支持,当前版本尚未包含。暂时保持关闭。",
"q425": "草稿层(MTP) - 随引擎推出",
"q426": "随引擎推出:此版本的引擎尚不支持草稿层(MTP)和图片读取。暂时保持关闭。"
"q426": "随引擎推出:此版本的引擎尚不支持草稿层(MTP)和图片读取。暂时保持关闭。",
"q427": "int8:质量与 fp16 相同,读取提示更快。",
"q428": "k8v4 和 q4_0:长上下文占用更少内存。",
"q429": "fp16:基准格式,占用内存最多。",
"q430": "fp8:类似 int8,较新,优先支持 NVIDIA。",
"q431": "自动:6 GB 及以上的显卡会开启草稿层。",
"q432": "自动:此显卡上草稿层保持关闭:显存不足 6 GB,或实测更慢。"
}
+50 -2
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_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, 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';
@@ -304,7 +304,7 @@ test('the strings of the Qwen4 panel are in all ten languages with the same plac
for (const l of langs) for (const k of keys) assert.equal(slots(catalogs[l][k]), slots(catalogs.en[k]), `${l} ${k} placeholders`);
for (const k of keys) assert.ok(!/tok\/s|tokens? per second/i.test(catalogs.en[k]), `${k} has no speed figure`);
const used = src('src/components/NativeModels.tsx') + src('server/native-settings.mjs') + src('src/lib/qwen4.ts');
for (const k of keys.filter(k => k !== 'q421' && k !== 'q416')) { // q421 is the build's own name, Ultra, shown through the catalog label; q416 is the settings hint of Loop for when its engine support lands (QWEN4_LOOP_ENGINE_READY), unused while it is coming
for (const k of keys.filter(k => k !== 'q421' && k !== 'q416' && k !== 'q411' && k !== 'q420')) { // q421 is the build's own name, Ultra, shown through the catalog label; q416 is the settings hint of Loop for when its engine support lands (QWEN4_LOOP_ENGINE_READY), unused while it is coming
const en = catalogs.en[k];
assert.ok(used.includes(en) || used.includes(en.replaceAll('\u2019', '\\u2019')) || used.includes(en.split('{0}')[0]), `${k} is used`);
}
@@ -489,3 +489,51 @@ test('a .strata build: the engine takes no MTP, pictures or Loop yet: one table
assert.ok(typeof c.q426 === 'string' && c.q426.length > 30 && c.q426 !== en.q426, `${l} q426`);
}
});
test('the K/V format: one table in the Python, the server and the screens; only what the engine takes is offered; int8 for the GGUF build, fp16 for the .strata builds', async () => {
const family = py('qwen4_family.py');
const choices = /KV_CHOICES = \{"gguf": \[([^\]]*)\], "strata": \[([^\]]*)\]\}/.exec(family);
const words = x => [...x.matchAll(/"([\w]+)"/g)].map(m => m[1]);
const python = { gguf: words(choices[1]), strata: words(choices[2]) };
assert.deepEqual({ gguf: [...QWEN4_KV_CHOICES.gguf], strata: [...QWEN4_KV_CHOICES.strata] }, python, 'server/qwen4.mjs mirrors the Python list');
const defaults = /KV_DEFAULT = \{"gguf": "(\w+)", "strata": "(\w+)"\}/.exec(family);
assert.deepEqual({ ...QWEN4_KV_DEFAULT }, { gguf: defaults[1], strata: defaults[2] });
assert.deepEqual({ ...QWEN4_KV_DEFAULT }, { gguf: 'int8', strata: 'fp16' });
assert.deepEqual({ ...QWEN4_KV_READY }, { 'gguf/fp8': /KV_READY = \{\("gguf", "fp8"\): (True|False)\}/.exec(family)[1] === 'True' });
assert.deepEqual({ ...QWEN4_KV_BACKENDS }, { fp8: ['cuda'] });
const screen = await bundle('./src/lib/qwen4');
assert.deepEqual({ gguf: [...screen.QWEN4_KV_CHOICES.gguf], strata: [...screen.QWEN4_KV_CHOICES.strata] }, python, 'src/lib/qwen4.ts mirrors it');
assert.deepEqual({ ...screen.QWEN4_KV_DEFAULT }, { gguf: 'int8', strata: 'fp16' });
assert.deepEqual({ ...screen.QWEN4_KV_READY }, { ...QWEN4_KV_READY });
for (const choicesOf of [qwen4KvChoices, screen.qwen4KvChoices]) {
assert.deepEqual(choicesOf('UD-Q4_K_XL'), ['int8', 'fp16', 'k8v4', 'q4_0'], 'fp8 is not ready: not offered');
assert.ok(!choicesOf('UD-Q4_K_XL').includes('k8v8'));
for (const b of ['Compact', 'Balanced', 'Ultra']) assert.deepEqual(choicesOf(b), ['fp16'], b);
}
assert.equal(qwen4KvDefault('UD-Q4_K_XL'), 'int8');
assert.equal(qwen4KvDefault('Compact'), 'fp16');
assert.equal(qwen4KvPick('UD-Q4_K_XL', 'cuda', 'q4_0'), 'q4_0');
assert.equal(qwen4KvPick('UD-Q4_K_XL', 'cuda', 'fp8'), 'int8', 'a format that is not offered falls back to the default');
assert.equal(qwen4KvPick('Compact', 'cuda', 'int8'), 'fp16', 'a .strata build keeps fp16');
assert.equal(screen.qwen4KvPick('UD-Q4_K_XL', 'cuda', 'k8v4', ['int8', 'fp16']), 'int8', 'the catalog row decides when it names the list');
// 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, /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;/);
assert.match(src('server/native-settings.mjs'), /Auto turns the draft layer on for graphics cards of 6 GB or more\. On forces it, Off never loads it\./);
// the lines, in every language
const dir = join(root, 'src', 'locales');
const en = JSON.parse(readFileSync(join(dir, 'gtui-en.json'), 'utf8'));
assert.equal(en.q427, 'int8: same quality as fp16, faster prompt reading.');
assert.equal(en.q428, 'k8v4 and q4_0: less memory for long context.');
assert.equal(en.q431, 'Auto turns the draft layer on for graphics cards of 6 GB or more.');
assert.match(en.q432, /under 6 GB/);
for (const l of ['de', 'fr', 'es', 'ru', 'pt', 'zh', 'ja', 'ko', 'he']) {
const c = JSON.parse(readFileSync(join(dir, `gtui-${l}.json`), 'utf8'));
for (let k = 427; k <= 432; k++) assert.ok(typeof c[`q${k}`] === 'string' && c[`q${k}`].length > 10 && c[`q${k}`] !== en[`q${k}`], `${l} q${k}`);
assert.ok(/6/.test(c.q431) && /6/.test(c.q432), `${l} the 6 GB line`);
}
});
+2 -1
View File
@@ -120,7 +120,8 @@ def extra_args(cfg: dict, base_args: list, exe: str | None = None, *, announce:
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
args = _without(args, ("--spec", "--spec-min-p"))
args += qwen4_family.mtp_engine_args(mtp, cfg.get(qwen4_family.MTP_MODE_KEY) or "auto", gguf=gguf)
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)
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
+5 -1
View File
@@ -84,9 +84,13 @@ class Sidecars(unittest.TestCase):
cfg["args"] = ["--native", "C:/m/trunk40.gguf", "--spec", "2", "--max-context", "32768"]
with with_info({"arch": "x", "images": "1", "mtp": "1"}):
args = server.engine_args(cfg, EXE, announce=False)
self.assertEqual(args[args.index("--spec") + 1], "4")
self.assertEqual(args[args.index("--spec") + 1], "3") # the K of the config (qwen4_mtp_spec), default 3
self.assertEqual(args[args.index("--spec-min-p") + 1], "0.5")
self.assertEqual(args.count("--spec"), 1)
cfg[F.MTP_SPEC_CONFIG_KEY] = 4
with with_info({"arch": "x", "images": "1", "mtp": "1"}):
args4 = server.engine_args(cfg, EXE, announce=False)
self.assertEqual(args4[args4.index("--spec") + 1], "4") # the K setup / the launcher chose for a 24 GB card
self.assertEqual(args[args.index("--mtp") + 1], str(self.mtp))
cfg[F.MTP_MODE_KEY] = "off"
with with_info({"arch": "x", "images": "1"}):
+50 -28
View File
@@ -11320,6 +11320,8 @@ def qwen4_mtp_mode(a) -> str:
def qwen4_gguf_bytes(role: str) -> int:
"""The size of one file of the UD-Q4_K_XL build: the pinned size when qwen4_family.GGUF_FILES has one, else the estimate of qwen4_fit (nothing is pinned until lane Q4-GGUF reports)."""
if role == "mtp": # the drafter is the runtime built at install (923 MiB), not Unsloth's 1.95 GB sidecar file
return int(qwen4_fit.GGUF_MTP_BYTES)
pinned = qwen4_family.GGUF_FILES[role][1]
if pinned:
return int(pinned)
@@ -11331,11 +11333,11 @@ def qwen4_gguf_download_gb(vision: bool = True, mtp: bool = True, loop: bool = F
return n / 1e9
def qwen4_gguf_advise(vram_gib, ram_gib, *, unified: bool = False, ctx=None, vision: bool = True, mtp: bool = True, loop: bool = False, disk_free_gb=None) -> dict:
def qwen4_gguf_advise(vram_gib, ram_gib, *, unified: bool = False, ctx=None, vision: bool = True, mtp: bool = True, loop: bool = False, disk_free_gb=None, kv: str | None = None) -> dict:
"""Where the UD-Q4_K_XL build lives on this PC, the same answer as qwen4_fit.advise gives for the other builds (the rule never recommends this build): the trunk on the card, what does not fit
in RAM, the PLE table (shard 2) in RAM or in the one pool. Estimates (qwen4_fit.GGUF_*) until the real sizes are pinned."""
F = qwen4_fit
need = (F.GGUF_TRUNK_BYTES + (F.GGUF_MTP_BYTES if mtp else 0) + (F.LOOP_BYTES if loop else 0)) / F.GIB + F.kv_gib(ctx) + F.WORK_GIB
need = (F.GGUF_TRUNK_BYTES + (F.GGUF_MTP_BYTES if mtp else 0) + (F.LOOP_BYTES if loop else 0)) / F.GIB + F.kv_gib(ctx, kv=kv or qwen4_family.kv_default(qwen4_family.GGUF_BUILD)) + F.WORK_GIB
ple = F.GGUF_PLE_BYTES / F.GIB
if unified:
pool = float(vram_gib or ram_gib or 0.0)
@@ -11350,12 +11352,15 @@ def qwen4_gguf_advise(vram_gib, ram_gib, *, unified: bool = False, ctx=None, vis
if mode == "short":
warnings.append(f"UD-Q4_K_XL needs about {ram_need:.0f} GiB of memory in all (video memory and RAM together); this PC has less, so it may not load or may be very slow. A smaller build is better here.")
elif not unified and vram_gib and vram_gib < F.GGUF_VRAM_MIN_GIB:
warnings.append(f"A card of {vram_gib:.0f} GB holds only part of UD-Q4_K_XL; the rest of the model is read from RAM, which is slower.")
slots = F.gguf_expert_slots(vram_gib)
warnings.append(f"A card of {vram_gib:.0f} GB holds only part of UD-Q4_K_XL" + (f" (about {slots} of the {F.GGUF_EXPERT_SLOTS_TOTAL} expert slots)" if slots else "") + "; the rest of the model is read from RAM, which is slower.")
if not unified and ram_gib is not None and float(ram_gib) < F.GGUF_RAM_NEED_GIB and mode != "short":
warnings.append(f"UD-Q4_K_XL runs best with about {F.GGUF_RAM_NEED_GIB:.0f} GB of RAM (the experts that do not fit the card and the 10.7 GiB PLE table are held there); this PC has {float(ram_gib):.0f} GB, so it may be slow.")
dl = qwen4_gguf_download_gb(vision, mtp, loop)
if disk_free_gb is not None and disk_free_gb < dl + F.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": qwen4_family.GGUF_BUILD, "ple": None, "mode": mode, "mode_words": F.MODE_WORDS[mode], "vram_need_gib": round(need, 2), "ram_need_gib": round(ram_need, 2),
"download_gb": round(dl, 2), "files": qwen4_family.gguf_files_of(vision, mtp), "warnings": warnings, "recommended": F.recommend(vram_gib, ram_gib, unified=unified, ctx=ctx), "backend": None}
"download_gb": round(dl, 2), "files": qwen4_family.gguf_files_of(vision), "warnings": warnings, "recommended": F.recommend(vram_gib, ram_gib, unified=unified, ctx=ctx), "backend": None}
def qwen4_gguf_urls(role: str) -> list:
@@ -11430,32 +11435,47 @@ def qwen4_gguf_prepare(folder: Path, shard1: Path, pack: Path) -> Path:
return trunk
def qwen4_gguf_mtp_rt(folder: Path, mtp_gguf: Path) -> Path | None:
"""The MTP sidecar of the UD-Q4_K_XL build as the engine's drafter runtime (tools/mtp_qwen4_rt.py writes <folder>/mtp-rt from the sidecar's GGUF). None (with one warning, MTP off) when this
Strata has no such tool or the conversion failed: MTP is optional and never stops the install."""
def qwen4_gguf_mtp_rt(folder: Path) -> Path | None:
"""The drafter of the UD-Q4_K_XL build, built at install the BF16 way (#7779): tools/mtp_fetch.py fetches only the `mtp.*` tensors of the PINNED Qwen revision by range requests (resumable, public Hugging Face),
tools/mtp_pack.py packs them with q8_0 experts, tools/mtp_rt.py makes the runtime folder <folder>/mtp-rt (923 MiB). An existing runtime is reused. Any step that fails or whose tool this Strata does not have
gives one warning and None: MTP is off for this build, the install goes on (MTP is optional and never stops it)."""
rt = folder / qwen4_family.GGUF_MTP_RT
if (rt / "dense.bin").is_file():
return rt
tool = ROOT / qwen4_family.GGUF_MTP_TOOL
if not tool.is_file():
warn(f"the tool that prepares the MTP sidecar ({qwen4_family.GGUF_MTP_TOOL}) is not in this Strata yet: MTP is off for this build")
fetch, pack, make = (ROOT / t for t in qwen4_family.GGUF_MTP_CHAIN)
missing = [t for t, p in zip(qwen4_family.GGUF_MTP_CHAIN, (fetch, pack, make)) if not p.is_file()]
if missing:
warn(f"the tool that prepares the draft layer ({missing[0]}) is not in this Strata yet: MTP is off for this build")
return None
work = folder / qwen4_family.GGUF_MTP_WORKDIR
packed = work / qwen4_family.GGUF_MTP_PACKED
repo = f"https://huggingface.co/{qwen4_family.MTP_REPO}/resolve/{qwen4_family.HF_REVISION}/" # the public Qwen repo at the PINNED revision (the one place that names the host)
steps = (("fetching the draft layer's tensors", [sys.executable, "-I", "-B", str(fetch), "fetch", "--out", str(work), "--repo", repo]),
("packing the draft layer", [sys.executable, "-I", "-B", str(pack), "--src", str(work), "--experts", "q8_0", "--out", str(packed)]),
("making the draft layer's runtime", [sys.executable, "-I", "-B", str(make), "--gguf", str(packed), "--out", str(rt)]))
try:
rt.mkdir(parents=True, exist_ok=True)
run([sys.executable, str(tool), "--gguf", str(mtp_gguf), "--out", str(rt)])
work.mkdir(parents=True, exist_ok=True)
for what, cmd in steps:
say(f" {what} ...")
run(cmd)
except (SystemExit, subprocess.SubprocessError, OSError) as e:
warn(f"the MTP sidecar could not be prepared ({e}): MTP is off for this build")
warn(f"the draft layer could not be prepared ({e}): MTP is off for this build")
return None
if not (rt / "dense.bin").is_file():
warn("the draft layer's runtime was not written: MTP is off for this build")
return None
shutil.rmtree(work, ignore_errors=True) # the fetched tensors and the packed GGUF are not needed again
return rt
def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *, model, ctx, tag, folder, own, backend, vram_gib, ram_gib, unified, vision, mtp_mode, effort, loop_on, ple_asked):
def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *, model, ctx, tag, folder, own, backend, vram_gib, ram_gib, unified, vision, mtp_mode, effort, loop_on, ple_asked, kv=None):
"""Steps 2-7 for the fourth Qwen4-35B-A3B build, Unsloth's UD-Q4_K_XL GGUF (community-supported), run by the same engine of the shape q4_lite: the two shards (shard 2 holds the PLE table:
no separate PLE download), the picture reader and the MTP sidecar when wanted, the trunk view and the pack prepared at install, the engine arguments from qwen4_family.gguf_engine_args."""
qwen4_gguf_tool(qwen4_family.GGUF_SPLIT_TOOL, "prepares the UD-Q4_K_XL file for the engine") # before anything is downloaded
if ple_asked:
warn("--ple does not apply to UD-Q4_K_XL: its second file holds the PLE table")
adv = qwen4_gguf_advise(vram_gib if not unified else None, ram_gib, unified=unified, ctx=ctx, vision=vision, mtp=mtp_mode != "off", loop=loop_on)
kv = kv or qwen4_family.kv_default(qwen4_family.GGUF_BUILD)
adv = qwen4_gguf_advise(vram_gib if not unified else None, ram_gib, unified=unified, ctx=ctx, vision=vision, mtp=mtp_mode != "off", loop=loop_on, kv=kv)
say()
say(f" {qwen4_family.GGUF_ABOUT}.")
say(f" Memory plan for this PC: {adv['mode_words']}")
@@ -11463,13 +11483,15 @@ def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *,
for w in adv["warnings"]:
warn(w)
left = 0.0
roles = ["shard1", "shard2"] + (["mmproj"] if vision else []) + (["mtp"] if mtp_mode != "off" else [])
roles = ["shard1", "shard2"] + (["mmproj"] if vision else []) # the drafter is built, not downloaded (qwen4_gguf_mtp_rt)
for r in roles:
base = qwen4_family.GGUF_FILES[r][0].rsplit("/", 1)[-1]
p = folder / base
if not qwen4_gguf_have(a, p, qwen4_family.GGUF_FILES[r][1]):
part = p.with_name(p.name + ".part")
left += (qwen4_gguf_bytes(r) - (part.stat().st_size if part.is_file() else 0)) / 1e9
if mtp_mode != "off" and not (folder / qwen4_family.GGUF_MTP_RT / "dense.bin").is_file():
left += (qwen4_fit.GGUF_MTP_FETCH_BYTES + qwen4_fit.GGUF_MTP_BYTES) / 1e9 # the draft layer is built at install: the fetched tensors (temporary) and the runtime
if not (folder / qwen4_family.GGUF_TRUNK_VIEW).is_file():
left += qwen4_family.GGUF_INSTALL_EXTRA_GB # the trunk view (24.1 GB), the pack and the MTP runtime are written at install
say(f" The install also writes about {qwen4_family.GGUF_INSTALL_EXTRA_GB:.0f} GB of prepared files beside the download.")
@@ -11492,17 +11514,12 @@ def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *,
step(5, f"downloading {fam['title']} {model}")
shard1 = qwen4_gguf_fetch(a, "shard1", folder, own)
shard2 = qwen4_gguf_fetch(a, "shard2", folder, own)
mmproj = mtp_gguf = None
mmproj = None
if vision:
try:
mmproj = qwen4_gguf_fetch(a, "mmproj", folder, own)
except SystemExit:
warn("the picture reader could not be fetched: pictures are off (run this again when it can, or put the file in " + str(folder) + ")")
if mtp_mode != "off":
try:
mtp_gguf = qwen4_gguf_fetch(a, "mtp", folder, own)
except SystemExit:
warn("the MTP sidecar could not be fetched: MTP is off (run this again when it can, or put the file in " + str(folder) + ")")
ok(f"model files: {shard1.name}, {shard2.name}")
step(6, "preparing the model for Strata")
@@ -11518,7 +11535,7 @@ def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *,
step(7, "writing the start script")
loop_path = qwen4_optional(a, qwen4_family.LOOP_FILE, folder, own, trunk, [data / "models" / qwen4_family.FAMILY], "Loop") if loop_on else None
ok(f"Loop: on ({loop_path.name}). {qwen4_family.LOOP_WORDS}" if loop_path is not None else f"Loop: off. {qwen4_family.LOOP_WORDS} (--loop on turns it on)")
mtp_rt = qwen4_gguf_mtp_rt(folder, mtp_gguf) if mtp_gguf is not None else None
mtp_rt = qwen4_gguf_mtp_rt(folder) if mtp_mode != "off" else None
ok(f"MTP: {'on' if mtp_mode == 'on' else 'auto (the engine decides at start whether it pays here)'} ({mtp_rt.name})" if mtp_rt is not None else "MTP: off")
ok("pictures: " + (f"on ({mmproj.name})" if mmproj is not None else "off"))
profile = folder / qwen4_family.GGUF_PROFILE_FILE # the uniform expert profile the engine wants beside the pack (81,944 B)
@@ -11528,7 +11545,8 @@ def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *,
if mmproj is not None and not reader.is_file():
warn(f"the picture reader program ({VEXE}) is not in the engine package yet: pictures are off for now")
mmproj = None
args = qwen4_family.gguf_engine_args(trunk, shard2, pack=pack, profile=profile, vision=mmproj, loop=loop_path, ctx=ctx) # 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
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
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"}
@@ -11542,6 +11560,7 @@ def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *,
if mtp_rt is not None:
cfg[qwen4_family.MTP_CONFIG_KEY] = str(mtp_rt)
cfg[qwen4_family.MTP_MODE_KEY] = "on" if mtp_mode == "on" else "auto"
cfg[qwen4_family.MTP_SPEC_CONFIG_KEY] = spec_k
if isinstance(getattr(a, "_roles", None), dict):
from strata_control import gpu_roles as GR
rcards = getattr(a, "_roles_cards", None) or [gpu]
@@ -11667,6 +11686,9 @@ def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
model = qwen4_family.ALL_BUILDS[int(ask("Which build?", [str(i) for i in range(1, len(qwen4_family.ALL_BUILDS) + 1)], str(qwen4_family.BUILDS.index(rec["build"]) + 1), a.yes)) - 1]
ok(f"size: {model}")
loop_on = qwen4_loop_wanted(a, model, backend) # Loop counts only where the engine supports it for this build and backend (qwen4_family.LOOP_READY)
kv, kv_note = qwen4_family.kv_word(getattr(a, "kv", None), model, backend) # the K/V format: the GGUF build int8 by default, the .strata builds fp16 only (qwen4_family.KV_CHOICES)
if kv_note:
warn(kv_note)
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")))
@@ -11692,12 +11714,12 @@ def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
own = bool(getattr(a, "gguf_dir", None))
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)
unified=unified, vision=vision, mtp_mode=mtp_mode, effort=effort, loop_on=loop_on, ple_asked=ple_asked, kv=kv)
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)
adv = qwen4_fit.advise(vram_gib if not unified else None, ram_gib, unified=unified, ctx=ctx, build=model, ple=ple_asked, vision=vision, mtp=mtp_mode != "off", loop=loop_on, backend=backend)
adv = qwen4_fit.advise(vram_gib if not unified else None, ram_gib, unified=unified, ctx=ctx, build=model, ple=ple_asked, vision=vision, mtp=mtp_mode != "off", loop=loop_on, backend=backend, kv=kv)
ple = ple_asked or adv["ple"]
say()
say(f" Memory plan for this PC: {adv['mode_words']}; the PLE table is {ple}" + (" (Q8_0: the RAM holds it)" if ple == "Q8" and not ple_asked else ""))
@@ -11721,8 +11743,8 @@ def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
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")
if a.rope_scaling or a.rope_scale or a.kv or a.resident_budget_gib is not None or a.low_ram not in (None, "auto"):
warn(f"--rope-scaling / --kv / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} does not use them")
if a.rope_scaling or a.rope_scale or a.resident_budget_gib is not None or a.low_ram not in (None, "auto"):
warn(f"--rope-scaling / --resident-budget-gib / --low-ram are Flash-Next settings: {fam['title']} does not use them")
step(3, "Python packages")
pip_install(runtime_packages(), "numpy, jinja2, regex, pyyaml, tqdm, requests, cmake, ninja, pillow, psutil, textual (the screens)")
+1 -1
View File
@@ -725,7 +725,7 @@ class Catalog:
return tokens * ling32_fit.LATENT_BYTES_PER_TOKEN / 1e9 # the 7 MLA layers' float32 latent cache; the 35 KDA layers keep a fixed state
if family == "qwen4-35b-a3b":
from strata_control import qwen4_fit
return tokens * qwen4_fit.KV_BYTES_PER_TOKEN / 1e9 # the 10 full-attention layers' K/V; the 30 GDN layers keep a fixed state
return tokens * qwen4_fit.kv_bytes_per_token(kv) / 1e9 # the 10 full-attention layers' K/V by format; the 30 GDN layers keep a fixed state
mod = self.strata.setup_module()
table = getattr(mod, "UD_FIT_KV_BYTES", None) or {"fp16": 2112, "int8": 1056, "q4_0": 576, "k8v4": 816}
return tokens * 13 * table.get(kv, 1056) / 1e9
+1 -1
View File
@@ -244,7 +244,7 @@ def assess(catalog, family: str | None, model: str | None, *, vision: str = "off
st.on_disk_gb = sum(p.stat().st_size for p in (folder / fam_mod.GGUF_FILES[r][0] for r in ("shard1", "shard2")) if p.is_file()) / 1e9
if not all((folder / fam_mod.GGUF_FILES[r][0]).is_file() for r in ("shard1", "shard2")):
st.parts.append(Part("weights", "the model", max(st.total_gb - st.on_disk_gb, 0.0)))
if mtp != "off" and not (folder / fam_mod.GGUF_FILES["mtp"][0]).is_file():
if mtp != "off" and not (folder / fam_mod.GGUF_MTP_RT / "dense.bin").is_file(): # the drafter is built at install, not downloaded
st.parts.append(Part("mtp", "the draft layer", round(qwen4_fit.GGUF_MTP_BYTES / 1e9, 2)))
if wants_pictures and not (folder / fam_mod.GGUF_FILES["mmproj"][0]).is_file():
st.parts.append(Part("mmproj", "the picture reader", round(qwen4_fit.GGUF_MMPROJ_BYTES / 1e9, 2)))
+12 -2
View File
@@ -326,7 +326,17 @@ def apply_choices(cfg: dict, s: S.LaunchSettings) -> dict:
args.extend([flag, value])
if s.family in ("ling-3.2-air", "qwen4-35b-a3b") or str(cfg.get("arch") or "").lower() in ("ling32", "qwen4exp_q4_lite"): # Ling-3.2-Air and Qwen4-35B-A3B: `--ctx`, and the Vision shard (`--vision FILE`, the encoder's `--vision-device`)
if s.context:
if str(cfg.get("arch") or "").lower() == "qwen4exp_q4_lite" or s.family == "qwen4-35b-a3b": # Qwen4: the .strata builds take --max-ctx and no --kv, the GGUF build --max-context and --kv (qwen4_family.KV_CHOICES)
from strata_control import qwen4_family as _q4
q4b = _q4.build_of_model_name(cfg.get("model_name")) or _q4.build_of_file(_q4.model_arg(args))
if s.context:
put("--max-context" if _q4.is_gguf_build(q4b) else "--max-ctx", str(int(s.context)))
while "--kv" in args:
at = args.index("--kv")
del args[at:at + 2]
if _q4.is_gguf_build(q4b):
put("--kv", _q4.kv_word(s.kv, q4b, cfg.get("backend"))[0])
elif s.context:
put("--ctx", str(int(s.context)))
if s.vision in ("off", "no"):
for flag in ("--vision", "--vision-device", "--vision-max-pixels"):
@@ -1546,7 +1556,7 @@ class Runner:
if ctx:
args += ["--context", str(ctx)]
args += ["--vision", self.vision_word()] # (Hy4-Flash: images are on by default; setup takes any word but no / none as "on")
if s.kv and not self.is_native_strata_family(): # Qwen/Gyro KV formats
if s.kv and (not self.is_native_strata_family() or self.is_qwen4()): # Qwen/Gyro KV formats, and Qwen4's (setup validates it per build: qwen4_family.KV_CHOICES)
args += ["--kv", s.kv]
elif s.kv and self.is_inkling():
be = None
+4
View File
@@ -548,6 +548,10 @@ def check_qwen4(s: LaunchSettings, *, vram_gb: float | None, ram_gb: float | Non
if s.mtp == "on":
out.append(Notice("warn", "MTP drafts several tokens per step: the model's own multi-token-prediction layer proposes them and the model checks them in one pass, so the answers are the same.",
"Take --mtp on away (or --mtp off) to start without it."))
if s.kv: # the K/V format: a word this build does not take is said once (qwen4_family.KV_CHOICES)
_, kv_note = qwen4_family.kv_word(s.kv, adv.get("build"), backend)
if kv_note:
out.append(Notice("warn", kv_note, ""))
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)
+63 -9
View File
@@ -233,25 +233,78 @@ GGUF_REMOTE = {"shard1": "UD-Q4_K_XL/" + GGUF_FILES["shard1"][0], "shard2": "UD-
#: extra disk the install needs beyond the download (Q4-GGUF): the trunk view 24.1 GB, the pack 0.78 GB and the MTP runtime 1.9 GB
GGUF_INSTALL_EXTRA_GB = 27.0
GGUF_TRUNK_VIEW = "trunk40.gguf" # written by tools/qwen4_split_gguf.py beside the shards
GGUF_MTP_RT = "mtp-rt" # written by tools/mtp_qwen4_rt.py
GGUF_MTP_RT = "mtp-rt" # the drafter runtime the engine reads (built at install by the BF16 route below)
#: THE drafter of the GGUF build (#7779's BF16 route, owner 2026-12-04): built at install from the public Qwen repo at the PINNED revision (HF_REVISION), only the `mtp.*` tensors by range requests (resumable, never
#: R2): tools/mtp_fetch.py fetch -> tools/mtp_pack.py --experts q8_0 -> tools/mtp_rt.py -> <folder>/mtp-rt (923 MiB). K of `--spec K` is 3 on every card (qwen4_fit.MTP_SPEC_DEFAULT). Unsloth's 1.95 GB MTP/mtp-Qwen4-35B-A3B-Q8_0.gguf is no longer downloaded.
MTP_REPO = "Qwen/Qwen4-35B-A3B" # the public repo (setup.py makes the URL: <host>/<repo>/resolve/<HF_REVISION>/)
GGUF_MTP_CHAIN = ("tools/mtp_fetch.py", "tools/mtp_pack.py", "tools/mtp_rt.py")
GGUF_MTP_WORKDIR = "mtp-bf16" # the fetched tensors and the packed GGUF: temporary, removed once the runtime is built
GGUF_MTP_PACKED = "mtp-q8_0.gguf"
MTP_SPEC_CONFIG_KEY = "qwen4_mtp_spec" # the run config's K of `--spec K` (an int; setup and the launcher write it from the card, serve uses it, default 3)
GGUF_SPLIT_TOOL = "tools/qwen4_split_gguf.py"
GGUF_MTP_TOOL = "tools/mtp_qwen4_rt.py"
GGUF_PACK_NAME = "pack-UD-Q4_K_XL" # the iq_pack output folder (data/packs/<tag>), the engine's --pack
GGUF_PROFILE_FILE = "expert-profile-40x256.bin" # a uniform 40-layer x 256-expert STRP profile (write_uniform_profile): tools/make_profile.py is hard-wired to 48 layers
#: the engine's start flags that Q4-GGUF ran the real model with (strata --serve --pack P --native T --native-dense-gguf T --ple-gguf SHARD2 --expert-profile F --expert-cache auto --prefill 4096
#: --max-context N --kv fp16 --vram-reserve-mib 512 --spec 2). A native pack needs --spec >= 2 even for plain decode. With MTP: --mtp <rt> --spec 4 --spec-min-p 0.5 in place of --spec 2.
GGUF_RUN_ARGS = ["--expert-cache", "auto", "--prefill", "4096", "--kv", "fp16", "--vram-reserve-mib", "512"]
GGUF_RUN_ARGS = ["--expert-cache", "auto", "--prefill", "4096", "--vram-reserve-mib", "512"]
GGUF_PLAIN_SPEC = ["--spec", "2"]
GGUF_SPEC_ARGS = ["--spec", "4", "--spec-min-p", "0.5"] # with --mtp <rt>
GGUF_SPEC_MIN_P = "0.5" # `--spec-min-p` with --mtp <rt>; K is qwen4_fit.mtp_spec_k(card) and the config's qwen4_mtp_spec (default 3)
GGUF_SPEC_DEFAULT_K = 3
def gguf_spec_args(k=None) -> list[str]:
"""The speculative flags of the GGUF build with the drafter: `--spec K --spec-min-p 0.5`."""
return ["--spec", str(int(k) if k else GGUF_SPEC_DEFAULT_K), "--spec-min-p", GGUF_SPEC_MIN_P]
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 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.
KV_CHOICES = {"gguf": ["int8", "fp16", "k8v4", "fp8", "q4_0"], "strata": ["fp16"]}
KV_DEFAULT = {"gguf": "int8", "strata": "fp16"}
#: a format the engine does not take yet, per (source, word): offered and written only where True. fp8 (E4M3, CUDA first) is in Q4-KV's branch only; flip ("gguf", "fp8") when it merges.
KV_READY = {("gguf", "fp8"): False}
#: a format that only some backends take: {word: backends}
KV_BACKENDS = {"fp8": ("cuda",)}
KV_WORDS = {"int8": "same quality as fp16, faster prompt reading", "k8v4": "less memory for long context", "q4_0": "less memory for long context", "fp16": "the reference, most memory",
"fp8": "like int8, new, NVIDIA first"}
def kv_choices(build, backend=None) -> list[str]:
"""The K/V formats offered for this build on this backend: the source's list, minus a format whose readiness entry is False and a format this backend does not take (no backend means cuda)."""
src = loop_source(build)
be = str(backend or "cuda").lower()
return [k for k in KV_CHOICES[src] if KV_READY.get((src, k), True) and be in KV_BACKENDS.get(k, (be,))]
def kv_default(build) -> str:
"""The K/V format of a start that names none: int8 for the GGUF build, fp16 for the .strata builds."""
return KV_DEFAULT[loop_source(build)]
def kv_word(word, build, backend=None) -> tuple[str, str | None]:
"""(format, note): the person's word when this build takes it, else the build's default with one plain note (None when there is nothing to say: no word, or a word that is fine)."""
default = kv_default(build)
w = str(word or "").strip().lower()
if not w:
return default, None
choices = kv_choices(build, backend)
if w in choices:
return w, None
if loop_source(build) == "strata":
return default, f"--kv {w}: the .strata builds keep the K/V cache in {default} for now, so that is what is used"
return default, f"--kv {w} is not a K/V format of this build (choose {', '.join(choices)}): {default} is used"
def is_gguf_build(build) -> bool:
return build in GGUF_BUILDS
def gguf_files_of(vision: bool = DEFAULT_VISION, mtp: bool = DEFAULT_MTP) -> list[str]:
"""The file names of the GGUF build, in download order: shard 1, shard 2 (the PLE table), then the picture reader and the MTP sidecar when wanted."""
def gguf_files_of(vision: bool = DEFAULT_VISION, mtp: bool = False) -> list[str]:
"""The file names of the GGUF build, in download order: shard 1, shard 2 (the PLE table), then the picture reader. The drafter is NOT a download any more (it is built at install from the Qwen repo,
GGUF_MTP_CHAIN): `mtp=True` adds Unsloth's own 1.95 GB sidecar GGUF, an optional role kept defined for a person who wants that file."""
order = ["shard1", "shard2"] + (["mmproj"] if vision else []) + (["mtp"] if mtp else [])
return [GGUF_FILES[r][0] for r in order]
@@ -271,16 +324,17 @@ 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) -> list[str]:
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."""
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)]
out += GGUF_RUN_ARGS
out += ["--kv", kv if kv in KV_CHOICES["gguf"] else KV_DEFAULT["gguf"]] # the K/V format (default int8: same quality as fp16, faster prompt reading)
out += loop_engine_args(loop, GGUF_BUILD) # the GGUF build's coda is universal
if vision:
out += ["--vision"] # a bare flag: the picture reader is the run config's "vision" section (strata-vision with the mmproj), as for Flash-Next
out += (([ENGINE_FILE_FLAGS["mtp"], str(mtp_rt)] + GGUF_SPEC_ARGS) if mtp_rt else GGUF_PLAIN_SPEC)
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))]
return out
@@ -380,13 +434,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) -> list[str]:
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)."""
if not mtp or str(mode or "auto").lower() == "off":
return []
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
return [ENGINE_FILE_FLAGS["mtp"], str(mtp)] + gguf_spec_args(spec_k)
# ---- download sources (the shipped list is the private Hugging Face repo until `released` is true) ----
+70 -13
View File
@@ -32,7 +32,8 @@ GGUF_BUILD = "UD-Q4_K_XL"
GGUF_TRUNK_BYTES = 24_719_106_144 # shard 1 (the model without the PLE table), the real size
GGUF_PLE_BYTES = 11_520_258_240 # shard 2: the per_layer_token_embd (IQ4_NL), the real size
GGUF_MMPROJ_BYTES = 902_822_144 # mmproj-BF16.gguf, the real size
GGUF_MTP_BYTES = 2_006_805_984 # mtp-Qwen4-35B-A3B-Q8_0.gguf (the runtime made from it is 1.9 GB and sits on the card: 1.99 GB of VRAM)
GGUF_MTP_BYTES = 923 * 2 ** 20 # the BF16-route drafter runtime (#7779, built at install): 923 MiB on the card (the Unsloth Q8_0 sidecar's 1.95 GB is no longer used)
GGUF_MTP_FETCH_BYTES = 5_200_000_000 # ESTIMATE: the BF16 `mtp.*` tensors of the Qwen repo that the install reads by range requests (the fused experts dominate); temporary, deleted once the runtime is built
GGUF_VRAM_MIN_GIB = 22.0 # ESTIMATE: same floor as Balanced (a 24 GB card holds the trunk)
# ---- THE table of the build rule: the video memory a card needs for each build (GiB, as the driver reports it: a 24 GB card shows about 23.99, a 32 GB card about 31.8) ----
@@ -46,7 +47,15 @@ DEFAULT_CONTEXT = 131072
CONTEXTS = [8192, 32768, 65536, 131072, 262144]
MAX_CONTEXT = 262144
#: K/V of the 10 full-attention layers: 2 KV heads x head_dim 256 x (K + V) x 2 bytes, a token; the 30 GDN layers keep a fixed state (about 63 MB a sequence)
KV_BYTES_PER_TOKEN = 10 * 2 * 256 * 2 * 2
#: the K/V cache bytes per token by format (Q4-KV's real numbers, 10 quasi-sparse-attention layers x 2 KV heads x 256; NOT the 13-layer tables of setup.py / vram_fit.py): fp16 20,480, int8 and fp8 10,560,
#: k8v4 8,160, q4_0 5,760 (at 32K: 0.67 / 0.35 / 0.27 / 0.19 GB). ONE table; the 30 GDN layers keep a fixed state (GDN_STATE_BYTES) whatever the format.
KV_BYTES_PER_TOKEN = {"fp16": 20_480, "int8": 10_560, "fp8": 10_560, "k8v4": 8_160, "q4_0": 5_760}
DEFAULT_KV = "fp16" # the format of the .strata builds and of every caller that names none (the GGUF build's default is qwen4_family.KV_DEFAULT["gguf"])
def kv_bytes_per_token(kv: str | None = None) -> int:
"""The K/V bytes per token of a format; an unknown or missing word counts as fp16."""
return KV_BYTES_PER_TOKEN.get(str(kv or DEFAULT_KV).lower(), KV_BYTES_PER_TOKEN[DEFAULT_KV])
GDN_STATE_BYTES = 30 * 32 * 128 * 128 * 4
WORK_GIB = 1.5 # CUDA / HIP / Metal context, activations and the engine's buffers beside the weights
VISION_GPU_GIB = 1.2 # the picture encoder's weights (0.83 GB) and its activations while it runs
@@ -68,10 +77,10 @@ def gib(nbytes: float) -> float:
return float(nbytes) / GIB
def kv_gib(ctx: int | None = None, parallel: int = 1) -> float:
def kv_gib(ctx: int | None = None, parallel: int = 1, kv: str | None = None) -> float:
"""The K/V and state memory of `ctx` tokens (GiB); `parallel` sequences keep their own."""
c = int(ctx or DEFAULT_CONTEXT)
return (c * KV_BYTES_PER_TOKEN + GDN_STATE_BYTES) * max(1, int(parallel)) / GIB
return (c * kv_bytes_per_token(kv) + GDN_STATE_BYTES) * max(1, int(parallel)) / GIB
def weights_gib(build: str, vision: bool = False, mtp: bool = False, loop: bool = False) -> float:
@@ -80,9 +89,9 @@ def weights_gib(build: str, vision: bool = False, mtp: bool = False, loop: bool
return n / GIB + (VISION_GPU_GIB if vision else 0.0)
def vram_need_gib(build: str, ctx: int | None = None, vision: bool = False, mtp: bool = False, loop: bool = False) -> float:
def vram_need_gib(build: str, ctx: int | None = None, vision: bool = False, mtp: bool = False, loop: bool = False, kv: str | None = None) -> float:
"""The video memory to keep the whole build on the card."""
return weights_gib(build, vision, mtp, loop) + kv_gib(ctx) + WORK_GIB
return weights_gib(build, vision, mtp, loop) + kv_gib(ctx, kv=kv) + WORK_GIB
def ple_gib(ple: str) -> float:
@@ -94,6 +103,34 @@ def disk_gb(build: str, ple: str = "Q4", vision: bool = True, mtp: bool = True,
return gb(BUILD_BYTES[build] + PLE_BYTES[ple] + (VISION_BYTES if vision else 0) + (MTP_BYTES if mtp else 0) + (LOOP_BYTES if loop else 0))
# ---- fit facts measured by Q4-CORE and Q4-SMALL (2026-12-04), ONE table each ----
#: the .strata builds on the standalone strata-q4-lite engine are fully resident today: Compact needs 12.9 GiB of video memory (trunk 2.6 + experts 8.2 + reserve), so it loads from 16 GB cards up and a 10 to 12 GB
#: card fails with "not enough device memory"; Balanced about 22 GB and Ultra about 29 GB (Q4-CORE). Below its floor a build is "short" until the engine's memory tiering (Q4-ELASTIC) lands; the GGUF build
#: (UD-Q4_K_XL) does run there. A unified pool has no floor of its own (the pool rule counts it).
STRATA_MIN_VRAM_GIB = {"Compact": 13.0, "Balanced": 22.0, "Ultra": 29.0}
STRATA_ELASTIC_NOTE = "needs more video memory until the engine's memory tiering lands"
#: the GGUF build (UD-Q4_K_XL) runs on every tested card with `--expert-cache auto` (the experts that do not fit the card go to RAM; the PLE table, 10.7 GiB, sits in RAM): about 64 GB of RAM in all is the
#: recommended amount (a warning below it, never a refusal). All 10240 expert slots fit video memory only on a 32 GB card; slots held by card size (informational, no limit): 16 GB ~5800, 12 GB ~3800, 10 GB ~2700, 8 GB ~1500 to 2000.
GGUF_RAM_NEED_GIB = 64.0
GGUF_EXPERT_SLOTS_TOTAL = 10240
GGUF_EXPERT_SLOTS_BY_VRAM = ((32.0, 10240), (16.0, 5800), (12.0, 3800), (10.0, 2700), (8.0, 1500))
def gguf_expert_slots(vram_gib: float | None) -> int | None:
"""About how many of the 10240 expert slots a discrete card of `vram_gib` holds (the largest row of GGUF_EXPERT_SLOTS_BY_VRAM it reaches); None below 8 GB or unknown. Informational."""
if not vram_gib:
return None
for floor, slots in GGUF_EXPERT_SLOTS_BY_VRAM:
if float(vram_gib) >= floor:
return slots
return None
def strata_below_floor(build: str, vram_gib: float | None, unified: bool = False) -> bool:
"""Is this .strata build short of video memory on this discrete card (below STRATA_MIN_VRAM_GIB)? Never for the GGUF build, a unified pool or an unknown card."""
return (not unified) and build in STRATA_MIN_VRAM_GIB and vram_gib is not None and 0 < float(vram_gib) < STRATA_MIN_VRAM_GIB[build]
# ---- the rule ----
def build_for_vram(vram_gib: float | None) -> str:
@@ -128,9 +165,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) -> 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) -> str:
""""resident" / "hybrid" / "unified" / "short": where the build lives on this PC."""
need = vram_need_gib(build, ctx, vision, mtp, loop)
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)
if unified:
return "unified" if need + ple_gib(ple) <= float(vram_gib or ram_gib or 0.0) - UMA_RESERVE_GIB else "short"
spill = max(0.0, need - float(vram_gib or 0.0))
@@ -150,21 +189,23 @@ def recommend(vram_gib: float | None, ram_gib: float, *, unified: bool = False,
def advise(vram_gib: float | None, ram_gib: float, *, unified: bool = False, ctx: int | None = None, disk_free_gb: float | None = None, build: str | None = None,
ple: str | None = None, vision: bool = True, mtp: bool = True, loop: bool = False, backend: str | None = None) -> dict:
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)
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)
need = vram_need_gib(b, ctx, False, mtp, loop)
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)
warnings: list[str] = []
if 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
ram_need = ple_gib(p) + spill + OS_RESERVE_GIB
if mode == "short":
if strata_below_floor(b, vram_gib, unified):
warnings.append(f"{b} needs {STRATA_MIN_VRAM_GIB[b]:g} GB of video memory on a card of this make: a card of {vram_gib:.0f} GB {STRATA_ELASTIC_NOTE}. UD-Q4_K_XL (the Unsloth GGUF build) does run on this card.")
elif mode == "short":
warnings.append(f"{b} with the {p} PLE table needs about {ram_need:.0f} GiB of memory in all (video memory and RAM together); this PC has less, so it may not load or may be very slow. A smaller build is better here.")
elif not unified and vram_gib and vram_gib < COMPACT_COMFORT_GIB and b == "Compact":
warnings.append(f"A card of {vram_gib:.0f} GB holds only part of Compact; the rest of the model is read from RAM, which is slower.")
@@ -276,7 +317,7 @@ def cuda_toolkit(arch) -> int:
# ---- MTP Auto (owner decision 2026-12-04): the draft layer is ON by default for every discrete card of MTP_AUTO_MIN_VRAM_GIB or more and for a unified pool, OFF below; `--mtp on|off` always wins ----
#: ONE table for the threshold (GiB of video memory on a DISCRETE card; a unified pool always counts as on). ESTIMATE-free: the owner's rule. The measured speeds behind the cards that are off are
#: Q4-SMALL's (2080 Ti 11 GB 64 tok/s without MTP against 60 with the 1.95 GB drafter; 3060 12 GB 66 against 59; on: 4060 Ti 16 GB 68 to 90, V100 32 GB 106 to 144, 5090 249 to 285).
MTP_AUTO_MIN_VRAM_GIB = 6.0
MTP_AUTO_MIN_VRAM_GIB = 6.0 # the owner's rule (>= 6 GB); Q4-SMALL measured the gain from 8 GB up (5060 8 GB: 62 -> 76 tok/s) and recommends 8, the 6 GB line stays
#: THE per-card fallback: a card whose name contains one of these words (lower case) has the draft layer OFF under Auto because it MEASURED slower there; {name word: why}. Empty until Q4-SMALL's rows
#: name a card (2080 Ti, 3060 with the big drafter; a card may go back to on when the smaller drafter wins there). An explicit `--mtp on` still forces it.
MTP_AUTO_OFF_CARDS: dict = {}
@@ -319,6 +360,22 @@ def mtp_auto_note(vram_gib: float | None, card_name: str | None = None) -> str:
AUTO_HELP = f"Auto turns the draft layer on for graphics cards of {MTP_AUTO_MIN_VRAM_GIB:g} GB or more."
#: the speculative depth K of the draft layer (`--spec K --spec-min-p 0.5`): 3 on EVERY card (Q4-SMALL, GGUF path, decode tok/s without MTP / Q8 sidecar K=3 / BF16 drafter K=3 / BF16 K=4: 5090 248/346/344/327,
#: 5080 16G 134/185/182/186, 5070 Ti 16G 134/174/184/178, 3080 10G 100/116/127/118, 3060 12G 61/71/86/69, 5060 8G 62/69/76/73: K=4 is never clearly better and loses on the 5090, 3080, 3060 and 5060). One
#: default, no boundary; MTP_SPEC_BY_CARD overrides by card-name substring (lower case) once a card is measured to want another K.
MTP_SPEC_DEFAULT = 3
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)."""
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
# ---- 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 ----
ENGINE_TOO_OLD = ("Qwen4-35B-A3B needs a newer engine than the one installed. Run `strata update` (or Download / repair in the app) to fetch the engine for it; "
+127 -2
View File
@@ -222,7 +222,8 @@ class EngineFlags(unittest.TestCase):
self.assertEqual(F.mtp_engine_args("/m/M.strata", "off"), [])
self.assertEqual(F.mtp_engine_args(None, "on"), [])
self.assertEqual(F.mtp_engine_args("/m/M.strata", "auto"), ["--mtp", "/m/M.strata", "--spec", "4"]) # a .strata build (the engine takes it: STRATA_READY)
self.assertEqual(F.mtp_engine_args("/m/rt", "auto", gguf=True), ["--mtp", "/m/rt", "--spec", "4", "--spec-min-p", "0.5"])
self.assertEqual(F.mtp_engine_args("/m/rt", "auto", gguf=True), ["--mtp", "/m/rt", "--spec", "3", "--spec-min-p", "0.5"]) # K defaults to 3
self.assertEqual(F.mtp_engine_args("/m/rt", "auto", gguf=True, spec_k=4), ["--mtp", "/m/rt", "--spec", "4", "--spec-min-p", "0.5"])
class StrataFlagTable(unittest.TestCase):
@@ -237,7 +238,8 @@ class StrataFlagTable(unittest.TestCase):
for flag in ("--native", "--ctx", "--vision", "--mtp", "--spec", "--loop", "--loop-file"):
self.assertNotIn(flag, args)
self.assertEqual(F.mtp_engine_args("/m/M.strata", "auto"), []) # a .strata build: no sidecar flag until the engine takes it
self.assertEqual(F.mtp_engine_args("/m/rt", "auto", gguf=True), ["--mtp", "/m/rt", "--spec", "4", "--spec-min-p", "0.5"]) # the GGUF build is unchanged
self.assertEqual(F.mtp_engine_args("/m/rt", "auto", gguf=True), ["--mtp", "/m/rt", "--spec", "3", "--spec-min-p", "0.5"]) # K defaults to 3
self.assertEqual(F.mtp_engine_args("/m/rt", "auto", gguf=True, spec_k=4), ["--mtp", "/m/rt", "--spec", "4", "--spec-min-p", "0.5"]) # the GGUF build is unchanged
def test_each_optional_flag_follows_its_own_word(self):
for role, flag in (("mtp", "--mtp"), ("vision", "--vision"), ("loop", "--loop")):
@@ -292,5 +294,128 @@ class MtpAuto(unittest.TestCase):
self.assertIn("under 6 GB", QF.mtp_auto_note(5.0))
class KvChoice(unittest.TestCase):
"""The K/V cache format: int8 by default for the GGUF build, fp16 only for the .strata builds; only the formats the engine takes are offered; the memory follows the format."""
def test_the_defaults_per_source(self):
self.assertEqual(F.kv_default("UD-Q4_K_XL"), "int8")
for b in ("Compact", "Balanced", "Ultra"):
self.assertEqual(F.kv_default(b), "fp16", b)
def test_only_the_formats_the_engine_takes_are_offered(self):
self.assertEqual(F.kv_choices("UD-Q4_K_XL"), ["int8", "fp16", "k8v4", "q4_0"]) # fp8 is not in int-0226 yet: behind KV_READY
self.assertNotIn("k8v8", F.kv_choices("UD-Q4_K_XL"))
for b in ("Compact", "Balanced", "Ultra"):
self.assertEqual(F.kv_choices(b), ["fp16"], b)
with mock.patch.dict(F.KV_READY, {("gguf", "fp8"): True}):
self.assertIn("fp8", F.kv_choices("UD-Q4_K_XL"))
self.assertIn("fp8", F.kv_choices("UD-Q4_K_XL", "cuda"))
self.assertNotIn("fp8", F.kv_choices("UD-Q4_K_XL", "hip")) # NVIDIA first
self.assertNotIn("fp8", F.kv_choices("UD-Q4_K_XL", "metal"))
self.assertEqual(F.kv_choices("Compact"), ["fp16"]) # a .strata build still takes fp16 only
self.assertEqual(F.kv_choices("UD-Q4_K_XL", "hip"), ["int8", "fp16", "k8v4", "q4_0"])
def test_an_unsupported_word_falls_back_with_a_note(self):
self.assertEqual(F.kv_word(None, "UD-Q4_K_XL"), ("int8", None))
self.assertEqual(F.kv_word("Q4_0", "UD-Q4_K_XL"), ("q4_0", None))
kv, note = F.kv_word("k8v8", "UD-Q4_K_XL")
self.assertEqual(kv, "int8")
self.assertIn("k8v8", note)
kv, note = F.kv_word("fp8", "UD-Q4_K_XL") # not ready yet
self.assertEqual(kv, "int8")
self.assertIsNotNone(note)
kv, note = F.kv_word("int8", "Compact")
self.assertEqual(kv, "fp16")
self.assertIn("keep the K/V cache in fp16", note)
self.assertEqual(F.kv_word("fp16", "Compact"), ("fp16", None))
def test_the_memory_follows_the_format(self):
self.assertEqual(QF.KV_BYTES_PER_TOKEN, {"fp16": 20_480, "int8": 10_560, "fp8": 10_560, "k8v4": 8_160, "q4_0": 5_760})
gdn = QF.GDN_STATE_BYTES
for kv, n in QF.KV_BYTES_PER_TOKEN.items():
self.assertAlmostEqual(QF.kv_gib(32768, kv=kv), (32768 * n + gdn) / QF.GIB, places=9)
self.assertEqual(QF.kv_gib(32768), QF.kv_gib(32768, kv="fp16")) # nothing named: fp16, as before
self.assertLess(QF.kv_gib(262144, kv="q4_0"), QF.kv_gib(262144, kv="k8v4"))
self.assertLess(QF.kv_gib(262144, kv="k8v4"), QF.kv_gib(262144, kv="int8"))
self.assertLess(QF.kv_gib(262144, kv="int8"), QF.kv_gib(262144))
self.assertAlmostEqual((QF.kv_gib(32768, kv="int8") - gdn / QF.GIB), 0.35, places=1) # Q4-KV: 0.35 GB at 32K
self.assertAlmostEqual(QF.kv_gib(262144, kv="fp16") - gdn / QF.GIB, 5.0, places=0)
a16, a8 = QF.advise(24.0, 64.0, ctx=262144, build="Balanced", kv="fp16"), QF.advise(24.0, 64.0, ctx=262144, build="Balanced", kv="q4_0")
self.assertGreater(a16["vram_need_gib"], a8["vram_need_gib"])
def test_the_gguf_arguments_carry_the_format(self):
g = F.gguf_engine_args("/t/trunk", "/t/s2")
self.assertEqual(g[g.index("--kv") + 1], "int8") # the default
self.assertEqual(g.count("--kv"), 1)
for kv in ("fp16", "k8v4", "q4_0"):
g = F.gguf_engine_args("/t/trunk", "/t/s2", kv=kv)
self.assertEqual(g[g.index("--kv") + 1], kv)
g = F.gguf_engine_args("/t/trunk", "/t/s2", kv="k8v8") # a word the build does not take
self.assertEqual(g[g.index("--kv") + 1], "int8")
self.assertNotIn("--kv", F.engine_args("/m/Q.strata", ple="/m/P.gguf", ctx=8192)) # the standalone host takes no --kv (it would exit 2)
class MtpSpecK(unittest.TestCase):
"""`--spec K --spec-min-p 0.5` of the GGUF build's drafter: K = 3 on every card (Q4-SMALL's matrix), one default and an empty per-card override table."""
def test_k_is_3_everywhere(self):
self.assertEqual(QF.MTP_SPEC_DEFAULT, 3)
self.assertEqual(QF.mtp_spec_k(), 3)
for card in ("NVIDIA GeForce RTX 5090", "RTX 5080", "RTX 3080", "RTX 3060", "RTX 5060", "Radeon RX 9070", "Apple M4"):
self.assertEqual(QF.mtp_spec_k(card), 3, card)
def test_the_per_card_table(self):
self.assertEqual(QF.MTP_SPEC_BY_CARD, {})
with mock.patch.dict(QF.MTP_SPEC_BY_CARD, {"3060": 2}):
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_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"])
g = F.gguf_engine_args("/t/trunk", "/t/s2", mtp_rt="/t/rt", spec_k=2)
self.assertEqual(g[g.index("--spec") + 1], "2")
self.assertEqual(g[g.index("--spec-min-p") + 1], "0.5")
g = F.gguf_engine_args("/t/trunk", "/t/s2", mtp_rt="/t/rt")
self.assertEqual(g[g.index("--spec") + 1], "3")
self.assertEqual(F.MTP_SPEC_CONFIG_KEY, "qwen4_mtp_spec")
self.assertEqual(F.MTP_REPO, "Qwen/Qwen4-35B-A3B") # the host name is only in setup.py
self.assertEqual(F.HF_REVISION, "849378c8db0d4537b7c6731738147378729d8920")
self.assertEqual(F.GGUF_MTP_CHAIN, ("tools/mtp_fetch.py", "tools/mtp_pack.py", "tools/mtp_rt.py"))
self.assertEqual(QF.MTP_AUTO_MIN_VRAM_GIB, 6.0)
class StrataFloors(unittest.TestCase):
"""The .strata builds hold the whole build on the card today: below a build's floor it is "short" (until the engine's memory tiering lands); the GGUF build is unaffected."""
def test_the_table(self):
self.assertEqual(QF.STRATA_MIN_VRAM_GIB, {"Compact": 13.0, "Balanced": 22.0, "Ultra": 29.0})
def test_below_the_floor_is_short_and_says_so(self):
for gib in (8.0, 10.0, 12.0, 12.9):
self.assertEqual(QF.mode_of("Compact", gib, 64.0), "short", gib)
a = QF.advise(gib, 64.0, build="Compact")
self.assertEqual(a["mode"], "short")
self.assertTrue(any("memory tiering lands" in w and "UD-Q4_K_XL" in w for w in a["warnings"]), a["warnings"])
self.assertNotEqual(QF.mode_of("Compact", 16.0, 64.0), "short")
self.assertNotEqual(QF.mode_of("Compact", 13.0, 64.0), "short")
self.assertEqual(QF.mode_of("Balanced", 21.0, 64.0), "short")
self.assertNotEqual(QF.mode_of("Balanced", 24.0, 64.0), "short")
self.assertEqual(QF.mode_of("Ultra", 24.0, 128.0), "short")
self.assertNotEqual(QF.mode_of("Ultra", 32.0, 128.0), "short")
def test_a_unified_pool_and_an_unknown_card_have_no_floor(self):
self.assertFalse(QF.strata_below_floor("Compact", None))
self.assertFalse(QF.strata_below_floor("Compact", 8.0, unified=True))
self.assertFalse(QF.strata_below_floor("UD-Q4_K_XL", 8.0))
self.assertTrue(QF.strata_below_floor("Compact", 8.0))
def test_the_rows_mark_the_short_build(self):
rows = {r["build"]: r for r in QF.rows(12.0, 64.0)}
self.assertEqual(rows["Compact"]["mode"], "short")
self.assertFalse(rows["Compact"]["fits"])
self.assertEqual(QF.recommend(12.0, 64.0)["build"], "Compact") # recommend() is unchanged (the lead decides with the coordinator)
if __name__ == "__main__":
unittest.main()
+4 -3
View File
@@ -121,7 +121,8 @@ class Config(unittest.TestCase):
def test_apply_choices_uses_ctx_and_the_vision_flag(self):
cfg = R.apply_choices(BASE, S.LaunchSettings(family=FAM, context=65536, vision="off"))
self.assertEqual(value(cfg["args"], "--ctx"), "65536")
self.assertEqual(value(cfg["args"], "--max-ctx"), "65536") # a .strata build: the standalone engine's own flag
self.assertNotIn("--kv", cfg["args"])
self.assertNotIn("--vision", cfg["args"])
self.assertNotIn("--max-context", cfg["args"])
@@ -390,8 +391,8 @@ class GgufBuild(unittest.TestCase):
self.assertEqual(kinds, ["weights", "mtp", "mmproj"])
for name in (self.G["shard1"][0], self.G["shard2"][0], self.G["mmproj"][0]):
(folder / name).write_bytes(b"x")
(folder / "MTP").mkdir()
(folder / self.G["mtp"][0]).write_bytes(b"x")
(folder / F.GGUF_MTP_RT).mkdir() # the drafter is the runtime built at install, not Unsloth's sidecar file
(folder / F.GGUF_MTP_RT / "dense.bin").write_bytes(b"x")
self.assertEqual(modelstate.assess(cat, FAM, "UD-Q4_K_XL", vision="on", data_dir=td, rows=[], mtp="auto", use_installed=False).parts, [])
off = modelstate.assess(cat, FAM, "UD-Q4_K_XL", vision="off", data_dir=td, rows=[], mtp="off", use_installed=False, loop="on")
self.assertEqual([p.kind for p in off.parts], ["loop"])
+11 -5
View File
@@ -847,7 +847,7 @@ class Strata:
"ram_gb": d["models"][model]["ram_gb"], "arena_gb": round(ling32_fit.rank_table().total / 1e9, 1), "vision": ling32_family.DEFAULT_VISION, "engine": None, "families": (family,),
"context_fit": None, "ling32": True, "footprint_gb": foot}
def qwen4_fit_row(self, build, ram, usable, ctx: int | None = None, vision: bool = True, loop: bool = False) -> dict | None:
def qwen4_fit_row(self, build, ram, usable, ctx: int | None = None, vision: bool = True, loop: bool = False, kv: str | None = None) -> dict | None:
"""Where Qwen4-35B-A3B `build` lives on this PC (strata_control/qwen4_fit.py): whole on the card, card + RAM, one memory pool, or too little memory; which PLE table (Q4 / Q8) the rule picks,
whether `build` is the recommended one, and the engine-pick row of the card (how far the model was run on it). None when the RAM is not known."""
if ram is None:
@@ -871,16 +871,19 @@ class Strata:
m = re.search(r"(\d+)\.?(\d)?\b", str(arch).replace("sm_", ""))
arch = (int(m.group(1)) * 10 + int(m.group(2) or 0) if m and m.group(2) is not None else int(m.group(1))) if m else None
from strata_control import qwen4_family
kv_eff = qwen4_family.kv_word(kv, build, backend)[0] # the K/V format this row is worked out with: the person's word, else the build's default
if qwen4_family.is_gguf_build(build):
adv = self.setup_module().qwen4_gguf_advise(vram_gib, ram_gib, unified=unified, ctx=ctx, vision=vision, loop=loop and qwen4_family.loop_ready(build, backend))
adv = self.setup_module().qwen4_gguf_advise(vram_gib, ram_gib, unified=unified, ctx=ctx, vision=vision, loop=loop and qwen4_family.loop_ready(build, backend), kv=kv_eff)
else:
adv = qwen4_fit.advise(vram_gib, ram_gib, unified=unified, ctx=ctx, build=build, vision=vision, loop=loop and qwen4_family.loop_ready(build, backend), backend=backend)
adv = qwen4_fit.advise(vram_gib, ram_gib, unified=unified, ctx=ctx, build=build, vision=vision, loop=loop and qwen4_family.loop_ready(build, backend), backend=backend, kv=kv_eff)
pick = qwen4_fit.engine_pick(backend, arch) if backend != "sycl" else {"key": "", "supported": False, "level": "unsupported", "words": "Intel Arc cards are not offered Qwen4-35B-A3B in this release"}
return {"build": adv["build"], "ple": adv["ple"], "mode": adv["mode"], "mode_words": adv["mode_words"], "recommended": adv["recommended"]["build"] == build,
"recommended_build": adv["recommended"]["build"], "unified": unified, "context": int(ctx or qwen4_fit.DEFAULT_CONTEXT), "warnings": adv["warnings"], "feasible": adv["mode"] != "short",
"placement": {"vram_gb": adv["vram_need_gib"], "ram_gb": adv["ram_need_gib"]}, "download_gb": adv["download_gb"], "files": adv["files"],
"backend": backend, "engine_exists": bool(pick.get("supported")), "engine": {"key": pick.get("key"), "level": pick.get("level"), "cuda": pick.get("cuda"), "words": pick.get("words")},
# 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),
"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)}
@@ -3186,9 +3189,12 @@ class Tools:
else:
have_files = qwen4_family.local_files(target / "models" / qwen4_family.FAMILY)
if qwen4_family.is_gguf_build(model):
roles = ["shard1", "shard2"] + (["mmproj"] if vision != "no" else []) + (["mtp"] if mtp != "off" else [])
roles = ["shard1", "shard2"] + (["mmproj"] if vision != "no" else [])
from strata_control import qwen4_fit
gdir = target / "models" / qwen4_family.FAMILY
left = sum(s.setup_module().qwen4_gguf_bytes(r) / 1e9 for r in roles if not (gdir / qwen4_family.GGUF_FILES[r][0].rsplit("/", 1)[-1]).is_file())
if mtp != "off" and not (gdir / qwen4_family.GGUF_MTP_RT / "dense.bin").is_file():
left += qwen4_fit.GGUF_MTP_BYTES / 1e9 # the draft layer is built at install (923 MiB), not downloaded as a file
md = {**md, "download_gb": round(left + (qwen4_fit_loop_gb if loop == "on" else 0.0), 1)}
else:
names = qwen4_family.files_of(model, vision=vision != "no" and qwen4_family.vision_ready(model), mtp=mtp != "off" and qwen4_family.mtp_ready(model), ple=(ple or "q4").upper(), loop=loop == "on")
@@ -3272,7 +3278,7 @@ class Tools:
row = s.ling32_fit_row(model, ram, s.engine_gpus(hw), context, vision != "no")
fit = None if row is None else ("may run slower" if row["mode"] == "cross_tier_ssd" else "fits")
elif md.get("qwen4"):
row = s.qwen4_fit_row(model, ram, s.engine_gpus(hw), context, vision != "no", loop == "on")
row = s.qwen4_fit_row(model, ram, s.engine_gpus(hw), context, vision != "no", loop == "on", kv)
fit = None if row is None else ("fits" if row["feasible"] and row["mode"] != "hybrid" else "may run slower")
elif md.get("inkling"):
row = s.inkling_fit_row(model, ram, s.engine_gpus(hw))
+115 -13
View File
@@ -260,7 +260,7 @@ class Install(unittest.TestCase):
unified = backend == "metal"
written, says, fetched = {}, [], []
gpu = {"index": 0, "name": "Test card", "vram_gb": vram, "count": 1, "arch": arch}
a = ns(context=kw.pop("context", 65536), models_dir=str(root / "models"), rope_scaling=None, rope_scale=None, kv=None, resident_budget_gib=None, low_ram=None,
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()
@@ -363,7 +363,10 @@ class Install(unittest.TestCase):
def test_a_pc_that_cannot_hold_the_build_is_told_not_refused(self):
rc, w, says, _, _ = self.run_install(model="Ultra", vram_gb=12.0, ram=16)
self.assertEqual(rc, 0)
self.assertTrue(any(s.startswith("warn") and "needs about" in s for s in says), says)
self.assertTrue(any(s.startswith("warn") and ("needs about" in s or "memory tiering lands" in s) for s in says), says)
rc, w, says, _, _ = self.run_install(model="Compact", vram_gb=12.0, ram=64) # a 12 GB card: Compact is short of video memory until the engine's tiering lands
self.assertEqual(rc, 0)
self.assertTrue(any(s.startswith("warn") and "needs 13 GB of video memory" in s and "UD-Q4_K_XL" in s for s in says), says)
def test_a_bad_build_name_stops_in_plain_words(self):
with mock.patch.object(setup, "fail", side_effect=SystemExit(1)) as fail:
@@ -457,20 +460,24 @@ class TokenizerFiles(unittest.TestCase):
class GgufBuild(unittest.TestCase):
"""The fourth build, Unsloth's UD-Q4_K_XL GGUF: downloads with no pins yet, the two preparation tools (faked), the engine arguments of qwen4_family.gguf_engine_args."""
def run_install(self, *, tools=("split", "mtp"), source=False, pins=None, **kw):
def run_install(self, *, tools=("split", "mtp"), source=False, pins=None, fail_steps=(), **kw):
with tempfile.TemporaryDirectory() as d:
root = Path(d)
fake_root = root / "src"
(fake_root / "tools").mkdir(parents=True)
if "split" in tools:
(fake_root / qwen4_family.GGUF_SPLIT_TOOL).write_text("# fake", encoding="utf-8")
if "mtp" in tools:
(fake_root / qwen4_family.GGUF_MTP_TOOL).write_text("# fake", encoding="utf-8")
for step in ("mtp", "mtp_fetch", "mtp_pack", "mtp_rt"): # the BF16-route chain: fetch -> pack -> rt (a tool name leaves its step out)
if step in tools or ("mtp" in tools and step != "mtp"):
if step != "mtp" and step not in tools and ("no_" + step) in tools:
continue
if step != "mtp":
(fake_root / "tools" / f"{step}.py").write_text("# fake", encoding="utf-8")
vram = kw.pop("vram_gb", 24.0)
ram = kw.pop("ram", 64)
written, says, ran, downloaded = {}, [], [], []
gpu = {"index": 0, "name": "Test card", "vram_gb": vram, "count": 1, "arch": "86"}
a = ns(model="UD-Q4_K_XL", context=65536, models_dir=str(root / "models"), rope_scaling=None, rope_scale=None, kv=None, resident_budget_gib=None, low_ram=None,
a = ns(model="UD-Q4_K_XL", 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()
@@ -483,15 +490,22 @@ class GgufBuild(unittest.TestCase):
def fake_run(cmd, *x, **y):
ran.append([str(c) for c in cmd])
tool = Path(str(cmd[1])).name
tool = Path(next(str(c) for c in cmd if str(c).endswith(".py"))).name
out = Path(str(cmd[cmd.index("--out") + 1]))
if tool in fail_steps:
raise SystemExit(1)
if tool == "qwen4_split_gguf.py":
out.write_bytes(b"trunk")
elif tool == "iq_pack.py":
(out / "tokenizer").mkdir(parents=True, exist_ok=True)
(out / "tokenizer" / "vocab.json").write_text("{}", encoding="utf-8")
(out / "native_experts.txt").write_text("x", encoding="utf-8")
elif tool == "mtp_qwen4_rt.py":
elif tool == "mtp_fetch.py":
out.mkdir(parents=True, exist_ok=True)
(out / "mtp-manifest.json").write_text("{}", encoding="utf-8")
elif tool == "mtp_pack.py":
out.write_bytes(b"packed")
elif tool == "mtp_rt.py":
out.mkdir(parents=True, exist_ok=True)
(out / "dense.bin").write_bytes(b"rt")
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,
@@ -527,15 +541,20 @@ class GgufBuild(unittest.TestCase):
self.assertEqual(cfg["vision"]["model"], str(trunk))
self.assertEqual(cfg["model_name"], "qwen4-35b-a3b-ud-q4_k_xl")
self.assertEqual(w["path"].name, "strata-qwen4-35b-a3b-ud-q4_k_xl.json")
self.assertEqual(cfg[qwen4_family.MTP_CONFIG_KEY], str(folder / qwen4_family.GGUF_MTP_RT)) # the runtime: serve turns it into --mtp <rt> --spec 4
self.assertEqual(cfg[qwen4_family.MTP_CONFIG_KEY], str(folder / qwen4_family.GGUF_MTP_RT)) # the runtime: serve turns it into --mtp <rt> --spec K --spec-min-p 0.5
self.assertEqual(cfg[qwen4_family.MTP_SPEC_CONFIG_KEY], 3) # K = 3 on every card
self.assertEqual(cfg["args"][cfg["args"].index("--spec") + 1], "2") # a native pack needs --spec >= 2; with MTP serve swaps it for --spec 4 --spec-min-p 0.5
self.assertEqual(cfg[qwen4_family.MTP_MODE_KEY], "auto")
self.assertEqual(cfg["tokenizer"], str(root / "data" / "packs" / "qwen4-35b-a3b-ud-q4_k_xl" / "tokenizer"))
tools = [Path(c[1]).name for c in ran]
self.assertEqual(tools, ["qwen4_split_gguf.py", "iq_pack.py", "mtp_qwen4_rt.py"])
tools = [Path(next(x for x in c if x.endswith(".py"))).name for c in ran]
self.assertEqual(tools, ["qwen4_split_gguf.py", "iq_pack.py", "mtp_fetch.py", "mtp_pack.py", "mtp_rt.py"]) # the BF16 route, in order
self.assertEqual(ran[2][ran[2].index("--repo") + 1], f"https://huggingface.co/Qwen/Qwen4-35B-A3B/resolve/{qwen4_family.HF_REVISION}/") # the PINNED revision, public Hugging Face
self.assertIn("q8_0", ran[3])
self.assertFalse((root / "models" / "qwen4-35b-a3b" / qwen4_family.GGUF_MTP_WORKDIR).exists()) # the fetched tensors are removed once the runtime is built
self.assertEqual(ran[0][2:], ["--gguf", str(folder / qwen4_family.GGUF_FILES["shard1"][0]), "--out", str(trunk)])
self.assertNotIn("PLE", " ".join(downloaded)) # shard 2 holds the PLE table: no separate download
self.assertEqual(len(downloaded), 4) # two shards, the picture reader, the MTP sidecar
self.assertEqual(len(downloaded), 3) # two shards and the picture reader: the 1.95 GB Unsloth MTP file is not downloaded any more
self.assertFalse(any("mtp-Qwen4-35B-A3B-Q8_0" in u for u in downloaded), downloaded)
self.assertTrue(all(u.startswith(f"https://huggingface.co/{qwen4_family.GGUF_REPO}/resolve/") for u in downloaded), downloaded)
self.assertTrue(any("no pinned size or SHA-256" in s for s in says), says) # nothing is verified by hash yet: said plainly
@@ -558,7 +577,7 @@ class GgufBuild(unittest.TestCase):
self.assertEqual(len(downloaded), 2)
self.assertNotIn("--vision", w["cfg"]["args"])
self.assertNotIn(qwen4_family.MTP_CONFIG_KEY, w["cfg"])
self.assertNotIn("mtp_qwen4_rt.py", [Path(c[1]).name for c in ran])
self.assertFalse([c for c in ran if "mtp_" in c[1] or any("mtp_" in x for x in c)]) # MTP off: no step of the chain runs
_, _, says, _, _, _ = self.run_install(ple="q8")
self.assertTrue(any(s.startswith("warn") and "--ple does not apply" in s for s in says), says)
with mock.patch.dict(qwen4_family.FILES, TINY):
@@ -779,5 +798,88 @@ class BlackwellCudaChoice(unittest.TestCase):
self.assertEqual(setup.cuda_choice([86, 120], None, None, qwen4=True), (13, None))
class KvInstall(unittest.TestCase):
"""setup --kv for Qwen4: validated against qwen4_family.KV_CHOICES; the GGUF build writes `--kv X` (int8 by default), a .strata build writes none and says so."""
def test_a_strata_build_writes_no_kv_and_a_word_gets_one_note(self):
rc, w, says, _, _ = Install.run_install(Install(), kv="int8")
self.assertNotIn("--kv", w["cfg"]["args"])
self.assertTrue(any(s.startswith("warn") and "keep the K/V cache in fp16" in s for s in says), says)
rc, w, says, _, _ = Install.run_install(Install())
self.assertNotIn("--kv", w["cfg"]["args"])
self.assertFalse(any("K/V cache" in s for s in says), says)
def test_the_gguf_build_defaults_to_int8_and_takes_the_listed_words(self):
rc, w, says, _, _, _ = GgufBuild.run_install(GgufBuild())
a = w["cfg"]["args"]
self.assertEqual(a[a.index("--kv") + 1], "int8")
for kv in ("q4_0", "k8v4", "fp16"):
rc, w, says, _, _, _ = GgufBuild.run_install(GgufBuild(), kv=kv)
a = w["cfg"]["args"]
self.assertEqual(a[a.index("--kv") + 1], kv)
rc, w, says, _, _, _ = GgufBuild.run_install(GgufBuild(), kv="k8v8")
a = w["cfg"]["args"]
self.assertEqual(a[a.index("--kv") + 1], "int8")
self.assertTrue(any(s.startswith("warn") and "k8v8" in s for s in says), says)
def test_the_catalog_row_lists_what_this_build_takes(self):
s = M.Strata(HERE.parent)
cards = [{"vendor": "nvidia", "vram_gb": 24.0, "arch": "86", "usable": True}]
g = s.qwen4_fit_row("UD-Q4_K_XL", 64.0, cards)
self.assertEqual((g["kv"], g["kv_default"], g["kv_choices"]), ("int8", "int8", ["int8", "fp16", "k8v4", "q4_0"]))
c = s.qwen4_fit_row("Compact", 64.0, cards)
self.assertEqual((c["kv"], c["kv_default"], c["kv_choices"]), ("fp16", "fp16", ["fp16"]))
self.assertEqual(s.qwen4_fit_row("UD-Q4_K_XL", 64.0, cards, kv="q4_0")["kv"], "q4_0")
self.assertLess(s.qwen4_fit_row("UD-Q4_K_XL", 64.0, cards, ctx=262144, kv="q4_0")["placement"]["vram_gb"], s.qwen4_fit_row("UD-Q4_K_XL", 64.0, cards, ctx=262144, kv="fp16")["placement"]["vram_gb"])
class MtpChain(unittest.TestCase):
"""The GGUF build's drafter is built at install: fetch (pinned Qwen revision) -> pack q8_0 -> rt; any failing step is MTP off with one warning, never a failed install."""
def test_a_failing_step_is_mtp_off_with_one_warning_and_the_install_goes_on(self):
for step in ("mtp_fetch.py", "mtp_pack.py", "mtp_rt.py"):
rc, w, says, ran, downloaded, root = GgufBuild.run_install(GgufBuild(), fail_steps=(step,))
self.assertEqual(rc, 0, step)
self.assertNotIn(qwen4_family.MTP_CONFIG_KEY, w["cfg"], step)
self.assertNotIn(qwen4_family.MTP_SPEC_CONFIG_KEY, w["cfg"], step)
self.assertEqual(len([s for s in says if s.startswith("warn") and "MTP is off for this build" in s]), 1, (step, says))
self.assertEqual(w["cfg"]["args"][w["cfg"]["args"].index("--spec") + 1], "2") # the plain native-pack start
def test_a_missing_tool_is_mtp_off_too(self):
for gone in ("no_mtp_fetch", "no_mtp_pack", "no_mtp_rt"):
rc, w, says, ran, _, _ = GgufBuild.run_install(GgufBuild(), tools=("split", "mtp", gone))
self.assertEqual(rc, 0, gone)
self.assertNotIn(qwen4_family.MTP_CONFIG_KEY, w["cfg"], gone)
def test_the_drafter_is_counted_as_the_runtime_not_the_sidecar_file(self):
self.assertEqual(setup.qwen4_gguf_bytes("mtp"), qwen4_fit.GGUF_MTP_BYTES)
self.assertEqual(qwen4_fit.GGUF_MTP_BYTES, 923 * 2 ** 20)
self.assertNotIn(qwen4_family.GGUF_FILES["mtp"][0], qwen4_family.gguf_files_of(True))
self.assertNotIn(qwen4_family.GGUF_FILES["mtp"][0], setup.qwen4_gguf_advise(24.0, 64.0)["files"])
self.assertIn(qwen4_family.GGUF_FILES["mtp"][0], qwen4_family.gguf_files_of(True, mtp=True)) # the optional role is still defined
with_mtp, without = setup.qwen4_gguf_download_gb(True, True), setup.qwen4_gguf_download_gb(True, False)
self.assertAlmostEqual(with_mtp - without, qwen4_fit.GGUF_MTP_BYTES / 1e9, places=3) # +0.97 GB, not +2.0 GB
class GgufRamAndSlots(unittest.TestCase):
"""UD-Q4_K_XL: about 64 GB of RAM is recommended (a warning below it), and the expert slots a card holds are said in words."""
def test_the_ram_recommendation(self):
self.assertEqual(qwen4_fit.GGUF_RAM_NEED_GIB, 64.0)
low = setup.qwen4_gguf_advise(24.0, 32.0)
self.assertTrue(any("about 64 GB of RAM" in w for w in low["warnings"]), low["warnings"])
self.assertFalse(any("about 64 GB of RAM" in w for w in setup.qwen4_gguf_advise(24.0, 64.0)["warnings"]))
self.assertFalse(any("about 64 GB of RAM" in w for w in setup.qwen4_gguf_advise(None, 16.0, unified=True)["warnings"])) # a unified pool has its own rule
def test_the_slots_by_card(self):
for gib, n in ((32.0, 10240), (31.5, 5800), (16.0, 5800), (12.0, 3800), (10.0, 2700), (8.0, 1500)):
self.assertEqual(qwen4_fit.gguf_expert_slots(gib), n, gib)
self.assertIsNone(qwen4_fit.gguf_expert_slots(6.0))
self.assertIsNone(qwen4_fit.gguf_expert_slots(None))
self.assertTrue(any("about 3800 of the 10240 expert slots" in w for w in setup.qwen4_gguf_advise(12.0, 64.0)["warnings"]))
row = M.Strata(HERE.parent).qwen4_fit_row("UD-Q4_K_XL", 64.0, [{"vendor": "nvidia", "vram_gb": 12.0, "arch": "86", "usable": True}])
self.assertEqual((row["expert_slots"], row["expert_slots_total"]), (3800, 10240))
if __name__ == "__main__":
unittest.main()