Merge f-0226-q4-core into f-0226-q4-ship

This commit is contained in:
Niko1221 committed 2026-12-04 08:24:55 +01:00
commit 7f2b94d2e8
91 files changed
+10549 -1245

No files matched your search

+35
View File
@@ -29,6 +29,8 @@ const add = {
q420: '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.',
q421: 'Ultra',
q422: 'Unsloth’s GGUF build, supported by the community. Setup prepares it for the engine, which takes a few minutes.',
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.',
},
de: {
q401: 'Speicherplan: Das ganze Modell passt in den Grafikspeicher; die PLE-Tabelle ({0}) liegt im RAM.',
@@ -53,6 +55,8 @@ const add = {
q420: 'Auto: Die Engine lädt die MTP-Entwurfsebene nur dort, wo sie auf diesem PC Antworten beschleunigt (sie prüft das beim Start). Ein erzwingt sie, Aus lädt sie nie. Die Datei ist 0,4 GB groß.',
q421: 'Ultra',
q422: 'Unsloths GGUF-Variante, von der Community unterstützt. Das Setup bereitet sie für die Engine vor, das dauert einige Minuten.',
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.',
},
es: {
q401: 'Plan de memoria: todo el modelo cabe en la memoria de vídeo; la tabla PLE ({0}) se guarda en la RAM.',
@@ -77,6 +81,8 @@ const add = {
q420: 'Auto: el motor carga la capa de borrador MTP solo donde acelera las respuestas en este PC (lo comprueba al iniciar). Activado la fuerza, Desactivado nunca la carga. El archivo ocupa 0,4 GB.',
q421: 'Ultra',
q422: 'La versión GGUF de Unsloth, con soporte de la comunidad. La instalación la prepara para el motor, lo que tarda unos minutos.',
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.',
},
fr: {
q401: 'Plan mémoire : tout le modèle tient dans la mémoire vidéo ; la table PLE ({0}) reste en RAM.',
@@ -101,6 +107,8 @@ const add = {
q420: 'Auto : le moteur charge la couche brouillon MTP seulement là où elle accélère les réponses sur ce PC (il le vérifie au démarrage). Activé la force, Désactivé ne la charge jamais. Le fichier fait 0,4 Go.',
q421: 'Ultra',
q422: 'La version GGUF d’Unsloth, prise en charge par la communauté. L’installation la prépare pour le moteur, ce qui prend quelques minutes.',
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.',
},
pt: {
q401: 'Plano de memória: o modelo inteiro cabe na memória de vídeo; a tabela PLE ({0}) fica na RAM.',
@@ -125,6 +133,8 @@ const add = {
q420: 'Auto: o motor carrega a camada de rascunho MTP só onde ela acelera as respostas neste PC (ele verifica ao iniciar). Ligado a força, Desligado nunca a carrega. O arquivo tem 0,4 GB.',
q421: 'Ultra',
q422: 'A versão GGUF da Unsloth, com suporte da comunidade. A configuração a prepara para o motor, o que leva alguns minutos.',
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.',
},
ru: {
q401: 'План памяти: вся модель помещается в видеопамять; таблица PLE ({0}) хранится в ОЗУ.',
@@ -149,6 +159,8 @@ const add = {
q420: 'Авто: движок загружает черновой слой MTP только там, где он ускоряет ответы на этом ПК (проверяет при запуске). Вкл. включает его всегда, Выкл. никогда не загружает. Файл занимает 0,4 ГБ.',
q421: 'Ultra',
q422: 'Версия GGUF от Unsloth, поддерживается сообществом. Установка подготавливает её для движка, это занимает несколько минут.',
q423: 'Loop (2 шага) - скоро',
q424: 'Скоро: для Loop (2 шага) нужна поддержка в движке, которой пока нет в этой версии. Пока он остаётся выключенным.',
},
zh: {
q401: '内存方案:整个模型放得进显存;PLE 表({0})保存在内存中。',
@@ -173,6 +185,8 @@ const add = {
q420: '自动:只有在这台电脑上能加快回答时,引擎才加载 MTP 草稿层(启动时检查)。开启则强制加载,关闭则从不加载。文件大小为 0.4 GB。',
q421: 'Ultra',
q422: 'Unsloth 的 GGUF 版本,由社区支持。安装程序会为引擎准备它,需要几分钟。',
q423: 'Loop(2 步)- 即将推出',
q424: '即将推出:Loop(2 步)需要引擎支持,当前版本尚未包含。暂时保持关闭。',
},
ja: {
q401: 'メモリ計画:モデル全体がビデオメモリに収まり、PLE テーブル({0})は RAM に置かれます。',
@@ -197,6 +211,8 @@ const add = {
q420: '自動:エンジンは、この PC で回答が速くなる場合にのみ MTP ドラフト層を読み込みます(起動時に確認します)。オンは強制し、オフは読み込みません。ファイルは 0.4 GB です。',
q421: 'Ultra',
q422: 'Unsloth の GGUF ビルドで、コミュニティがサポートしています。セットアップがエンジン用に準備するため、数分かかります。',
q423: 'Loop(2 ステップ)- 近日対応',
q424: '近日対応:Loop(2 ステップ)にはエンジン側の対応が必要で、このリリースにはまだ含まれていません。当面はオフのままです。',
},
ko: {
q401: '메모리 계획: 모델 전체가 비디오 메모리에 들어가며, PLE 테이블({0})은 RAM에 보관됩니다.',
@@ -221,6 +237,8 @@ const add = {
q420: '자동: 엔진은 이 PC에서 응답이 빨라질 때만 MTP 초안 레이어를 불러옵니다(시작할 때 확인). 켬은 강제로 불러오고, 끔은 절대 불러오지 않습니다. 파일 크기는 0.4 GB입니다.',
q421: 'Ultra',
q422: 'Unsloth의 GGUF 빌드이며 커뮤니티에서 지원합니다. 설정이 엔진용으로 준비하며 몇 분이 걸립니다.',
q423: 'Loop(2단계) - 곧 제공',
q424: '곧 제공: Loop(2단계)에는 엔진 지원이 필요하며 이번 릴리스에는 아직 없습니다. 당분간 꺼진 상태로 유지됩니다.',
},
he: {
q401: 'תוכנית זיכרון: כל המודל נכנס בזיכרון הווידאו; טבלת ה-PLE ({0}) נשמרת ב-RAM.',
@@ -245,13 +263,30 @@ const add = {
q420: 'אוטומטי: המנוע טוען את שכבת הטיוטה MTP רק במקום שבו היא מאיצה תשובות במחשב הזה (הוא בודק בהפעלה). מופעל כופה אותה, כבוי לא טוען אותה לעולם. הקובץ הוא 0.4 GB.',
q421: 'Ultra',
q422: 'גרסת ה-GGUF של Unsloth, בתמיכת הקהילה. ההתקנה מכינה אותה למנוע, וזה לוקח כמה דקות.',
q423: 'Loop (2 צעדים) - בקרוב',
q424: 'בקרוב: ל-Loop (2 צעדים) דרושה תמיכה במנוע שעדיין אינה בגרסה הזו. בינתיים הוא נשאר כבוי.',
},
};
// Loop's real cost (Q4-LOOP, 0.2.26): the sentence that said "slower, a bit more accurate" now says what it costs. Applied to q414-q416 of every language, also when the key is already there.
const costFix = {
en: ['Slower, a bit more accurate.', 'Slower (about 40% fewer words per second while writing, prompt reading about half as fast), a little closer to the original model.'],
de: ['Langsamer, etwas genauer.', 'Langsamer (beim Schreiben etwa 40 % weniger Wörter pro Sekunde, das Lesen des Prompts etwa halb so schnell), etwas näher am ursprünglichen Modell.'],
es: ['Más lento, algo más preciso.', 'Más lento (al escribir, un 40 % menos de palabras por segundo; la lectura del prompt va a la mitad de velocidad), algo más cercano al modelo original.'],
fr: ['Plus lent, un peu plus précis.', 'Plus lent (environ 40 % de mots en moins par seconde à l’écriture, lecture de l’invite environ deux fois plus lente), un peu plus proche du modèle d’origine.'],
pt: ['Mais lento, um pouco mais preciso.', 'Mais lento (cerca de 40 % menos palavras por segundo ao escrever, e a leitura do prompt é cerca de metade da velocidade), um pouco mais próximo do modelo original.'],
ru: ['Медленнее, чуть точнее.', 'Медленнее (примерно на 40 % меньше слов в секунду при написании, чтение запроса примерно вдвое медленнее), чуть ближе к исходной модели.'],
zh: ['更慢,略微更准确。', '更慢(写作时每秒词数约少 40%,读取提示约慢一半),略微更接近原始模型。'],
ja: ['遅くなりますが、少し正確になります。', '遅くなります(書き込み中の毎秒の語数が約 40% 減り、プロンプトの読み込みは約半分の速さ)が、元のモデルに少し近づきます。'],
ko: ['더 느리지만 조금 더 정확합니다.', '더 느립니다(쓰는 동안 초당 단어 수가 약 40% 줄고 프롬프트 읽기는 약 절반 속도). 대신 원래 모델에 조금 더 가까워집니다.'],
he: ['לאט יותר, מדויק קצת יותר.', 'לאט יותר (בכתיבה כ-40% פחות מילים בשנייה, וקריאת ההנחיה כמחצית מהמהירות), קרוב קצת יותר למודל המקורי.'],
};
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;
const [was, now] = costFix[lang];
for (const k of ['q414', 'q415', 'q416']) if (typeof data[k] === 'string' && data[k].includes(was)) data[k] = data[k].replace(was, now);
writeFileSync(file, JSON.stringify(data, null, 1) + '\n');
}
console.log('ok');
+4 -3
View File
@@ -4,7 +4,7 @@ import { createJobStore } from './native-job-store.mjs';
import { isHy4, isHy4Family, isHy4Gguf, isHy4GgufModel, hy4VisionShard, withoutHy4Vision, withoutHy4GgufDrafting } from './hy4.mjs';
import { isInkling, isInklingFamily, inklingVisionShard, withoutInklingVision } from './inkling.mjs';
import { isLing32, isLing32Family, ling32VisionShard, LING32_ARCH, LING32_MTP_KEY, LING32_MTP_FILE, LING32_MTP_MODE_KEY, ling32MtpChoice, ling32MtpPatch, ling32SkipChoice, ling32WithSkip, withoutLing32Skip, LING32_SKIP_FLAG, LING32_SKIP_MEDIUM, LING32_SKIP_CHOICES, LING32_READY_S, LING32_DRAIN_S } from './ling32.mjs';
import { isQwen4, isQwen4Family, QWEN4_ARCH, QWEN4_MTP_KEY, QWEN4_MTP_FILE, QWEN4_MTP_MODE_KEY, qwen4MtpChoice, qwen4MtpPatch, qwen4EffortChoice, qwen4LoopChoice, qwen4LoopPath, qwen4WithLoop, QWEN4_LOOP_CHOICES, QWEN4_LOOP_MISSING, QWEN4_READY_S, QWEN4_DRAIN_S } from './qwen4.mjs';
import { isQwen4, isQwen4Family, QWEN4_ARCH, QWEN4_MTP_KEY, QWEN4_MTP_FILE, QWEN4_MTP_MODE_KEY, qwen4MtpChoice, qwen4MtpPatch, qwen4EffortChoice, qwen4LoopChoice, qwen4LoopPath, qwen4WithLoop, QWEN4_LOOP_CHOICES, QWEN4_LOOP_ENGINE_READY, QWEN4_LOOP_MISSING, QWEN4_READY_S, QWEN4_DRAIN_S } from './qwen4.mjs';
import { isNativeStrata, isNativeStrataFamily, nativeStrataVisionShard, withoutNativeStrataVision } from './native-strata.mjs';
import { metricsPowerW, noteEnginePower } from './energy-meter.mjs';
import { spawn } from 'node:child_process';
@@ -572,7 +572,7 @@ return {summary:result.summary??(customRow?'Removed from Strata. Your model file
if(isNativeStrata(cfg)){if((noReader||args.vision==='no'||(args.vision===undefined&&config.ui_vision_enabled===false))&&Array.isArray(cfg.args))cfg.args=withoutNativeStrataVision(cfg,cfg.args);}
else if(!cfg.vision&&Array.isArray(cfg.args))cfg.args=withoutVisionFlag(cfg.args);
/* Ling-3.2-Air: its draft layer is the MTP sidecar named by "ling32_mtp" in the run config (serve turns it into the engine's flags). The "Draft layer (MTP)" switch off leaves the key out of this start (the saved file keeps it); on, with no key saved, takes the sidecar the installer put beside the model. "drafting": "off" in a Ling file only says there is no Qwen draft pack. */
if(isQwen4(cfg)&&cfg.q4_loop!==undefined){const choice=cfg.q4_loop;delete cfg.q4_loop;if(QWEN4_LOOP_CHOICES.includes(choice)){const path=qwen4LoopPath(cfg,repo());if(choice==='on'&&!path)throw new Error(QWEN4_LOOP_MISSING);const done=qwen4WithLoop(cfg,choice,path);for(const k of Object.keys(cfg))if(!(k in done))delete cfg[k];Object.assign(cfg,done);}}else if(!isQwen4(cfg))delete cfg.q4_loop; /* Loop (2 steps), off unless chosen: the key and the two flags, or neither */
if(isQwen4(cfg)&&cfg.q4_loop!==undefined){const choice=cfg.q4_loop;delete cfg.q4_loop;if(QWEN4_LOOP_CHOICES.includes(choice)){const path=qwen4LoopPath(cfg,repo());if(choice==='on'&&QWEN4_LOOP_ENGINE_READY&&!path)throw new Error(QWEN4_LOOP_MISSING);const done=qwen4WithLoop(cfg,choice,path);for(const k of Object.keys(cfg))if(!(k in done))delete cfg[k];Object.assign(cfg,done);}}else if(!isQwen4(cfg))delete cfg.q4_loop; /* Loop (2 steps), off unless chosen: the key and the two flags, or neither */
if(isQwen4(cfg)&&cfg.q4_mtp!==undefined){if(cfg.q4_mtp!==null)for(const [k,v] of Object.entries(qwen4MtpPatch(cfg.q4_mtp))){if(v===null)delete cfg[k];else cfg[k]=v;}delete cfg.q4_mtp;}else if(!isQwen4(cfg))delete cfg.q4_mtp; /* Qwen4-35B-A3B: the same Draft layer menu, its own key (qwen4_mtp is the sidecar's path) */
if(isLing32(cfg)&&cfg.ling_mtp!==undefined){if(cfg.ling_mtp!==null)for(const [k,v] of Object.entries(ling32MtpPatch(cfg.ling_mtp))){if(v===null)delete cfg[k];else cfg[k]=v;}delete cfg.ling_mtp;} /* the Draft layer menu of the Models page (a Load's values) or the settings: off / on / auto */
if(isQwen4(cfg)){if(cfg.mtp===false)delete cfg[QWEN4_MTP_KEY];else if(cfg.mtp===true&&!cfg[QWEN4_MTP_KEY]){const at=(cfg.args??[]).findIndex(a=>a==='--native'||a==='--model'),model=at>=0?cfg.args[at+1]:null,side=model?join(dirname(resolve(repo(),model)),QWEN4_MTP_FILE):null;if(side&&existsSync(side))cfg[QWEN4_MTP_KEY]=side;}}
@@ -773,7 +773,8 @@ return {summary:result.summary??(customRow?'Removed from Strata. Your model file
/* Ling-3.2-Air's Expert skip chosen in this Load is saved with the model, as the Terminal's `--expert-skip` saves it (the pair in the args and in user_args), so it is still there after a restart and in the Terminal. A Load that carries no choice leaves the saved config alone. */
if(isLing32(config)&&LING32_SKIP_CHOICES.includes(args.values?.ling_skip)&&ling32SkipChoice(config)!==args.values.ling_skip){const saved=ling32WithSkip(config,args.values.ling_skip);try{writeConfigExact(configFile,saved);config=saved;}catch{/* a read-only folder: this start still carries the choice (buildConfig) */}}
/* Qwen4's Loop (2 steps) chosen in this Load is saved with the model (the key and the two flags, in the args and in user_args), so it is there after a restart and in the Terminal. A Load with no choice leaves the saved config alone. */
if(isQwen4(config)&&QWEN4_LOOP_CHOICES.includes(args.values?.q4_loop)&&qwen4LoopChoice(config)!==args.values.q4_loop){const path=qwen4LoopPath(config,repo());if(args.values.q4_loop==='on'&&!path)throw new Error(QWEN4_LOOP_MISSING);const saved=qwen4WithLoop(config,args.values.q4_loop,path);try{writeConfigExact(configFile,saved);config=saved;}catch{/* a read-only folder: this start still carries the choice (buildConfig) */}}
const q4LoopWant=QWEN4_LOOP_ENGINE_READY?args.values?.q4_loop:(isQwen4(config)&&qwen4LoopChoice(config)==='on'?'off':undefined); /* Loop is coming: nothing is turned on, and a key an earlier version saved is stripped */
if(isQwen4(config)&&QWEN4_LOOP_CHOICES.includes(q4LoopWant)&&qwen4LoopChoice(config)!==q4LoopWant){const path=qwen4LoopPath(config,repo());if(q4LoopWant==='on'&&!path)throw new Error(QWEN4_LOOP_MISSING);const saved=qwen4WithLoop(config,q4LoopWant,path);try{writeConfigExact(configFile,saved);config=saved;}catch{/* a read-only folder: this start still carries the choice (buildConfig) */}}
/* Read pictures is on and the picture files are not here: the Load fetches those files (about 0.9 GB, once) and nothing else of the model, then goes on. No internet: the model loads without pictures and the page says so. */
let picturesNote=null;{const got=await ensurePictures(job,args,configFile,config,{missing:entry.picturesMissing===true});if(job.state!=='running')return;config=got.config;args=got.args;picturesNote=got.note;}
/* One drafter per run (strata_control/drafting.py): switching to the MTP on a model set up for DFlash2 fetches the layer once, here; DFlash2 is fetched below. */
+1 -1
View File
@@ -15,7 +15,7 @@ export const NATIVE_FIELDS=[
{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_loop',label:'Loop (2 steps)',group:'Serving',type:'enum',choices:['off','on'],hint:'Loop (2 steps): thinks each word twice. Slower, a bit more accurate. 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:'q4_loop',label:'Loop (2 steps) - coming soon',group:'Serving',type:'enum',choices:['off','on'],hint:'Coming soon: Loop (2 steps) needs engine support that is not in this release yet. It stays off for now.'},
{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.'},
{id:'drafting',label:'Drafting',group:'Serving',type:'enum',choices:['auto','mtp','dflash2','off'],hint:draftingHint(1.2)},
+21 -11
View File
@@ -32,32 +32,42 @@ export const qwen4MtpChoice = config => config?.mtp === false ? 'off' : (config?
/** What to write into a run config for a choice: off = the app's switch false, on = switch true and mode on, auto = neither (the engine decides). */
export const qwen4MtpPatch = choice => choice === 'off' ? { mtp: false } : choice === 'on' ? { mtp: true, [QWEN4_MTP_MODE_KEY]: 'on' } : { mtp: null, [QWEN4_MTP_MODE_KEY]: null };
/** Loop (2 steps), OFF by default (owner): the model's recurrent-depth adapter, a 147 MB file (terminal/strata_control/qwen4_family.py LOOP_FILE, LOOP_CONFIG_KEY, ENGINE_FILE_FLAGS["loop"],
* ENGINE_LOOP_STEPS_FLAG, LOOP_STEPS). Shown only for Qwen4-35B-A3B with Strata's own quantization. ON = the run config's `qwen4_loop` holds the file's path and the engine's arguments carry
* the two flags below; OFF = neither. The flag names are PROVISIONAL (phaseA-tests/qwen4/CORE-API.md decides): they are in this ONE table. */
* ENGINE_LOOP_STEPS_FLAG, ENGINE_LOOP_CODA_FLAG, ENGINE_LOOP_DIRECT_FLAG, LOOP_STEPS). Shown only for Qwen4-35B-A3B with Strata's own quantization. ON = the run config's `qwen4_loop` holds the file's path and
* the engine's arguments carry `--loop-adapter FILE --loop-passes 2 --loop-coda universal|compact --loop-direct-t1` (Q4-LOOP's real flags; the coda is compact ONLY for the Compact build); OFF = none of them.
* The flag names are in this ONE table (and tests/qwen4-family.test.mjs pins them to qwen4_family.py). */
export const QWEN4_LOOP_FILE = 'Qwen4-35B-A3B-Loop.safetensors';
export const QWEN4_LOOP_KEY = 'qwen4_loop';
export const QWEN4_LOOP_STEPS = 2;
export const QWEN4_LOOP_FLAGS = Object.freeze({ file: '--loop', steps: '--loop-steps' });
export const QWEN4_LOOP_FLAGS = Object.freeze({ file: '--loop-adapter', steps: '--loop-passes', coda: '--loop-coda', direct: '--loop-direct-t1' });
/** The `--loop-coda` of the model a run config names: compact ONLY for the Compact .strata build; universal for Balanced, Ultra and the GGUF build (qwen4_family.loop_coda). */
export const qwen4LoopCoda = model => /(^|[\\/])Qwen4-35B-A3B-Compact\.strata$/i.test(String(model ?? '')) ? 'compact' : 'universal';
export const QWEN4_LOOP_CHOICES = ['off', 'on'];
/** THE Loop switch (mirrors terminal/strata_control/qwen4_family.py LOOP_ENGINE_READY and src/lib/qwen4.ts; tests/qwen4-family.test.mjs pins the three together). False: Loop is shown as "coming soon" and disabled,
* a request for `on` is written as off (no key, no flags, no download) and a saved key is stripped at the next Load. Flip to true when Q4-LOOP's engine flags land. */
export const QWEN4_LOOP_ENGINE_READY = false;
export const QWEN4_LOOP_COMING_LABEL = 'Loop (2 steps) - coming soon';
export const QWEN4_LOOP_COMING_NOTE = 'Coming soon: Loop (2 steps) needs engine support that is not in this release yet. It stays off for now.';
/** The Loop choice of a saved run config as the menu says it: on when the key names a file, else off. */
export const qwen4LoopChoice = config => typeof config?.[QWEN4_LOOP_KEY] === 'string' && config[QWEN4_LOOP_KEY] ? 'on' : 'off';
/** `args` without the Loop file and its step count. */
/** `args` without any Loop flag: --loop-adapter FILE, --loop-passes N, --loop-coda C and the bare --loop-direct-t1. */
export function withoutQwen4Loop(args) {
const list = (Array.isArray(args) ? args : []).map(String), out = [];
for (let i = 0; i < list.length; i++) {
if (list[i] === QWEN4_LOOP_FLAGS.file || list[i] === QWEN4_LOOP_FLAGS.steps) { if (i + 1 < list.length && !list[i + 1].startsWith('--')) i++; continue; }
if (list[i] === QWEN4_LOOP_FLAGS.direct) continue;
if (list[i] === QWEN4_LOOP_FLAGS.file || list[i] === QWEN4_LOOP_FLAGS.steps || list[i] === QWEN4_LOOP_FLAGS.coda) { if (i + 1 < list.length && !list[i + 1].startsWith('--')) i++; continue; }
out.push(list[i]);
}
return out;
}
/** The args with Loop on (the two flags last) or off (none of them). */
export const qwen4LoopArgs = (args, path) => path ? [...withoutQwen4Loop(args), QWEN4_LOOP_FLAGS.file, String(path), QWEN4_LOOP_FLAGS.steps, String(QWEN4_LOOP_STEPS)] : withoutQwen4Loop(args);
/** A run config with the Loop choice written: on = the key and the two flags in "args" and "user_args" (so a later setup run or Load keeps them), off = none of them. */
export function qwen4WithLoop(config, choice, path) {
const on = choice === 'on' && !!path;
/** The args with Loop on (the four flags last, the coda by the model `model`) or off (none of them). */
export const qwen4LoopArgs = (args, path, model) => path ? [...withoutQwen4Loop(args), QWEN4_LOOP_FLAGS.file, String(path), QWEN4_LOOP_FLAGS.steps, String(QWEN4_LOOP_STEPS), QWEN4_LOOP_FLAGS.coda, qwen4LoopCoda(model), QWEN4_LOOP_FLAGS.direct] : withoutQwen4Loop(args);
/** A run config with the Loop choice written: on = the key and the loop flags in "args" (the three with a value also in "user_args", so a later setup run or Load keeps them; the bare --loop-direct-t1 only in "args"), off = none of them. */
export function qwen4WithLoop(config, choice, path, ready = QWEN4_LOOP_ENGINE_READY) {
const on = choice === 'on' && ready && !!path;
let user = setUserFlag(captureUserArgs(config), QWEN4_LOOP_FLAGS.file, on ? path : null);
user = setUserFlag(user, QWEN4_LOOP_FLAGS.steps, on ? QWEN4_LOOP_STEPS : null);
const next = { ...config, args: withoutQwen4Loop(config.args) };
user = setUserFlag(user, QWEN4_LOOP_FLAGS.coda, on ? qwen4LoopCoda(qwen4ModelArg(config)) : null);
const next = { ...config, args: [...withoutQwen4Loop(config.args), ...(on ? [QWEN4_LOOP_FLAGS.direct] : [])] };
if (on) next[QWEN4_LOOP_KEY] = String(path); else delete next[QWEN4_LOOP_KEY];
return stampedUserArgs(next, user);
}
+5 -5
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, isQwen4GgufBuild } from '../lib/qwen4';
import { QWEN4_FAMILY, QWEN4_LOOP_ENGINE_READY, isQwen4GgufBuild } from '../lib/qwen4';
export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine }: {
onOtherModels: () => void;
onImport?: () => void;
@@ -147,7 +147,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
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 downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), ...((isLingSelected || isQ4Selected) && lingMtp !== 'auto' ? { mtp: lingMtp } : {}), ...(q4Own && q4Loop === 'on' ? { loop: 'on' } : {}), ...(isLingSelected && lingSkip === 'medium' ? { ling_skip: lingSkip } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), ...(contextPicked ? { contextChosen: true } : {}) };
const downloadValues = { ...values, ...(draftingChoices ? { drafting } : {}), ...((isLingSelected || isQ4Selected) && lingMtp !== 'auto' ? { mtp: lingMtp } : {}), ...(q4Own && QWEN4_LOOP_ENGINE_READY && q4Loop === 'on' ? { loop: 'on' } : {}), ...(isLingSelected && lingSkip === 'medium' ? { ling_skip: lingSkip } : {}), vision: selectedSize?.images && vision !== 'no' ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), ...(contextPicked ? { contextChosen: true } : {}) };
useEffect(() => { if (!native?.catalog || family)
return; const current = native.instances.find(i => i.id === native.defaultId); const rec = native.catalog.recommendation ?? { family: null, model: null }; const loadedFamily = families.find(f => f.sizes.some(s => s.id === current?.model)); const have = new Set((native.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); const installedFamily = families.find(f => f.sizes.some(s => have.has(s.id))); const diskFamily = families.find(f => f.sizes.some(s => s.files_on_disk)); const f = loadedFamily ?? installedFamily ?? diskFamily ?? families.find(f => f.family === rec.family || f.sizes.some(s => s.sourceFamily === rec.family)) ?? families[0]; if (f) {
setFamily(f.family);
@@ -224,7 +224,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine
const picturesByLoad = fetchesPictures(selectedSize, native?.packaged);
async function load() { if (!selectedSize)
return; setPlan(null); setDrafterGb(null); await perform(async () => { if (installed?.ready && context === installed.context && (!selectedSize?.images || vision === 'no' || picturesByLoad || installed.images && installed.images !== 'off') && (!installed.kv || kv === installed.kv || kv === tunedNow?.fields.kv) && (lowRam === (installed.lowRamMode ?? 'auto') || lowRam === tunedNow?.fields.lowRam) && !((isLingSelected || isQ4Selected) && lingMtp === 'on' && installed.draftLayer === false) && !(q4Own && q4Loop === 'on' && installed.q4Loop !== 'on')) {
const result = await nativeAction<NativeJob>('operations', { kind: 'load', args: { model: selectedSize.id, resourceProfile, vision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), ...(contextPicked && !installed.contextChosen ? { contextChosen: true } : {}), multiple: expert && multiple, ...(draftingChoices ? { values: { drafting } } : isLingSelected && (lingMtp !== (installed?.lingMtp ?? 'auto') || lingSkip !== (installed?.lingSkip ?? 'off')) ? { values: { ...(lingMtp !== (installed?.lingMtp ?? 'auto') ? { ling_mtp: lingMtp } : {}), ...(lingSkip !== (installed?.lingSkip ?? 'off') ? { ling_skip: lingSkip } : {}) } } : isQ4Selected && (lingMtp !== (installed?.lingMtp ?? 'auto') || (q4Own && q4Loop !== (installed?.q4Loop ?? 'off'))) ? { values: { ...(lingMtp !== (installed?.lingMtp ?? 'auto') ? { q4_mtp: lingMtp } : {}), ...(q4Own && q4Loop !== (installed?.q4Loop ?? 'off') ? { q4_loop: q4Loop } : {}) } } : {}), ...(roleCards.length > 1 ? (roles && (customRoles || savedDiffers) ? { gpuRoles: effectiveRoles, ...(!isHy4Selected ? { layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) } : cardsGpus.length ? { gpus: cardsGpus, gpusFromRecommendation: true, ...(!isHy4Selected ? { layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) } : {}) : {}) } });
const result = await nativeAction<NativeJob>('operations', { kind: 'load', args: { model: selectedSize.id, resourceProfile, vision: selectedSize?.images ? vision : 'no', ...(noReader ? { visionUnavailable: true } : {}), ...(contextPicked && !installed.contextChosen ? { contextChosen: true } : {}), multiple: expert && multiple, ...(draftingChoices ? { values: { drafting } } : isLingSelected && (lingMtp !== (installed?.lingMtp ?? 'auto') || lingSkip !== (installed?.lingSkip ?? 'off')) ? { values: { ...(lingMtp !== (installed?.lingMtp ?? 'auto') ? { ling_mtp: lingMtp } : {}), ...(lingSkip !== (installed?.lingSkip ?? 'off') ? { ling_skip: lingSkip } : {}) } } : isQ4Selected && (lingMtp !== (installed?.lingMtp ?? 'auto') || (q4Own && q4Loop !== (installed?.q4Loop ?? 'off'))) ? { values: { ...(lingMtp !== (installed?.lingMtp ?? 'auto') ? { q4_mtp: lingMtp } : {}), ...(q4Own && QWEN4_LOOP_ENGINE_READY && q4Loop !== (installed?.q4Loop ?? 'off') ? { q4_loop: q4Loop } : {}) } } : {}), ...(roleCards.length > 1 ? (roles && (customRoles || savedDiffers) ? { gpuRoles: effectiveRoles, ...(!isHy4Selected ? { layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) } : cardsGpus.length ? { gpus: cardsGpus, gpusFromRecommendation: true, ...(!isHy4Selected ? { layerSplit: expert && cardsGpus.length > 1 ? split : 'auto' } : {}) } : {}) : {}) } });
setJobId(result.id);
}
else {
@@ -393,8 +393,8 @@ function Qwen4Plan({ selectedModel, q4, mtp, onMtp, loop, onLoop, loopOffered, i
{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("Draft layer (MTP)")}</span><Select ariaLabel={tr("Draft layer (MTP)")} value={mtp} disabled={disabled} options={['auto', 'on', 'off'].map(v => ({ value: v, label: tr(mtpWords[v]) }))} onChange={v => onMtp(String(v))}/>
<small className="muted native-kv-hint">{tr(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}
{loopOffered && q4.engine_exists !== false ? <div className="native-choice__row"><div className="native-choice__col"><span className="native-choice__label">{tr("Loop (2 steps)")}</span><Select ariaLabel={tr("Loop (2 steps)")} value={loop} disabled={disabled} options={[{ value: 'off', label: tr("Off") }, { value: 'on', label: tr("On") }]} onChange={v => onLoop(String(v))}/>
<small className="muted native-kv-hint">{tr(loop === 'on' && installedLoop !== 'on' ? "Loop (2 steps): thinks each word twice. Slower, a bit more accurate. 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, a bit more accurate. It has no effect while Effort is Off.")}</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(QWEN4_LOOP_ENGINE_READY ? "Loop (2 steps)" : "Loop (2 steps) - coming soon")}</span><Select ariaLabel={tr(QWEN4_LOOP_ENGINE_READY ? "Loop (2 steps)" : "Loop (2 steps) - coming soon")} value={QWEN4_LOOP_ENGINE_READY ? loop : 'off'} disabled={disabled || !QWEN4_LOOP_ENGINE_READY} options={[{ value: 'off', label: tr("Off") }, { value: 'on', label: tr("On") }]} onChange={v => onLoop(String(v))}/>
<small className="muted native-kv-hint">{tr(!QWEN4_LOOP_ENGINE_READY ? "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>;
}
+3 -3
View File
@@ -10,7 +10,7 @@ import { draftingChoices } from '../lib/drafting';
import { NativeMcpEditor } from './NativeMcpEditor';
import { choiceOptions, choiceValue, isNumberChoice, withChoice } from '../lib/speed-choice';
import { HY4_FAMILY, INKLING_FAMILY, LING_FAMILY } from '../lib/native-catalog';
import { QWEN4_FAMILY, QWEN4_EFFORT_CHOICES, nativeFieldShown } from '../lib/qwen4';
import { QWEN4_FAMILY, QWEN4_EFFORT_CHOICES, QWEN4_LOOP_ENGINE_READY, nativeFieldShown } from '../lib/qwen4';
/** Native engine fields that apply only to the Qwen Flash-Next engine (strata-hy4 ignores them). */
const HY4_HIDDEN_FIELDS = new Set(['mtp', 'batchMtp', 'layer_split', 'gpu_order', 'split_skip_if_fits', 'vram_elastic', 'vram_reserve_mib', 'prompt_cache_spread', 'vision_tokens', 'vision_min_tokens', 'parallel', 'effort_position', 'anthropic_thinking']);
/** Native engine fields that Inkling-2-Mini (strata-inkling) ignores — no thinking mode, and `parallel` (1..64) IS shown! */
@@ -165,8 +165,8 @@ function NativeFieldInput({ field, value, onChange }: {
return <Select disabled={field.supported === false} ariaLabel={tr(field.label)} value={value ?? 'off'} options={[{ value: 'off', label: tr("Off") }, { value: 'medium', label: tr("Medium") }, ...(value === 'custom' ? [{ value: 'custom', label: tr("Custom (set in the run config)") }] : [])]} onChange={v => onChange(String(v))}/>;
if (field.id === 'effort') // Qwen4-35B-A3B's four thinking levels, in words (High is the default)
return <Select disabled={field.supported === false} ariaLabel={tr(field.label)} value={value ?? 'high'} options={QWEN4_EFFORT_CHOICES.map(c => ({ value: c.value, label: tr(c.label) }))} onChange={v => onChange(String(v))}/>;
if (field.id === 'q4_loop') // Loop (2 steps): Off (the default) or On
return <Select disabled={field.supported === false} ariaLabel={tr(field.label)} value={value ?? 'off'} options={[{ value: 'off', label: tr("Off") }, { value: 'on', label: tr("On") }]} onChange={v => onChange(String(v))}/>;
if (field.id === 'q4_loop') // Loop (2 steps): Off (the default) or On; disabled ("coming soon") until the engine supports it
return <Select disabled={field.supported === false || !QWEN4_LOOP_ENGINE_READY} ariaLabel={tr(field.label)} value={QWEN4_LOOP_ENGINE_READY ? value ?? 'off' : 'off'} options={[{ value: 'off', label: tr("Off") }, { value: 'on', label: tr("On") }]} onChange={v => onChange(String(v))}/>;
if (field.type === 'enum')
return <Select disabled={field.supported === false} ariaLabel={tr(field.label)} value={value ?? ''} options={[{ value: '', label: 'Default' }, ...(field.choices ?? []).map(v => ({ value: v, label: v }))]} onChange={v => onChange(v || null)}/>;
if (field.type === 'number')
+2
View File
@@ -3,6 +3,8 @@
* terminal/strata_control/qwen4_fit.py, and tests/qwen4-family.test.mjs reads that file and pins the numbers below to it).
*/
export const QWEN4_FAMILY = 'qwen4-35b-a3b';
/** THE Loop switch (qwen4_family.py LOOP_ENGINE_READY; server/qwen4.mjs mirrors it; tests/qwen4-family.test.mjs pins them together): false = "Loop (2 steps) - coming soon", disabled. */
export const QWEN4_LOOP_ENGINE_READY = false;
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. */
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "Auto: Die Entwurfsebene wird nur verwendet, wo sie auf diesem PC Antworten beschleunigt; die Engine prüft das beim Start. Die Datei ist 0,4 GB groß.",
"q412": "Die Entwurfsebene rät mehrere Wörter im Voraus, um schneller zu antworten. Die Datei ist 0,4 GB groß.",
"q413": "Loop (2 Schritte)",
"q414": "Loop (2 Schritte): denkt jedes Wort zweimal. Langsamer, etwas genauer. Ohne Wirkung, solange der Aufwand aus ist.",
"q415": "Loop (2 Schritte): denkt jedes Wort zweimal. Langsamer, etwas genauer. Die Datei (147 MB) wird einmal heruntergeladen, danach lädt das Modell mit ihr. Ohne Wirkung, solange der Aufwand aus ist.",
"q416": "Loop (2 Schritte): denkt jedes Wort zweimal. Langsamer, etwas genauer. Standardmäßig aus. Braucht eine Datei von 147 MB, die der Download-Schritt lädt, wenn Loop an ist. Ohne Wirkung, solange der Aufwand aus ist.",
"q414": "Loop (2 Schritte): denkt jedes Wort zweimal. Langsamer (beim Schreiben etwa 40 % weniger Wörter pro Sekunde, das Lesen des Prompts etwa halb so schnell), etwas näher am ursprünglichen Modell. Ohne Wirkung, solange der Aufwand aus ist.",
"q415": "Loop (2 Schritte): denkt jedes Wort zweimal. Langsamer (beim Schreiben etwa 40 % weniger Wörter pro Sekunde, das Lesen des Prompts etwa halb so schnell), etwas näher am ursprünglichen Modell. Die Datei (147 MB) wird einmal heruntergeladen, danach lädt das Modell mit ihr. Ohne Wirkung, solange der Aufwand aus ist.",
"q416": "Loop (2 Schritte): denkt jedes Wort zweimal. Langsamer (beim Schreiben etwa 40 % weniger Wörter pro Sekunde, das Lesen des Prompts etwa halb so schnell), etwas näher am ursprünglichen Modell. Standardmäßig aus. Braucht eine Datei von 147 MB, die der Download-Schritt lädt, wenn Loop an ist. Ohne Wirkung, solange der Aufwand aus ist.",
"q417": "Aufwand als Standard",
"q418": "Wie intensiv Qwen4-35B-A3B nachdenkt, wenn eine Anfrage nichts sagt (das Denken-Menü eines Chats tut es). Aus antwortet sofort; Niedrig, Hoch und Sehr hoch denken zuerst nach, jeweils länger: langsamer, besser bei schweren Fragen.",
"q419": "Sehr hoch",
"q420": "Auto: Die Engine lädt die MTP-Entwurfsebene nur dort, wo sie auf diesem PC Antworten beschleunigt (sie prüft das beim Start). Ein erzwingt sie, Aus lädt sie nie. Die Datei ist 0,4 GB groß.",
"q421": "Ultra",
"q422": "Unsloths GGUF-Variante, von der Community unterstützt. Das Setup bereitet sie für die Engine vor, das dauert einige Minuten."
"q422": "Unsloths GGUF-Variante, von der Community unterstützt. Das Setup bereitet sie für die Engine vor, das dauert einige Minuten.",
"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."
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "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.",
"q412": "The draft layer guesses several words ahead to answer faster. It is a 0.4 GB file.",
"q413": "Loop (2 steps)",
"q414": "Loop (2 steps): thinks each word twice. Slower, a bit more accurate. It has no effect while Effort is Off.",
"q415": "Loop (2 steps): thinks each word twice. Slower, a bit more accurate. Its 147 MB file is downloaded once, then the model loads with it. It has no effect while Effort is Off.",
"q416": "Loop (2 steps): thinks each word twice. Slower, a bit more accurate. 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.",
"q414": "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.",
"q415": "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.",
"q416": "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.",
"q417": "Effort by default",
"q418": "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.",
"q419": "X-High",
"q420": "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.",
"q421": "Ultra",
"q422": "Unsloth’s GGUF build, supported by the community. Setup prepares it for the engine, which takes a few minutes."
"q422": "Unsloth’s GGUF build, supported by the community. Setup prepares it for the engine, which takes a few minutes.",
"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."
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "Auto: la capa de borrador solo se usa donde acelera las respuestas en este PC; el motor lo comprueba al iniciar. El archivo ocupa 0,4 GB.",
"q412": "La capa de borrador adivina varias palabras por adelantado para responder más rápido. Es un archivo de 0,4 GB.",
"q413": "Loop (2 pasos)",
"q414": "Loop (2 pasos): piensa cada palabra dos veces. Más lento, algo más preciso. No tiene efecto mientras el esfuerzo esté desactivado.",
"q415": "Loop (2 pasos): piensa cada palabra dos veces. Más lento, algo más preciso. Su archivo de 147 MB se descarga una vez y luego el modelo se carga con él. No tiene efecto mientras el esfuerzo esté desactivado.",
"q416": "Loop (2 pasos): piensa cada palabra dos veces. Más lento, algo más preciso. Desactivado por defecto. Necesita un archivo de 147 MB que el paso de descarga obtiene cuando Loop está activado. No tiene efecto mientras el esfuerzo esté desactivado.",
"q414": "Loop (2 pasos): piensa cada palabra dos veces. Más lento (al escribir, un 40 % menos de palabras por segundo; la lectura del prompt va a la mitad de velocidad), algo más cercano al modelo original. No tiene efecto mientras el esfuerzo esté desactivado.",
"q415": "Loop (2 pasos): piensa cada palabra dos veces. Más lento (al escribir, un 40 % menos de palabras por segundo; la lectura del prompt va a la mitad de velocidad), algo más cercano al modelo original. Su archivo de 147 MB se descarga una vez y luego el modelo se carga con él. No tiene efecto mientras el esfuerzo esté desactivado.",
"q416": "Loop (2 pasos): piensa cada palabra dos veces. Más lento (al escribir, un 40 % menos de palabras por segundo; la lectura del prompt va a la mitad de velocidad), algo más cercano al modelo original. Desactivado por defecto. Necesita un archivo de 147 MB que el paso de descarga obtiene cuando Loop está activado. No tiene efecto mientras el esfuerzo esté desactivado.",
"q417": "Esfuerzo por defecto",
"q418": "Cuánto piensa Qwen4-35B-A3B cuando una solicitud no dice nada (lo hace el menú de razonamiento de un chat). Desactivado responde enseguida; Bajo, Alto y Muy alto piensan antes, cada vez más: más lento, mejor en preguntas difíciles.",
"q419": "Muy alto",
"q420": "Auto: el motor carga la capa de borrador MTP solo donde acelera las respuestas en este PC (lo comprueba al iniciar). Activado la fuerza, Desactivado nunca la carga. El archivo ocupa 0,4 GB.",
"q421": "Ultra",
"q422": "La versión GGUF de Unsloth, con soporte de la comunidad. La instalación la prepara para el motor, lo que tarda unos minutos."
"q422": "La versión GGUF de Unsloth, con soporte de la comunidad. La instalación la prepara para el motor, lo que tarda unos minutos.",
"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."
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "Auto : la couche brouillon n’est utilisée que là où elle accélère les réponses sur ce PC ; le moteur le vérifie au démarrage. Le fichier fait 0,4 Go.",
"q412": "La couche brouillon devine plusieurs mots à l’avance pour répondre plus vite. C’est un fichier de 0,4 Go.",
"q413": "Loop (2 étapes)",
"q414": "Loop (2 étapes) : réfléchit deux fois à chaque mot. Plus lent, un peu plus précis. Sans effet tant que l’effort est désactivé.",
"q415": "Loop (2 étapes) : réfléchit deux fois à chaque mot. Plus lent, un peu plus précis. Son fichier de 147 Mo est téléchargé une fois, puis le modèle se charge avec lui. Sans effet tant que l’effort est désactivé.",
"q416": "Loop (2 étapes) : réfléchit deux fois à chaque mot. Plus lent, un peu plus précis. Désactivé par défaut. Demande un fichier de 147 Mo que l’étape de téléchargement récupère quand Loop est activé. Sans effet tant que l’effort est désactivé.",
"q414": "Loop (2 étapes) : réfléchit deux fois à chaque mot. Plus lent (environ 40 % de mots en moins par seconde à l’écriture, lecture de l’invite environ deux fois plus lente), un peu plus proche du modèle d’origine. Sans effet tant que l’effort est désactivé.",
"q415": "Loop (2 étapes) : réfléchit deux fois à chaque mot. Plus lent (environ 40 % de mots en moins par seconde à l’écriture, lecture de l’invite environ deux fois plus lente), un peu plus proche du modèle d’origine. Son fichier de 147 Mo est téléchargé une fois, puis le modèle se charge avec lui. Sans effet tant que l’effort est désactivé.",
"q416": "Loop (2 étapes) : réfléchit deux fois à chaque mot. Plus lent (environ 40 % de mots en moins par seconde à l’écriture, lecture de l’invite environ deux fois plus lente), un peu plus proche du modèle d’origine. Désactivé par défaut. Demande un fichier de 147 Mo que l’étape de téléchargement récupère quand Loop est activé. Sans effet tant que l’effort est désactivé.",
"q417": "Effort par défaut",
"q418": "À quel point Qwen4-35B-A3B réfléchit quand une requête ne dit rien (le menu Raisonnement d’une conversation le fait). Désactivé répond tout de suite ; Faible, Élevé et Très élevé réfléchissent d’abord, de plus en plus longtemps : plus lent, meilleur sur les questions difficiles.",
"q419": "Très élevé",
"q420": "Auto : le moteur charge la couche brouillon MTP seulement là où elle accélère les réponses sur ce PC (il le vérifie au démarrage). Activé la force, Désactivé ne la charge jamais. Le fichier fait 0,4 Go.",
"q421": "Ultra",
"q422": "La version GGUF d’Unsloth, prise en charge par la communauté. L’installation la prépare pour le moteur, ce qui prend quelques minutes."
"q422": "La version GGUF d’Unsloth, prise en charge par la communauté. L’installation la prépare pour le moteur, ce qui prend quelques minutes.",
"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."
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "אוטומטי: שכבת הטיוטה משמשת רק במקום שבו היא מאיצה תשובות במחשב הזה; המנוע בודק זאת בהפעלה. הקובץ הוא 0.4 GB.",
"q412": "שכבת הטיוטה מנחשת כמה מילים קדימה כדי לענות מהר יותר. זה קובץ של 0.4 GB.",
"q413": "Loop (2 צעדים)",
"q414": "Loop (2 צעדים): חושב על כל מילה פעמיים. לאט יותר, מדויק קצת יותר. אין לזה השפעה כשהמאמץ כבוי.",
"q415": "Loop (2 צעדים): חושב על כל מילה פעמיים. לאט יותר, מדויק קצת יותר. הקובץ שלו (147 MB) יורד פעם אחת, ואז המודל נטען איתו. אין לזה השפעה כשהמאמץ כבוי.",
"q416": "Loop (2 צעדים): חושב על כל מילה פעמיים. לאט יותר, מדויק קצת יותר. כבוי כברירת מחדל. צריך קובץ של 147 MB ששלב ההורדה מביא כש-Loop מופעל. אין לזה השפעה כשהמאמץ כבוי.",
"q414": "Loop (2 צעדים): חושב על כל מילה פעמיים. לאט יותר (בכתיבה כ-40% פחות מילים בשנייה, וקריאת ההנחיה כמחצית מהמהירות), קרוב קצת יותר למודל המקורי. אין לזה השפעה כשהמאמץ כבוי.",
"q415": "Loop (2 צעדים): חושב על כל מילה פעמיים. לאט יותר (בכתיבה כ-40% פחות מילים בשנייה, וקריאת ההנחיה כמחצית מהמהירות), קרוב קצת יותר למודל המקורי. הקובץ שלו (147 MB) יורד פעם אחת, ואז המודל נטען איתו. אין לזה השפעה כשהמאמץ כבוי.",
"q416": "Loop (2 צעדים): חושב על כל מילה פעמיים. לאט יותר (בכתיבה כ-40% פחות מילים בשנייה, וקריאת ההנחיה כמחצית מהמהירות), קרוב קצת יותר למודל המקורי. כבוי כברירת מחדל. צריך קובץ של 147 MB ששלב ההורדה מביא כש-Loop מופעל. אין לזה השפעה כשהמאמץ כבוי.",
"q417": "מאמץ כברירת מחדל",
"q418": "כמה Qwen4-35B-A3B חושב כשבקשה לא אומרת דבר (תפריט ההנמקה של שיחה כן אומר). כבוי עונה מיד; נמוך, גבוה וגבוה מאוד חושבים קודם, כל פעם יותר: לאט יותר, טוב יותר בשאלות קשות.",
"q419": "גבוה מאוד",
"q420": "אוטומטי: המנוע טוען את שכבת הטיוטה MTP רק במקום שבו היא מאיצה תשובות במחשב הזה (הוא בודק בהפעלה). מופעל כופה אותה, כבוי לא טוען אותה לעולם. הקובץ הוא 0.4 GB.",
"q421": "Ultra",
"q422": "גרסת ה-GGUF של Unsloth, בתמיכת הקהילה. ההתקנה מכינה אותה למנוע, וזה לוקח כמה דקות."
"q422": "גרסת ה-GGUF של Unsloth, בתמיכת הקהילה. ההתקנה מכינה אותה למנוע, וזה לוקח כמה דקות.",
"q423": "Loop (2 צעדים) - בקרוב",
"q424": "בקרוב: ל-Loop (2 צעדים) דרושה תמיכה במנוע שעדיין אינה בגרסה הזו. בינתיים הוא נשאר כבוי."
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "自動:ドラフト層は、この PC で回答が速くなる場合にのみ使われます。エンジンが起動時に確認します。ファイルは 0.4 GB です。",
"q412": "ドラフト層は数語先を推測して、回答を速くします。ファイルは 0.4 GB です。",
"q413": "Loop(2 ステップ)",
"q414": "Loop(2 ステップ):各単語を 2 回考えます。遅くなりますが、少し正確になります。 思考の強さがオフの間は効果がありません。",
"q415": "Loop(2 ステップ):各単語を 2 回考えます。遅くなりますが、少し正確になります。147 MB のファイルは一度だけダウンロードされ、その後モデルはそれと一緒に読み込まれます。 思考の強さがオフの間は効果がありません。",
"q416": "Loop(2 ステップ):各単語を 2 回考えます。遅くなりますが、少し正確になります。既定ではオフです。Loop をオンにすると、ダウンロード手順が 147 MB のファイルを取得します。 思考の強さがオフの間は効果がありません。",
"q414": "Loop(2 ステップ):各単語を 2 回考えます。遅くなります(書き込み中の毎秒の語数が約 40% 減り、プロンプトの読み込みは約半分の速さ)が、元のモデルに少し近づきます。 思考の強さがオフの間は効果がありません。",
"q415": "Loop(2 ステップ):各単語を 2 回考えます。遅くなります(書き込み中の毎秒の語数が約 40% 減り、プロンプトの読み込みは約半分の速さ)が、元のモデルに少し近づきます。147 MB のファイルは一度だけダウンロードされ、その後モデルはそれと一緒に読み込まれます。 思考の強さがオフの間は効果がありません。",
"q416": "Loop(2 ステップ):各単語を 2 回考えます。遅くなります(書き込み中の毎秒の語数が約 40% 減り、プロンプトの読み込みは約半分の速さ)が、元のモデルに少し近づきます。既定ではオフです。Loop をオンにすると、ダウンロード手順が 147 MB のファイルを取得します。 思考の強さがオフの間は効果がありません。",
"q417": "既定の思考の強さ",
"q418": "リクエストが何も指定しないときに Qwen4-35B-A3B がどれだけ考えるか(チャットの推論メニューは指定します)。オフはすぐに答えます。低・高・最高は先に考え、段階ごとに長くなります。遅くなりますが、難しい質問に向いています。",
"q419": "最高",
"q420": "自動:エンジンは、この PC で回答が速くなる場合にのみ MTP ドラフト層を読み込みます(起動時に確認します)。オンは強制し、オフは読み込みません。ファイルは 0.4 GB です。",
"q421": "Ultra",
"q422": "Unsloth の GGUF ビルドで、コミュニティがサポートしています。セットアップがエンジン用に準備するため、数分かかります。"
"q422": "Unsloth の GGUF ビルドで、コミュニティがサポートしています。セットアップがエンジン用に準備するため、数分かかります。",
"q423": "Loop(2 ステップ)- 近日対応",
"q424": "近日対応:Loop(2 ステップ)にはエンジン側の対応が必要で、このリリースにはまだ含まれていません。当面はオフのままです。"
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "자동: 초안 레이어는 이 PC에서 응답이 빨라질 때만 사용됩니다. 엔진이 시작할 때 확인합니다. 파일 크기는 0.4 GB입니다.",
"q412": "초안 레이어는 몇 단어 앞을 미리 추측해 더 빠르게 응답합니다. 파일 크기는 0.4 GB입니다.",
"q413": "Loop (2단계)",
"q414": "Loop (2단계): 각 단어를 두 번 생각합니다. 더 느리지만 조금 더 정확합니다. 사고 강도가 꺼져 있으면 효과가 없습니다.",
"q415": "Loop (2단계): 각 단어를 두 번 생각합니다. 더 느리지만 조금 더 정확합니다. 147 MB 파일은 한 번만 내려받고, 그다음 모델이 그 파일과 함께 불러와집니다. 사고 강도가 꺼져 있으면 효과가 없습니다.",
"q416": "Loop (2단계): 각 단어를 두 번 생각합니다. 더 느리지만 조금 더 정확합니다. 기본값은 꺼짐입니다. Loop를 켜면 다운로드 단계에서 147 MB 파일을 받습니다. 사고 강도가 꺼져 있으면 효과가 없습니다.",
"q414": "Loop (2단계): 각 단어를 두 번 생각합니다. 더 느립니다(쓰는 동안 초당 단어 수가 약 40% 줄고 프롬프트 읽기는 약 절반 속도). 대신 원래 모델에 조금 더 가까워집니다. 사고 강도가 꺼져 있으면 효과가 없습니다.",
"q415": "Loop (2단계): 각 단어를 두 번 생각합니다. 더 느립니다(쓰는 동안 초당 단어 수가 약 40% 줄고 프롬프트 읽기는 약 절반 속도). 대신 원래 모델에 조금 더 가까워집니다. 147 MB 파일은 한 번만 내려받고, 그다음 모델이 그 파일과 함께 불러와집니다. 사고 강도가 꺼져 있으면 효과가 없습니다.",
"q416": "Loop (2단계): 각 단어를 두 번 생각합니다. 더 느립니다(쓰는 동안 초당 단어 수가 약 40% 줄고 프롬프트 읽기는 약 절반 속도). 대신 원래 모델에 조금 더 가까워집니다. 기본값은 꺼짐입니다. Loop를 켜면 다운로드 단계에서 147 MB 파일을 받습니다. 사고 강도가 꺼져 있으면 효과가 없습니다.",
"q417": "기본 사고 강도",
"q418": "요청이 아무것도 지정하지 않을 때 Qwen4-35B-A3B가 얼마나 깊이 생각하는지입니다(채팅의 추론 메뉴는 지정합니다). 끔은 바로 답하고, 낮음·높음·매우 높음은 먼저 생각하며 단계마다 더 오래 걸립니다. 더 느리지만 어려운 질문에 더 좋습니다.",
"q419": "매우 높음",
"q420": "자동: 엔진은 이 PC에서 응답이 빨라질 때만 MTP 초안 레이어를 불러옵니다(시작할 때 확인). 켬은 강제로 불러오고, 끔은 절대 불러오지 않습니다. 파일 크기는 0.4 GB입니다.",
"q421": "Ultra",
"q422": "Unsloth의 GGUF 빌드이며 커뮤니티에서 지원합니다. 설정이 엔진용으로 준비하며 몇 분이 걸립니다."
"q422": "Unsloth의 GGUF 빌드이며 커뮤니티에서 지원합니다. 설정이 엔진용으로 준비하며 몇 분이 걸립니다.",
"q423": "Loop(2단계) - 곧 제공",
"q424": "곧 제공: Loop(2단계)에는 엔진 지원이 필요하며 이번 릴리스에는 아직 없습니다. 당분간 꺼진 상태로 유지됩니다."
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "Auto: a camada de rascunho só é usada onde acelera as respostas neste PC; o motor verifica ao iniciar. O arquivo tem 0,4 GB.",
"q412": "A camada de rascunho adivinha várias palavras à frente para responder mais rápido. É um arquivo de 0,4 GB.",
"q413": "Loop (2 passos)",
"q414": "Loop (2 passos): pensa em cada palavra duas vezes. Mais lento, um pouco mais preciso. Não tem efeito enquanto o esforço estiver desligado.",
"q415": "Loop (2 passos): pensa em cada palavra duas vezes. Mais lento, um pouco mais preciso. O arquivo de 147 MB é baixado uma vez e depois o modelo carrega com ele. Não tem efeito enquanto o esforço estiver desligado.",
"q416": "Loop (2 passos): pensa em cada palavra duas vezes. Mais lento, um pouco mais preciso. Desligado por padrão. Precisa de um arquivo de 147 MB que a etapa de download busca quando o Loop está ligado. Não tem efeito enquanto o esforço estiver desligado.",
"q414": "Loop (2 passos): pensa em cada palavra duas vezes. Mais lento (cerca de 40 % menos palavras por segundo ao escrever, e a leitura do prompt é cerca de metade da velocidade), um pouco mais próximo do modelo original. Não tem efeito enquanto o esforço estiver desligado.",
"q415": "Loop (2 passos): pensa em cada palavra duas vezes. Mais lento (cerca de 40 % menos palavras por segundo ao escrever, e a leitura do prompt é cerca de metade da velocidade), um pouco mais próximo do modelo original. O arquivo de 147 MB é baixado uma vez e depois o modelo carrega com ele. Não tem efeito enquanto o esforço estiver desligado.",
"q416": "Loop (2 passos): pensa em cada palavra duas vezes. Mais lento (cerca de 40 % menos palavras por segundo ao escrever, e a leitura do prompt é cerca de metade da velocidade), um pouco mais próximo do modelo original. Desligado por padrão. Precisa de um arquivo de 147 MB que a etapa de download busca quando o Loop está ligado. Não tem efeito enquanto o esforço estiver desligado.",
"q417": "Esforço padrão",
"q418": "Quanto o Qwen4-35B-A3B pensa quando uma solicitação não diz nada (o menu de raciocínio de uma conversa diz). Desligado responde logo; Baixo, Alto e Muito alto pensam antes, cada vez mais: mais lento, melhor em perguntas difíceis.",
"q419": "Muito alto",
"q420": "Auto: o motor carrega a camada de rascunho MTP só onde ela acelera as respostas neste PC (ele verifica ao iniciar). Ligado a força, Desligado nunca a carrega. O arquivo tem 0,4 GB.",
"q421": "Ultra",
"q422": "A versão GGUF da Unsloth, com suporte da comunidade. A configuração a prepara para o motor, o que leva alguns minutos."
"q422": "A versão GGUF da Unsloth, com suporte da comunidade. A configuração a prepara para o motor, o que leva alguns minutos.",
"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."
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "Авто: черновой слой используется только там, где он ускоряет ответы на этом ПК; движок проверяет это при запуске. Файл занимает 0,4 ГБ.",
"q412": "Черновой слой угадывает несколько слов вперёд, чтобы отвечать быстрее. Это файл на 0,4 ГБ.",
"q413": "Loop (2 шага)",
"q414": "Loop (2 шага): обдумывает каждое слово дважды. Медленнее, чуть точнее. Не действует, пока усилие выключено.",
"q415": "Loop (2 шага): обдумывает каждое слово дважды. Медленнее, чуть точнее. Его файл (147 МБ) скачивается один раз, затем модель загружается вместе с ним. Не действует, пока усилие выключено.",
"q416": "Loop (2 шага): обдумывает каждое слово дважды. Медленнее, чуть точнее. По умолчанию выключен. Нужен файл на 147 МБ, который шаг загрузки скачивает, когда Loop включён. Не действует, пока усилие выключено.",
"q414": "Loop (2 шага): обдумывает каждое слово дважды. Медленнее (примерно на 40 % меньше слов в секунду при написании, чтение запроса примерно вдвое медленнее), чуть ближе к исходной модели. Не действует, пока усилие выключено.",
"q415": "Loop (2 шага): обдумывает каждое слово дважды. Медленнее (примерно на 40 % меньше слов в секунду при написании, чтение запроса примерно вдвое медленнее), чуть ближе к исходной модели. Его файл (147 МБ) скачивается один раз, затем модель загружается вместе с ним. Не действует, пока усилие выключено.",
"q416": "Loop (2 шага): обдумывает каждое слово дважды. Медленнее (примерно на 40 % меньше слов в секунду при написании, чтение запроса примерно вдвое медленнее), чуть ближе к исходной модели. По умолчанию выключен. Нужен файл на 147 МБ, который шаг загрузки скачивает, когда Loop включён. Не действует, пока усилие выключено.",
"q417": "Усилие по умолчанию",
"q418": "Насколько долго Qwen4-35B-A3B думает, если запрос ничего не говорит (так делает меню рассуждений в чате). Выкл. отвечает сразу; Низкое, Высокое и Очень высокое сначала думают, каждый раз дольше: медленнее, лучше на сложных вопросах.",
"q419": "Очень высокое",
"q420": "Авто: движок загружает черновой слой MTP только там, где он ускоряет ответы на этом ПК (проверяет при запуске). Вкл. включает его всегда, Выкл. никогда не загружает. Файл занимает 0,4 ГБ.",
"q421": "Ultra",
"q422": "Версия GGUF от Unsloth, поддерживается сообществом. Установка подготавливает её для движка, это занимает несколько минут."
"q422": "Версия GGUF от Unsloth, поддерживается сообществом. Установка подготавливает её для движка, это занимает несколько минут.",
"q423": "Loop (2 шага) - скоро",
"q424": "Скоро: для Loop (2 шага) нужна поддержка в движке, которой пока нет в этой версии. Пока он остаётся выключенным."
}
+6 -4
View File
@@ -114,13 +114,15 @@
"q411": "自动:只有在这台电脑上能加快回答时才使用草稿层;引擎会在启动时检查。文件大小为 0.4 GB。",
"q412": "草稿层会提前猜出几个词,让回答更快。文件大小为 0.4 GB。",
"q413": "Loop(2 步)",
"q414": "Loop(2 步):每个词想两遍。更慢,略微更准确。 在思考强度为关闭时不起作用。",
"q415": "Loop(2 步):每个词想两遍。更慢,略微更准确。它的 147 MB 文件只下载一次,之后模型会带着它加载。 在思考强度为关闭时不起作用。",
"q416": "Loop(2 步):每个词想两遍。更慢,略微更准确。默认关闭。需要一个 147 MB 的文件,开启 Loop 时由下载步骤获取。 在思考强度为关闭时不起作用。",
"q414": "Loop(2 步):每个词想两遍。更慢(写作时每秒词数约少 40%,读取提示约慢一半),略微更接近原始模型。 在思考强度为关闭时不起作用。",
"q415": "Loop(2 步):每个词想两遍。更慢(写作时每秒词数约少 40%,读取提示约慢一半),略微更接近原始模型。它的 147 MB 文件只下载一次,之后模型会带着它加载。 在思考强度为关闭时不起作用。",
"q416": "Loop(2 步):每个词想两遍。更慢(写作时每秒词数约少 40%,读取提示约慢一半),略微更接近原始模型。默认关闭。需要一个 147 MB 的文件,开启 Loop 时由下载步骤获取。 在思考强度为关闭时不起作用。",
"q417": "默认思考强度",
"q418": "当请求没有指定时,Qwen4-35B-A3B 思考的程度(聊天的推理菜单会指定)。关闭会立即回答;低、高和超高会先思考,一级比一级久:更慢,更适合难题。",
"q419": "超高",
"q420": "自动:只有在这台电脑上能加快回答时,引擎才加载 MTP 草稿层(启动时检查)。开启则强制加载,关闭则从不加载。文件大小为 0.4 GB。",
"q421": "Ultra",
"q422": "Unsloth 的 GGUF 版本,由社区支持。安装程序会为引擎准备它,需要几分钟。"
"q422": "Unsloth 的 GGUF 版本,由社区支持。安装程序会为引擎准备它,需要几分钟。",
"q423": "Loop(2 步)- 即将推出",
"q424": "即将推出:Loop(2 步)需要引擎支持,当前版本尚未包含。暂时保持关闭。"
}
+65 -14
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, qwen4ModelArg, QWEN4_GGUF_BUILD, QWEN4_GGUF_TITLE, QWEN4_ALL_BUILDS, isQwen4GgufBuild,
withoutQwen4Loop, qwen4WithLoop, qwen4LoopCoda, QWEN4_LOOP_ENGINE_READY, 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';
@@ -79,6 +79,9 @@ test('the Python side and the screens agree: builds, fit table, effort levels, L
assert.equal(/LOOP_STEPS = (\d+)/.exec(family)[1], String(QWEN4_LOOP_STEPS));
assert.equal(/ENGINE_FILE_FLAGS = \{[^}]*"loop": "([^"]+)"/.exec(family)[1], QWEN4_LOOP_FLAGS.file);
assert.equal(/ENGINE_LOOP_STEPS_FLAG = "([^"]+)"/.exec(family)[1], QWEN4_LOOP_FLAGS.steps);
assert.equal(/ENGINE_LOOP_CODA_FLAG = "([^"]+)"/.exec(family)[1], QWEN4_LOOP_FLAGS.coda);
assert.equal(/ENGINE_LOOP_DIRECT_FLAG = "([^"]+)"/.exec(family)[1], QWEN4_LOOP_FLAGS.direct);
assert.deepEqual(Object.values(QWEN4_LOOP_FLAGS), ['--loop-adapter', '--loop-passes', '--loop-coda', '--loop-direct-t1']);
assert.equal(/MTP_CONFIG_KEY = "(\w+)"/.exec(family)[1], 'qwen4_mtp');
assert.equal(/MTP_MODE_KEY = "(\w+)"/.exec(family)[1], 'qwen4_mtp_mode');
assert.equal(/GGUF_BUILD = "([\w-]+)"/.exec(family)[1], QWEN4_GGUF_BUILD, 'the fourth build');
@@ -224,20 +227,25 @@ test('the Draft layer choice (MTP): off is the switch false, on forces the sidec
test('Loop (2 steps) is off by default and is the key plus the two flags, or neither', () => {
assert.equal(qwen4LoopChoice(q4Cfg), 'off');
assert.equal(qwen4LoopChoice({}), 'off');
const on = qwen4WithLoop(q4Cfg, 'on', '/m/Qwen4-35B-A3B-Loop.safetensors');
const on = qwen4WithLoop(q4Cfg, 'on', '/m/Qwen4-35B-A3B-Loop.safetensors', true); // the engine supports Loop: the switch's on behaviour
assert.equal(on[QWEN4_LOOP_KEY], '/m/Qwen4-35B-A3B-Loop.safetensors');
assert.equal(qwen4LoopChoice(on), 'on');
assert.deepEqual(on.args.slice(-4), ['--loop', '/m/Qwen4-35B-A3B-Loop.safetensors', '--loop-steps', '2'], 'the flag names are the one table');
assert.deepEqual(on.user_args, ['--loop', '/m/Qwen4-35B-A3B-Loop.safetensors', '--loop-steps', '2'], 'a later setup run keeps it');
assert.deepEqual(qwen4LoopArgs(['--ctx', '1'], '/x'), ['--ctx', '1', '--loop', '/x', '--loop-steps', '2']);
assert.deepEqual(qwen4LoopArgs(['--ctx', '1', '--loop', '/old', '--loop-steps', '4'], '/x'), ['--ctx', '1', '--loop', '/x', '--loop-steps', '2'], 'never twice');
assert.deepEqual(on.args.slice(-6), ['--loop-adapter', '/m/Qwen4-35B-A3B-Loop.safetensors', '--loop-passes', '2', '--loop-coda', 'compact'], 'Q4-LOOP\'s flags, the Compact build: the compact coda');
assert.ok(on.args.includes('--loop-direct-t1'), 'the server\'s direct flag is there with Loop on');
assert.equal(on.args.filter(a => a === '--loop-direct-t1').length, 1);
assert.deepEqual(on.user_args, ['--loop-adapter', '/m/Qwen4-35B-A3B-Loop.safetensors', '--loop-passes', '2', '--loop-coda', 'compact'], 'a later setup run keeps it (the bare flag is only in args)');
assert.deepEqual(qwen4LoopArgs(['--ctx', '1'], '/x', '/m/Qwen4-35B-A3B-Compact.strata'), ['--ctx', '1', '--loop-adapter', '/x', '--loop-passes', '2', '--loop-coda', 'compact', '--loop-direct-t1']);
assert.deepEqual(qwen4LoopArgs(['--ctx', '1', '--loop-adapter', '/old', '--loop-passes', '4', '--loop-coda', 'compact', '--loop-direct-t1'], '/x', '/m/Qwen4-35B-A3B-Ultra.strata'), ['--ctx', '1', '--loop-adapter', '/x', '--loop-passes', '2', '--loop-coda', 'universal', '--loop-direct-t1'], 'never twice; universal for every build but Compact');
for (const m of ['/m/Qwen4-35B-A3B-Balanced.strata', '/m/Qwen4-35B-A3B-Ultra.strata', '/m/trunk40.gguf', null]) assert.equal(qwen4LoopCoda(m), 'universal', String(m));
assert.equal(qwen4LoopCoda('C:\\m\\Qwen4-35B-A3B-Compact.strata'), 'compact');
assert.deepEqual(qwen4LoopArgs(['--ctx', '1'], null), ['--ctx', '1'], 'off passes nothing');
const off = qwen4WithLoop(on, 'off', null);
assert.equal(QWEN4_LOOP_KEY in off, false);
assert.equal('user_args' in off, false);
assert.deepEqual(off.args, q4Cfg.args, 'off is the start as it was');
assert.deepEqual(withoutQwen4Loop(on.args), q4Cfg.args);
assert.deepEqual(qwen4WithLoop(q4Cfg, 'off', null).args, q4Cfg.args, 'off on a config that never had it changes nothing');
assert.equal(qwen4WithLoop(q4Cfg, 'on', null)[QWEN4_LOOP_KEY], undefined, 'on without a file is not written');
assert.equal(qwen4WithLoop(q4Cfg, 'on', null, true)[QWEN4_LOOP_KEY], undefined, 'on without a file is not written');
assert.equal(qwen4ModelArg(q4Cfg), '/m/Qwen4-35B-A3B-Compact.strata');
assert.equal(qwen4ModelArg({ args: ['--model', 'm.strata'] }), 'm.strata');
assert.equal(QWEN4_LOOP_FILE, 'Qwen4-35B-A3B-Loop.safetensors');
@@ -248,7 +256,7 @@ test('Loop (2 steps) is off by default and is the key plus the two flags, or nei
const control = src('server/native-control.mjs');
assert.match(control, /if\(isQwen4Family\(args\.family\)&&args\.loop==='on'&&!custom\)allowed\.push\('loop'\)/);
assert.match(control, /QWEN4_LOOP_MISSING/);
assert.match(src('src/components/NativeModels.tsx'), /\.\.\.\(q4Own && q4Loop === 'on' \? \{ loop: 'on' \} : \{\}\)/);
assert.match(src('src/components/NativeModels.tsx'), /\.\.\.\(q4Own && QWEN4_LOOP_ENGINE_READY && q4Loop === 'on' \? \{ loop: 'on' \} : \{\}\)/);
});
test('Loop and the Qwen4 rows are hidden for every other family and for a custom build', async () => {
@@ -273,7 +281,7 @@ test('Loop and the Qwen4 rows are hidden for every other family and for a custom
assert.match(models, /loopOffered && q4\.engine_exists !== false/);
const natives = src('server/native-settings.mjs');
assert.match(natives, /id:'effort',label:'Effort by default',group:'Responses',type:'enum',choices:\['off','low','high','xhigh'\]/);
assert.match(natives, /id:'q4_loop',label:'Loop \(2 steps\)',group:'Serving',type:'enum',choices:\['off','on'\]/);
assert.match(natives, /id:'q4_loop',label:'Loop \(2 steps\) - coming soon',group:'Serving',type:'enum',choices:\['off','on'\]/);
assert.match(natives, /APP_OWNED_FIELDS=\[[^\]]*'q4_mtp','q4_loop'\]/);
assert.ok(!/tok\/s/.test(models.slice(models.indexOf('function Qwen4Plan'), models.indexOf('function LingPlan'))), 'the app prints no speed figure');
});
@@ -290,13 +298,13 @@ test('the strings of the Qwen4 panel are in all ten languages with the same plac
const dir = join(root, 'src', 'locales');
const langs = ['en', 'de', 'fr', 'es', 'ru', 'pt', 'zh', 'ja', 'ko', 'he'];
const catalogs = Object.fromEntries(langs.map(l => [l, JSON.parse(readFileSync(join(dir, `gtui-${l}.json`), 'utf8'))]));
const keys = Array.from({ length: 22 }, (_, i) => `q4${String(i + 1).padStart(2, '0')}`);
const keys = Array.from({ length: 24 }, (_, i) => `q4${String(i + 1).padStart(2, '0')}`);
for (const l of langs) for (const k of keys) assert.ok(typeof catalogs[l][k] === 'string' && catalogs[l][k].length > 0, `${l} ${k}`);
const slots = s => (s.match(/\{\d+\}/g) ?? []).sort().join();
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')) { // q421 is the build's own name, Ultra, shown through the catalog label
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
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`);
}
@@ -329,8 +337,9 @@ test('the fourth build, Unsloth UD-Q4_K_XL, sits after the three, is never the r
assert.equal(qwen4VisionShard(gguf), '/m/mmproj-BF16.gguf', 'its picture reader is the mmproj, not Vision.strata');
assert.deepEqual(withoutQwen4Vision(gguf.args), ['--native', '/m/trunk40.gguf', '--native-dense-gguf', '/m/trunk40.gguf', '--ple-gguf', '/m/shard2.gguf', '--mtp', '/m/mtp-rt', '--spec', '4']);
assert.equal(qwen4ModelArg(gguf), '/m/trunk40.gguf');
const on = qwen4WithLoop(gguf, 'on', '/m/Qwen4-35B-A3B-Loop.safetensors');
assert.deepEqual(on.args.slice(-4), ['--loop', '/m/Qwen4-35B-A3B-Loop.safetensors', '--loop-steps', '2'], 'Loop works like the other builds');
const on = qwen4WithLoop(gguf, 'on', '/m/Qwen4-35B-A3B-Loop.safetensors', true);
assert.deepEqual(on.args.slice(-6), ['--loop-adapter', '/m/Qwen4-35B-A3B-Loop.safetensors', '--loop-passes', '2', '--loop-coda', 'universal'], 'Loop works like the other builds: universal for the GGUF build');
assert.ok(on.args.includes('--loop-direct-t1'));
assert.deepEqual(qwen4WithLoop(on, 'off', null).args, gguf.args);
assert.equal(qwen4EffortChoice({ ...gguf, effort: 'low' }), 'low', 'Effort works like the other builds');
assert.equal(qwen4MtpChoice(gguf), 'auto');
@@ -351,5 +360,47 @@ test('the fourth build, Unsloth UD-Q4_K_XL, sits after the three, is never the r
}
const en = JSON.parse(readFileSync(join(dir, 'gtui-en.json'), 'utf8'));
for (const k of ['q414', 'q415', 'q416']) assert.ok(en[k].endsWith('It has no effect while Effort is Off.'), k);
assert.match(src('server/native-settings.mjs'), /when Loop is on\. It has no effect while Effort is Off\.'/, 'the settings hint says it too');
assert.match(src('server/native-settings.mjs'), /Coming soon: Loop \(2 steps\) needs engine support that is not in this release yet\. It stays off for now\.'/, 'the settings hint says it is coming');
for (const l of ['en', 'de', 'fr', 'es', 'ru', 'pt', 'zh', 'ja', 'ko', 'he']) { // the coming-soon label and sentence, in every language
const c = JSON.parse(readFileSync(join(dir, `gtui-${l}.json`), 'utf8'));
assert.ok(typeof c.q423 === 'string' && c.q423.length > 8 && c.q423 !== c.q413, `${l} q423`);
assert.ok(typeof c.q424 === 'string' && c.q424.length > 30, `${l} q424`);
}
assert.equal(en.q423, 'Loop (2 steps) - coming soon');
for (const l of ['en', 'de', 'fr', 'es', 'ru', 'pt', 'zh', 'ja', 'ko', 'he']) { // the real cost, in every language: about 40% fewer words per second, prompt reading about half as fast
const c = JSON.parse(readFileSync(join(dir, `gtui-${l}.json`), 'utf8'));
for (const k of ['q414', 'q415', 'q416']) assert.ok(/40/.test(c[k]), `${l} ${k} names the 40% cost`);
}
for (const k of ['q414', 'q415', 'q416']) assert.match(en[k], /Slower \(about 40% fewer words per second while writing, prompt reading about half as fast\), a little closer to the original model\./, k);
assert.ok(!/a bit more accurate/.test(JSON.stringify(en)), 'the old claim is gone');
});
test('Loop (2 steps) is "coming": one switch, the Python, the server and the screens agree, and on writes nothing', async () => {
const family = py('qwen4_family.py');
assert.match(family, /^LOOP_ENGINE_READY = False$/m, 'qwen4_family.LOOP_ENGINE_READY');
assert.equal(QWEN4_LOOP_ENGINE_READY, false, 'server/qwen4.mjs mirrors it');
const qwen4Screen = await bundle('./src/lib/qwen4');
const screen = qwen4Screen.QWEN4_LOOP_ENGINE_READY;
assert.equal(screen, QWEN4_LOOP_ENGINE_READY, 'src/lib/qwen4.ts mirrors it');
assert.equal(QWEN4_LOOP_COMING_LABEL, /LOOP_COMING_LABEL = "([^"]+)"/.exec(family)[1]);
// while it is false: on is written as off (no key, no flags), off changes nothing
const path = '/m/Qwen4-35B-A3B-Loop.safetensors';
const coming = qwen4WithLoop(q4Cfg, 'on', path);
assert.equal(coming[QWEN4_LOOP_KEY], undefined);
assert.deepEqual(coming.args, q4Cfg.args);
assert.equal(qwen4LoopChoice(coming), 'off');
// a key an earlier version saved is taken out when the choice is written as off
const saved = qwen4WithLoop(q4Cfg, 'on', path, true);
assert.equal(qwen4LoopChoice(saved), 'on');
const stripped = qwen4WithLoop(saved, 'off', null);
assert.equal(stripped[QWEN4_LOOP_KEY], undefined);
assert.deepEqual(stripped.args, q4Cfg.args);
// the screens: disabled select with the coming label, nothing sent to Download or Load while it is false
const models = src('src/components/NativeModels.tsx');
assert.match(models, /disabled=\{disabled \|\| !QWEN4_LOOP_ENGINE_READY\}/);
assert.match(models, /tr\(QWEN4_LOOP_ENGINE_READY \? "Loop \(2 steps\)" : "Loop \(2 steps\) - coming soon"\)/);
assert.match(models, /q4Own && QWEN4_LOOP_ENGINE_READY && q4Loop !== \(installed\?\.q4Loop \?\? 'off'\)/);
assert.match(src('src/components/NativeSettings.tsx'), /disabled=\{field\.supported === false \|\| !QWEN4_LOOP_ENGINE_READY\}/);
assert.match(src('server/native-control.mjs'), /QWEN4_LOOP_ENGINE_READY\?args\.values\?\.q4_loop:/);
assert.equal(qwen4Screen.nativeFieldShown('q4_loop', { isLing: false, isQwen4: true, ownQuant4: true }), true, 'visible, not hidden');
});
+117
View File
@@ -0,0 +1,117 @@
# Looped Qwen3.8-Flash-Next Adapter (`--loop-adapter`)
Opt-in support for running **Looped `Qwen3.8-Flash-Next` (125B-A6B MoE + 51.2B PLE N-gram, `qwen4_exp`)** adapters directly inside Strata's RAM-offloaded CUDA engine.
When `--loop-adapter` is omitted, Strata runs the stock 48-layer forward path.
## CLI Options
- `--loop-adapter FILE`: path to the Looped adapter `.safetensors` checkpoint (reads optional sibling `.json` metadata for `core_start`, `core_end`, `coda_lora_layers`, `lora_alpha`, `t_max`, `mode`).
- `--loop-passes N`: number of recurrent passes `T` over the core layers `[core_start, core_end)` (default `2` when `--loop-adapter` is set; supports `2..8`).
- `--loop-cd-omega F`: optional ratio-preserving LoopCD-Hidden weight applied after the final recurrent pass (default `0.0`).
- `--loop-cd-thinking`: opt-in `<think>...</think>` gating for LoopCD-Hidden (`default_thinking=false, include_end_token=false` semantics). When omitted, `--loop-cd-omega` applies unconditionally to every token (legacy behavior). When enabled, LoopCD-Hidden is applied starting on `<think>` through the token before `</think>`, and leaves `</think>` and all non-thinking tokens bit-identical to `omega = 0.0`.
- `--loop-cd-think-ids START END`: token IDs for `<think>` and `</think>` used by `--loop-cd-thinking` (default `248068 248069` for `Qwen3.8-Flash-Next`; `serve/server.py` also auto-resolves them from the loaded tokenizer when not explicitly set).
## Per-Request Serving Controls (`--serve` / `serve/server.py`)
When serving mixed traffic with `--loop-adapter FILE --loop-passes N` (`N >= 2`), clients can control looped depth and LoopCD-Hidden per request on `/v1/chat/completions`, `/v1/responses`, and `/v1/messages` (as top-level JSON fields, or via `extra_body` in OpenAI/Anthropic SDKs):
- `"loop_passes"`: `1` (exact stock 48-layer single-pass bypass: zero extra core passes, zero workspace/mixer/LoRA/LoopCD hooks) or `N` (the engine's loaded `--loop-passes`). Invalid values return HTTP `400`.
- Why `{1, N}`: pass gates and LoRAs pre-fold `rem_idx = N - 1 - p` at adapter load time so weights are never duplicated in VRAM; `1` bypasses the adapter completely and `N` runs the loaded recurrent depth.
- **Lazy `T=1` CUDA graph bank:** the engine captures the `T=1` bypass decode/commit CUDA graphs lazily on the first `loop_passes=1` request (`0 MiB` extra startup VRAM when unused; `+66 MiB` measured on RTX 3090 across all 6 verify window widths when first used). Works on single-GPU, non-cyclic multi-GPU, and cyclic multi-GPU `--layer-split`.
- `"loop_cd_omega"`: finite float overriding `--loop-cd-omega` for that request (`0.0` disables LoopCD-Hidden; ignored when `loop_passes=1`).
- `"loop_cd_thinking"`: boolean overriding `--loop-cd-thinking` for that request. Because `Verifier` reads a per-token device omega vector staged from pinned host memory before each graph launch, switching `loop_cd_omega`, `loop_cd_thinking`, or entering/exiting `<think>` spans requires **zero extra CUDA graph captures**.
- **Automatic direct-mode bypass (`--loop-direct-t1` / `"loop_direct_t1": true`):** optional server flag/config key on `serve/server.py`. When enabled on a server started with `--loop-passes N >= 2`, requests with thinking disabled (`chat_template_kwargs: {"enable_thinking": false}`, `reasoning_effort: "none"`, Responses `reasoning: {"effort": "none"}`, or Anthropic `thinking: {"type": "disabled"}`) automatically run at stock `loop_passes=1` unless the request explicitly sends `"loop_passes"`.
- **Conversation cache / KV isolation:** RAM conversation snapshots, retained KV reuse, SSD spill entries, and `SAVE`/`LOAD` session files are tagged with a `loop_key` encoding `(active_passes, cd_omega, cd_thinking, think_ids)`. A prefix evaluated at `T=1` is never reused for a `T=2` request (or across incompatible LoopCD settings), and vice versa.
Example (`/v1/chat/completions`):
```bash
# Fast stock T=1 direct answer on a server running --loop-adapter ... --loop-passes 2
curl http://127.0.0.1:8095/v1/chat/completions -H 'Content-Type: application/json' -d '{
"model": "qwen3.8-flash-next",
"messages": [{"role": "user", "content": "What is 2+2?"}],
"chat_template_kwargs": {"enable_thinking": false},
"loop_passes": 1
}'
# Looped T=2 reasoning with <think>-only LoopCD-Hidden
curl http://127.0.0.1:8095/v1/chat/completions -H 'Content-Type: application/json' -d '{
"model": "qwen3.8-flash-next",
"messages": [{"role": "user", "content": "Prove sqrt(2) is irrational."}],
"loop_passes": 2,
"loop_cd_omega": 0.5,
"loop_cd_thinking": true
}'
```
The underlying engine stdin protocol exposes the same optional `GEN` keys (`loop_passes=N`, `loop_cd_omega=F`, `loop_cd_thinking=0|1`) and reports `loop_passes=N loop_cd_omega=F loop_cd_thinking=0|1` on the startup `INFO` line when `--loop-adapter` is loaded.
## Architecture & Memory
- **Zero weight duplication:** extra core passes (`p = 1 .. T-1` over layers `16..31`) reuse the exact same quantized dense weights, VRAM expert cache, and RAM-offloaded MoE experts as pass `0`.
- **Per-pass isolated state:** `SessionState` allocates distinct GDN recurrent/conv states (`+(T-1) * 12`) and QSA KV/indexer states (`+(T-1) * 4`) for extra core passes so recurrent refinement never aliases pass `0` memory.
- **Bit-exact FP32 recurrence & LoRA math:**
- `HCWorkspaceEntry`: 4-stream grouped RMSNorm (`eps = 1e-6`), per-stream RMS-matched anchor interpolation, and pre-folded `(p_idx, rem_idx)` low-rank entry gate.
- `HCCrossPassMixer`: per-step 4-stream grouped RMSNorm + low-rank cross-pass delta with pre-folded `gamma` and `delta_kappa`.
- Pre-folded per-pass LoRAs on all core projections (GDN `qkv/z/a/b/out`, QSA `q/k/v/o`, MoE router `gate`, shared expert `gate/up/down`) plus coda LoRAs on layers `32..39`.
- Adapter VRAM footprint: `~268 MiB` FP32 for `T = 2`.
- **Both paths covered:** chunked prompt prefill (`Prefill`, cuBLAS-accelerated LoRA/Mixer/WorkspaceEntry GEMMs) and CUDA-graph decode (`Verifier`).
- **Cyclic multi-GPU splits:** with `--layer-split`, a cut may land anywhere, including inside the recurrent core `(core_start, core_end)`. The core's extra passes then hop between GPUs: each decode window and each prompt chunk visits the stages in turn, and only the stages that own core layers are visited again on each extra pass. The rows (plus the `m_prev` checkpoint the next pass needs) cross over pinned host memory. Every pass keeps its own isolated GDN/QSA state, so a GPU never reads another pass's memory. `--layer-split auto` knows the core layers cost `T` times a plain layer and places the cut to balance that, e.g. `K=25` on two equal RTX 3090s with `T=2`.
- **Full Strata stack compatibility:** works seamlessly with Strata's 8-channel resident RAM expert arena, `--ple-io ram|direct`, `--expert-cache auto`, `--kv int8`, `DFlash2` speculative drafting (`--draft dflash2 --spec 4`), and multi-GPU `--layer-split` (manual cuts and `auto`, with cuts inside or outside the core; measured on 2 GPUs).
## Example (Single GPU + RAM Expert Arena + DFlash2)
```bash
STRATA_HC_Q8=1 STRATA_ROUTE_TAIL_SKIP=0 STRATA_NO_LARGEPAGES=1 \
./strata \
--pack /path/to/packs/ud-iq4_xs \
--native /path/to/Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00004.gguf \
--ple-gguf /path/to/Qwen3.8-Flash-Next-UD-IQ4_XS-00004-of-00004.gguf \
--expert-profile terminal/data/expert-profile.bin \
--expert-cache auto \
--prefill auto \
--max-context 32768 \
--kv int8 \
--mtp /path/to/mtp/rt \
--draft dflash2 \
--draft-model /path/to/qwen3.8-flash-next-dflash2.q4_0-selq4.pack \
--mtp-draft-vocab /path/to/draft_vocab.bin \
--spec 4 \
--draft-conf 0.5 \
--gpu 0 \
--loop-adapter /path/to/ckpt_final.safetensors \
--loop-passes 2 \
--tokens-file prompt_tokens.txt \
--max-new 512
```
## Multi-GPU (cyclic layer split)
For multi-GPU OpenAI-compatible serving (`--serve` / `serve.server`), list the GPUs and let the split balance the recurrent core:
```bash
--gpu 0,2 --layer-split auto
```
Any free GPUs can be listed (`--gpu 0,1`, `--gpu 0,2`, ...). With `--loop-adapter` active, `auto` weighs the core layers `[core_start, core_end)` by `T` and cuts where the per-decode-window time balances. On two equal cards that is near the middle of the core: `K=25` on two RTX 3090s with `T=2`. A manual `--layer-split K` is accepted too, including values inside the core. The itinerary is built for 3 and 4 GPUs as well, but only 2 GPUs have been measured. When free VRAM is short, `auto` first shares the layers by free memory and skips this search.
With `--loop-adapter`, `--batch` stops at start and `--pipeline-windows` is turned off, wherever the cut is. A cut inside the core also cannot be used with `--split-device 0` (stops at start with a message) or `STRATA_SPLIT_OVERLAP` (turned off).
Measured on 2× RTX 3090 (GPU 0 and 2), IQ4_XS + RAM expert arena + DFlash2, `--loop-passes 2`, a 17.3K-token prompt, 512 new tokens:
| Setup | Prompt (tok/s) | Decode (tok/s) |
|---|---|---|
| One GPU | 2125-2155 | 79-80 |
| `--layer-split 32` (core on one card, previous build) | 1936-1941 | 87-92 |
| `--layer-split 24` (cyclic) | 2089-2125 | 98-101 |
| `--layer-split auto` (picked `K=25`, cyclic) | 2128-2149 | 98-100 |
Decode gains about a quarter over one card. Prompt reading is at one card's speed: an earlier stage can start chunk c+1 while the last stage finishes chunk c, but the core's repeated visits on each GPU still make the stages mostly take turns.
On RAM-offloaded MoE, one large chunk per visit beats smaller chunks with more overlap: each visit streams its layers' missing experts once per chunk, and that streaming sets most of a chunk's cost. A deeper overlap of the two cards' visits was tried and kept the output byte for byte, but it read the 17.3K-token prompt at 1843-2069 tok/s against 2077-2149 tok/s for the default (2× RTX 3090, GPU 2 and 3, `--layer-split 24`, `T=2`, other jobs on the host), and 4352-token chunks fell to about 1500-1640 tok/s (GPU 0 and 2), so neither ships. Decode stays at 98-101 tok/s (the table above).
## Credits
- Recurrent core architecture inspired by [`jasontitus/loopedqwen`](https://github.com/jasontitus/loopedqwen) (MIT).
- Looped Qwen3.8-Flash-Next checkpoint and initial CUDA engine integration by [`alesha-pro`](https://github.com/alesha-pro/Strata) ([`alesha-pro/Looped-Qwen3.8-Flash-Next`](https://huggingface.co/alesha-pro/Looped-Qwen3.8-Flash-Next)).
+15 -10
View File
@@ -30,13 +30,13 @@ Off unless you set them. The last column says where each one is described.
| `STRATA_ATTN_RS` | number | Intel Arc | [INTEL.md](INTEL.md) |
| `STRATA_AUX_CPUS` | text | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
| `STRATA_AUX_STAGER` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md), [README.md](bench-results/2026-10-08-community-2x-rtx3080-20gb-ud-q4-k-xl-512k-pool/README.md) |
| `STRATA_BATCH_DECODE_SHARE` | number | NVIDIA and AMD, Intel Arc | [BATCHING.md](BATCHING.md) |
| `STRATA_BATCH_DECODE_SHARE` | number | NVIDIA and AMD, Intel Arc | [BATCHING.md](BATCHING.md), [QWEN4_35B.md](QWEN4_35B.md) |
| `STRATA_BATCH_MTP` | on / off | NVIDIA and AMD, Intel Arc | [BATCHING.md](BATCHING.md) |
| `STRATA_BATCH_MTP_ATTN_SLOTS` | number | NVIDIA and AMD | - |
| `STRATA_BATCH_MTP_FUSED` | on / off | NVIDIA and AMD | - |
| `STRATA_BATCH_QSA_STREAM_OPT` | on / off | NVIDIA and AMD | - |
| `STRATA_BATCH_SIDE_MIXER` | on / off | NVIDIA and AMD | - |
| `STRATA_BATCH_YIELD_CHUNKS` | number | NVIDIA and AMD | [BATCHING.md](BATCHING.md) |
| `STRATA_BATCH_YIELD_CHUNKS` | number | NVIDIA and AMD | [BATCHING.md](BATCHING.md), [QWEN4_35B.md](QWEN4_35B.md) |
| `STRATA_CACHE_DIR` | on / off | Intel Arc | [INTEL_INT8_EXPERTS.md](INTEL_INT8_EXPERTS.md) |
| `STRATA_CACHE_MESSAGE_BOUNDARY` | number | NVIDIA and AMD, Intel Arc | [MESSAGE_BOUNDARY_CACHE.md](MESSAGE_BOUNDARY_CACHE.md), [PROMPT_CACHE_TAIL.md](PROMPT_CACHE_TAIL.md) |
| `STRATA_CKPT_ASYNC` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
@@ -315,7 +315,7 @@ Off unless you set them. The last column says where each one is described.
| `STRATA_MTP_Q8_SM60` | on / off | NVIDIA and AMD | [release-notes-0.2.7.md](release-notes-0.2.7.md) |
| `STRATA_MTP_ROOM_MIN` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
| `STRATA_NIB_GU_PROTO` | number | NVIDIA and AMD | [OLDER_GPUS.md](OLDER_GPUS.md) |
| `STRATA_NO_ARENA_THP` | on / off | NVIDIA and AMD, Intel Arc | [TROUBLESHOOTING.md](TROUBLESHOOTING.md), [README.md](bench-results/2026-10-12-community-gfx1103/README.md) |
| `STRATA_NO_ARENA_THP` | on / off | NVIDIA and AMD, Intel Arc | [QWEN4_35B.md](QWEN4_35B.md), [TROUBLESHOOTING.md](TROUBLESHOOTING.md), [README.md](bench-results/2026-10-12-community-gfx1103/README.md) |
| `STRATA_NO_AVXVNNI` | number | CPU | [DETAILS.md](DETAILS.md) |
| `STRATA_NO_TQ_KERNELS` | number | CPU | [GYRO.md](GYRO.md) |
| `STRATA_NUMA_ARENA` | on / off | NVIDIA and AMD, CPU | [NVIDIA_V100.md](NVIDIA_V100.md) |
@@ -367,7 +367,7 @@ Off unless you set them. The last column says where each one is described.
| `STRATA_PIN_BY_NEED` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md), [DOCKER.md](DOCKER.md), [TERMINAL_LAUNCH.md](TERMINAL_LAUNCH.md) |
| `STRATA_PIN_GUARD` | number | NVIDIA and AMD | [TROUBLESHOOTING.md](TROUBLESHOOTING.md) |
| `STRATA_PIN_RESERVE_GIB` | number | NVIDIA and AMD | [TROUBLESHOOTING.md](TROUBLESHOOTING.md) |
| `STRATA_PIPED_CONCURRENT` | text | NVIDIA and AMD | [AMD_HIP.md](AMD_HIP.md), [BATCHING.md](BATCHING.md) |
| `STRATA_PIPED_CONCURRENT` | text | NVIDIA and AMD | [AMD_HIP.md](AMD_HIP.md), [BATCHING.md](BATCHING.md), [QWEN4_35B.md](QWEN4_35B.md) |
| `STRATA_PIPED_CONCURRENT_PRIO` | number | NVIDIA and AMD | [BATCHING.md](BATCHING.md) |
| `STRATA_PIPED_DECODE_MAX_MS` | number | NVIDIA and AMD | [BATCHING.md](BATCHING.md) |
| `STRATA_PIPED_DECODE_MIN_MS` | number | NVIDIA and AMD | [BATCHING.md](BATCHING.md) |
@@ -460,7 +460,7 @@ Off unless you set them. The last column says where each one is described.
| `STRATA_SPLIT_HEADROOM_TOL` | number | Intel Arc | [INTEL_ARC.md](INTEL_ARC.md) |
| `STRATA_SPLIT_LINK_MIN` | text | NVIDIA and AMD | [MULTI_GPU.md](MULTI_GPU.md) |
| `STRATA_SPLIT_MTP_BATCH` | text | NVIDIA and AMD | [BATCHING.md](BATCHING.md), [MULTI_GPU.md](MULTI_GPU.md), [README.md](bench-results/2026-10-08-community-2x-rtx3080-20gb-ud-q4-k-xl-512k-pool/README.md) |
| `STRATA_SPLIT_OVERLAP` | number | NVIDIA and AMD | [MULTI_GPU.md](MULTI_GPU.md), [README.md](bench-results/2026-10-20-0.2.1-idle-gpu/README.md) |
| `STRATA_SPLIT_OVERLAP` | number | NVIDIA and AMD | [LOOPED_ADAPTER.md](LOOPED_ADAPTER.md), [MULTI_GPU.md](MULTI_GPU.md), [README.md](bench-results/2026-10-20-0.2.1-idle-gpu/README.md) |
| `STRATA_SPLIT_UNIFORM` | on / off | NVIDIA and AMD | [MULTI_GPU.md](MULTI_GPU.md) |
| `STRATA_SPLIT_WAIT_MS` | number | NVIDIA and AMD | [MULTI_GPU.md](MULTI_GPU.md) |
| `STRATA_SSD_GBPS` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md) |
@@ -489,7 +489,7 @@ Off unless you set them. The last column says where each one is described.
| `STRATA_WATCHDOG_S` | text | NVIDIA and AMD, Intel Arc | [DETAILS.md](DETAILS.md) |
| `STRATA_WDDM_BUDGET` | number | AMD, Intel Arc | [AMD_HIP.md](AMD_HIP.md) |
## Switches that go back to earlier behaviour (188)
## Switches that go back to earlier behaviour (193)
These behaviours are on by default. Setting the switch returns the earlier behaviour; the notes in the register say which
version made it the default.
@@ -648,6 +648,11 @@ version made it the default.
| `STRATA_Q2_WARP` | on / off | NVIDIA and AMD | v0.2.16 | [DETAILS.md](DETAILS.md) |
| `STRATA_Q36_CHUNK` | number | NVIDIA and AMD | v0.2.16 | [QWEN36.md](QWEN36.md) |
| `STRATA_Q36_KEEP_STAGING` | on / off | NVIDIA and AMD | v0.2.17 | - |
| `STRATA_Q4_ATTN_EAGER` | on / off | NVIDIA and AMD | - | - |
| `STRATA_Q4_GRAPH` | on / off | NVIDIA and AMD | - | - |
| `STRATA_Q4_NOFUSE` | on / off | NVIDIA and AMD | - | - |
| `STRATA_Q4_NO_PACK` | on / off | NVIDIA and AMD | - | - |
| `STRATA_Q4_ONE_STREAM` | on / off | NVIDIA and AMD | - | - |
| `STRATA_QFUSE_HC_LOCAL` | text | NVIDIA and AMD | v0.2.16 | - |
| `STRATA_QSA_EARLY_EXIT` | number | NVIDIA and AMD, Intel Arc | v0.2.16 | - |
| `STRATA_QSA_FUSE_NR` | on / off | NVIDIA and AMD | v0.2.16 | - |
@@ -733,21 +738,21 @@ The engine flags named here are provisional until the engine's own list is final
|---|---|---|---|
| `--effort off/low/high/xhigh` | how hard Qwen4-35B-A3B thinks before it answers (reasoning_content): high is the model's own default; low and xhigh think less and more, off answers at once. Goes to the run config key `effort` and, through qwen4_family.EFFORT_TEMPLATE_VALUE, to the config's reasoning_effort (the level of requests that name none; a request's own level wins). Not an engine flag | launcher-flag | default |
| `--thinking on/off` | for Qwen4-35B-A3B the older on / off word for --effort: on is high, off is off (strata_control/qwen4_family.py effort_of) | launcher-flag | default |
| `--loop on/off` | Qwen4-35B-A3B Loop adapter (2 steps): thinks each word twice. Slower, a bit more accurate. It has no effect while Effort is Off (the Loop file is strata_dual_coda_loop_v1 with bypass_effort_off). Strata's own builds only. On downloads the Loop file (Qwen4-35B-A3B-Loop.safetensors, 147 MB) and counts it in the memory plan; off leaves it out of the download and the plan | launcher-flag | opt-in |
| `--loop on/off` | COMING SOON (not in this release: Loop stays off until the engine support lands, qwen4_family.LOOP_ENGINE_READY). Qwen4-35B-A3B Loop adapter (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 (the Loop file is strata_dual_coda_loop_v1 with bypass_effort_off). Strata's own builds only. On downloads the Loop file (Qwen4-35B-A3B-Loop.safetensors, 147 MB) and counts it in the memory plan; off leaves it out of the download and the plan | launcher-flag | opt-in |
| `--ple q4/q8` | the PLE n-gram table of Qwen4-35B-A3B: Q4 (Qwen4-35B-A3B-PLE-Q4.gguf, 11.5 GB) or Q8_0 (21.8 GB, more exact). Nothing said: the fit rule of strata_control/qwen4_fit.py (Q8_0 only when the RAM also holds it) | launcher-flag | default |
| `--model Compact/Balanced/Ultra/UD-Q4_K_XL` | the build of Qwen4-35B-A3B: Compact for a 12 to 16 GB card, Balanced for 24 GB, Ultra for 32 GB or more (qwen4_fit.VRAM_BUILDS, one table; a Mac or Spark pool takes the biggest that fits); the fourth build UD-Q4_K_XL is Unsloth's GGUF (community-supported, the same engine, shard 2 holds the PLE table so --ple is not used), listed next to the three and never recommended by the rule | launcher-flag | default |
| `--mtp auto/on/off` | the MTP sidecar of Qwen4-35B-A3B (Qwen4-35B-A3B-MTP.strata, 375 MB, in the default download set): the model's own multi-token-prediction layer drafts several tokens per step and the model checks them in one pass, so the answers are the same. auto (the default) lets the engine decide at start, on forces it, off leaves it out | launcher-flag | default |
| `--vision on/off/gpu/cpu` | pictures for Qwen4-35B-A3B: on by default (the Vision shard Qwen4-35B-A3B-Vision.strata, 893 MB, is in the download set); off leaves the shard out. Only on an engine that says images=1 (serve starts without the reader and says so otherwise) | launcher-flag | default |
| `--vision FILE` | the Vision shard of Qwen4-35B-A3B the engine reads pictures with (flag name in qwen4_family.ENGINE_FILE_FLAGS, provisional until Q4-CORE's CORE-API.md); serve takes it out when the engine does not say images=1 | engine-flag | default |
| `--native FILE --ple-gguf FILE (engine)` | how the engine is handed the Qwen4-35B-A3B model (.strata) and its PLE table (.gguf): one table, qwen4_family.ENGINE_FILE_FLAGS, provisional until Q4-CORE's CORE-API.md | engine-flag | default |
| `--loop FILE --loop-steps 2 (engine)` | the Loop file and its step count, made from the run config key `qwen4_loop` at the start (only when Loop is on); provisional until CORE-API.md | engine-flag | opt-in |
| `--loop-adapter FILE --loop-passes 2 --loop-coda universal/compact --loop-direct-t1 (engine)` | COMING SOON (not in this release: Loop stays off until Q4-LOOP's engine support is merged, qwen4_family.LOOP_ENGINE_READY). The Loop file, 2 passes, the coda (compact only for the Compact build, universal for Balanced, Ultra and UD-Q4_K_XL) and the server's --loop-direct-t1, made from the run config key `qwen4_loop` at the start (only when Loop is on; off passes nothing) | engine-flag | opt-in |
| `STRATA_QWEN4_SOURCE` | a base URL that holds the Qwen4-35B-A3B files (the model is not published; the shipped list is the private Hugging Face repo and counts only when `released` is true in data/qwen4-sources.json) | env | opt-in |
| `STRATA_QWEN4_SHOW` | 1 lists Qwen4-35B-A3B in the model list without a source or a file (the tests and the owner use it); the release itself is the one word released in data/qwen4-sources.json | env | research |
| `qwen4_mtp (run config key)` | the sidecar's path in the run config; serve makes the engine's MTP flags from it at the start (qwen4_family.mtp_engine_args). Not kept in the arguments, because Control reads `--mtp <folder>` as Flash-Next's draft layer | launcher-flag | default |
| `qwen4_mtp_mode (run config key)` | the word next to the sidecar's path: auto (also when absent) or on (forced); no path = off | launcher-flag | default |
| `qwen4_loop (run config key)` | the Loop file's path in the run config, present only when Loop is on; serve makes `--loop FILE --loop-steps 2` from it at the start | launcher-flag | opt-in |
| `qwen4_loop (run config key)` | COMING SOON (not in this release: Loop stays off until the engine support lands, qwen4_family.LOOP_ENGINE_READY). the Loop file's path in the run config, present only when Loop is on; serve makes `--loop-adapter FILE --loop-passes 2 --loop-coda C --loop-direct-t1` from it at the start | launcher-flag | opt-in |
| `effort (run config key)` | the thinking effort of Qwen4-35B-A3B (off / low / high / xhigh) the launcher writes next to the plain `thinking` switch; serve turns it into the config's reasoning_effort | launcher-flag | default |
| `--effort off/low/high/xhigh (setup)` | setup's thinking effort of Qwen4-35B-A3B: written to the run config key `effort` (and the plain `thinking` switch beside it); the launcher's --effort is the same setting | setup-flag | default |
| `--loop on/off (setup)` | setup's Loop choice for Qwen4-35B-A3B: on fetches Qwen4-35B-A3B-Loop.safetensors (147 MB) and writes the run config key `qwen4_loop` and the engine's loop flags; off (the default) fetches and writes nothing | setup-flag | opt-in |
| `--loop on/off (setup)` | COMING SOON (not in this release: Loop stays off until the engine support lands, qwen4_family.LOOP_ENGINE_READY). setup's Loop choice for Qwen4-35B-A3B: on fetches Qwen4-35B-A3B-Loop.safetensors (147 MB) and writes the run config key `qwen4_loop` and the engine's loop flags (--loop-adapter, --loop-passes, --loop-coda, --loop-direct-t1); off (the default) fetches and writes nothing | setup-flag | opt-in |
| `--ple q4/q8 (setup)` | setup's PLE table choice for Qwen4-35B-A3B (the same setting as the launcher's --ple) | setup-flag | default |
+5
View File
@@ -232,6 +232,11 @@ if(STRATA_BUILD_CONVERSATION_TESTS)
add_executable(session_save_reclaim_test src/core/session_save_reclaim_test.cpp src/core/conversation_file.cpp)
target_include_directories(session_save_reclaim_test PRIVATE include)
add_test(NAME session_save_reclaim_test COMMAND session_save_reclaim_test)
add_executable(loop_adapter_test src/kernels/loop_adapter_test.cpp src/core/conversation_file.cpp)
target_include_directories(loop_adapter_test PRIVATE include)
target_compile_features(loop_adapter_test PRIVATE cxx_std_17)
target_link_libraries(loop_adapter_test PRIVATE Threads::Threads)
add_test(NAME loop_adapter_test COMMAND loop_adapter_test)
endif()
if(STRATA_HIP_GFX906)
+2 -1
View File
@@ -89,6 +89,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
src/kernels/cuda/kv_q4.cu
src/kernels/cuda/fused_gr.cu
src/kernels/cuda/cvec.cu
src/kernels/cuda/loop_adapter.cu
src/kernels/cuda/qsa_decode_attn.cu
src/kernels/cuda/qsa_prompt_attn.cu
src/kernels/cuda/fused_gdn.cu
@@ -120,7 +121,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
COMPILE_OPTIONS "-mavx;-mno-avx2;-mno-fma;-mno-f16c")
endif()
endif()
target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact)
target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact ${_strata_gpu_blas_target})
# Exact gfx1100 prompt scorer (PR1825 method port): optional standalone test,
# also available where the published source omits tests/.
option(STRATA_PARITY_GFX1100_QSA_SCORES "Build the exact gfx1100 QSA score/ID check" OFF)
@@ -106,6 +106,8 @@ struct ConversationKvReuse {
// The conversation the image was captured from (the first stage's only): a park reuses it only for the prefix it
// shares with the conversation then in the main session (a batch slot may have replaced that session's K/V since).
std::vector<int32_t> ids;
// Loop execution mode compatibility key (0 when --loop-adapter is off; prevents cross-mode K/V reuse).
uint64_t loop_key = 0;
size_t bytes() const {
size_t n = kv.capacity() * sizeof(ConversationKv) + stages.capacity() * sizeof(ConversationKvReuse) +
ids.capacity() * sizeof(int32_t);
@@ -217,6 +219,7 @@ struct SavedConversation {
std::vector<ConversationCheckpoint> checkpoints;
std::vector<ConversationKv> kv; // main layers followed by the draft layer
bool cvec = true;
uint64_t loop_key = 0; // looped adapter execution mode key (0 = stock, 1 = T=1 bypass, >=2 = looped config hash)
// with a layer split, the later stages' own images, one per stage, in stage order
std::vector<SavedConversation> stage_images;
// STRATA_PARK_ASYNC: set while a background copy fills this image's K/V; its deleter waits for that copy, and as
@@ -334,10 +337,11 @@ public:
// `stage_kv`: with a layer split, the later stages' restored K/V (one per stage), retained with the first's.
// `ids`: the conversation the K/V belongs to (take_reuse_for refuses it for any other; none: never reused).
void retain(std::vector<ConversationKv>&& kv, int64_t tokens,
std::vector<std::vector<ConversationKv>>&& stage_kv = {}, std::vector<int32_t> ids = {}) {
std::vector<std::vector<ConversationKv>>&& stage_kv = {}, std::vector<int32_t> ids = {},
uint64_t loop_key = 0) {
reuse_ = {};
ConversationKvReuse candidate{std::move(kv), tokens, tokens, {}, std::move(ids)};
for (auto& k : stage_kv) candidate.stages.push_back(ConversationKvReuse{std::move(k), tokens, tokens, {}, {}});
ConversationKvReuse candidate{std::move(kv), tokens, tokens, {}, std::move(ids), loop_key};
for (auto& k : stage_kv) candidate.stages.push_back(ConversationKvReuse{std::move(k), tokens, tokens, {}, {}, loop_key});
if (enabled() && candidate.bytes() <= budget_ - bytes_) reuse_ = std::move(candidate);
}
void limit_reuse(int64_t first_dirty) {
@@ -350,8 +354,9 @@ public:
// from, and nothing when they share none. Without this a park after a batch slot gave its conversation back to the
// main session wrote the RESTORED conversation's K/V into the new one's image (#1503, a cross-conversation leak).
template<class Token>
ConversationKvReuse take_reuse_for(const std::vector<Token>& live) {
ConversationKvReuse take_reuse_for(const std::vector<Token>& live, uint64_t loop_key = 0) {
ConversationKvReuse r = std::exchange(reuse_, {});
if (r.loop_key != loop_key) return {};
const int64_t n = std::min<int64_t>((int64_t) r.ids.size(), (int64_t) live.size());
int64_t same = 0;
while (same < n && (int64_t) r.ids[(size_t) same] == (int64_t) live[(size_t) same]) ++same;
@@ -364,8 +369,8 @@ public:
int64_t retained_tokens() const { return reuse_.kv.empty() ? 0 : reuse_.unchanged_tokens; }
// take_reuse_for can use a positive prefix exactly when the first tokens match.
template<class Token>
bool has_reuse_for(const std::vector<Token>& live) const {
return retained_tokens() > 0 && !reuse_.ids.empty() && !live.empty() &&
bool has_reuse_for(const std::vector<Token>& live, uint64_t loop_key = 0) const {
return retained_tokens() > 0 && reuse_.loop_key == loop_key && !reuse_.ids.empty() && !live.empty() &&
(int64_t) reuse_.ids.front() == (int64_t) live.front();
}
bool can_fit(size_t incoming, size_t held = 0) const {
@@ -374,13 +379,14 @@ public:
}
template<class Token>
Match best(const std::vector<Token>& prompt, const std::vector<ConversationImageKey>& images, bool cvec) const {
Match best(const std::vector<Token>& prompt, const std::vector<ConversationImageKey>& images, bool cvec,
uint64_t loop_key = 0) const {
Match best;
// Ties prefer the most recently parked branch. The caller prefers its
// already-active state when that offers the same prefix length.
for (size_t i = entries_.size(); i-- > 0;) {
const auto& e = entries_[i];
if (e.cvec != cvec) continue;
if (e.cvec != cvec || e.loop_key != loop_key) continue;
auto consider = [&](const ConversationCheckpoint& c, bool live) {
const int64_t n = conversation_prefix(c, prompt, images);
if (n > best.tokens) best = {i, n, live, serials_[i]};
@@ -394,9 +400,10 @@ public:
/// A parked conversation holds this state already (its live tokens or one of its checkpoints start with `ids`,
/// same pictures, same steering): see conversation_covers. Read-only; no LRU effect.
template<class Token>
bool holds(const std::vector<Token>& ids, const std::vector<ConversationImageKey>& images, bool cvec) const {
bool holds(const std::vector<Token>& ids, const std::vector<ConversationImageKey>& images, bool cvec,
uint64_t loop_key = 0) const {
for (const auto& e : entries_) {
if (e.cvec != cvec) continue;
if (e.cvec != cvec || e.loop_key != loop_key) continue;
if (conversation_covers(e.live, ids, images)) return true;
for (const auto& c : e.checkpoints)
if (conversation_covers(c, ids, images)) return true;
@@ -555,7 +562,7 @@ public:
}
size_t drop_superseded(const std::vector<int32_t>& ids, const std::vector<ConversationImageKey>& images,
const std::vector<ConversationCheckpoint>& checkpoints, bool cvec,
std::vector<size_t>* dropped_tokens = nullptr) {
std::vector<size_t>* dropped_tokens = nullptr, uint64_t loop_key = 0) {
auto held = [&](const ConversationCheckpoint& c) {
if (c.ids == ids && c.imgs == images) return true;
for (const auto& k : checkpoints)
@@ -568,7 +575,7 @@ public:
const ConversationCheckpoint* deepest = nullptr;
for (const auto& c : e.checkpoints)
if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c;
if (e.cvec == cvec && !(guarded_ != 0 && serials_[i] == guarded_) &&
if (e.cvec == cvec && e.loop_key == loop_key && !(guarded_ != 0 && serials_[i] == guarded_) &&
((deepest && !deepest->ids.empty() && held(*deepest)) || live_extended_by(e, ids, images))) {
if (dropped_tokens) dropped_tokens->push_back(e.live.ids.size());
bytes_ -= e.bytes();
@@ -588,7 +595,8 @@ public:
// for a 5 K-token prefix). True when drop_superseded(ids, images, checkpoints, cvec) would drop an entry that has a checkpoint the
// given chain does not hold. Nothing is changed.
bool supersedes_richer(const std::vector<int32_t>& ids, const std::vector<ConversationImageKey>& images,
const std::vector<ConversationCheckpoint>& checkpoints, bool cvec) const {
const std::vector<ConversationCheckpoint>& checkpoints, bool cvec,
uint64_t loop_key = 0) const {
auto held = [&](const ConversationCheckpoint& c) {
if (c.ids == ids && c.imgs == images) return true;
for (const auto& k : checkpoints)
@@ -600,7 +608,7 @@ public:
const ConversationCheckpoint* deepest = nullptr;
for (const auto& c : e.checkpoints)
if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c;
if (e.cvec != cvec || !deepest || deepest->ids.empty() || !held(*deepest) ||
if (e.cvec != cvec || e.loop_key != loop_key || !deepest || deepest->ids.empty() || !held(*deepest) ||
(guarded_ != 0 && serials_[i] == guarded_))
continue;
for (const auto& c : e.checkpoints)
@@ -614,10 +622,11 @@ public:
/// park now would only rewrite what a turn from now drops: the prefix such an entry holds is this conversation's
/// prefix, and the conversation only appends, so the copy stays usable for the reuse it was made for.
size_t parked_prefix_tokens(const std::vector<int32_t>& ids, const std::vector<ConversationImageKey>& images,
const std::vector<ConversationCheckpoint>& checkpoints, bool cvec) const {
const std::vector<ConversationCheckpoint>& checkpoints, bool cvec,
uint64_t loop_key = 0) const {
size_t longest = 0;
for (const auto& e : entries_) {
if (e.cvec != cvec) continue;
if (e.cvec != cvec || e.loop_key != loop_key) continue;
const ConversationCheckpoint* deepest = nullptr;
for (const auto& c : e.checkpoints)
if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c;
@@ -633,7 +642,7 @@ public:
bool put(SavedConversation&& image, size_t held = 0) {
const size_t n = image.bytes();
if (!enabled() || held > budget_ || n > budget_ - held) return false; // make_room's refusal, first
drop_superseded(image.live.ids, image.live.imgs, image.checkpoints, image.cvec);
drop_superseded(image.live.ids, image.live.imgs, image.checkpoints, image.cvec, nullptr, image.loop_key);
if (!make_room(n, held)) return false;
entries_.push_back(std::move(image));
serials_.push_back(next_serial_++);
@@ -660,7 +669,7 @@ public:
image = std::move(staged);
throw;
}
drop_superseded(staged.live.ids, staged.live.imgs, staged.checkpoints, staged.cvec);
drop_superseded(staged.live.ids, staged.live.imgs, staged.checkpoints, staged.cvec, nullptr, staged.loop_key);
entries_.back() = std::move(staged);
++next_serial_;
bytes_ += n;
@@ -121,6 +121,7 @@ struct ConversationView {
const std::vector<ConversationImageKey>& images;
const std::vector<ConversationCheckpoint>& checkpoints;
bool cvec;
uint64_t loop_key = 0;
};
bool conversation_snapshot_bytes(const ConversationView& view, const SessionState& session,
const ModelGeometry& g, const QsaState& draft, size_t& bytes, std::string& error);
@@ -276,6 +276,7 @@ public:
std::filesystem::path file;
uint64_t bytes = 0;
bool cvec = false;
uint64_t loop_key = 0;
uint64_t used = 0; // last use (written, matched-and-read): the least recently used goes first
ConversationCheckpoint live; // ids and images only
std::vector<ConversationCheckpoint> checkpoints; // ids and images only
@@ -343,7 +344,7 @@ public:
}
Entry e;
if (ok) {
e.serial = serial; e.file = f; e.bytes = written; e.cvec = image.cvec;
e.serial = serial; e.file = f; e.bytes = written; e.cvec = image.cvec; e.loop_key = image.loop_key;
e.live = stub(image.live);
for (const auto& c : image.checkpoints) e.checkpoints.push_back(stub(c));
}
@@ -370,12 +371,13 @@ public:
/// The entry and the prefix it gives `prompt`, by the RAM cache's rule (ConversationCache::best): its live state or a
/// checkpoint, same pictures, same steering; ties prefer the newest. Reach it by `serial` (find / take_serial).
template <class Token>
ConversationCache::Match best(const std::vector<Token>& prompt, const std::vector<ConversationImageKey>& images, bool cvec) const {
ConversationCache::Match best(const std::vector<Token>& prompt, const std::vector<ConversationImageKey>& images,
bool cvec, uint64_t loop_key = 0) const {
std::lock_guard<std::mutex> lk(mu_);
ConversationCache::Match m;
for (size_t i = entries_.size(); i-- > 0;) {
const Entry& e = entries_[i];
if (e.cvec != cvec) continue;
if (e.cvec != cvec || e.loop_key != loop_key) continue;
auto consider = [&](const ConversationCheckpoint& c, bool live) {
const int64_t n = conversation_prefix(c, prompt, images);
if (n > m.tokens) m = {i, n, live, e.serial};
@@ -440,11 +442,13 @@ public:
/// A snapshot of the same conversation is being parked, grown past these tokens: deletes the entries (file and index file)
/// whose live tokens are a prefix of `image_live` (same steering and pictures) - they would never be read again. Returns the
/// token counts of the deleted entries.
std::vector<size_t> drop_superseded(const std::vector<int32_t>& ids, const std::vector<ConversationImageKey>& imgs, bool cvec) {
std::vector<size_t> drop_superseded(const std::vector<int32_t>& ids, const std::vector<ConversationImageKey>& imgs,
bool cvec, uint64_t loop_key = 0) {
SavedConversation image_live; // (tokens and pictures only)
image_live.live.ids = ids;
image_live.live.imgs = imgs;
image_live.cvec = cvec;
image_live.loop_key = loop_key;
std::lock_guard<std::mutex> lk(mu_);
std::vector<size_t> out;
for (size_t i = entries_.size(); i-- > 0;)
@@ -483,7 +487,7 @@ private:
/// `e` is a prefix (equal or shorter) of `image`'s live tokens, same steering and pictures: `image` serves every resume `e` could
static bool superseded_by(const Entry& e, const SavedConversation& image) {
const size_t n = e.live.ids.size();
if (n == 0 || e.cvec != image.cvec || n > image.live.ids.size() ||
if (n == 0 || e.cvec != image.cvec || e.loop_key != image.loop_key || n > image.live.ids.size() ||
!std::equal(e.live.ids.begin(), e.live.ids.end(), image.live.ids.begin())) return false;
for (const auto& k : e.live.imgs) { // its pictures are the first ones of the image's
bool found = false;
@@ -504,9 +508,11 @@ private:
for (const auto& k : c.imgs) { put_pod(b, k.start); put_pod(b, k.hash); }
}
static bool meta_write(const std::filesystem::path& f, const Entry& e, const SessionFileIdentity& id) {
std::string b = "SPM1";
std::string b = e.loop_key != 0 ? "SPM2" : "SPM1";
put_pod(b, id.model); put_pod(b, id.config);
put_pod(b, (uint8_t) e.cvec); put_pod(b, e.bytes);
put_pod(b, (uint8_t) e.cvec);
if (e.loop_key != 0) put_pod(b, e.loop_key);
put_pod(b, e.bytes);
put_ckpt(b, e.live);
put_pod(b, (uint64_t) e.checkpoints.size());
for (const auto& c : e.checkpoints) put_ckpt(b, c);
@@ -573,11 +579,13 @@ private:
std::fclose(fp);
} else good = false;
Rd r{b};
good = good && b.compare(0, 4, "SPM1") == 0;
const bool is_v2 = b.size() >= 4 && b.compare(0, 4, "SPM2") == 0;
good = good && (is_v2 || (b.size() >= 4 && b.compare(0, 4, "SPM1") == 0));
if (good) {
r.at = 4;
const uint64_t model = r.pod<uint64_t>(), config = r.pod<uint64_t>();
f.e.cvec = r.pod<uint8_t>() != 0;
f.e.loop_key = is_v2 ? r.pod<uint64_t>() : 0;
f.e.bytes = r.pod<uint64_t>();
good = !r.bad && model == id.model && config == id.config && fs::file_size(sess, e2) == f.e.bytes && !e2 &&
get_ckpt(r, f.e.live, f.e.bytes);
@@ -631,9 +639,10 @@ private:
/// steering): for the images the background writer still holds in RAM. {tokens, live}; tokens 0 = none.
template <class Token>
std::pair<int64_t, bool> conversation_image_prefix(const SavedConversation& s, const std::vector<Token>& prompt,
const std::vector<ConversationImageKey>& images, bool cvec) {
const std::vector<ConversationImageKey>& images, bool cvec,
uint64_t loop_key = 0) {
std::pair<int64_t, bool> m{0, false};
if (s.cvec != cvec) return m;
if (s.cvec != cvec || s.loop_key != loop_key) return m;
const int64_t l = conversation_prefix(s.live, prompt, images);
if (l > m.first) m = {l, true};
for (const auto& c : s.checkpoints) {
+69 -1
View File
@@ -27,6 +27,7 @@
#include "strata/core/flag_order.hpp"
#include "strata/core/layer.hpp"
#include "strata/core/session.hpp"
#include "strata/kernels/loop_adapter.hpp"
#include "strata/kernels/sampler.hpp"
#include "strata/kernels/window_limits.hpp"
#include "strata/kernels/verify_kernels.hpp"
@@ -233,6 +234,39 @@ public:
void set_next(Verifier* next, void* next_user) { next_ = next; next_user_ = next_user; }
/// floats per token in a hand-off buffer
static int64_t handoff_floats(const ModelGeometry& g) { return (int64_t) g.hc * g.n_embd + g.n_embd + g.hc; }
/// floats per token in a cyclic split's hand-off: the residual hand-off, then a relayed m_prev (hc x n_embd)
static int64_t cyclic_handoff_floats(const ModelGeometry& g) { return handoff_floats(g) + (int64_t) g.hc * g.n_embd; }
/// CYCLIC LAYER SPLIT (looped adapter, a stage boundary inside the recurrent core): the window visits the
/// physical stages in the order of `hops` (shared by every stage; each entry is a stage's verifier and its
/// visit), one captured graph per visit and window size. This stage runs `visits` (from
/// build_loop_itinerary, owner == this stage) and writes visit j's residual to `hand_out[j]` (null on the
/// final visit); every visit but the first reads `hand_in`, sized for cyclic_handoff_floats rows. `run` on
/// the first stage runs the whole itinerary; `commit` and the tap gather keep following the physical chain.
/// Set before `init`, after set_stage; overlapped hand-offs and pipelined windows are not used with it.
struct CycHop {
Verifier* ver = nullptr;
int visit = 0;
};
void set_cyclic(std::vector<strata::kernels::LoopVisit> visits, std::vector<float*> hand_out, const float* hand_in,
const std::vector<CycHop>* hops) {
cyc_visits_ = std::move(visits);
cyc_out_ = std::move(hand_out);
cyc_hand_in_ = hand_in;
cyc_hops_ = hops;
cyc_graphs_.assign(cyc_visits_.size(), CycGraphs{});
cyc_loaded_ = 0;
}
bool cyclic() const { return cyc_hops_ != nullptr; }
/// Per-request Looped adapter configuration (propagates down `next_` to every stage in a layer split):
/// `passes == 1` switches to a lazily-captured stock 48-layer CUDA graph bank (bypassing extra passes, LoRAs,
/// workspace/mixer, and LoopCD); `passes >= 2` runs the loaded looped graphs with live per-token LoopCD-Hidden
/// (`cd_omega`, optional `<think>`-span gating starting from `in_thinking`).
bool set_loop_request(int passes, float cd_omega, bool cd_thinking, bool in_thinking, std::string& err);
/// Update the committed `<think>`-span tracking state on this stage and any successors without changing `passes`.
void set_loop_cd_in_thinking(bool in_thinking);
/// Keep the first `n_keep` (1..T) tokens of the last window; advances `ss.ple_prev` by them.
bool commit(int n_keep, std::string& err);
@@ -641,6 +675,37 @@ private:
bool chain_overlap() const; ///< this stage hands off through a flag to a next stage that waits on it
Verifier* next_ = nullptr;
void* next_user_ = nullptr;
// set_cyclic: this stage's visits, their hand-offs, the shared itinerary, the visit being recorded / run, and
// the window graphs of the visits not loaded into exec_ / exec_nr_ (cyc_select swaps them in)
struct CycGraphs {
cudaGraphExec_t exec[2][strata::kernels::kVerifyLongT + 1] = {};
cudaGraphExec_t exec_nr[2][strata::kernels::kVerifyLongT + 1] = {};
bool launched[2][strata::kernels::kVerifyLongT + 1] = {};
bool launched_nr[2][strata::kernels::kVerifyLongT + 1] = {};
};
std::vector<strata::kernels::LoopVisit> cyc_visits_;
std::vector<float*> cyc_out_;
const float* cyc_hand_in_ = nullptr;
const std::vector<CycHop>* cyc_hops_ = nullptr;
std::vector<CycGraphs> cyc_graphs_;
int cyc_loaded_ = 0; ///< the visit whose graphs are in exec_ / exec_nr_
int cyc_visit_ = 0; ///< the visit being recorded / run
int cyc_hop_ = 0; ///< its place in the itinerary (set by the hop before it)
bool cyc_entered_ = false; ///< run() was entered from the previous hop (not from the caller)
void cyc_select(int visit);
std::vector<strata::kernels::LoopStep> cyc_owner_steps() const; ///< every step this stage runs in a window
// Per-request loop_passes == 1 stock single-pass bypass graph bank (lazily captured on first T=1 request)
CycGraphs bypass_graphs_;
cudaGraphExec_t bypass_commit_exec_ = nullptr;
bool bypass_loaded_ = false;
void select_loop_bypass(bool bypass);
// Per-request LoopCD-Hidden state (read via mapped staging h_cd_omega_/m_cd_omega_ inside captured graphs)
bool loop_req_set_ = false;
float loop_cd_omega_ = 0.0f;
bool loop_cd_thinking_ = false;
bool loop_cd_in_thinking_ = false;
float* h_cd_omega_ = nullptr;
float* m_cd_omega_ = nullptr;
bool ple_stage() const { return lb_ <= 1 && 1 < le_; } ///< holds layer 1, where the PLE block runs
void stage_inputs(int T, const int32_t* tokens, int64_t pos0);
bool staged_ = false;
@@ -764,7 +829,7 @@ private:
bool commit_pending_ = false;
cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts)
using FlagSet = strata::core::FlagRaise;
FlagSet flag_sets_[2 * 64 * 2] = {}; // host-function arguments, one per (layer, group)
FlagSet flag_sets_[2 * 160 * 2] = {}; // host-function arguments, one per (step, group)
static void fetch_dma(void* ctx, const uint8_t* const* src, int n, size_t bytes);
static void raise_flag(uint32_t* flag, uint32_t value);
/// Flag B for `want`, behind every copy queued on copy_ (an empty plan must not overtake an earlier layer's DMA).
@@ -788,6 +853,9 @@ private:
void* arena_ = nullptr;
int32_t *tok_ = nullptr, *step_ = nullptr, *pos_ = nullptr, *commit_ = nullptr;
float *ple_ = nullptr, *emb_ = nullptr, *R_ = nullptr, *mixed_ = nullptr, *bo_ = nullptr;
float *R_anchor_ = nullptr, *R_mprev_ = nullptr, *R_m0_ = nullptr; // Looped adapter residual checkpoints
float *ab_alpha_ = nullptr, *ab_beta_ = nullptr; // Looped adapter GDN a/b LoRA scratch
float *cd_omega_ = nullptr; // Looped adapter per-token LoopCD omega [T]
float *inj_ = nullptr, *inj2_ = nullptr, *lo_ = nullptr, *rs_ = nullptr, *xn_ = nullptr;
uint8_t* xq_ = nullptr; // T columns of q8_1
uint8_t* xil_ = nullptr; // fork F4: the interleaved copy of xq_'s 2-4 columns
@@ -0,0 +1,298 @@
// include/strata/kernels/loop_adapter.hpp - Looped Qwen3.8-Flash-Next (qwen4_exp) recurrent core adapter.
//
// Opt-in (--loop-adapter <ckpt.safetensors> [--loop-passes N]): when unloaded, zero overhead and byte-identical
// to stock Strata. When loaded, executes T passes over core layers [core_start, core_end) with:
// * Anchor-grounded 4-stream HCWorkspaceEntry (FP32 grouped RMSNorm + RMS-matched interpolation + low-rank gate)
// * Per-step 4-stream HCCrossPassMixer (FP32 grouped RMSNorm + low-rank delta + delta_kappa scaling)
// * Pre-folded per-pass core LoRAs (GDN qkv/z/a/b/out, QSA q/k/v/o, MoE router gate, shared expert gate/up/down)
// * Coda LoRAs on layers [core_end, core_end + coda_lora_layers)
// * Distinct GDN and QSA recurrent/KV state slots per pass p = 1..T-1 while sharing 100% of base weights & RAM experts.
#pragma once
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
namespace strata::kernels {
enum class LoopTarget : int {
kGdnQkv = 0,
kGdnZ = 1,
kGdnA = 2,
kGdnB = 3,
kGdnOut = 4,
kQsaQ = 5,
kQsaK = 6,
kQsaV = 7,
kQsaO = 8,
kMoeGate = 9,
kShGate = 10,
kShUp = 11,
kShDown = 12,
kAttn = 13, ///< strata_dual_coda_loop_v1: hidden -> r -> hidden delta on the token-mixer block's output (input: the HC-mixed block input)
kMlp = 14, ///< same, on the MoE block's output (input: the HC-mixed MoE input)
kCount = 15,
};
/// think_start_id value that selects the "sticky close" gate of the dual-coda format: the per-token flag is 1 from the
/// first `</think>` token (inclusive) to the end of the sequence (the trainer's `cumsum(ids == 248069) > 0`).
constexpr int32_t kLoopStickyClose = -2;
struct LoopLoraPair {
const float* a = nullptr; ///< device [rank, in_dim] FP32 row-major
const float* b_eff = nullptr; ///< device [out_dim, rank] FP32 row-major (alpha/rank * pass_gate pre-folded)
int in_dim = 0;
int out_dim = 0;
int rank = 0;
bool valid() const { return a != nullptr && b_eff != nullptr && rank > 0; }
};
struct LoopStep {
int64_t layer = 0; ///< physical layer 0..n_layers-1 (base weights & routed experts)
int pass = 0; ///< 0 = prelude / core pass 0 / coda; 1..T-1 = extra core passes
int core_step = -1; ///< 0..(core_end-core_start-1) on pass >= 1, else -1
int64_t gdn_slot = -1; ///< GDN state ordinal (allocated in SessionState::gdn_state)
int64_t qsa_slot = -1; ///< QSA state ordinal (allocated in SessionState::qsa_states)
bool save_anchor_before = false; ///< true before core_start on pass 0 when stage starts at core_start
bool save_anchor_after = false; ///< true after prelude end (layer == core_start - 1)
bool save_mprev_after = false; ///< true after core_end - 1 on every pass
bool run_workspace_entry = false; ///< true before core_step == 0 on pass >= 1
bool run_cross_pass_mixer = false; ///< true before every core_step on pass >= 1
bool materialize_after = false; ///< true if R must be materialized at end of this step
bool pending_before = false; ///< true if previous step left a deferred FFN write
};
struct LoopAdapter {
bool is_loaded = false;
int num_passes = 1; ///< T (1 = off, 2+ = looped)
int core_start = 16; ///< inclusive
int core_end = 32; ///< exclusive
int coda_lora_layers = 8; ///< layers [core_end, core_end + coda_lora_layers)
int t_max = 3; ///< checkpoint trained T_max (for slot clamping)
float lora_alpha = 32.0f;
float cd_omega = 0.0f;
bool cd_thinking = false; ///< --loop-cd-thinking: gate LoopCD-Hidden to active <think>...</think> spans
int32_t think_start_id = 248068; ///< <think> special token ID (default: Qwen3.8-Flash-Next)
int32_t think_end_id = 248069; ///< </think> special token ID (default: Qwen3.8-Flash-Next)
int64_t n_layers = 48;
int64_t n_embd = 2560;
int64_t hc = 4;
int64_t hc_dim = 10240;
int entry_rank = 128;
int mixer_rank = 128;
int total_lora_hooks = 0;
std::string mode = "gated_workspace";
std::string ckpt_path;
// strata_dual_coda_loop_v1 (the owner's Qwen4-35B-A3B-Loop.safetensors), trainer 03_train_dual_coda_loop.py:
bool dual_coda = false; ///< true: mixer = anchor + sigmoid(gate) * up(silu(down(rms(exit - x)))), entry = the anchor,
///< LoRAs on the block outputs (scale 0.25), coda LoRA delta * (after </think> ? cd_omega[l] : 1)
std::string coda_sel = "universal"; ///< "universal" | "compact" (coda_lora.<sel>.*)
std::vector<float> coda_cd; ///< meta.cd_omega, one per coda layer (host copy)
bool loaded() const { return is_loaded && num_passes >= 2; }
int core_len() const { return core_end - core_start; }
int extra_passes() const { return loaded() ? (num_passes - 1) : 0; }
/// Lookup pre-folded LoRA for `(pass, physical_layer, target)`. Returns null if absent.
const LoopLoraPair* lora(int pass, int64_t layer, LoopTarget target) const;
/// True if any LoRA is attached for `(pass, physical_layer)` on the given target.
bool has_lora(int pass, int64_t layer, LoopTarget target) const { return lora(pass, layer, target) != nullptr; }
/// True if any GDN LoRA (qkv/z/a/b/out) is active on `(pass, layer)`.
bool has_gdn_lora(int pass, int64_t layer) const {
return has_lora(pass, layer, LoopTarget::kGdnQkv) || has_lora(pass, layer, LoopTarget::kGdnZ) ||
has_lora(pass, layer, LoopTarget::kGdnA) || has_lora(pass, layer, LoopTarget::kGdnB) ||
has_lora(pass, layer, LoopTarget::kGdnOut);
}
/// True if any shared-expert LoRA (gate/up/down) is active on `(pass, layer)`.
bool has_sh_lora(int pass, int64_t layer) const {
return has_lora(pass, layer, LoopTarget::kShGate) || has_lora(pass, layer, LoopTarget::kShUp) ||
has_lora(pass, layer, LoopTarget::kShDown);
}
};
/// Global loaded loop adapter (unloaded by default).
const LoopAdapter& loop_adapter();
/// Load adapter checkpoint (`.safetensors` + optional sibling `.json`), pre-fold all pass gates for
/// `num_passes`, and upload FP32 weights + tiny fixed scratch buffers to the current CUDA device.
bool loop_adapter_load(const std::string& safetensors_path, int num_passes, float cd_omega, int64_t n_layers,
int64_t n_embd, int64_t hc, std::string& summary, std::string& err, bool cd_thinking = false,
int32_t think_start_id = 248068, int32_t think_end_id = 248069);
/// strata_dual_coda_loop_v1 files only: which coda LoRA set to use ("universal" for Ultra / Balanced / GGUF quants,
/// "compact" for the Compact tier). Call before loop_adapter_load. Default "universal".
void loop_adapter_set_coda(const std::string& sel);
/// loop_lora_add for the dual-coda hooks (kAttn / kMlp): on a coda layer the LoRA delta of row t is scaled by
/// `flag[t] > 0.5 ? cd_omega[layer - core_end] : 1` (flag = the after-</think> per-token vector, device, [n_tok]).
void loop_lora_add_gated(const float* x, int x_ld, float* y, int y_ld, int pass, int64_t layer, LoopTarget target,
int n_tok, void* stream, const float* flag);
/// Replicate the loaded loop adapter onto the current CUDA device (for `--layer-split` multi-GPU stages).
/// No-op if unloaded or already present on the current device.
bool loop_adapter_replicate(std::string& err);
/// Free GPU memory held by the global loop adapter (safe to call on shutdown).
void loop_adapter_free();
/// Advance thinking-span state by one token (vllm_looped_qwen38 `compute_thinking_token_mask` semantics with
/// `default_thinking=False, include_end_token=False`): entering `<think>` turns gating on (inclusive of `<think>`),
/// seeing `</think>` turns gating off immediately (exclusive of `</think>`).
inline bool loop_think_step(bool in_thinking, int64_t token, int32_t think_start_id, int32_t think_end_id) {
if (think_start_id == kLoopStickyClose) return in_thinking || token == (int64_t) think_end_id; // dual-coda: seen </think>
if (token == (int64_t) think_start_id) return true;
if (token == (int64_t) think_end_id) return false;
return in_thinking;
}
/// Thinking-span state after consuming `tokens[0 .. n-1]` from initial state `in_thinking`.
template <class Token>
inline bool loop_think_state_after(const Token* tokens, int64_t n, int32_t think_start_id, int32_t think_end_id,
bool in_thinking = false) {
if (tokens == nullptr || n <= 0 || (think_start_id < 0 && think_start_id != kLoopStickyClose) || think_end_id < 0 ||
think_start_id == think_end_id)
return in_thinking;
bool s = in_thinking;
for (int64_t i = 0; i < n; ++i) s = loop_think_step(s, (int64_t) tokens[i], think_start_id, think_end_id);
return s;
}
/// Fill `omega_out[0 .. n-1]` with per-token effective LoopCD-Hidden weights for `tokens[0 .. n-1]`,
/// returning the updated thinking-span state after `tokens[n-1]`.
/// When `cd_thinking` is false, fills every entry with `omega` (unconditional legacy behavior).
/// When `cd_thinking` is true, sets `omega_out[i] = omega` iff token `i` is inside an active `<think>` span.
template <class Token>
inline bool loop_cd_fill_omega(const Token* tokens, int64_t n, float omega, bool cd_thinking, int32_t think_start_id,
int32_t think_end_id, bool in_thinking, float* omega_out) {
if (n <= 0 || omega_out == nullptr) return in_thinking;
bool s = in_thinking;
if (think_start_id == kLoopStickyClose && think_end_id >= 0) { // dual-coda: flag = 1 from </think> on (omega unused)
for (int64_t i = 0; i < n; ++i) {
s = loop_think_step(s, (int64_t) tokens[i], think_start_id, think_end_id);
omega_out[i] = s ? 1.0f : 0.0f;
}
return s;
}
if (!cd_thinking || think_start_id < 0 || think_end_id < 0 || think_start_id == think_end_id) {
for (int64_t i = 0; i < n; ++i) omega_out[i] = omega;
return s;
}
for (int64_t i = 0; i < n; ++i) {
s = loop_think_step(s, (int64_t) tokens[i], think_start_id, think_end_id);
omega_out[i] = s ? omega : 0.0f;
}
return s;
}
/// Conversation-cache / checkpoint compatibility key for the active loop execution mode.
/// Returns 0 when no loop adapter is loaded, 1 for stock T=1 single-pass bypass (invariant to LoopCD settings),
/// and a non-zero hash >= 2 encoding `(active_passes, cd_omega, cd_thinking, think_ids)` for looped T >= 2 requests.
inline uint64_t loop_cache_key_for(bool loaded, int active_passes, float cd_omega, bool cd_thinking,
int32_t think_start_id, int32_t think_end_id) {
if (!loaded) return 0;
if (active_passes <= 1) return 1;
uint32_t obits = 0;
if (cd_omega != 0.0f) std::memcpy(&obits, &cd_omega, sizeof obits);
const bool th = (obits != 0) && cd_thinking;
uint64_t h = 1469598103934665603ull;
auto mix = [&](uint64_t v) {
for (int i = 0; i < 8; ++i) {
h ^= (v >> (i * 8)) & 0xffu;
h *= 1099511628211ull;
}
};
mix((uint64_t) active_passes);
mix((uint64_t) obits);
mix(th ? 1ull : 0ull);
if (th) {
mix((uint64_t) (uint32_t) think_start_id);
mix((uint64_t) (uint32_t) think_end_id);
}
return h < 2 ? h + 2 : h;
}
inline uint64_t loop_cache_key(int active_passes, float cd_omega, bool cd_thinking) {
const LoopAdapter& la = loop_adapter();
return loop_cache_key_for(la.loaded(), active_passes, cd_omega, cd_thinking, la.think_start_id, la.think_end_id);
}
/// Number of extra GDN / QSA state slots needed for `[layer_lo, layer_hi)` when loop adapter is loaded.
int64_t loop_extra_gdn_slots(int64_t layer_lo, int64_t layer_hi, int64_t qsa_interval);
int64_t loop_extra_qsa_slots(int64_t layer_lo, int64_t layer_hi, int64_t qsa_interval);
/// Build the ordered execution schedule for `[layer_lo, layer_hi)`.
/// When unloaded or `bypass == true` (per-request `loop_passes=1`), returns `[layer_lo, ..., layer_hi - 1]` with
/// `pass = 0` and standard state ordinals.
std::vector<LoopStep> build_loop_schedule(int64_t n_layers, int64_t qsa_interval, int64_t layer_lo, int64_t layer_hi,
bool bypass = false);
/// One visit of a cyclic layer split: a run of consecutive steps of the whole model's looped order that one physical
/// stage executes before the residual moves to another stage. The global order is [0, core_end) on pass 0, then
/// [core_start, core_end) on every pass 1..T-1, then the coda [core_end, n_layers) on pass 0.
struct LoopVisit {
int owner = 0; ///< physical stage index (the owner of every step's layer)
std::vector<LoopStep> steps; ///< state ordinals are the owner's (its session carve: base range, then extras)
bool embed = false; ///< the first visit: embeds the tokens (no hand-in)
bool head = false; ///< the final visit: runs the head (no hand-out)
int mprev_in = 0; ///< 0: none; 1: m_prev is the handed-in residual (the wrap); 2: relayed beside it
bool mprev_out = false; ///< the next visit takes m_prev relayed (mprev_in == 2)
bool owner_first = false; ///< the owner's first visit of a window / chunk
bool owner_last = false; ///< the owner's last visit of a window / chunk
bool ple = false; ///< holds layer 1 on pass 0 (the PLE block)
};
/// True when the adapter is loaded and a stage boundary in `stage_begin` (the first layer of each stage, [0] == 0)
/// lies strictly inside the recurrent core: the stages then run a cyclic itinerary (build_loop_itinerary).
bool loop_split_cyclic(const std::vector<int64_t>& stage_begin);
/// The cyclic itinerary of a layer split (empty when unloaded). Visits are in execution order; each physical stage
/// owns several. Pass-0 steps use the whole-model state ordinals; a pass p >= 1 step on a stage [u, v) uses
/// F(v) + (p - 1) * h + r, where F counts the layers of its type before v, h is the stage's core layers of that type
/// and r the layer's rank among them - the order session_init carves the stage's extra slots in.
std::vector<LoopVisit> build_loop_itinerary(int64_t n_layers, int64_t qsa_interval, const std::vector<int64_t>& stage_begin);
/// Does a step's output feed a DFlash2 tap? Outside the core only pass 0 runs; inside it the last pass is final.
inline bool loop_tap_pass(const LoopStep& s, const LoopAdapter& la, bool bypass = false) {
if (!la.loaded() || bypass) return true;
const bool core = s.layer >= la.core_start && s.layer < la.core_end;
return core ? s.pass == la.num_passes - 1 : s.pass == 0;
}
/// Anchor-grounded 4-stream HCWorkspaceEntry for `pass_idx = pass - 1` (`0 .. T-2`).
/// `anchor`, `m_prev`, `R_out` are `[n_tok, hc_dim]` contiguous FP32 on device (`R_out` may alias `m_prev`).
void loop_workspace_entry(const float* anchor, const float* m_prev, float* R_out, int pass_idx, int n_tok,
void* stream);
/// 4-stream HCCrossPassMixer for `pass_idx = pass - 1`, `core_step = 0 .. core_len - 1`.
/// `x`, `m_prev`, `R_out` are `[n_tok, hc_dim]` contiguous FP32 on device (`R_out` may alias `x`).
void loop_cross_pass_mixer(const float* x, const float* m_prev, float* R_out, int pass_idx, int core_step, int n_tok,
void* stream);
/// Add LoRA delta `y += (x @ A^T) @ B_eff^T` for `n_tok` rows with arbitrary input/output row strides.
/// No-op if no LoRA is registered for `(pass, layer, target)`.
void loop_lora_add(const float* x, int x_ld, float* y, int y_ld, int pass, int64_t layer, LoopTarget target,
int n_tok, void* stream);
/// Same as `loop_lora_add`, reading IEEE FP16 (`uint16_t`) activations `x_f16` (used by prefill GEMM path).
void loop_lora_add_f16(const uint16_t* x_f16, int x_ld, float* y, int y_ld, int pass, int64_t layer,
LoopTarget target, int n_tok, void* stream);
/// Batched GDN alpha/beta epilogue for `n_tok` rows:
/// gate_out[t, h] = softplus(alpha[t, h] + dt[h]) * ssm_a[h]
/// beta_out[t, h] = sigmoid(beta[t, h])
void loop_gdn_ab_epilogue(const float* alpha, const float* beta, const float* dt, const float* ssm_a,
float* gate_out, float* beta_out, int hv, int n_tok, void* stream);
/// Optional ratio-preserving LoopCD-Hidden on `[n_tok, hc_dim]` when `omega != 0.0f`.
void loop_cd_hidden(const float* m_cur, const float* m_ref, float* R_out, float omega, int n_tok, void* stream);
/// CUDA-graph-safe per-token ratio-preserving LoopCD-Hidden on `[n_tok, hc_dim]`.
/// Reads `omega_per_tok[t]` from device memory; tokens with `omega == 0.0f` leave `R_out` bit-identical to `m_cur`.
void loop_cd_hidden_per_tok(const float* m_cur, const float* m_ref, float* R_out, const float* omega_per_tok,
int n_tok, void* stream);
} // namespace strata::kernels
@@ -81,7 +81,7 @@ void shared_expert(const uint8_t* x_q8_0, const uint8_t* x_q8k, const uint16_t*
void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw,
const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd,
int64_t n_ff, void* stream, const void* x_q8_1_ready = nullptr,
int lfuse = 0); // S26 STRATA_LFUSE: bit 0 gate computed + applied by the caller, bit 1 gate/up pair
int lfuse = 0, int loop_pass = -1, int64_t loop_layer = -1); // S26 STRATA_LFUSE + Looped adapter LoRA
/// The MoE block's final combination, `ref/moe.py::moe` L156:
///
@@ -12,6 +12,7 @@
#define cublasCreate hipblasCreate
#define cublasDestroy hipblasDestroy
#define cublasSetStream hipblasSetStream
#define cublasSgemm hipblasSgemm
#define cublasGemmEx hipblasGemmEx
#define CUBLAS_OP_N HIPBLAS_OP_N
#define CUBLAS_OP_T HIPBLAS_OP_T
+30
View File
@@ -26,6 +26,7 @@
namespace strata::core { class PeerExperts; }
namespace strata::kernels::cpu { class ExpertPool; }
namespace strata::kernels { struct LoopVisit; }
namespace strata::prefill {
@@ -289,6 +290,20 @@ public:
stage_lb_ = layer_begin; stage_le_ = layer_end; next_ = next;
}
/// CYCLIC LAYER SPLIT (a looped adapter with a stage boundary inside its recurrent core): `paths[s]` is stage s's
/// prompt path (0 = the first) and `stage_begin[s]` its first layer. A prompt's chunks then run the itinerary of
/// kernels::build_loop_itinerary: each stage reads its visits of a chunk in order, on a thread of its own, once the
/// visit before has handed its rows on, and starts the next chunk after its last visit of this one. `run` on the
/// first path reads the prompt; `on_chunk` stays on the last. Call after set_stage, before `init`.
static void set_cyclic(const std::vector<Prefill*>& paths, const std::vector<int64_t>& stage_begin,
const core::ModelGeometry& g);
/// Per-request Looped adapter configuration (propagated to every stage in a layer split):
/// `passes == 1` bypasses the recurrent core & LoRAs for exact stock 48-layer prefill; `passes >= 2` runs the
/// loaded looped depth with per-token LoopCD-Hidden (`cd_omega`, optional `<think>`-span gating starting from
/// `in_thinking` at `pos0`). No-op when `--loop-adapter` is not loaded.
void set_loop_request(int passes, float cd_omega, bool cd_thinking, bool in_thinking);
/// LAYER SPLIT: `helper` is another stage's prompt path (another GPU). A prompt of one chunk runs the stages one
/// after the other, so while this stage reads it the helper's GPU idles: it then streams a share of this stage's
/// non-resident experts over its own PCIe link into its own (lent) prompt buffers, computes their rows, and sends
@@ -400,6 +415,21 @@ private:
std::future<bool> next_run_;
int hand_buf_ = 0;
struct Cyc; ///< set_cyclic: the itinerary and a run's progress (every stage's)
std::shared_ptr<Cyc> cyc_;
int cyc_stage_ = 0;
const kernels::LoopVisit* cyc_vis_ = nullptr; ///< the visit run_impl reads (null: the stage's own layers)
float* cyc_out_ = nullptr; ///< ... its rows' hand-off (null on the final visit)
float* cyc_mprev_out_ = nullptr; ///< ... the m_prev it relays to the next visit
const float* cyc_mprev_in_ = nullptr; ///< ... the m_prev relayed to it
const float* cyc_cd_omega_ = nullptr; ///< ... per-token LoopCD omega slice for this chunk
bool loop_req_set_ = false; ///< true after set_loop_request()
bool loop_bypass_ = false; ///< per-request loop_passes == 1 stock 48-layer bypass
float loop_cd_omega_ = 0.0f; ///< per-request LoopCD-Hidden weight
bool loop_cd_thinking_ = false; ///< per-request <think>-only LoopCD-Hidden gating
bool loop_cd_in_thinking_ = false; ///< thinking-span state at pos0 of this run/chunk
bool run_cyclic(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err);
bool carve(std::size_t T, void* alloc); // the device buffers of a chunk (prefill.cpp's Alloc)
void release(); // the destructor's cleanup (also `reset`'s)
struct Impl;
+4 -1
View File
@@ -205,7 +205,7 @@ set(STRATA_METAL_HOST_SOURCES
${S}/core/native_head.cpp ${S}/core/native_dense.cpp ${S}/core/verify.cpp ${S}/core/mtp.cpp
${S}/core/conversation_snapshot.cpp ${S}/core/conversation_state.cpp ${S}/core/conversation_memory.cpp
${S}/core/peer_experts.cpp ${S}/core/arch_defaults.cpp ${S}/core/vmm.cpp ${S}/core/conversation_file.cpp
${S}/kernels/ngram.cpp ${S}/ngram/ple_reader.cpp ${S}/platform/direct_file.cpp ${S}/platform/io_priority.cpp
${S}/kernels/ngram.cpp ${S}/kernels/loop_adapter_stub.cpp ${S}/ngram/ple_reader.cpp ${S}/platform/direct_file.cpp ${S}/platform/io_priority.cpp
${S}/prefill/prefill.cpp
${S}/spec/suffix_drafter.cpp ${S}/spec/controller.cpp ${S}/spec/draft_policy.cpp ${S}/spec/draft_source.cpp
${S}/kernels/cpu/pool.cpp ${S}/kernels/cpu/expert_layout.cpp ${S}/kernels/cpu/native_expert.cpp
@@ -251,3 +251,6 @@ endif()
# the decode window on its own (probe/window_probe.cpp): the engine's process state without the engine, for looking at a Metal fault
add_executable(window_probe probe/window_probe.cpp)
target_link_libraries(window_probe PRIVATE strata_metal_kernels strata_metal_host strata_metal_kernels)
# teacher-forced scoring of token lists on the decode window (the Qwen4 exactness gate: tests/qwen4/q4_drift.py reads its .tf.bin files)
add_executable(q4_tf_probe probe/q4_tf_probe.cpp)
target_link_libraries(q4_tf_probe PRIVATE strata_metal_kernels strata_metal_host strata_metal_kernels)
+119
View File
@@ -0,0 +1,119 @@
// q4m_moe.metal - the routed experts of a Qwen4-35B-A3B .strata file (per-expert S_K codes 1..8, FWHT-128 convention of Ling's expert body) for the
// decode window. Compiled after sk_codes.metal in the same library (it uses sk_row_dot / sk_sb_bytes).
//
// expert body (Section 4 of the file, at ExpertDesc.off): fp16 S_xd[n_ff] | W_gu [2 n_ff, n_embd] in gu_code (gate rows, then up rows) | W_dn [n_embd, n_ff] at dn_off in dn_code
// x_h = FWHT128(x); gu = W_gu x_h; a = silu(gate) * up / S_xd; a_h = FWHT128(a); y = W_dn a_h
// One pair p = token * topk + slot per row of the grids; ids come from moe_route (the window's router), weights are applied by q4m_combine.
struct SxDesc { ulong off; int gu_code; int dn_code; int dn_off; int body_bytes; };
struct SxArgs { int layer_base; int topk; int n_embd; int n_ff; int n_tok; };
inline int sk_sb_rt(int code) { return code == 1 ? 58 : (code == 2 || code == 7) ? 70 : code == 3 ? 102 : code == 4 ? 134 : code == 5 ? 166 : code == 6 ? 198 : 262; }
inline float sk_dot_code(int code, device const uchar* rowp, int nsb, device const float* x, uint lane) {
float acc[1] = {0.0f};
switch (code) {
case 1: sk_row_dot<1, 1>(rowp, nsb, x, nsb * 256, 1, 0, lane, acc); break;
case 2: sk_row_dot<2, 1>(rowp, nsb, x, nsb * 256, 1, 0, lane, acc); break;
case 3: sk_row_dot<3, 1>(rowp, nsb, x, nsb * 256, 1, 0, lane, acc); break;
case 4: sk_row_dot<4, 1>(rowp, nsb, x, nsb * 256, 1, 0, lane, acc); break;
case 5: sk_row_dot<5, 1>(rowp, nsb, x, nsb * 256, 1, 0, lane, acc); break;
case 6: sk_row_dot<6, 1>(rowp, nsb, x, nsb * 256, 1, 0, lane, acc); break;
case 7: sk_row_dot<7, 1>(rowp, nsb, x, nsb * 256, 1, 0, lane, acc); break;
default: sk_row_dot<8, 1>(rowp, nsb, x, nsb * 256, 1, 0, lane, acc); break;
}
return acc[0];
}
// FWHT-128 of a 128-block held 4 values per lane of a simdgroup (lane l: elements 4l..4l+3), normalised by 1/sqrt(128): Ling's fwht128_simd
inline void q4m_fwht128_simd(thread float* v, uint lane) {
const float a0 = v[0] + v[1], a1 = v[0] - v[1], a2 = v[2] + v[3], a3 = v[2] - v[3];
v[0] = a0 + a2; v[1] = a1 + a3; v[2] = a0 - a2; v[3] = a1 - a3;
#pragma unroll
for (uint mask = 1; mask <= 16; mask <<= 1) {
const bool upper = (lane & mask) != 0;
#pragma unroll
for (int i = 0; i < 4; ++i) {
const float p = simd_shuffle_xor(v[i], ushort(mask));
v[i] = upper ? (p - v[i]) : (v[i] + p);
}
}
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] *= 0.08838834764831845f;
}
// y[row] = FWHT128(x[row]) per 128-block, rows of `n` floats; grid (n / 128 / 4, rows), 128 threads
kernel void q4m_fwht128(device const float* x [[buffer(0)]], device float* y [[buffer(1)]], constant int& n [[buffer(2)]],
uint2 gid [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
const int blk = int(gid.x) * 4 + int(tid >> 5);
if (blk * 128 >= n) return;
const uint lane = tid & 31;
const ulong at = (ulong)gid.y * n + (ulong)blk * 128 + lane * 4;
const float4 f = *(device const float4*)(x + at);
float v[4] = {f.x, f.y, f.z, f.w};
q4m_fwht128_simd(v, lane);
*(device float4*)(y + at) = float4(v[0], v[1], v[2], v[3]);
}
// gu[p][r] = W_gu(row r) . xr[token]; grid (2 n_ff / 4, P), 128 threads (a simdgroup per row)
kernel void q4m_moe_gu(device const uchar* sec4 [[buffer(0)]], device const SxDesc* desc [[buffer(1)]], device const int* ids [[buffer(2)]],
device const float* xr [[buffer(3)]], device float* gu [[buffer(4)]], constant SxArgs& a [[buffer(5)]],
uint2 gid [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
const int rows = 2 * a.n_ff;
const int row = int(gid.x) * 4 + int(tid >> 5);
if (row >= rows) return;
const int p = int(gid.y), token = p / a.topk;
const uint lane = tid & 31;
const SxDesc d = desc[a.layer_base + ids[p]];
const int nsb = a.n_embd >> 8;
device const uchar* rowp = sec4 + d.off + (ulong)(2 * a.n_ff) + (ulong)row * nsb * sk_sb_rt(d.gu_code);
float acc = sk_dot_code(d.gu_code, rowp, nsb, xr + (ulong)token * a.n_embd, lane);
acc = simd_sum(acc);
if (lane == 0) gu[(ulong)p * rows + row] = acc;
}
// act[p] = FWHT128(silu(gate) * up / S_xd); grid P, n_ff / 128 simdgroups
kernel void q4m_moe_act(device const uchar* sec4 [[buffer(0)]], device const SxDesc* desc [[buffer(1)]], device const int* ids [[buffer(2)]],
device const float* gu [[buffer(3)]], device float* act [[buffer(4)]], constant SxArgs& a [[buffer(5)]],
uint p [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
const uint lane = tid & 31, b = tid >> 5;
device const half* sxd = (device const half*)(sec4 + desc[a.layer_base + ids[p]].off);
device const float* g = gu + (ulong)p * 2 * a.n_ff;
float v[4];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const int e = int(b) * 128 + int(lane) * 4 + i;
const float gv = g[e];
v[i] = (gv / (1.0f + exp(-gv))) * g[a.n_ff + e] / float(sxd[e]);
}
q4m_fwht128_simd(v, lane);
*(device float4*)(act + (ulong)p * a.n_ff + b * 128 + lane * 4) = float4(v[0], v[1], v[2], v[3]);
}
// ye[p][r] = W_dn(row r) . act[p]; grid (n_embd / 4, P), 128 threads
kernel void q4m_moe_dn(device const uchar* sec4 [[buffer(0)]], device const SxDesc* desc [[buffer(1)]], device const int* ids [[buffer(2)]],
device const float* act [[buffer(3)]], device float* ye [[buffer(4)]], constant SxArgs& a [[buffer(5)]],
uint2 gid [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
const int row = int(gid.x) * 4 + int(tid >> 5);
if (row >= a.n_embd) return;
const int p = int(gid.y);
const uint lane = tid & 31;
const SxDesc d = desc[a.layer_base + ids[p]];
const int nsb = a.n_ff >> 8;
device const uchar* rowp = sec4 + d.off + (ulong)d.dn_off + (ulong)row * nsb * sk_sb_rt(d.dn_code);
float acc = sk_dot_code(d.dn_code, rowp, nsb, act + (ulong)p * a.n_ff, lane);
acc = simd_sum(acc);
if (lane == 0) ye[(ulong)p * a.n_embd + row] = acc;
}
// bo[t][d] = sum_k w[t][k] * ye[t * topk + k][d] + sigmoid(sg[t]) * ysh[t][d]; one thread per element
kernel void q4m_combine(device const float* ye [[buffer(0)]], device const float* w [[buffer(1)]], device const float* ysh [[buffer(2)]],
device const float* sg [[buffer(3)]], device float* bo [[buffer(4)]], constant SxArgs& a [[buffer(5)]],
uint gid [[thread_position_in_grid]]) {
const uint t = gid / a.n_embd, d = gid % a.n_embd;
if (int(t) >= a.n_tok) return;
float s = 0.0f;
for (int k = 0; k < a.topk; ++k) s += w[t * a.topk + k] * ye[((ulong)t * a.topk + k) * a.n_embd + d];
const float gs = 1.0f / (1.0f + exp(-sg[t]));
bo[gid] = fma(gs, ysh[gid], s);
}
+411
View File
@@ -0,0 +1,411 @@
// sk_codes.metal - the S_K superblock family (codes 1..8) of the .strata v1.1/v1.2 container as Metal row-dot kernels, compiled at run time.
//
// A superblock is 256 weights: fp16 D, 4 x uint8 sub-block scales u (eff = D * u / 255 per 64 weights), then the payload of the code:
// 1 S1.5 58 B 6 + 52: 5 trits per byte, base 3, digit j of byte b is weight 5b + j, value (digit - 1)
// 2..6 S2_K..S6_K: symmetric half-integer q in 0..2^bits-1, centre (2^bits - 1) / 2 removed; packing as Ling's ling32_core.metal
// 7 S2_E8P 70 B 6 + 64: per 8 weights two bytes (index into the 256 x 8 magnitude table E8P_TAB, 8 sign bits: bit j negates weight j)
// 8 S8_K 262 B 6 + 256 int8
// The arithmetic is Ling's (ling32_core.metal row_dot): a simdgroup computes NT token dot products of one row, lane = (group of 64, 8 weights).
// The expert inputs of a Qwen4 .strata file go through FWHT-128 first (the caller); nothing here transforms activations.
// E8P_TAB is the exact table of production_quant_suite/ling32_squant_codecs_v11.py _build_e8p_codebook_256 (also sq.e8p_tables in section 1 of the file).
#include <metal_stdlib>
using namespace metal;
constexpr int sk_sb_bytes(int c) { return c == 1 ? 58 : c == 2 || c == 7 ? 70 : c == 3 ? 102 : c == 4 ? 134 : c == 5 ? 166 : c == 6 ? 198 : 262; }
constant uchar E8P_TAB[2048] = {
0, 0, 0, 0, 0, 0, 0, 0, // 0
2, 2, 0, 0, 0, 0, 0, 0, // 1
2, 0, 2, 0, 0, 0, 0, 0, // 2
2, 0, 0, 2, 0, 0, 0, 0, // 3
2, 0, 0, 0, 2, 0, 0, 0, // 4
2, 0, 0, 0, 0, 2, 0, 0, // 5
2, 0, 0, 0, 0, 0, 2, 0, // 6
2, 0, 0, 0, 0, 0, 0, 2, // 7
0, 2, 2, 0, 0, 0, 0, 0, // 8
0, 2, 0, 2, 0, 0, 0, 0, // 9
0, 2, 0, 0, 2, 0, 0, 0, // 10
0, 2, 0, 0, 0, 2, 0, 0, // 11
0, 2, 0, 0, 0, 0, 2, 0, // 12
0, 2, 0, 0, 0, 0, 0, 2, // 13
0, 0, 2, 2, 0, 0, 0, 0, // 14
0, 0, 2, 0, 2, 0, 0, 0, // 15
0, 0, 2, 0, 0, 2, 0, 0, // 16
0, 0, 2, 0, 0, 0, 2, 0, // 17
0, 0, 2, 0, 0, 0, 0, 2, // 18
0, 0, 0, 2, 2, 0, 0, 0, // 19
0, 0, 0, 2, 0, 2, 0, 0, // 20
0, 0, 0, 2, 0, 0, 2, 0, // 21
0, 0, 0, 2, 0, 0, 0, 2, // 22
0, 0, 0, 0, 2, 2, 0, 0, // 23
0, 0, 0, 0, 2, 0, 2, 0, // 24
0, 0, 0, 0, 2, 0, 0, 2, // 25
0, 0, 0, 0, 0, 2, 2, 0, // 26
0, 0, 0, 0, 0, 2, 0, 2, // 27
0, 0, 0, 0, 0, 0, 2, 2, // 28
1, 1, 1, 1, 1, 1, 1, 1, // 29
4, 0, 0, 0, 0, 0, 0, 0, // 30
0, 4, 0, 0, 0, 0, 0, 0, // 31
0, 0, 4, 0, 0, 0, 0, 0, // 32
0, 0, 0, 4, 0, 0, 0, 0, // 33
0, 0, 0, 0, 4, 0, 0, 0, // 34
0, 0, 0, 0, 0, 4, 0, 0, // 35
0, 0, 0, 0, 0, 0, 4, 0, // 36
0, 0, 0, 0, 0, 0, 0, 4, // 37
2, 2, 2, 2, 0, 0, 0, 0, // 38
2, 2, 2, 0, 2, 0, 0, 0, // 39
2, 2, 2, 0, 0, 2, 0, 0, // 40
2, 2, 2, 0, 0, 0, 2, 0, // 41
2, 2, 2, 0, 0, 0, 0, 2, // 42
2, 2, 0, 2, 2, 0, 0, 0, // 43
2, 2, 0, 2, 0, 2, 0, 0, // 44
2, 2, 0, 2, 0, 0, 2, 0, // 45
2, 2, 0, 2, 0, 0, 0, 2, // 46
2, 2, 0, 0, 2, 2, 0, 0, // 47
2, 2, 0, 0, 2, 0, 2, 0, // 48
2, 2, 0, 0, 2, 0, 0, 2, // 49
2, 2, 0, 0, 0, 2, 2, 0, // 50
2, 2, 0, 0, 0, 2, 0, 2, // 51
2, 2, 0, 0, 0, 0, 2, 2, // 52
2, 0, 2, 2, 2, 0, 0, 0, // 53
2, 0, 2, 2, 0, 2, 0, 0, // 54
2, 0, 2, 2, 0, 0, 2, 0, // 55
2, 0, 2, 2, 0, 0, 0, 2, // 56
2, 0, 2, 0, 2, 2, 0, 0, // 57
2, 0, 2, 0, 2, 0, 2, 0, // 58
2, 0, 2, 0, 2, 0, 0, 2, // 59
2, 0, 2, 0, 0, 2, 2, 0, // 60
2, 0, 2, 0, 0, 2, 0, 2, // 61
2, 0, 2, 0, 0, 0, 2, 2, // 62
2, 0, 0, 2, 2, 2, 0, 0, // 63
2, 0, 0, 2, 2, 0, 2, 0, // 64
2, 0, 0, 2, 2, 0, 0, 2, // 65
2, 0, 0, 2, 0, 2, 2, 0, // 66
2, 0, 0, 2, 0, 2, 0, 2, // 67
2, 0, 0, 2, 0, 0, 2, 2, // 68
2, 0, 0, 0, 2, 2, 2, 0, // 69
2, 0, 0, 0, 2, 2, 0, 2, // 70
2, 0, 0, 0, 2, 0, 2, 2, // 71
2, 0, 0, 0, 0, 2, 2, 2, // 72
0, 2, 2, 2, 2, 0, 0, 0, // 73
0, 2, 2, 2, 0, 2, 0, 0, // 74
0, 2, 2, 2, 0, 0, 2, 0, // 75
0, 2, 2, 2, 0, 0, 0, 2, // 76
0, 2, 2, 0, 2, 2, 0, 0, // 77
0, 2, 2, 0, 2, 0, 2, 0, // 78
0, 2, 2, 0, 2, 0, 0, 2, // 79
0, 2, 2, 0, 0, 2, 2, 0, // 80
0, 2, 2, 0, 0, 2, 0, 2, // 81
0, 2, 2, 0, 0, 0, 2, 2, // 82
0, 2, 0, 2, 2, 2, 0, 0, // 83
0, 2, 0, 2, 2, 0, 2, 0, // 84
0, 2, 0, 2, 2, 0, 0, 2, // 85
0, 2, 0, 2, 0, 2, 2, 0, // 86
0, 2, 0, 2, 0, 2, 0, 2, // 87
0, 2, 0, 2, 0, 0, 2, 2, // 88
0, 2, 0, 0, 2, 2, 2, 0, // 89
0, 2, 0, 0, 2, 2, 0, 2, // 90
0, 2, 0, 0, 2, 0, 2, 2, // 91
0, 2, 0, 0, 0, 2, 2, 2, // 92
0, 0, 2, 2, 2, 2, 0, 0, // 93
0, 0, 2, 2, 2, 0, 2, 0, // 94
0, 0, 2, 2, 2, 0, 0, 2, // 95
0, 0, 2, 2, 0, 2, 2, 0, // 96
0, 0, 2, 2, 0, 2, 0, 2, // 97
0, 0, 2, 2, 0, 0, 2, 2, // 98
0, 0, 2, 0, 2, 2, 2, 0, // 99
0, 0, 2, 0, 2, 2, 0, 2, // 100
0, 0, 2, 0, 2, 0, 2, 2, // 101
0, 0, 2, 0, 0, 2, 2, 2, // 102
0, 0, 0, 2, 2, 2, 2, 0, // 103
0, 0, 0, 2, 2, 2, 0, 2, // 104
0, 0, 0, 2, 2, 0, 2, 2, // 105
0, 0, 0, 2, 0, 2, 2, 2, // 106
0, 0, 0, 0, 2, 2, 2, 2, // 107
3, 1, 1, 1, 1, 1, 1, 1, // 108
1, 3, 1, 1, 1, 1, 1, 1, // 109
1, 1, 3, 1, 1, 1, 1, 1, // 110
1, 1, 1, 3, 1, 1, 1, 1, // 111
1, 1, 1, 1, 3, 1, 1, 1, // 112
1, 1, 1, 1, 1, 3, 1, 1, // 113
1, 1, 1, 1, 1, 1, 3, 1, // 114
1, 1, 1, 1, 1, 1, 1, 3, // 115
2, 2, 2, 2, 2, 2, 0, 0, // 116
2, 2, 2, 2, 2, 0, 2, 0, // 117
2, 2, 2, 2, 2, 0, 0, 2, // 118
2, 2, 2, 2, 0, 2, 2, 0, // 119
2, 2, 2, 2, 0, 2, 0, 2, // 120
2, 2, 2, 2, 0, 0, 2, 2, // 121
2, 2, 2, 0, 2, 2, 2, 0, // 122
2, 2, 2, 0, 2, 2, 0, 2, // 123
2, 2, 2, 0, 2, 0, 2, 2, // 124
2, 2, 2, 0, 0, 2, 2, 2, // 125
2, 2, 0, 2, 2, 2, 2, 0, // 126
2, 2, 0, 2, 2, 2, 0, 2, // 127
2, 2, 0, 2, 2, 0, 2, 2, // 128
2, 2, 0, 2, 0, 2, 2, 2, // 129
2, 2, 0, 0, 2, 2, 2, 2, // 130
2, 0, 2, 2, 2, 2, 2, 0, // 131
2, 0, 2, 2, 2, 2, 0, 2, // 132
2, 0, 2, 2, 2, 0, 2, 2, // 133
2, 0, 2, 2, 0, 2, 2, 2, // 134
2, 0, 2, 0, 2, 2, 2, 2, // 135
2, 0, 0, 2, 2, 2, 2, 2, // 136
0, 2, 2, 2, 2, 2, 2, 0, // 137
0, 2, 2, 2, 2, 2, 0, 2, // 138
0, 2, 2, 2, 2, 0, 2, 2, // 139
0, 2, 2, 2, 0, 2, 2, 2, // 140
0, 2, 2, 0, 2, 2, 2, 2, // 141
0, 2, 0, 2, 2, 2, 2, 2, // 142
0, 0, 2, 2, 2, 2, 2, 2, // 143
3, 3, 1, 1, 1, 1, 1, 1, // 144
3, 1, 3, 1, 1, 1, 1, 1, // 145
3, 1, 1, 3, 1, 1, 1, 1, // 146
3, 1, 1, 1, 3, 1, 1, 1, // 147
3, 1, 1, 1, 1, 3, 1, 1, // 148
3, 1, 1, 1, 1, 1, 3, 1, // 149
3, 1, 1, 1, 1, 1, 1, 3, // 150
1, 3, 3, 1, 1, 1, 1, 1, // 151
1, 3, 1, 3, 1, 1, 1, 1, // 152
1, 3, 1, 1, 3, 1, 1, 1, // 153
1, 3, 1, 1, 1, 3, 1, 1, // 154
1, 3, 1, 1, 1, 1, 3, 1, // 155
1, 3, 1, 1, 1, 1, 1, 3, // 156
1, 1, 3, 3, 1, 1, 1, 1, // 157
1, 1, 3, 1, 3, 1, 1, 1, // 158
1, 1, 3, 1, 1, 3, 1, 1, // 159
1, 1, 3, 1, 1, 1, 3, 1, // 160
1, 1, 3, 1, 1, 1, 1, 3, // 161
1, 1, 1, 3, 3, 1, 1, 1, // 162
1, 1, 1, 3, 1, 3, 1, 1, // 163
1, 1, 1, 3, 1, 1, 3, 1, // 164
1, 1, 1, 3, 1, 1, 1, 3, // 165
1, 1, 1, 1, 3, 3, 1, 1, // 166
1, 1, 1, 1, 3, 1, 3, 1, // 167
1, 1, 1, 1, 3, 1, 1, 3, // 168
1, 1, 1, 1, 1, 3, 3, 1, // 169
1, 1, 1, 1, 1, 3, 1, 3, // 170
1, 1, 1, 1, 1, 1, 3, 3, // 171
4, 2, 0, 2, 0, 0, 0, 0, // 172
4, 2, 0, 0, 0, 2, 0, 0, // 173
4, 2, 0, 0, 0, 0, 0, 2, // 174
4, 0, 2, 0, 2, 0, 0, 0, // 175
4, 0, 2, 0, 0, 0, 2, 0, // 176
4, 0, 0, 2, 0, 2, 0, 0, // 177
4, 0, 0, 2, 0, 0, 0, 2, // 178
4, 0, 0, 0, 2, 0, 2, 0, // 179
4, 0, 0, 0, 0, 2, 0, 2, // 180
2, 4, 0, 2, 0, 0, 0, 0, // 181
2, 4, 0, 0, 0, 2, 0, 0, // 182
2, 4, 0, 0, 0, 0, 0, 2, // 183
0, 4, 2, 2, 0, 0, 0, 0, // 184
0, 4, 2, 0, 0, 2, 0, 0, // 185
0, 4, 2, 0, 0, 0, 0, 2, // 186
0, 4, 0, 2, 2, 0, 0, 0, // 187
0, 4, 0, 2, 0, 0, 2, 0, // 188
0, 4, 0, 0, 2, 2, 0, 0, // 189
0, 4, 0, 0, 2, 0, 0, 2, // 190
0, 4, 0, 0, 0, 2, 2, 0, // 191
0, 4, 0, 0, 0, 0, 2, 2, // 192
2, 0, 4, 0, 2, 0, 0, 0, // 193
2, 0, 4, 0, 0, 0, 2, 0, // 194
0, 2, 4, 2, 0, 0, 0, 0, // 195
0, 2, 4, 0, 0, 2, 0, 0, // 196
0, 2, 4, 0, 0, 0, 0, 2, // 197
0, 0, 4, 2, 0, 2, 0, 0, // 198
0, 0, 4, 2, 0, 0, 0, 2, // 199
0, 0, 4, 0, 2, 0, 2, 0, // 200
0, 0, 4, 0, 0, 2, 0, 2, // 201
2, 2, 0, 4, 0, 0, 0, 0, // 202
2, 0, 0, 4, 0, 2, 0, 0, // 203
2, 0, 0, 4, 0, 0, 0, 2, // 204
0, 2, 2, 4, 0, 0, 0, 0, // 205
0, 2, 0, 4, 2, 0, 0, 0, // 206
0, 2, 0, 4, 0, 0, 2, 0, // 207
0, 0, 2, 4, 0, 2, 0, 0, // 208
0, 0, 2, 4, 0, 0, 0, 2, // 209
0, 0, 0, 4, 2, 2, 0, 0, // 210
0, 0, 0, 4, 2, 0, 0, 2, // 211
0, 0, 0, 4, 0, 2, 2, 0, // 212
0, 0, 0, 4, 0, 0, 2, 2, // 213
2, 0, 2, 0, 4, 0, 0, 0, // 214
2, 0, 0, 0, 4, 0, 2, 0, // 215
0, 2, 0, 2, 4, 0, 0, 0, // 216
0, 2, 0, 0, 4, 2, 0, 0, // 217
0, 2, 0, 0, 4, 0, 0, 2, // 218
0, 0, 2, 0, 4, 0, 2, 0, // 219
0, 0, 0, 2, 4, 2, 0, 0, // 220
0, 0, 0, 2, 4, 0, 0, 2, // 221
0, 0, 0, 0, 4, 2, 0, 2, // 222
2, 2, 0, 0, 0, 4, 0, 0, // 223
2, 0, 0, 2, 0, 4, 0, 0, // 224
2, 0, 0, 0, 0, 4, 0, 2, // 225
0, 2, 2, 0, 0, 4, 0, 0, // 226
0, 2, 0, 0, 2, 4, 0, 0, // 227
0, 2, 0, 0, 0, 4, 2, 0, // 228
0, 0, 2, 2, 0, 4, 0, 0, // 229
0, 0, 2, 0, 0, 4, 0, 2, // 230
0, 0, 0, 2, 2, 4, 0, 0, // 231
0, 0, 0, 2, 0, 4, 2, 0, // 232
0, 0, 0, 0, 2, 4, 0, 2, // 233
0, 0, 0, 0, 0, 4, 2, 2, // 234
2, 0, 2, 0, 0, 0, 4, 0, // 235
2, 0, 0, 0, 2, 0, 4, 0, // 236
0, 2, 0, 2, 0, 0, 4, 0, // 237
0, 2, 0, 0, 0, 2, 4, 0, // 238
0, 2, 0, 0, 0, 0, 4, 2, // 239
0, 0, 2, 0, 2, 0, 4, 0, // 240
0, 0, 0, 2, 0, 2, 4, 0, // 241
0, 0, 0, 2, 0, 0, 4, 2, // 242
0, 0, 0, 0, 0, 2, 4, 2, // 243
2, 2, 0, 0, 0, 0, 0, 4, // 244
2, 0, 0, 2, 0, 0, 0, 4, // 245
2, 0, 0, 0, 0, 2, 0, 4, // 246
0, 2, 2, 0, 0, 0, 0, 4, // 247
0, 2, 0, 0, 2, 0, 0, 4, // 248
0, 2, 0, 0, 0, 0, 2, 4, // 249
0, 0, 2, 2, 0, 0, 0, 4, // 250
0, 0, 2, 0, 0, 2, 0, 4, // 251
0, 0, 0, 2, 2, 0, 0, 4, // 252
0, 0, 0, 2, 0, 0, 2, 4, // 253
0, 0, 0, 0, 2, 2, 0, 4, // 254
0, 0, 0, 0, 0, 2, 2, 4, // 255
};
// 8 consecutive weights idx0..idx0+7 (idx0 % 8 == 0) of a superblock payload `pl` (even byte address) as floats, the code's centre removed
template <int CODE>
inline void sk_load8(device const uchar* pl, int idx0, thread float* q) {
if (CODE == 8) {
device const ushort* p = (device const ushort*)(pl + idx0);
#pragma unroll
for (int i = 0; i < 4; ++i) {
const char2 c = as_type<char2>(p[i]);
q[2 * i] = float(c.x);
q[2 * i + 1] = float(c.y);
}
return;
}
if (CODE == 7) {
const ushort pr = *(device const ushort*)(pl + 2 * (idx0 >> 3));
const uint idx = pr & 255u, sg = pr >> 8;
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float m = float(E8P_TAB[idx * 8 + j]);
q[j] = ((sg >> j) & 1u) ? -m : m;
}
return;
}
if (CODE == 1) {
// weights idx0..idx0+7 live in at most three bytes: 5b .. 5b + 4
const int b0 = idx0 / 5, r0 = idx0 - b0 * 5;
uint v[3];
#pragma unroll
for (int k = 0; k < 3; ++k) v[k] = pl[b0 + k < 52 ? b0 + k : 51];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int i = r0 + j, k = i / 5, d = i - k * 5;
const uint p3 = d == 0 ? 1u : d == 1 ? 3u : d == 2 ? 9u : d == 3 ? 27u : 81u;
q[j] = float(int((v[k] / p3) % 3u) - 1);
}
return;
}
if (CODE == 2 || CODE == 3) {
const ushort u = *(device const ushort*)(pl + (idx0 >> 2));
#pragma unroll
for (int j = 0; j < 8; ++j) q[j] = float((u >> (2 * j)) & 3);
if (CODE == 3) {
const uint hb = pl[64 + (idx0 >> 3)];
#pragma unroll
for (int j = 0; j < 8; ++j) q[j] += float(((hb >> j) & 1u) << 2);
}
const float half_ = CODE == 2 ? 1.5f : 3.5f;
#pragma unroll
for (int j = 0; j < 8; ++j) q[j] -= half_;
return;
}
device const ushort* p = (device const ushort*)(pl + (idx0 >> 1));
#pragma unroll
for (int i = 0; i < 2; ++i) {
const uint u = p[i];
q[4 * i + 0] = float(u & 15u);
q[4 * i + 1] = float((u >> 4) & 15u);
q[4 * i + 2] = float((u >> 8) & 15u);
q[4 * i + 3] = float((u >> 12) & 15u);
}
if (CODE == 5) {
const uint hb = pl[128 + (idx0 >> 3)];
#pragma unroll
for (int j = 0; j < 8; ++j) q[j] += float(((hb >> j) & 1u) << 4);
} else if (CODE == 6) {
const uint h = *(device const ushort*)(pl + 128 + (idx0 >> 2));
#pragma unroll
for (int j = 0; j < 8; ++j) q[j] += float(((h >> (2 * j)) & 3u) << 4);
}
const float half_ = CODE == 4 ? 7.5f : CODE == 5 ? 15.5f : 31.5f;
#pragma unroll
for (int j = 0; j < 8; ++j) q[j] -= half_;
}
inline float sk_eff(device const uchar* blk, int g) {
const float Dh = float(as_type<half>(*(device const ushort*)blk));
return Dh * (float(blk[2 + g]) / 255.0f);
}
// a simdgroup computes NT token dot products of one weight row (nsb superblocks); x rows are K floats apart
template <int CODE, int NT>
inline void sk_row_dot(device const uchar* rowp, int nsb, device const float* x, int K, int N, int t0, uint lane, thread float* acc) {
const int g = lane >> 3, in_g = (lane & 7) * 8, idx0 = g * 64 + in_g;
constexpr int SBB = sk_sb_bytes(CODE);
for (int sb = 0; sb < nsb; ++sb) {
device const uchar* blk = rowp + sb * SBB;
const float eff = sk_eff(blk, g);
float q[8];
sk_load8<CODE>(blk + 6, idx0, q);
#pragma unroll
for (int t = 0; t < NT; ++t) {
if (t0 + t >= N) break;
device const float4* xp = (device const float4*)(x + (ulong)(t0 + t) * K + sb * 256 + idx0);
const float4 xa = xp[0], xb = xp[1];
float s = q[0] * xa.x;
s += q[1] * xa.y; s += q[2] * xa.z; s += q[3] * xa.w;
s += q[4] * xb.x; s += q[5] * xb.y; s += q[6] * xb.z; s += q[7] * xb.w;
acc[t] += eff * s;
}
}
}
// out[t][row] (+)= W_row . x_t. grid (ceil(rows / 4), ceil(N / NT)), 128 threads (4 rows, one simdgroup each)
template <int CODE, int NT>
kernel void sk_gemv(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]], device float* out [[buffer(2)]],
constant int& rows [[buffer(3)]], constant int& K [[buffer(4)]], constant int& N [[buffer(5)]],
constant int& out_stride [[buffer(6)]], constant int& accumulate [[buffer(7)]],
uint2 gid [[threadgroup_position_in_grid]], uint tid [[thread_index_in_threadgroup]]) {
const int row = int(gid.x) * 4 + int(tid >> 5);
if (row >= rows) return;
const uint lane = tid & 31;
const int t0 = int(gid.y) * NT, nsb = K >> 8;
float acc[NT];
#pragma unroll
for (int t = 0; t < NT; ++t) acc[t] = 0.0f;
sk_row_dot<CODE, NT>(W + (ulong)row * nsb * sk_sb_bytes(CODE), nsb, x, K, N, t0, lane, acc);
#pragma unroll
for (int t = 0; t < NT; ++t) acc[t] = simd_sum(acc[t]);
if (lane == 0) {
#pragma unroll
for (int t = 0; t < NT; ++t)
if (t0 + t < N) {
device float* o = out + (ulong)(t0 + t) * out_stride + row;
*o = accumulate ? *o + acc[t] : acc[t];
}
}
}
#define SK_INST(C, NT) template [[host_name("sk_gemv_" #C "_" #NT)]] kernel void sk_gemv<C, NT>(device const uchar*, device const float*, device float*, constant int&, constant int&, constant int&, constant int&, constant int&, uint2, uint);
SK_INST(1, 1) SK_INST(1, 4) SK_INST(1, 16)
SK_INST(2, 1) SK_INST(2, 4) SK_INST(2, 16)
SK_INST(3, 1) SK_INST(3, 4) SK_INST(3, 16)
SK_INST(4, 1) SK_INST(4, 4) SK_INST(4, 16)
SK_INST(5, 1) SK_INST(5, 4) SK_INST(5, 16)
SK_INST(6, 1) SK_INST(6, 4) SK_INST(6, 16)
SK_INST(7, 1) SK_INST(7, 4) SK_INST(7, 16)
SK_INST(8, 1) SK_INST(8, 4) SK_INST(8, 16)
+196
View File
@@ -0,0 +1,196 @@
// metal/probe/q4_tf_probe.cpp - teacher-forced scoring of a token list on the Metal decode window, for the Qwen4 exactness gate
// (phaseA-tests/qwen4/ref q4_drift.py). Needs the engine's process state only (the window, the PLE table), no server.
//
// q4_tf_probe <model-metal.gguf> --ple <ple-shard.gguf> --cells N --out DIR --job ID:CONT_OFFSET:ROWS:IDS.txt [--job ...] [--topk K]
//
// IDS.txt is the comma separated full_ids of one probe. The prompt tokens [0, CONT_OFFSET) go through the prompt chain (no logits);
// then the tokens [CONT_OFFSET, CONT_OFFSET + ROWS) are run in decode windows of up to 8 rows with the head on, and the logits of every row
// are written to DIR/ID.tf.bin in the Ling --jobs layout: int32 P, int32 K; int32 ids[P][K] (descending by logit); float32 logits[P][K];
// float32 lse[P] (logsumexp over the whole vocabulary). Row j is position CONT_OFFSET + j. This is teacher forcing by decode windows
// (the engine's own decode path), not one prefill pass; the log says so.
#include "strata/core/session.hpp"
#include "strata/core/geometry.hpp"
#include "strata/core/layer.hpp"
#include "strata/kernels/ngram.hpp"
#include "strata/artifact/gguf_reader.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <functional>
#include <numeric>
#include <sstream>
#include <string>
#include <vector>
namespace strata::metal_engine {
void set_model_shard(const char* shard1);
void* window_create();
bool window_init(void* w, const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int max_t, int64_t max_cells, int64_t* n_vocab, std::string& err);
bool window_run(void* w, int T, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err);
bool window_commit(void* w, int n_keep, std::string& err);
bool window_copy_logits(void* w, int t, float* host);
void window_reset(const strata::core::SessionState* ss);
bool prompt_run(const int64_t* tokens, int64_t n, int64_t pos0, const float* const* embd_rows,
const std::function<bool(const float*, int64_t, int64_t, std::string&)>& on_chunk, std::string& err);
} // namespace strata::metal_engine
namespace {
struct Job { std::string id; int64_t off = 0; int rows = 0; std::string path; };
}
int main(int argc, char** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: q4_tf_probe <model-metal.gguf> --ple F --cells N --out DIR --job ID:OFF:ROWS:IDS.txt ...\n"); return 2; }
std::string ple_path, outdir = ".";
int64_t cells = 8192;
int K = 256, bench_n = 0;
std::vector<Job> jobs;
for (int i = 2; i + 1 < argc; i += 2) {
const std::string a = argv[i];
if (a == "--ple") ple_path = argv[i + 1];
else if (a == "--cells") cells = std::atoll(argv[i + 1]);
else if (a == "--out") outdir = argv[i + 1];
else if (a == "--topk") K = std::atoi(argv[i + 1]);
else if (a == "--bench") bench_n = std::atoi(argv[i + 1]);
else if (a == "--job") {
Job j;
std::string s = argv[i + 1];
std::vector<std::string> p;
std::stringstream ss(s);
std::string t;
while (std::getline(ss, t, ':')) p.push_back(t);
if (p.size() != 4) { std::fprintf(stderr, "bad --job %s\n", s.c_str()); return 2; }
j.id = p[0]; j.off = std::atoll(p[1].c_str()); j.rows = std::atoi(p[2].c_str()); j.path = p[3];
jobs.push_back(j);
} else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; }
}
setenv("STRATA_METAL_STREAM", "0", 1);
strata::metal_engine::set_model_shard(argv[1]);
strata::core::SessionState ss;
std::string err;
strata::kernels::PleTable table;
static float dummy_f[16] = {};
static uint16_t dummy_h[16] = {};
static int32_t dummy_i[4] = {-1, -1, -1, -1};
if (!ple_path.empty()) {
strata::kernels::PleIoOptions pio;
if (!table.open(ple_path, err, pio)) { std::printf("PLE table: %s\n", err.c_str()); return 5; }
ss.ple.table = &table;
ss.ple.consts = strata::kernels::ple_artifact_consts();
{ // the model file's own PLE hash constants (generate.cpp does the same); Qwen4's head sizes are not Flash-Next's
strata::GgufFile mg(argv[1]);
strata::GgufFile mp(ple_path);
const std::string pfx = std::string(strata::model_family_arch(strata::core::kCompiledGeometry.family)) + ".";
auto arr = [&](const char* k, std::vector<uint64_t>& out) {
const strata::MetaValue* v = mp.get(pfx + k); // the PLE table's own file first
if (v == nullptr) v = mg.get(pfx + k);
if (v == nullptr || v->type != strata::MetaType::ARRAY) return false;
for (const strata::MetaValue& e : v->items) out.push_back(e.u);
return true;
};
std::vector<uint64_t> pm, pv, po;
if (arr("ple.layer_multipliers", pm) && arr("ple.head_vocab_sizes", pv) && arr("ple.head_offsets", po)) {
if (!strata::kernels::ple_consts_from_arrays(pm, pv, po, table.rows(), ss.ple.consts, err)) { std::printf("PLE constants: %s\n", err.c_str()); return 5; }
std::printf("q4_tf_probe: PLE hash constants from the model file (head 0 vocabulary %llu)\n", (unsigned long long) pv[0]);
} else {
std::printf("q4_tf_probe: the model file carries no PLE hash constants: Flash-Next's defaults\n");
}
}
ss.ple.hist = dummy_f; ss.ple.emb_dev = dummy_f; ss.ple.emb_host = dummy_f; ss.ple.scratch = dummy_f;
ss.ple.token = dummy_i; ss.ple.prev = dummy_i;
ss.ple.w.key_bf16 = dummy_h; ss.ple.w.value_bf16 = dummy_h; ss.ple.w.norm_key = dummy_f; ss.ple.w.norm_query = dummy_f;
ss.ple.w.norm_conv = dummy_f; ss.ple.w.conv1d_f16 = dummy_h;
std::printf("q4_tf_probe: PLE table %s open, %llu rows\n", ple_path.c_str(), (unsigned long long) table.rows());
} else {
std::printf("q4_tf_probe: NO PLE table (the model's n-gram block is skipped; not the real model)\n");
}
int64_t nv = 0;
void* w = strata::metal_engine::window_create();
const auto t0 = std::chrono::steady_clock::now();
if (!strata::metal_engine::window_init(w, strata::core::kCompiledGeometry, ss, 8, cells, &nv, err)) { std::printf("init failed: %s\n", err.c_str()); return 3; }
std::printf("q4_tf_probe: init ok, vocabulary %lld, %lld cells, %.0f ms; teacher forcing by decode windows of 8 rows (not one prefill pass)\n",
(long long) nv, (long long) cells, std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());
int64_t last_pos = 0;
std::vector<float> lg((size_t) nv);
std::vector<int32_t> idx((size_t) nv);
for (const Job& j : jobs) {
std::ifstream in(j.path);
std::string line;
std::getline(in, line);
std::vector<int64_t> ids;
{
std::stringstream s2(line);
std::string tok;
while (std::getline(s2, tok, ',')) if (!tok.empty()) ids.push_back(std::atoll(tok.c_str()));
}
if ((int64_t) ids.size() < j.off + j.rows) { std::printf("%s: only %zu ids for offset %lld + %d rows\n", j.id.c_str(), ids.size(), (long long) j.off, j.rows); return 6; }
if (j.off + j.rows > cells) { std::printf("%s: %lld cells needed, --cells %lld\n", j.id.c_str(), (long long) (j.off + j.rows), (long long) cells); return 6; }
const auto t1 = std::chrono::steady_clock::now();
strata::metal_engine::window_reset(&ss);
ss.ple_prev[0] = ss.ple_prev[1] = -1;
if (std::getenv("Q4_TF_WINDOW_PREFILL")) { // the prompt through decode windows of 8 (a .strata expert source has no prompt-chain MoE yet)
for (int64_t r0 = 0; r0 < j.off; r0 += 8) {
const int T = (int) std::min<int64_t>(8, j.off - r0);
int32_t win[8], out[8] = {};
for (int t = 0; t < T; ++t) win[t] = (int32_t) ids[(size_t) (r0 + t)];
if (!strata::metal_engine::window_run(w, T, win, r0, false, out, err) || !strata::metal_engine::window_commit(w, T, err)) { std::printf("%s: prefill window at %lld failed: %s\n", j.id.c_str(), (long long) r0, err.c_str()); return 6; }
}
} else if (j.off > 0 && !strata::metal_engine::prompt_run(ids.data(), j.off, 0, nullptr, nullptr, err)) { std::printf("%s: prompt failed: %s\n", j.id.c_str(), err.c_str()); return 6; }
const double t_pre = std::chrono::duration<double>(std::chrono::steady_clock::now() - t1).count();
std::vector<int32_t> oid((size_t) j.rows * K);
std::vector<float> olg((size_t) j.rows * K), lse((size_t) j.rows);
bool nan = false;
for (int r0 = 0; r0 < j.rows; r0 += 8) {
const int T = std::min(8, j.rows - r0);
int32_t win[8], out[8] = {};
for (int t = 0; t < T; ++t) win[t] = (int32_t) ids[(size_t) (j.off + r0 + t)];
if (!strata::metal_engine::window_run(w, T, win, j.off + r0, true, out, err)) { std::printf("%s: window at row %d failed: %s\n", j.id.c_str(), r0, err.c_str()); return 7; }
for (int t = 0; t < T; ++t) {
if (!strata::metal_engine::window_copy_logits(w, t, lg.data())) { std::printf("%s: no logits row %d\n", j.id.c_str(), r0 + t); return 8; }
const int r = r0 + t;
double mx = -1e300;
for (int64_t v = 0; v < nv; ++v) { if (!std::isfinite(lg[(size_t) v])) nan = true; mx = std::max(mx, (double) lg[(size_t) v]); }
double sum = 0;
for (int64_t v = 0; v < nv; ++v) sum += std::exp((double) lg[(size_t) v] - mx);
lse[(size_t) r] = (float) (mx + std::log(sum));
std::iota(idx.begin(), idx.end(), 0);
std::partial_sort(idx.begin(), idx.begin() + K, idx.end(), [&](int32_t a, int32_t b) { return lg[(size_t) a] > lg[(size_t) b] || (lg[(size_t) a] == lg[(size_t) b] && a < b); });
for (int k = 0; k < K; ++k) { oid[(size_t) r * K + k] = idx[(size_t) k]; olg[(size_t) r * K + k] = lg[(size_t) idx[(size_t) k]]; }
}
if (!strata::metal_engine::window_commit(w, T, err)) { std::printf("%s: commit failed: %s\n", j.id.c_str(), err.c_str()); return 9; }
}
last_pos = j.off + j.rows;
std::ofstream f(outdir + "/" + j.id + ".tf.bin", std::ios::binary | std::ios::trunc);
const int32_t P = j.rows, KK = K;
f.write((const char*) &P, 4); f.write((const char*) &KK, 4);
f.write((const char*) oid.data(), (std::streamsize) oid.size() * 4);
f.write((const char*) olg.data(), (std::streamsize) olg.size() * 4);
f.write((const char*) lse.data(), (std::streamsize) lse.size() * 4);
std::ofstream g(outdir + "/" + j.id + ".gen.json");
g << "{\"id\":\"" << j.id << "\",\"nan\":" << (nan ? "true" : "false") << "}\n";
std::printf("%s: prompt %lld tokens in %.2f s, %d rows, total %.2f s, nan=%d\n", j.id.c_str(), (long long) j.off, t_pre, j.rows,
std::chrono::duration<double>(std::chrono::steady_clock::now() - t1).count(), (int) nan);
std::fflush(stdout);
}
if (bench_n > 0) { // decode speed: single-token windows after the last job's context, the head on (no sampling, no host work beyond the window)
const int64_t p0 = last_pos;
int32_t tok = 1000, out = 0;
std::vector<double> ms;
for (int i = 0; i < bench_n; ++i) {
const auto tb = std::chrono::steady_clock::now();
if (!strata::metal_engine::window_run(w, 1, &tok, p0 + i, true, &out, err) || !strata::metal_engine::window_commit(w, 1, err)) { std::printf("bench window %d failed: %s\n", i, err.c_str()); return 10; }
ms.push_back(std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - tb).count());
tok = out;
}
std::sort(ms.begin(), ms.end());
double sum = 0;
for (double v : ms) sum += v;
std::printf("q4_tf_probe: bench %d single-token windows at position %lld: median %.2f ms, mean %.2f ms, p90 %.2f ms -> %.1f tok/s (median)\n", bench_n, (long long) p0, ms[ms.size() / 2], sum / ms.size(), ms[(size_t) (ms.size() * 0.9)], 1000.0 / ms[ms.size() / 2]);
}
std::printf("q4_tf_probe: ok\n");
return 0;
}
+1 -1
View File
@@ -321,7 +321,7 @@ namespace strata::kernels { void sample_tokens(const float * p0, int p1, int p2,
namespace strata::kernels { void scale_inplace(float * p0, int64_t p1, float p2, void * p3) { strata::metal_engine::missing("strata::kernels::scale_inplace"); } }
namespace strata::kernels { void scatter_rows_f32(const float * p0, float * p1, const int32_t * p2, int64_t p3, int64_t p4, void * p5) { strata::metal_engine::missing("strata::kernels::scatter_rows_f32"); } }
namespace strata::kernels { void shared_expert(const uint8_t * p0, const uint8_t * p1, const uint16_t * p2, const SForm & p3, const uint8_t * p4, const float * p5, const float * p6, const SForm & p7, const uint8_t * p8, const float * p9, const float * p10, const SForm & p11, const uint8_t * p12, const float * p13, const float * p14, const uint16_t * p15, float * p16, float * p17, int64_t p18, int64_t p19, int p20, void * p21, const float * p22, const NativeSharedWeights * p23) { strata::metal_engine::missing("strata::kernels::shared_expert"); } }
namespace strata::kernels { void shared_expert_multi(int p0, const float * p1, const uint16_t * p2, const NativeSharedWeights & p3, const uint16_t * p4, float * p5, float * p6, float * p7, float * p8, int64_t p9, int64_t p10, void * p11, const void * p12, int p13) { strata::metal_engine::missing("strata::kernels::shared_expert_multi"); } }
namespace strata::kernels { void shared_expert_multi(int p0, const float * p1, const uint16_t * p2, const NativeSharedWeights & p3, const uint16_t * p4, float * p5, float * p6, float * p7, float * p8, int64_t p9, int64_t p10, void * p11, const void * p12, int p13, int p14, int64_t p15) { strata::metal_engine::missing("strata::kernels::shared_expert_multi"); } }
namespace strata::kernels { void silu_inplace(float * p0, int64_t p1, void * p2) { strata::metal_engine::missing("strata::kernels::silu_inplace"); } }
namespace strata::kernels { void spec_draft_sample(float * p0, int p1, const int32_t * p2, const int32_t * p3, int p4, const SamplerParams * p5, int32_t * p6, int p7, int p8, const int32_t * p9, void * p10, int32_t * p11, float * p12, int32_t * p13, int p14, float p15, void * p16) { strata::metal_engine::missing("strata::kernels::spec_draft_sample"); } }
namespace strata::kernels { void topk_512_step(const float * p0, const QsaShapes & p1, int64_t p2, const int32_t * p3, int32_t * p4, void * p5) { strata::metal_engine::missing("strata::kernels::topk_512_step"); } }
+135 -2
View File
@@ -56,6 +56,7 @@ namespace strata::gpu { void* host_view(const void* device_pointer); }
#include <set>
#include <string>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/sysctl.h>
#include <mach/mach.h>
#include <thread>
@@ -451,6 +452,14 @@ private:
bool bigs_ok_ = false;
std::vector<mtl::Buffer> gstBig_, hbBig_, kqBig_, vqBig_, kscBig_, vscBig_, tailBig_, deadBig_, pooledBig_;
mtl::Buffer pleBig_, rinfo_;
// Qwen4-35B-A3B .strata (GGUF key qwen4exp.strata_experts): the dense half is in the GGUF (tools: strata_to_gguf.py), the routed experts are read
// from the owner's file by q4m_moe.metal (per-expert S_K codes 1..8, FWHT-128 convention); sx_on_ replaces the window's expert dispatches
bool sx_on_ = false;
int lsx_ = -1;
mtl::Buffer sx4_, sxd_, sxr_, sgu_;
void* sx_map_ = nullptr;
size_t sx_len_ = 0;
bool sx_open(const std::string& path, std::string& err);
size_t st_gst_ = 0, st_hist_ = 0, st_kq_ = 0, st_sc_ = 0, st_tail_ = 0, st_dead_ = 0, st_pooled_ = 0, st_ple_ = 0; // bytes between sets
// --vision: the slots' own M-RoPE tables side by side (set idx at idx * st_mrope_), so a batch row rotates by its own
// slot's table (rinfo_ row word 3: its offset in ints); allocated with the slots, only when the table is set
@@ -711,6 +720,63 @@ long repack_pid_running(const std::string& model_file) {
}
} // namespace
static constexpr int NEXP_SX = 256; // routed experts per layer of Qwen4-35B-A3B
// The routed experts of a Qwen4 .strata file: the header's section table (no zstd: the manifest is not needed), the expert directory
// (Section 3, 32-byte entries, [layer * n_expert + expert]) as the descriptor table of q4m_moe.metal, Section 4 mapped and wrapped.
bool Window::sx_open(const std::string& path, std::string& err) {
struct SxDescH { uint64_t off; int32_t gu, dn, dn_off, body; };
std::FILE* fp = std::fopen(path.c_str(), "rb");
if (!fp) { err = "metal window: cannot open the .strata experts file " + path; return false; }
uint8_t hdr[4096];
const size_t got = std::fread(hdr, 1, sizeof hdr, fp);
if (got != sizeof hdr || std::memcmp(hdr, "STRATA\0\1", 8) != 0) { std::fclose(fp); err = "metal window: " + path + " is not a .strata v1 file"; return false; }
uint16_t nsec = 0;
std::memcpy(&nsec, hdr + 14, 2);
uint64_t probe = 0;
std::memcpy(&probe, hdr + 0x10, 8);
const size_t toff = probe < 4096 ? 0x20 : 0x10;
if (nsec < 5 || nsec > 8) { std::fclose(fp); err = "metal window: unexpected section count in " + path; return false; }
uint64_t fo[8] = {}, bl[8] = {};
for (int i = 0; i < nsec; ++i) {
std::memcpy(&fo[i], hdr + toff + 64 * i, 8);
std::memcpy(&bl[i], hdr + toff + 64 * i + 8, 8);
}
const size_t n_ent = (size_t) (bl[3] / 32), want = (size_t) G_NL * (size_t) NEXP_SX;
if (n_ent != want) { std::fclose(fp); err = "metal window: the expert directory has " + std::to_string(n_ent) + " entries, expected " + std::to_string(want); return false; }
std::vector<uint8_t> dir((size_t) bl[3]);
if (std::fseek(fp, (long) fo[3], SEEK_SET) != 0 || std::fread(dir.data(), 1, dir.size(), fp) != dir.size()) { std::fclose(fp); err = "metal window: cannot read the expert directory"; return false; }
std::fclose(fp);
std::vector<SxDescH> d(n_ent);
for (size_t i = 0; i < n_ent; ++i) {
const uint8_t* e = dir.data() + 32 * i;
uint64_t off; uint32_t bb, dno;
std::memcpy(&off, e + 8, 8);
std::memcpy(&bb, e + 16, 4);
std::memcpy(&dno, e + 20, 4);
d[i] = {off, (int32_t) e[2], (int32_t) e[3], (int32_t) dno, (int32_t) bb};
const uint16_t eid = (uint16_t) (e[0] | (e[1] << 8));
if (eid != (uint16_t) (i % NEXP_SX)) { err = "metal window: the expert directory is not in layer * 256 + expert order"; return false; }
}
if (fo[4] % 16384 || bl[4] % 16384) { err = "metal window: Section 4 of " + path + " is not 16 KiB aligned"; return false; }
const int fd = ::open(path.c_str(), O_RDONLY);
if (fd < 0) { err = "metal window: cannot open " + path; return false; }
sx_map_ = ::mmap(nullptr, (size_t) bl[4], PROT_READ, MAP_PRIVATE, fd, (off_t) fo[4]);
::close(fd);
if (sx_map_ == MAP_FAILED) { sx_map_ = nullptr; err = "metal window: mmap of the experts of " + path + " failed"; return false; }
sx_len_ = (size_t) bl[4];
{ // read every page once so that no first token waits for the disk
volatile uint8_t sink = 0;
for (size_t o = 0; o < sx_len_; o += 16384) sink = sink + ((const uint8_t*) sx_map_)[o];
(void) sink;
}
sx4_ = cx_->wrap(sx_map_, sx_len_, (size_t) 8 << 20);
if (sx4_.handle == nullptr) { err = "metal window: cannot wrap the experts of " + path + " as a Metal buffer"; return false; }
sxd_ = cx_->alloc(n_ent * sizeof(SxDescH));
std::memcpy(sxd_.ptr, d.data(), n_ent * sizeof(SxDescH));
std::fprintf(stderr, "strata metal: Qwen4 .strata experts from %s (%.2f GiB, %zu experts)\n", path.c_str(), sx_len_ / 1073741824.0, n_ent);
return true;
}
bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionState& ss, const std::string& shard1,
int max_t, int64_t max_cells, std::string& err) {
ss_ = &ss;
@@ -735,6 +801,10 @@ bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionSta
}
if (!f_.open(shard1, err)) return false;
cx_ = std::make_unique<mtl::Context>();
if (const auto it = f_.meta_str.find("qwen4exp.strata_experts"); it != f_.meta_str.end()) {
sx_on_ = true;
if (!sx_open(it->second, err)) return false;
}
stream_ = ExpertStream::wanted(f_, *cx_);
g_f16_auto = f16_auto_for(f_.path, stream_); // STRATA_METAL_F16 unset: a resident IQ3_S / Q2_0 pack takes the fp16 decode windows
if (stream_) {
@@ -795,6 +865,7 @@ bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionSta
lqsa_ = cc(lib_qsa());
lsmp_ = cc(lib_sample());
lple_ = cc(lib_ple(engine_msl_dir()));
if (sx_on_) lsx_ = cx_->compile({"sk_codes.metal", "q4m_moe.metal"}, "");
}
const int MAXC = (int) std::max<int64_t>(4096, (max_cells + 64) / 4 * 4 + 64), MB = MAXC / 4 + 2;
@@ -816,6 +887,7 @@ bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionSta
zL_ = A(4 * (size_t) G_NGDN * MAXT * G_ZV); ydump_ = A(4 * MAXT * G_ZV);
keyn_ = A(4 * MAXT * G_HCD); qn_ = A(4 * MAXT * G_HCD); gated_ = A(4 * MAXT * G_HCD); normW_ = A(4 * MAXT * G_HCD);
mrope_ = A(12 * (size_t) (MAXC + 16));
if (sx_on_) { sxr_ = A(4 * (size_t) MAXT * N); sgu_ = A(4 * (size_t) MAXT * TOPK * 2 * NFF); }
bigs_ok_ = g_slot_cap > 0;
const size_t NSET = 1 + (size_t) std::max(0, g_slot_cap);
auto R256 = [](size_t b) { return (b + 255) / 256 * 256; };
@@ -1308,7 +1380,68 @@ void Window::layer(std::vector<mtl::Dispatch>& ds, int l, int ntok, int64_t pos0
gemv(ds, T(b + "ffn_up_shexp.weight"), XF_, ush_, NFF, ntok);
nb_ = true;
gemv(ds, T(b + "ffn_gate_inp_shexp.weight"), XF_, sg_, 1, ntok);
{
if (sx_on_) {
// Qwen4 .strata routed experts: the router (moe_route: ids_ / wts_), the shared expert as in the GGUF path, then q4m_moe.metal
MoeArgs a{};
a.n_embd = N;
a.n_ff = NFF;
a.n_tok = ntok;
a.topk = TOPK;
a.n_expert = nexp_;
mtl::Dispatch r;
r.p = P(lib_, "moe_route", {}, "moe_route");
r.args = {mtl::Arg::B(logits_), mtl::Arg::B(ids_), mtl::Arg::B(wts_), mtl::Arg::B(plan_), mtl::Arg::V(a)};
r.tg[0] = 512;
push(ds, r);
{
GlueArgs ga{NFF, MAXT, N, TOPK};
mtl::Dispatch d;
d.p = P(lib_, "swiglu_prep", x16c(), x16k("swiglu_prep"));
d.args = {mtl::Arg::B(gsh_), mtl::Arg::B(ush_), mtl::Arg::B(XH_.b), mtl::Arg::V(ga)};
d.grid[0] = NFF / 16;
d.grid[1] = ntok;
d.tg[0] = 16;
push(ds, d);
}
gemv(ds, T(b + "ffn_down_shexp.weight"), XH_, ysh_, N, ntok);
struct SxArgs { int32_t layer_base, topk, n_embd, n_ff, n_tok; } sa{l * nexp_, TOPK, N, NFF, ntok};
const int P_ = ntok * TOPK;
mtl::Dispatch fw;
const int nn = N;
fw.p = P(lsx_, "q4m_fwht128", {}, "q4m_fwht128");
fw.args = {mtl::Arg::B(XF_.b), mtl::Arg::B(sxr_), mtl::Arg::V(nn)}; // plane 0 of the prepared activation: the raw float x, row t at t * N
fw.grid[0] = (N / 128 + 3) / 4;
fw.grid[1] = ntok;
fw.tg[0] = 128;
push(ds, fw);
mtl::Dispatch gu;
gu.p = P(lsx_, "q4m_moe_gu", {}, "q4m_moe_gu");
gu.args = {mtl::Arg::B(sx4_), mtl::Arg::B(sxd_), mtl::Arg::B(ids_), mtl::Arg::B(sxr_), mtl::Arg::B(sgu_), mtl::Arg::V(sa)};
gu.grid[0] = (2 * NFF + 3) / 4;
gu.grid[1] = P_;
gu.tg[0] = 128;
push(ds, gu);
mtl::Dispatch ac;
ac.p = P(lsx_, "q4m_moe_act", {}, "q4m_moe_act");
ac.args = {mtl::Arg::B(sx4_), mtl::Arg::B(sxd_), mtl::Arg::B(ids_), mtl::Arg::B(sgu_), mtl::Arg::B(h_), mtl::Arg::V(sa)};
ac.grid[0] = P_;
ac.tg[0] = 32 * (NFF / 128);
push(ds, ac);
mtl::Dispatch dn;
dn.p = P(lsx_, "q4m_moe_dn", {}, "q4m_moe_dn");
dn.args = {mtl::Arg::B(sx4_), mtl::Arg::B(sxd_), mtl::Arg::B(ids_), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::V(sa)};
dn.grid[0] = (N + 3) / 4;
dn.grid[1] = P_;
dn.tg[0] = 128;
push(ds, dn);
mtl::Dispatch cb;
cb.p = P(lsx_, "q4m_combine", {}, "q4m_combine");
cb.args = {mtl::Arg::B(ye_), mtl::Arg::B(wts_), mtl::Arg::B(ysh_), mtl::Arg::B(sg_), mtl::Arg::B(bo_), mtl::Arg::V(sa)};
cb.grid[0] = (ntok * N + 255) / 256;
cb.tg[0] = 256;
push(ds, cb);
}
if (!sx_on_) {
MoeArgs a{};
const gguf::Tensor &tg_ = T(b + "ffn_gate_exps.weight"), &tu = T(b + "ffn_up_exps.weight"),
&td = T(b + "ffn_down_exps.weight");
@@ -1412,7 +1545,7 @@ void Window::layer(std::vector<mtl::Dispatch>& ds, int l, int ntok, int64_t pos0
dd.ind_off = P_IDN * 4;
push(ds, dd);
}
{
if (!sx_on_) {
GlueArgs a{N, (uint32_t) ntok, N, TOPK};
mtl::Dispatch d;
d.p = P(lib_, k_comb(), {}, k_comb());
+108
View File
@@ -0,0 +1,108 @@
// metal/tests/sk_codes_parity.cpp - sk_codes.metal (the S_K family, codes 1..8 of the .strata container) against an independent CPU decode.
// Random superblocks (small fp16 D, random sub-block scales, random payload; S1.5 bytes below 243), every code, 1 / 4 / 16 tokens, awkward
// row counts, K = 512 and 2048; the reference decodes weight by weight following ling32_squant_codecs_v11.py decode_sk_gpu and sums in double.
#include "mtl_rt.h"
#include "ref_quant.h"
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include "sk_e8p_tab.inc"
namespace {
int sbb(int c) { return c == 1 ? 58 : (c == 2 || c == 7) ? 70 : c == 3 ? 102 : c == 4 ? 134 : c == 5 ? 166 : c == 6 ? 198 : 262; }
// weight i (0..255) of a superblock, as the python decoder gives it
double weight(const uint8_t* blk, int code, int i) {
uint16_t dh;
std::memcpy(&dh, blk, 2);
const double D = ref::f16_to_f32(dh);
const int g = i / 64;
const double eff = D * (blk[2 + g] / 255.0);
const uint8_t* pl = blk + 6;
double q = 0;
if (code == 8) q = (int8_t) pl[i];
else if (code == 7) {
const int grp = i / 8, j = i % 8;
const int idx = pl[2 * grp], sg = pl[2 * grp + 1];
const double m = kE8pTab[idx * 8 + j];
q = ((sg >> j) & 1) ? -m : m;
} else if (code == 1) {
const int b = i / 5, d = i % 5;
int v = pl[b];
for (int k = 0; k < d; ++k) v /= 3;
q = (v % 3) - 1;
} else if (code == 2) {
q = ((pl[i / 4] >> (2 * (i % 4))) & 3) - 1.5;
} else if (code == 3) {
const int lo = (pl[i / 4] >> (2 * (i % 4))) & 3, hi = (pl[64 + i / 8] >> (i % 8)) & 1;
q = (lo | (hi << 2)) - 3.5;
} else if (code == 4) {
q = ((i & 1) ? (pl[i / 2] >> 4) : (pl[i / 2] & 15)) - 7.5;
} else if (code == 5) {
const int lo = (i & 1) ? (pl[i / 2] >> 4) : (pl[i / 2] & 15), hi = (pl[128 + i / 8] >> (i % 8)) & 1;
q = (lo | (hi << 4)) - 15.5;
} else {
const int lo = (i & 1) ? (pl[i / 2] >> 4) : (pl[i / 2] & 15), hi = (pl[128 + i / 4] >> (2 * (i % 4))) & 3;
q = (lo | (hi << 4)) - 31.5;
}
return q * eff;
}
} // namespace
int main() {
mtl::Context cx;
const int lib = cx.compile({"sk_codes.metal"});
std::printf("device %s\n", cx.device_name().c_str());
int fails = 0, runs = 0;
for (int code = 1; code <= 8; ++code) {
for (int K : {512, 2048}) {
for (int rows : {37, 128}) {
for (int NT : {1, 4, 16}) {
const int N = NT == 1 ? 1 : NT == 4 ? 6 : 19; // a ragged last token group
const int nsb = K / 256, SB = sbb(code);
mtl::Buffer W = cx.alloc((size_t) rows * nsb * SB), x = cx.alloc(4 * (size_t) N * K), y = cx.alloc(4 * (size_t) N * rows);
ref::Rng r(100 + code * 7 + K + rows + NT);
uint8_t* w = W.as<uint8_t>();
for (int rr = 0; rr < rows * nsb; ++rr) {
uint8_t* blk = w + (size_t) rr * SB;
const uint16_t dh = ref::f32_to_f16(0.002f + 0.004f * r.uni());
std::memcpy(blk, &dh, 2);
for (int g = 0; g < 4; ++g) blk[2 + g] = (uint8_t) (1 + r.next() % 255);
for (int b = 6; b < SB; ++b) blk[b] = (uint8_t) (r.next() & 255);
if (code == 1) for (int b = 6; b < SB; ++b) blk[b] = (uint8_t) (r.next() % 243);
}
for (size_t i = 0; i < (size_t) N * K; ++i) x.as<float>()[i] = r.sym();
mtl::Pipeline p = cx.pipeline(lib, "sk_gemv_" + std::to_string(code) + "_" + std::to_string(NT));
struct A { int rows, K, N, stride, acc; } a{rows, K, N, rows, 0};
mtl::Dispatch d;
d.p = &p;
d.args = {mtl::Arg::B(W), mtl::Arg::B(x), mtl::Arg::B(y), mtl::Arg::V(a.rows), mtl::Arg::V(a.K), mtl::Arg::V(a.N), mtl::Arg::V(a.stride), mtl::Arg::V(a.acc)};
d.grid[0] = (rows + 3) / 4; d.grid[1] = (N + NT - 1) / NT; d.tg[0] = 128;
std::vector<mtl::Dispatch> ds{d};
cx.run(ds);
double num = 0, den = 0, mx = 0;
for (int t = 0; t < N; ++t)
for (int rr = 0; rr < rows; ++rr) {
double s = 0;
for (int sb = 0; sb < nsb; ++sb)
for (int i = 0; i < 256; ++i) s += weight(w + ((size_t) rr * nsb + sb) * SB, code, i) * (double) x.as<float>()[(size_t) t * K + sb * 256 + i];
const double e = y.as<float>()[(size_t) t * rows + rr] - s;
num += e * e; den += s * s; mx = std::fmax(mx, std::fabs(e));
}
const double rel = std::sqrt(num / den);
++runs;
const bool ok = rel < 2e-6;
if (!ok) ++fails;
if (!ok || (K == 2048 && rows == 128 && NT == 16)) std::printf("code %d K %d rows %d NT %d: rel L2 %.2e max abs %.2e %s\n", code, K, rows, NT, rel, mx, ok ? "PASS" : "FAIL");
}
}
}
}
std::printf("sk_codes_parity: %d runs, %d failures\n", runs, fails);
return fails ? 1 : 0;
}
+259
View File
@@ -0,0 +1,259 @@
// generated from production_quant_suite/ling32_squant_codecs_v11.py _build_e8p_codebook_256: the 256 x 8 magnitude table (sq.e8p_tables)
static const unsigned char kE8pTab[2048] = {
0, 0, 0, 0, 0, 0, 0, 0, // 0
2, 2, 0, 0, 0, 0, 0, 0, // 1
2, 0, 2, 0, 0, 0, 0, 0, // 2
2, 0, 0, 2, 0, 0, 0, 0, // 3
2, 0, 0, 0, 2, 0, 0, 0, // 4
2, 0, 0, 0, 0, 2, 0, 0, // 5
2, 0, 0, 0, 0, 0, 2, 0, // 6
2, 0, 0, 0, 0, 0, 0, 2, // 7
0, 2, 2, 0, 0, 0, 0, 0, // 8
0, 2, 0, 2, 0, 0, 0, 0, // 9
0, 2, 0, 0, 2, 0, 0, 0, // 10
0, 2, 0, 0, 0, 2, 0, 0, // 11
0, 2, 0, 0, 0, 0, 2, 0, // 12
0, 2, 0, 0, 0, 0, 0, 2, // 13
0, 0, 2, 2, 0, 0, 0, 0, // 14
0, 0, 2, 0, 2, 0, 0, 0, // 15
0, 0, 2, 0, 0, 2, 0, 0, // 16
0, 0, 2, 0, 0, 0, 2, 0, // 17
0, 0, 2, 0, 0, 0, 0, 2, // 18
0, 0, 0, 2, 2, 0, 0, 0, // 19
0, 0, 0, 2, 0, 2, 0, 0, // 20
0, 0, 0, 2, 0, 0, 2, 0, // 21
0, 0, 0, 2, 0, 0, 0, 2, // 22
0, 0, 0, 0, 2, 2, 0, 0, // 23
0, 0, 0, 0, 2, 0, 2, 0, // 24
0, 0, 0, 0, 2, 0, 0, 2, // 25
0, 0, 0, 0, 0, 2, 2, 0, // 26
0, 0, 0, 0, 0, 2, 0, 2, // 27
0, 0, 0, 0, 0, 0, 2, 2, // 28
1, 1, 1, 1, 1, 1, 1, 1, // 29
4, 0, 0, 0, 0, 0, 0, 0, // 30
0, 4, 0, 0, 0, 0, 0, 0, // 31
0, 0, 4, 0, 0, 0, 0, 0, // 32
0, 0, 0, 4, 0, 0, 0, 0, // 33
0, 0, 0, 0, 4, 0, 0, 0, // 34
0, 0, 0, 0, 0, 4, 0, 0, // 35
0, 0, 0, 0, 0, 0, 4, 0, // 36
0, 0, 0, 0, 0, 0, 0, 4, // 37
2, 2, 2, 2, 0, 0, 0, 0, // 38
2, 2, 2, 0, 2, 0, 0, 0, // 39
2, 2, 2, 0, 0, 2, 0, 0, // 40
2, 2, 2, 0, 0, 0, 2, 0, // 41
2, 2, 2, 0, 0, 0, 0, 2, // 42
2, 2, 0, 2, 2, 0, 0, 0, // 43
2, 2, 0, 2, 0, 2, 0, 0, // 44
2, 2, 0, 2, 0, 0, 2, 0, // 45
2, 2, 0, 2, 0, 0, 0, 2, // 46
2, 2, 0, 0, 2, 2, 0, 0, // 47
2, 2, 0, 0, 2, 0, 2, 0, // 48
2, 2, 0, 0, 2, 0, 0, 2, // 49
2, 2, 0, 0, 0, 2, 2, 0, // 50
2, 2, 0, 0, 0, 2, 0, 2, // 51
2, 2, 0, 0, 0, 0, 2, 2, // 52
2, 0, 2, 2, 2, 0, 0, 0, // 53
2, 0, 2, 2, 0, 2, 0, 0, // 54
2, 0, 2, 2, 0, 0, 2, 0, // 55
2, 0, 2, 2, 0, 0, 0, 2, // 56
2, 0, 2, 0, 2, 2, 0, 0, // 57
2, 0, 2, 0, 2, 0, 2, 0, // 58
2, 0, 2, 0, 2, 0, 0, 2, // 59
2, 0, 2, 0, 0, 2, 2, 0, // 60
2, 0, 2, 0, 0, 2, 0, 2, // 61
2, 0, 2, 0, 0, 0, 2, 2, // 62
2, 0, 0, 2, 2, 2, 0, 0, // 63
2, 0, 0, 2, 2, 0, 2, 0, // 64
2, 0, 0, 2, 2, 0, 0, 2, // 65
2, 0, 0, 2, 0, 2, 2, 0, // 66
2, 0, 0, 2, 0, 2, 0, 2, // 67
2, 0, 0, 2, 0, 0, 2, 2, // 68
2, 0, 0, 0, 2, 2, 2, 0, // 69
2, 0, 0, 0, 2, 2, 0, 2, // 70
2, 0, 0, 0, 2, 0, 2, 2, // 71
2, 0, 0, 0, 0, 2, 2, 2, // 72
0, 2, 2, 2, 2, 0, 0, 0, // 73
0, 2, 2, 2, 0, 2, 0, 0, // 74
0, 2, 2, 2, 0, 0, 2, 0, // 75
0, 2, 2, 2, 0, 0, 0, 2, // 76
0, 2, 2, 0, 2, 2, 0, 0, // 77
0, 2, 2, 0, 2, 0, 2, 0, // 78
0, 2, 2, 0, 2, 0, 0, 2, // 79
0, 2, 2, 0, 0, 2, 2, 0, // 80
0, 2, 2, 0, 0, 2, 0, 2, // 81
0, 2, 2, 0, 0, 0, 2, 2, // 82
0, 2, 0, 2, 2, 2, 0, 0, // 83
0, 2, 0, 2, 2, 0, 2, 0, // 84
0, 2, 0, 2, 2, 0, 0, 2, // 85
0, 2, 0, 2, 0, 2, 2, 0, // 86
0, 2, 0, 2, 0, 2, 0, 2, // 87
0, 2, 0, 2, 0, 0, 2, 2, // 88
0, 2, 0, 0, 2, 2, 2, 0, // 89
0, 2, 0, 0, 2, 2, 0, 2, // 90
0, 2, 0, 0, 2, 0, 2, 2, // 91
0, 2, 0, 0, 0, 2, 2, 2, // 92
0, 0, 2, 2, 2, 2, 0, 0, // 93
0, 0, 2, 2, 2, 0, 2, 0, // 94
0, 0, 2, 2, 2, 0, 0, 2, // 95
0, 0, 2, 2, 0, 2, 2, 0, // 96
0, 0, 2, 2, 0, 2, 0, 2, // 97
0, 0, 2, 2, 0, 0, 2, 2, // 98
0, 0, 2, 0, 2, 2, 2, 0, // 99
0, 0, 2, 0, 2, 2, 0, 2, // 100
0, 0, 2, 0, 2, 0, 2, 2, // 101
0, 0, 2, 0, 0, 2, 2, 2, // 102
0, 0, 0, 2, 2, 2, 2, 0, // 103
0, 0, 0, 2, 2, 2, 0, 2, // 104
0, 0, 0, 2, 2, 0, 2, 2, // 105
0, 0, 0, 2, 0, 2, 2, 2, // 106
0, 0, 0, 0, 2, 2, 2, 2, // 107
3, 1, 1, 1, 1, 1, 1, 1, // 108
1, 3, 1, 1, 1, 1, 1, 1, // 109
1, 1, 3, 1, 1, 1, 1, 1, // 110
1, 1, 1, 3, 1, 1, 1, 1, // 111
1, 1, 1, 1, 3, 1, 1, 1, // 112
1, 1, 1, 1, 1, 3, 1, 1, // 113
1, 1, 1, 1, 1, 1, 3, 1, // 114
1, 1, 1, 1, 1, 1, 1, 3, // 115
2, 2, 2, 2, 2, 2, 0, 0, // 116
2, 2, 2, 2, 2, 0, 2, 0, // 117
2, 2, 2, 2, 2, 0, 0, 2, // 118
2, 2, 2, 2, 0, 2, 2, 0, // 119
2, 2, 2, 2, 0, 2, 0, 2, // 120
2, 2, 2, 2, 0, 0, 2, 2, // 121
2, 2, 2, 0, 2, 2, 2, 0, // 122
2, 2, 2, 0, 2, 2, 0, 2, // 123
2, 2, 2, 0, 2, 0, 2, 2, // 124
2, 2, 2, 0, 0, 2, 2, 2, // 125
2, 2, 0, 2, 2, 2, 2, 0, // 126
2, 2, 0, 2, 2, 2, 0, 2, // 127
2, 2, 0, 2, 2, 0, 2, 2, // 128
2, 2, 0, 2, 0, 2, 2, 2, // 129
2, 2, 0, 0, 2, 2, 2, 2, // 130
2, 0, 2, 2, 2, 2, 2, 0, // 131
2, 0, 2, 2, 2, 2, 0, 2, // 132
2, 0, 2, 2, 2, 0, 2, 2, // 133
2, 0, 2, 2, 0, 2, 2, 2, // 134
2, 0, 2, 0, 2, 2, 2, 2, // 135
2, 0, 0, 2, 2, 2, 2, 2, // 136
0, 2, 2, 2, 2, 2, 2, 0, // 137
0, 2, 2, 2, 2, 2, 0, 2, // 138
0, 2, 2, 2, 2, 0, 2, 2, // 139
0, 2, 2, 2, 0, 2, 2, 2, // 140
0, 2, 2, 0, 2, 2, 2, 2, // 141
0, 2, 0, 2, 2, 2, 2, 2, // 142
0, 0, 2, 2, 2, 2, 2, 2, // 143
3, 3, 1, 1, 1, 1, 1, 1, // 144
3, 1, 3, 1, 1, 1, 1, 1, // 145
3, 1, 1, 3, 1, 1, 1, 1, // 146
3, 1, 1, 1, 3, 1, 1, 1, // 147
3, 1, 1, 1, 1, 3, 1, 1, // 148
3, 1, 1, 1, 1, 1, 3, 1, // 149
3, 1, 1, 1, 1, 1, 1, 3, // 150
1, 3, 3, 1, 1, 1, 1, 1, // 151
1, 3, 1, 3, 1, 1, 1, 1, // 152
1, 3, 1, 1, 3, 1, 1, 1, // 153
1, 3, 1, 1, 1, 3, 1, 1, // 154
1, 3, 1, 1, 1, 1, 3, 1, // 155
1, 3, 1, 1, 1, 1, 1, 3, // 156
1, 1, 3, 3, 1, 1, 1, 1, // 157
1, 1, 3, 1, 3, 1, 1, 1, // 158
1, 1, 3, 1, 1, 3, 1, 1, // 159
1, 1, 3, 1, 1, 1, 3, 1, // 160
1, 1, 3, 1, 1, 1, 1, 3, // 161
1, 1, 1, 3, 3, 1, 1, 1, // 162
1, 1, 1, 3, 1, 3, 1, 1, // 163
1, 1, 1, 3, 1, 1, 3, 1, // 164
1, 1, 1, 3, 1, 1, 1, 3, // 165
1, 1, 1, 1, 3, 3, 1, 1, // 166
1, 1, 1, 1, 3, 1, 3, 1, // 167
1, 1, 1, 1, 3, 1, 1, 3, // 168
1, 1, 1, 1, 1, 3, 3, 1, // 169
1, 1, 1, 1, 1, 3, 1, 3, // 170
1, 1, 1, 1, 1, 1, 3, 3, // 171
4, 2, 0, 2, 0, 0, 0, 0, // 172
4, 2, 0, 0, 0, 2, 0, 0, // 173
4, 2, 0, 0, 0, 0, 0, 2, // 174
4, 0, 2, 0, 2, 0, 0, 0, // 175
4, 0, 2, 0, 0, 0, 2, 0, // 176
4, 0, 0, 2, 0, 2, 0, 0, // 177
4, 0, 0, 2, 0, 0, 0, 2, // 178
4, 0, 0, 0, 2, 0, 2, 0, // 179
4, 0, 0, 0, 0, 2, 0, 2, // 180
2, 4, 0, 2, 0, 0, 0, 0, // 181
2, 4, 0, 0, 0, 2, 0, 0, // 182
2, 4, 0, 0, 0, 0, 0, 2, // 183
0, 4, 2, 2, 0, 0, 0, 0, // 184
0, 4, 2, 0, 0, 2, 0, 0, // 185
0, 4, 2, 0, 0, 0, 0, 2, // 186
0, 4, 0, 2, 2, 0, 0, 0, // 187
0, 4, 0, 2, 0, 0, 2, 0, // 188
0, 4, 0, 0, 2, 2, 0, 0, // 189
0, 4, 0, 0, 2, 0, 0, 2, // 190
0, 4, 0, 0, 0, 2, 2, 0, // 191
0, 4, 0, 0, 0, 0, 2, 2, // 192
2, 0, 4, 0, 2, 0, 0, 0, // 193
2, 0, 4, 0, 0, 0, 2, 0, // 194
0, 2, 4, 2, 0, 0, 0, 0, // 195
0, 2, 4, 0, 0, 2, 0, 0, // 196
0, 2, 4, 0, 0, 0, 0, 2, // 197
0, 0, 4, 2, 0, 2, 0, 0, // 198
0, 0, 4, 2, 0, 0, 0, 2, // 199
0, 0, 4, 0, 2, 0, 2, 0, // 200
0, 0, 4, 0, 0, 2, 0, 2, // 201
2, 2, 0, 4, 0, 0, 0, 0, // 202
2, 0, 0, 4, 0, 2, 0, 0, // 203
2, 0, 0, 4, 0, 0, 0, 2, // 204
0, 2, 2, 4, 0, 0, 0, 0, // 205
0, 2, 0, 4, 2, 0, 0, 0, // 206
0, 2, 0, 4, 0, 0, 2, 0, // 207
0, 0, 2, 4, 0, 2, 0, 0, // 208
0, 0, 2, 4, 0, 0, 0, 2, // 209
0, 0, 0, 4, 2, 2, 0, 0, // 210
0, 0, 0, 4, 2, 0, 0, 2, // 211
0, 0, 0, 4, 0, 2, 2, 0, // 212
0, 0, 0, 4, 0, 0, 2, 2, // 213
2, 0, 2, 0, 4, 0, 0, 0, // 214
2, 0, 0, 0, 4, 0, 2, 0, // 215
0, 2, 0, 2, 4, 0, 0, 0, // 216
0, 2, 0, 0, 4, 2, 0, 0, // 217
0, 2, 0, 0, 4, 0, 0, 2, // 218
0, 0, 2, 0, 4, 0, 2, 0, // 219
0, 0, 0, 2, 4, 2, 0, 0, // 220
0, 0, 0, 2, 4, 0, 0, 2, // 221
0, 0, 0, 0, 4, 2, 0, 2, // 222
2, 2, 0, 0, 0, 4, 0, 0, // 223
2, 0, 0, 2, 0, 4, 0, 0, // 224
2, 0, 0, 0, 0, 4, 0, 2, // 225
0, 2, 2, 0, 0, 4, 0, 0, // 226
0, 2, 0, 0, 2, 4, 0, 0, // 227
0, 2, 0, 0, 0, 4, 2, 0, // 228
0, 0, 2, 2, 0, 4, 0, 0, // 229
0, 0, 2, 0, 0, 4, 0, 2, // 230
0, 0, 0, 2, 2, 4, 0, 0, // 231
0, 0, 0, 2, 0, 4, 2, 0, // 232
0, 0, 0, 0, 2, 4, 0, 2, // 233
0, 0, 0, 0, 0, 4, 2, 2, // 234
2, 0, 2, 0, 0, 0, 4, 0, // 235
2, 0, 0, 0, 2, 0, 4, 0, // 236
0, 2, 0, 2, 0, 0, 4, 0, // 237
0, 2, 0, 0, 0, 2, 4, 0, // 238
0, 2, 0, 0, 0, 0, 4, 2, // 239
0, 0, 2, 0, 2, 0, 4, 0, // 240
0, 0, 0, 2, 0, 2, 4, 0, // 241
0, 0, 0, 2, 0, 0, 4, 2, // 242
0, 0, 0, 0, 0, 2, 4, 2, // 243
2, 2, 0, 0, 0, 0, 0, 4, // 244
2, 0, 0, 2, 0, 0, 0, 4, // 245
2, 0, 0, 0, 0, 2, 0, 4, // 246
0, 2, 2, 0, 0, 0, 0, 4, // 247
0, 2, 0, 0, 2, 0, 0, 4, // 248
0, 2, 0, 0, 0, 0, 2, 4, // 249
0, 0, 2, 2, 0, 0, 0, 4, // 250
0, 0, 2, 0, 0, 2, 0, 4, // 251
0, 0, 0, 2, 2, 0, 0, 4, // 252
0, 0, 0, 2, 0, 0, 2, 4, // 253
0, 0, 0, 0, 2, 2, 0, 4, // 254
0, 0, 0, 0, 0, 2, 2, 4, // 255
};
+10
View File
@@ -692,12 +692,14 @@ void put_payload(Out& o, const SavedConversation& s, const std::vector<SessionKv
put_checkpoint(o, s.live);
o.u64(s.checkpoints.size());
for (const auto& c : s.checkpoints) put_checkpoint(o, c);
constexpr uint64_t kLoopKeyMagic = 0x4c4f4f504b455931ull; // "LOOPKEY1"
if (sources) {
o.u64(sources->size());
for (const auto& k : *sources) {
put_kv_header(o, k.format, k.cells, k.heads, k.head_dim, k.page_size, k.pooled_rows, k.idx_dim);
for (size_t part = 0; part < 5; ++part) o.source(k, part);
}
if (s.loop_key != 0) { o.u64(kLoopKeyMagic); o.u64(s.loop_key); }
return;
}
o.u64(s.kv.size());
@@ -705,6 +707,7 @@ void put_payload(Out& o, const SavedConversation& s, const std::vector<SessionKv
put_kv_header(o, k.format, k.cells, k.heads, k.head_dim, k.page_size, k.pooled_rows, k.idx_dim);
o.buffer(k.k); o.buffer(k.v); o.buffer(k.k_scale); o.buffer(k.v_scale); o.buffer(k.pooled);
}
if (s.loop_key != 0) { o.u64(kLoopKeyMagic); o.u64(s.loop_key); }
}
// ---- parsing: every count is checked against the bytes left and the caller's limits before anything is allocated
@@ -792,6 +795,13 @@ bool get_payload(In& in, SavedConversation& s) {
if (!in.buffer(k.k, 0) || !in.buffer(k.v, 1) || !in.buffer(k.k_scale, 2) || !in.buffer(k.v_scale, 3) ||
!in.buffer(k.pooled, 4)) return false;
}
s.loop_key = 0;
if (in.left == 16) {
uint64_t magic = 0, lk = 0;
if (!in.u64(magic) || !in.u64(lk)) return false;
if (magic != 0x4c4f4f504b455931ull) return in.fail("invalid trailing payload bytes");
s.loop_key = lk;
}
return true;
}
+12 -5
View File
@@ -2,6 +2,7 @@
#include "conversation_checked.hpp"
#include "conversation_copy.hpp"
#include "conversation_trace.hpp"
#include "strata/kernels/loop_adapter.hpp"
#include <chrono>
#include <cstdio>
#include <cstdlib>
@@ -140,8 +141,11 @@ bool conversation_session_sizes(const ModelGeometry& g, const SessionState& ss,
std::string& error) {
if (!conversation_state_sizes(g, z, error)) return false;
const int64_t n_gdn = g.n_gdn_layers(), n_qsa = g.n_qsa_layers();
if (ss.gdn_alloc < 0 || ss.gdn_alloc > n_gdn || ss.qsa_ord0 < 0 || ss.qsa_alloc < 0 ||
ss.qsa_ord0 > n_qsa || ss.qsa_alloc > n_qsa - ss.qsa_ord0)
// a looped adapter's extra passes carve their own rows after the stage's base range
const int64_t x_gdn = strata::kernels::loop_extra_gdn_slots(0, g.n_layers, g.qsa_interval);
const int64_t x_qsa = strata::kernels::loop_extra_qsa_slots(0, g.n_layers, g.qsa_interval);
if (ss.gdn_alloc < 0 || ss.gdn_alloc > n_gdn + x_gdn || ss.qsa_ord0 < 0 || ss.qsa_alloc < 0 ||
ss.qsa_ord0 > n_qsa || ss.qsa_alloc > n_qsa + x_qsa - ss.qsa_ord0)
return fail(error, "invalid session layer carve");
// z.gdn is n_gdn whole rows; the session holds gdn_alloc of them (all of them for the default full range)
z.gdn = n_gdn > 0 ? z.gdn / (size_t) n_gdn * (size_t) ss.gdn_alloc : 0;
@@ -588,7 +592,8 @@ bool conversation_snapshot_save(SavedConversation& image, const ConversationView
captured.live.ids = view.ids; captured.live.imgs = view.images;
const auto p1 = now();
const long cf0 = ptr ? conversation_trace::thread_minflt() : 0;
captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints, storage);
captured.cvec = view.cvec; captured.loop_key = view.loop_key;
captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints, storage);
const long ck_faults = ptr ? conversation_trace::thread_minflt() - cf0 : 0;
if (ptr) // (E1: where each copied checkpoint's running state went: faults of the whole copy, address, heap or mapping)
for (const auto& c : captured.checkpoints)
@@ -708,7 +713,8 @@ bool conversation_snapshot_sources(SavedConversation& meta, std::vector<SessionK
captured.geometry = geometry_key(g);
captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi;
captured.live.ids = view.ids; captured.live.imgs = view.images;
captured.cvec = view.cvec; captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints);
captured.cvec = view.cvec; captured.loop_key = view.loop_key;
captured.checkpoints = conversation_detail::copy_checkpoints_beating(view.checkpoints);
if (!conversation_checkpoint_save(captured.live, ss, g, error)) return false;
// STRATA_CKPT_ASYNC: the caller writes `meta` to the session file at once, so the running state's copy lands first
conversation_checkpoint_join(captured.live.gdn.data());
@@ -764,7 +770,7 @@ bool conversation_snapshot_validate(const SavedConversation& image, const Sessio
// an image holds exactly one carve's running state and K/V: same layer range or nothing
if (image.layer_lo != ss.layer_lo || image.layer_hi != ss.layer_hi)
return fail(error, "snapshot from another session layer range");
const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec};
const ConversationView view{image.live.ids, image.live.imgs, image.checkpoints, image.cvec, image.loop_key};
if (!view_validate(view, ss, g, error) || !conversation_checkpoint_validate(image.live, ss, g, error)) return false;
const size_t layers = owned_qsa(ss);
if (image.kv.size() != layers + (draft ? 1 : 0)) return fail(error, "invalid K/V layer count");
@@ -839,6 +845,7 @@ ConversationSwap conversation_snapshot_swap(ConversationSwapPlan& plan, SavedCon
captured.geometry = geometry_key(g);
captured.layer_lo = ss.layer_lo; captured.layer_hi = ss.layer_hi;
captured.cvec = active.cvec;
captured.loop_key = active.loop_key;
captured.live.ids = conversation_detail::copy_beating(active.ids);
captured.live.imgs = conversation_detail::copy_beating(active.images);
captured.checkpoints = conversation_detail::copy_checkpoints_beating(active.checkpoints);
+11 -5
View File
@@ -5,6 +5,7 @@
#include "strata/core/progress.hpp"
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/loop_adapter.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
@@ -54,8 +55,10 @@ uint64_t session_bytes(const ModelGeometry& g, int64_t max_cells, int64_t k, int
// QSA layers are `l % interval == interval-1`, so exactly `bound / interval` of them live below `bound`
const int64_t I = std::max<int64_t>(g.qsa_interval, 1);
const int64_t q_lo = layer_lo / I, q_hi = layer_hi / I;
const int64_t q_n = std::max<int64_t>(q_hi - q_lo, g.n_qsa_layers() > 0 ? 1 : 0);
const int64_t gdn_n = std::max<int64_t>((layer_hi - layer_lo) - std::max<int64_t>(q_hi - q_lo, 0), 0);
const int64_t extra_q = strata::kernels::loop_extra_qsa_slots(layer_lo, layer_hi, I);
const int64_t extra_g = strata::kernels::loop_extra_gdn_slots(layer_lo, layer_hi, I);
const int64_t q_n = std::max<int64_t>(q_hi - q_lo, g.n_qsa_layers() > 0 ? 1 : 0) + extra_q;
const int64_t gdn_n = std::max<int64_t>((layer_hi - layer_lo) - std::max<int64_t>(q_hi - q_lo, 0), 0) + extra_g;
uint64_t n = 0;
n += gdn_buffers_bytes(g);
n += (uint64_t) gdn_n * gdn_state_floats(g) * 4;
@@ -87,10 +90,12 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void
s.layer_hi = layer_hi;
const int64_t I = std::max<int64_t>(g.qsa_interval, 1);
const int64_t q_n_range = layer_hi / I - layer_lo / I;
const int64_t extra_q = strata::kernels::loop_extra_qsa_slots(layer_lo, layer_hi, I);
const int64_t extra_g = strata::kernels::loop_extra_gdn_slots(layer_lo, layer_hi, I);
s.qsa_ord0 = layer_lo / I;
s.qsa_alloc = std::max<int64_t>(q_n_range, g.n_qsa_layers() > 0 ? 1 : 0);
s.qsa_alloc = std::max<int64_t>(q_n_range, g.n_qsa_layers() > 0 ? 1 : 0) + extra_q;
s.gdn_ord0 = layer_lo - layer_lo / I;
s.gdn_alloc = std::max<int64_t>((layer_hi - layer_lo) - q_n_range, 0);
s.gdn_alloc = std::max<int64_t>((layer_hi - layer_lo) - q_n_range, 0) + extra_g;
gdn_buffers_init(g, take(gdn_buffers_bytes(g)), s.gdn);
s.gdn_state = (float*) take((uint64_t) s.gdn_alloc * gdn_state_floats(g) * 4);
@@ -102,7 +107,8 @@ uint64_t session_init(const ModelGeometry& g, int64_t max_cells, int64_t k, void
// owns the RoPE table that the others - and the prefill staging identity, and the MTP drafter - borrow.
const uint64_t first = qsa_state_bytes(g, max_cells, true), rest = qsa_state_bytes(g, max_cells, false);
s.qsa_state_arena = take(g.n_qsa_layers() > 0 ? first + (uint64_t) (s.qsa_alloc - 1) * rest : 0);
s.qsa_states = new QsaState[(size_t) g.n_qsa_layers()]();
const int64_t qsa_arr_n = std::max<int64_t>(g.n_qsa_layers() + extra_q, s.qsa_ord0 + s.qsa_alloc);
s.qsa_states = new QsaState[(size_t) qsa_arr_n]();
s.qsa_buf_arena = take(qsa_buffers_bytes(g, max_cells));
uint8_t* qp = (uint8_t*) s.qsa_state_arena;
+417 -78
View File
@@ -43,6 +43,7 @@
#include "strata/kernels/cpu/hadamard.hpp"
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/native_router.hpp"
#include "strata/kernels/router_top10.hpp"
#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/elementwise.hpp"
@@ -50,6 +51,7 @@
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/route_prior.hpp"
#include "strata/kernels/cvec.hpp"
#include "strata/kernels/loop_adapter.hpp"
#include "strata/kernels/gr.hpp"
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
@@ -784,13 +786,26 @@ Verifier::~Verifier() {
}
if (cs_) cudaStreamSynchronize(cs_);
if (sh_cs_) cudaStreamSynchronize(sh_cs_);
if (bypass_loaded_) select_loop_bypass(false);
for (auto& row : exec_)
for (auto& e : row)
if (e) cudaGraphExecDestroy(e);
for (auto& row : exec_nr_)
for (auto& e : row)
if (e) cudaGraphExecDestroy(e);
for (size_t v = 0; v < cyc_graphs_.size(); ++v) { // (the loaded visit's graphs are exec_ / exec_nr_ above)
if ((int) v == cyc_loaded_) continue;
for (auto* tab : {&cyc_graphs_[v].exec, &cyc_graphs_[v].exec_nr})
for (auto& row : *tab)
for (auto& e : row)
if (e) cudaGraphExecDestroy(e);
}
for (auto* tab : {&bypass_graphs_.exec, &bypass_graphs_.exec_nr})
for (auto& row : *tab)
for (auto& e : row)
if (e) cudaGraphExecDestroy(e);
if (commit_exec_) cudaGraphExecDestroy(commit_exec_);
if (bypass_commit_exec_) cudaGraphExecDestroy(bypass_commit_exec_);
for (auto& kv : exec_bm_)
if (kv.second) cudaGraphExecDestroy(kv.second);
for (auto& kv : commit_bm_)
@@ -835,7 +850,7 @@ Verifier::~Verifier() {
if (mk_counters_) cudaFree(mk_counters_);
if (hcount_d_) cudaFree(hcount_d_);
void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,
h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_, h_bal_, h_mk_stall_};
h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_, h_bal_, h_mk_stall_, h_cd_omega_};
for (void* h : hosts)
if (h) cudaFreeHost(h);
}
@@ -1043,6 +1058,15 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
err = "verify: the stage's layer range or its hand-off buffers are wrong";
return false;
}
if (cyclic()) {
bool ok_c = !cyc_visits_.empty() && cyc_out_.size() == cyc_visits_.size();
for (size_t j = 0; ok_c && j < cyc_visits_.size(); ++j) {
const auto& v = cyc_visits_[j];
ok_c = !v.steps.empty() && (v.embed || cyc_hand_in_ != nullptr) && (v.head || cyc_out_[j] != nullptr);
for (const auto& s : v.steps) ok_c = ok_c && s.layer >= lb_ && s.layer < le_;
}
if (!ok_c) { err = "verify: the cyclic split's visits or their hand-off buffers are wrong"; return false; }
}
const WeightRef* wo = wt.find("output.weight");
if (wo == nullptr) { err = "verify: output.weight is missing"; return false; }
n_vocab_ = wo->ne1;
@@ -1056,7 +1080,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
const uint64_t C = (uint64_t) g.ssm_conv_channels, ZV = (uint64_t) g.ssm_value_dim, HV = (uint64_t) g.ssm_v_heads;
const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv;
const uint64_t IQ = (uint64_t) g.idx_q_heads, ID = (uint64_t) g.idx_key_dim;
const uint64_t nG = (uint64_t) g.n_gdn_layers(), nQ = (uint64_t) g.n_qsa_layers();
const uint64_t nG = (uint64_t) (g.n_gdn_layers() + strata::kernels::loop_extra_gdn_slots(0, g.n_layers, g.qsa_interval));
const uint64_t nQ = (uint64_t) (g.n_qsa_layers() + strata::kernels::loop_extra_qsa_slots(0, g.n_layers, g.qsa_interval));
const uint64_t HS = (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM;
const uint64_t TS = (uint64_t) (s.idx_block - 1) * ID;
const int max_in = (int) std::max<uint64_t>(std::max<uint64_t>(N, ZV), NH * HD);
@@ -1080,6 +1105,11 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) &&
mapped(64, (void**) &h_mk_stall_, (void**) &m_mk_stall_) &&
mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_);
if (ok && strata::kernels::loop_adapter().loaded()) {
const size_t cd_cap = ((size_t) T + 3u) & ~3u; // copy_from_mapped copies multiples of 4 floats
ok = mapped(cd_cap * 4, (void**) &h_cd_omega_, (void**) &m_cd_omega_);
if (ok && h_cd_omega_ != nullptr) std::memset(h_cd_omega_, 0, cd_cap * 4);
}
if (!ok) { err = "verify: mapped staging allocation failed " + strata::core::pin_exhausted_hint(); return false; }
if (h_mk_stall_ != nullptr) *h_mk_stall_ = 0u;
if (g_megakernel() && mk_counters_ == nullptr) mk_counters_ = strata::kernels::mk_counters_alloc();
@@ -1162,15 +1192,17 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
tap_split_ = true;
std::fprintf(stderr, "strata: STRATA_TAP_FILE %s: %zu taps of %lld floats per row (layer split: gathered from every stage)\n", tap_split_path, nt_all, (long long) N);
}
if (bal_ != nullptr) { // set_pcie_balance: four stamp words per (layer, group)
if (!mapped((size_t) g.n_layers * 2 * 4 * 8, (void**) &h_bal_, (void**) &m_bal_)) {
if (bal_ != nullptr) { // set_pcie_balance: four stamp words per (step, group)
const size_t bal_n = std::max<size_t>((size_t) g.n_layers,
strata::kernels::build_loop_schedule(g.n_layers, g.qsa_interval, lb_, le_).size());
if (!mapped(bal_n * 2 * 4 * 8, (void**) &h_bal_, (void**) &m_bal_)) {
err = "verify: mapped balance stamps allocation failed";
return false;
}
bal_p_.assign((size_t) g.n_layers * 2, 0.0);
bal_nc_.assign((size_t) g.n_layers * 2, 0);
bal_np_.assign((size_t) g.n_layers * 2, 0);
bal_ok_.assign((size_t) g.n_layers * 2, 0);
bal_p_.assign(bal_n * 2, 0.0);
bal_nc_.assign(bal_n * 2, 0);
bal_np_.assign(bal_n * 2, 0);
bal_ok_.assign(bal_n * 2, 0);
bal_->on = true;
}
// the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1)
@@ -1211,6 +1243,14 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
tok_ = b.take<int32_t>(T); step_ = b.take<int32_t>(T * strata::kernels::kStepCount);
pos_ = b.take<int32_t>(T * (NH + NKV + IQ)); commit_ = b.take<int32_t>(2 + T);
ple_ = b.take<float>(T * N); emb_ = b.take<float>(T * N); R_ = b.take<float>(T * HC * N);
if (strata::kernels::loop_adapter().loaded()) {
R_anchor_ = b.take<float>(T * HC * N);
R_mprev_ = b.take<float>(T * HC * N);
R_m0_ = b.take<float>(T * HC * N);
ab_alpha_ = b.take<float>(T * HV);
ab_beta_ = b.take<float>(T * HV);
cd_omega_ = b.take<float>(((uint64_t) T + 3ull) & ~3ull);
}
mixed_ = b.take<float>(T * N); bo_ = b.take<float>(T * N);
inj_ = b.take<float>(T * HC); inj2_ = b.take<float>(T * HC);
lo_ = b.take<float>(T * (uint64_t) g.hc_lr); rs_ = b.take<float>(T * HC); xn_ = b.take<float>(T * HC * N);
@@ -1478,6 +1518,93 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState&
const float* Verifier::final_R(int t) const { return R_ + (size_t) t * (size_t) (g_->hc * g_->n_embd); }
void Verifier::cyc_select(int visit) {
if (visit == cyc_loaded_ || visit < 0 || visit >= (int) cyc_graphs_.size()) return;
CycGraphs& out = cyc_graphs_[(size_t) cyc_loaded_];
std::memcpy(out.exec, exec_, sizeof exec_);
std::memcpy(out.exec_nr, exec_nr_, sizeof exec_nr_);
std::memcpy(out.launched, launched_, sizeof launched_);
std::memcpy(out.launched_nr, launched_nr_, sizeof launched_nr_);
const CycGraphs& in = cyc_graphs_[(size_t) visit];
std::memcpy(exec_, in.exec, sizeof exec_);
std::memcpy(exec_nr_, in.exec_nr, sizeof exec_nr_);
std::memcpy(launched_, in.launched, sizeof launched_);
std::memcpy(launched_nr_, in.launched_nr, sizeof launched_nr_);
cyc_loaded_ = visit;
}
std::vector<strata::kernels::LoopStep> Verifier::cyc_owner_steps() const {
std::vector<strata::kernels::LoopStep> all;
for (const auto& v : cyc_visits_) all.insert(all.end(), v.steps.begin(), v.steps.end());
return all;
}
void Verifier::select_loop_bypass(bool bypass) {
if (bypass == bypass_loaded_) return;
if (!cyclic()) {
CycGraphs tmp;
std::memcpy(tmp.exec, exec_, sizeof exec_);
std::memcpy(tmp.exec_nr, exec_nr_, sizeof exec_nr_);
std::memcpy(tmp.launched, launched_, sizeof launched_);
std::memcpy(tmp.launched_nr, launched_nr_, sizeof launched_nr_);
std::memcpy(exec_, bypass_graphs_.exec, sizeof exec_);
std::memcpy(exec_nr_, bypass_graphs_.exec_nr, sizeof exec_nr_);
std::memcpy(launched_, bypass_graphs_.launched, sizeof launched_);
std::memcpy(launched_nr_, bypass_graphs_.launched_nr, sizeof launched_nr_);
bypass_graphs_ = tmp;
} else if (bypass) {
if (cyc_loaded_ >= 0 && cyc_loaded_ < (int) cyc_graphs_.size()) {
CycGraphs& out = cyc_graphs_[(size_t) cyc_loaded_];
std::memcpy(out.exec, exec_, sizeof exec_);
std::memcpy(out.exec_nr, exec_nr_, sizeof exec_nr_);
std::memcpy(out.launched, launched_, sizeof launched_);
std::memcpy(out.launched_nr, launched_nr_, sizeof launched_nr_);
}
std::memcpy(exec_, bypass_graphs_.exec, sizeof exec_);
std::memcpy(exec_nr_, bypass_graphs_.exec_nr, sizeof exec_nr_);
std::memcpy(launched_, bypass_graphs_.launched, sizeof launched_);
std::memcpy(launched_nr_, bypass_graphs_.launched_nr, sizeof launched_nr_);
} else {
std::memcpy(bypass_graphs_.exec, exec_, sizeof exec_);
std::memcpy(bypass_graphs_.exec_nr, exec_nr_, sizeof exec_nr_);
std::memcpy(bypass_graphs_.launched, launched_, sizeof launched_);
std::memcpy(bypass_graphs_.launched_nr, launched_nr_, sizeof launched_nr_);
if (cyc_loaded_ >= 0 && cyc_loaded_ < (int) cyc_graphs_.size()) {
const CycGraphs& in = cyc_graphs_[(size_t) cyc_loaded_];
std::memcpy(exec_, in.exec, sizeof exec_);
std::memcpy(exec_nr_, in.exec_nr, sizeof exec_nr_);
std::memcpy(launched_, in.launched, sizeof launched_);
std::memcpy(launched_nr_, in.launched_nr, sizeof launched_nr_);
} else {
std::memset(exec_, 0, sizeof exec_);
std::memset(exec_nr_, 0, sizeof exec_nr_);
std::memset(launched_, 0, sizeof launched_);
std::memset(launched_nr_, 0, sizeof launched_nr_);
}
}
std::swap(commit_exec_, bypass_commit_exec_);
bypass_loaded_ = bypass;
}
bool Verifier::set_loop_request(int passes, float cd_omega, bool cd_thinking, bool in_thinking, std::string& err) {
const auto& la = strata::kernels::loop_adapter();
const bool want_bypass = la.loaded() && passes == 1;
if (want_bypass != bypass_loaded_) {
if (!wait_commit(err)) return false;
select_loop_bypass(want_bypass);
}
loop_req_set_ = true;
loop_cd_omega_ = cd_omega;
loop_cd_thinking_ = cd_thinking;
loop_cd_in_thinking_ = in_thinking;
return next_ == nullptr || next_->set_loop_request(passes, cd_omega, cd_thinking, in_thinking, err);
}
void Verifier::set_loop_cd_in_thinking(bool in_thinking) {
loop_cd_in_thinking_ = in_thinking;
if (next_ != nullptr) next_->set_loop_cd_in_thinking(in_thinking);
}
// ================================ THE WINDOW, AS CAPTURED ================================
//
// Plan v0.3 P6 (split window): with `groups_ == 2` the window's tokens are cut into two groups A = [0, T/2 up) and
@@ -1524,7 +1651,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
return t;
};
// fork 34a35db: the GDN gates and the QSA indexer beside the projections (STRATA_SIDE_MIXER=1; 0 / unset = in line)
const int side_mixer_mode = g_side_mixer();
const bool loop_on = loop_adapter().loaded() && !bypass_loaded_;
const int side_mixer_mode = loop_on ? 0 : g_side_mixer();
const bool side_mixer = side_mixer_mode >= 1;
const bool batch_side = batch_rec_ && batch_side_mixer_on();
const bool side_proj = side_mixer_mode >= 2 && (!batch_rec_ || batch_side); // fork b063c13: the GDN gate projection, the QSA queries
@@ -1649,6 +1777,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// ---- the window's inputs, from mapped staging. With branches the steps and positions (first read by the first
// layer's mixer) cross PCIe on side 1 beside the embedding and the first hyper-connection read.
copy_i32_from_mapped(tok_, m_tok_, T, cs);
if (loop_on && cd_omega_ != nullptr && m_cd_omega_ != nullptr)
copy_from_mapped(cd_omega_, m_cd_omega_, ((int64_t) T + 3) & ~3ll, cs);
bool inputs_pending = false;
cudaStream_t in_s = cs;
if (br) {
@@ -1665,13 +1795,21 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's
// residual, pending write and inject (see set_stage)
const int64_t HB = Verifier::handoff_floats(g);
if (lb_ > 0) {
const float* hin = hand_in_ + (size_t) hrow0 * HB; // the group's rows: [R][bo][inj] contiguous
const bool cyc = cyclic() && !bypass_loaded_ && !batch_rec_;
const strata::kernels::LoopVisit* cvis = cyc ? &cyc_visits_[(size_t) cyc_visit_] : nullptr;
if (cyc ? !cvis->embed : lb_ > 0) {
const float* hin = (cyc ? cyc_hand_in_ : hand_in_) + (size_t) hrow0 * HB; // the group's rows: [R][bo][inj] contiguous
// the overlapped split: this graph was launched before the previous stage finished - wait for its hand-off
if (hflag_in_d_ != nullptr && !batch_rec_) wait_handoff(hflag_in_d_, 1u, herr_d_, g_split_wait_ns, cs);
if (hflag_in_d_ != nullptr && !batch_rec_ && !cyc) wait_handoff(hflag_in_d_, 1u, herr_d_, g_split_wait_ns, cs);
copy_from_mapped(R_, hin, (int64_t) T * HC * N, cs);
copy_from_mapped(bo_, hin + (size_t) T * HC * N, (int64_t) T * N, cs);
copy_from_mapped(inj2_, hin + (size_t) T * (HC + 1) * N, (int64_t) T * HC, cs);
// a cyclic visit on a later pass: the previous pass's core output - the residual itself on the wrap into the
// core's first stage, else relayed after the hand-off (the workspace entry overwrites R, so never an alias)
if (cyc && cvis->mprev_in == 1)
cudaMemcpyAsync(R_mprev_, R_, (size_t) T * HC * N * sizeof(float), cudaMemcpyDeviceToDevice, cs);
else if (cyc && cvis->mprev_in == 2)
copy_from_mapped(R_mprev_, hin + (size_t) T * HB, (int64_t) T * HC * N, cs);
} else if (const NativeEmbed* ne = native_embed()) { // plan v0.3 P6: the GGUF-form table
ne->gather_dev(tok_, T, emb_, cs);
broadcast_streams(emb_, R_, N, (int) HC, T, cs);
@@ -1691,20 +1829,27 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
broadcast_streams(emb_, R_, N, (int) HC, T, cs);
}
// per-layer state indices (GDN and QSA layers are numbered separately)
std::vector<int64_t> gdn_idx((size_t) g.n_layers, -1), qsa_idx((size_t) g.n_layers, -1);
{
int64_t qi = 0, gi = 0;
for (int64_t l = 0; l < g.n_layers; ++l) {
if (is_qsa_layer(g, l)) qsa_idx[(size_t) l] = qi++;
else gdn_idx[(size_t) l] = gi++;
}
}
// execution schedule (0..n_layers-1 when loop adapter is off or bypassed; expands core passes when on)
const auto loop_plan = cyc ? cvis->steps : build_loop_schedule(g.n_layers, g.qsa_interval, lb_, le_, bypass_loaded_);
// ---------------------------------------------------------------- pre(l, group): up to the ring
auto pre = [&](int64_t l, int grp) -> bool {
// ---------------------------------------------------------------- pre(sidx, group): up to the ring
auto pre = [&](size_t sidx, int grp) -> bool {
const LoopStep& stp = loop_plan[sidx];
const int64_t l = stp.layer;
const int pass = stp.pass;
const int tb = tb_[grp], te = te_[grp], n = te - tb;
stamp(l, 0, grp);
if (stp.save_anchor_before) {
cudaMemcpyAsync(R_anchor_ + (size_t) tb * HC * N, Rt(tb), (size_t) n * HC * N * sizeof(float),
cudaMemcpyDeviceToDevice, cs);
}
if (stp.run_workspace_entry) {
loop_workspace_entry(R_anchor_ + (size_t) tb * HC * N, R_mprev_ + (size_t) tb * HC * N, Rt(tb),
pass - 1, n, cs);
}
if (stp.run_cross_pass_mixer) {
loop_cross_pass_mixer(Rt(tb), R_mprev_ + (size_t) tb * HC * N, Rt(tb), pass - 1, stp.core_step, n, cs);
}
const LayerView v(wt, l);
const char* pfx[2] = {"hc_attn_", "hc_ffn_"};
const WeightRef *wn[2], *wd[2], *wu[2], *wi[2];
@@ -1715,10 +1860,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
wi[h] = need(v, (std::string(pfx[h]) + "inject.weight").c_str(), err);
if (!wn[h] || !wd[h] || !wu[h] || !wi[h]) return false;
}
// the previous layer's FFN write, folded into this layer's first read (a control vector after it has
// already applied it)
bool pending = l > 0 && !cvec().covers(l - 1);
if (l == 1 && ple_on) {
// the previous step's FFN write, folded into this step's first read (unless already materialized)
bool pending = loop_on
? (stp.pending_before && sidx > 0 && !cvec().covers(loop_plan[sidx - 1].layer))
: (l > 0 && !cvec().covers(l - 1));
if (l == 1 && pass == 0 && ple_on) {
if (grp == 0) {
if (ar_on()) wait_flag_ge(m_flag_, 1, cs);
copy_from_mapped(ple_, m_ple_, (int64_t) T * N, cs);
@@ -1891,15 +2037,21 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
if (!native_of(wqkv, v.name("attn_qkv.weight"), err) || !native_of(wg, v.name("attn_gate.weight"), err) ||
!native_of(wout, v.name("ssm_out.weight"), err))
return false;
const int64_t gi = gdn_idx[(size_t) l];
const int64_t gi = stp.gdn_slot;
float* state = ss.gdn_state + (size_t) (gi - ss.gdn_ord0) * gdn_floats;
float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
float* qkv = qkv_L_ + (size_t) gi * MT * C;
float* hb = h_L_ + (size_t) gi * MT * C;
float* gate = gate_L_ + (size_t) gi * MT * HV;
float* beta = beta_L_ + (size_t) gi * MT * HV;
const bool use_mk = g_megakernel() && mk_counters_ != nullptr && lb_ == 0 && le_ == g.n_layers &&
next_ == nullptr && !br && !sidem && !side_proj && !batch_rec_ && !self_commit &&
const bool has_gdn_l = loop_on && loop_adapter().has_gdn_lora(pass, l);
const bool has_ab_l = loop_on && (loop_adapter().has_lora(pass, l, LoopTarget::kGdnA) ||
loop_adapter().has_lora(pass, l, LoopTarget::kGdnB));
const bool gdn_sidem = sidem && !has_gdn_l;
const bool gdn_side_proj = side_proj && !has_gdn_l;
const bool gdn_br = br && !has_gdn_l;
const bool use_mk = !has_gdn_l && g_megakernel() && mk_counters_ != nullptr && lb_ == 0 && le_ == g.n_layers &&
next_ == nullptr && !gdn_br && !gdn_sidem && !gdn_side_proj && !batch_rec_ && !self_commit &&
tb == 0 && n >= 1 && n <= 8 && wqkv->native_type == 8 && wg->native_type == 8 &&
wout->native_type == 8;
if (use_mk) {
@@ -1917,7 +2069,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
stamp(l, 2, grp); stamp(l, 3, grp); stamp(l, 4, grp); stamp(l, 5, grp); stamp(l, 6, grp);
il_ready = false;
} else {
if (sidem) { // the gates (a few blocks, latency-bound) beside the projections, joined below
if (gdn_sidem) { // the gates (a few blocks, latency-bound) beside the projections, joined below
if (!branch(mfork_, cs, side_, "fork")) return false;
gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
(const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N,
@@ -1926,7 +2078,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
if (cudaEventRecord(mjoin_, side_) != cudaSuccess) { err = "verify: the GDN gates' branch could not join"; return false; }
}
if (!q8_attn) quant_in(xm, (int) N);
if (side_proj) { // the gate projection (compute-bound for i-quants) beside qkv and the conv
if (gdn_side_proj) { // the gate projection (compute-bound for i-quants) beside qkv and the conv
// the branch reads F4's interleaved copy too (written on cs before the fork; bitwise native_mmvq's
// output), and qkv is recorded before the branch's launch, so its grid is dispatched first and the
// conv / recurrence that wait for it start sooner (z is read only after the recurrence)
@@ -1942,7 +2094,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
else native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, side2_);
if (cudaEventRecord(pjoin_, side2_) != cudaSuccess) { err = "verify: the gate projection's branch could not join"; return false; }
}
if (br) { // STRATA_DF_BRANCH: a/b and z beside q/k/v and the conv; all of them read only this layer's input
if (gdn_br) { // STRATA_DF_BRANCH: a/b and z beside q/k/v and the conv; all of them read only this layer's input
fork(0);
gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
(const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N,
@@ -1951,10 +2103,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n,
df_side_[1]);
}
const bool fuse_ab = fuse_convab_on() && !br && !batch_rec_ && !prof_on_ && !sidem; // the side mixer computes the gates on its branch
strata::dispatch::notef("gdn layer: side_gates=%ld side_proj=%ld df_branch=%ld", (long) sidem, (long) side_proj, (long) br);
const bool fuse_ab = fuse_convab_on() && !gdn_br && !batch_rec_ && !prof_on_ && !gdn_sidem && !has_ab_l;
strata::dispatch::notef("gdn layer: side_gates=%ld side_proj=%ld df_branch=%ld", (long) gdn_sidem, (long) gdn_side_proj, (long) gdn_br);
strata::dispatch::notef("gdn layer: conv+ab fused=%ld batch_rows=%ld", (long) fuse_ab, (long) batch_rec_);
if (!side_proj) mm(wqkv, qkv + (size_t) tb * C, (int) N, (int) C); // with side_proj: above, first
if (!gdn_side_proj) mm(wqkv, qkv + (size_t) tb * C, (int) N, (int) C); // with side_proj: above, first
if (has_gdn_l) loop_lora_add(xm, (int) N, qkv + (size_t) tb * C, (int) C, pass, l, LoopTarget::kGdnQkv, n, cs);
stamp(l, 2, grp);
if (batch_rec_) { // contiguous rows may be proposals for the same slot
for (int t = tb; t < te;) {
@@ -1978,22 +2131,31 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb,
self_commit);
stamp(l, 3, grp);
if (br) { // gate, beta and z, before the recurrence reads them
if (gdn_br) { // gate, beta and z, before the recurrence reads them
join(0);
join(1);
} else {
if (!fuse_ab && !sidem) // the gates: the HIP fused conv kernel (143-amdk) or the side mixer's branch, else here
if (has_ab_l) {
bf16_gemv_fp32_mmvf_multi(xm, N, (const uint16_t*) wa->data, ab_alpha_ + (size_t) tb * HV, HV, N, HV, n, cs);
bf16_gemv_fp32_mmvf_multi(xm, N, (const uint16_t*) wb->data, ab_beta_ + (size_t) tb * HV, HV, N, HV, n, cs);
loop_lora_add(xm, (int) N, ab_alpha_ + (size_t) tb * HV, (int) HV, pass, l, LoopTarget::kGdnA, n, cs);
loop_lora_add(xm, (int) N, ab_beta_ + (size_t) tb * HV, (int) HV, pass, l, LoopTarget::kGdnB, n, cs);
loop_gdn_ab_epilogue(ab_alpha_ + (size_t) tb * HV, ab_beta_ + (size_t) tb * HV,
(const float*) wdt->data, (const float*) wsa->data,
gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) HV, n, cs);
} else if (!fuse_ab && !gdn_sidem) // the gates: the HIP fused conv kernel (143-amdk) or the side mixer's branch, else here
gdn_ab_multi(xm, (const uint16_t*) wa->data, (const uint16_t*) wb->data, (const float*) wdt->data,
(const float*) wsa->data, gate + (size_t) tb * HV, beta + (size_t) tb * HV, (int) N, (int) HV,
n, cs);
stamp(l, 4, grp);
if (!side_proj) mm(wg, z_ + (size_t) tb * ZV, (int) N, (int) ZV);
if (!gdn_side_proj) mm(wg, z_ + (size_t) tb * ZV, (int) N, (int) ZV);
if (has_gdn_l) loop_lora_add(xm, (int) N, z_ + (size_t) tb * ZV, (int) ZV, pass, l, LoopTarget::kGdnZ, n, cs);
stamp(l, 5, grp);
if (side_proj && cudaStreamWaitEvent(cs, pjoin_, 0) != cudaSuccess) {
if (gdn_side_proj && cudaStreamWaitEvent(cs, pjoin_, 0) != cudaSuccess) {
err = "verify: the gate projection's branch could not join";
return false;
}
if (sidem && cudaStreamWaitEvent(cs, mjoin_, 0) != cudaSuccess) {
if (gdn_sidem && cudaStreamWaitEvent(cs, mjoin_, 0) != cudaSuccess) {
err = "verify: the GDN gates' branch could not join";
return false;
}
@@ -2034,11 +2196,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
if (!g_qfuse() || batch_rec_) quant_in(y_ + (size_t) tb * ZV, (int) ZV);
else il_ready = false;
mm(wout, bo_ + tb * N, (int) ZV, (int) N);
if (has_gdn_l) loop_lora_add(y_ + (size_t) tb * ZV, (int) ZV, bo_ + (size_t) tb * N, (int) N, pass, l, LoopTarget::kGdnOut, n, cs);
}
} else {
// ======================= QSA =======================
const int64_t qi = qsa_idx[(size_t) l];
const int64_t qi = stp.qsa_slot;
const QsaState& st = ss.qsa_states[qi];
const bool has_qsa_l = loop_on && (loop_adapter().has_lora(pass, l, LoopTarget::kQsaQ) ||
loop_adapter().has_lora(pass, l, LoopTarget::kQsaK) ||
loop_adapter().has_lora(pass, l, LoopTarget::kQsaV) ||
loop_adapter().has_lora(pass, l, LoopTarget::kQsaO));
const WeightRef *wik = need(v, "indexer.k_proj.weight", err), *wq = need(v, "attn_q.weight", err),
*wk = need(v, "attn_k.weight", err), *wv = need(v, "attn_v.weight", err),
*wo = need(v, "attn_output.weight", err), *wiq = need(v, "indexer.q_proj.weight", err),
@@ -2083,7 +2250,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
if (!q8_attn) quant_in(xm, (int) N);
// STRATA_DF_BRANCH: the query side (q and its norm/RoPE/rotation on side 0, the indexer query on side 1)
// beside the K/V side; the indexer query joins before the block scores, the query before attention
const bool qbr = br && qb;
const bool qbr = br && qb && !has_qsa_l;
if (qbr) {
fork(0);
native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N,
@@ -2309,6 +2476,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD), n, ns);
else native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N,
(int) (NH * 2 * HD), n, ns);
if (has_qsa_l)
loop_lora_add(xm, (int) N, qfull_ + (size_t) tb * NH * 2 * HD, (int) (NH * 2 * HD), pass, l,
LoopTarget::kQsaQ, n, ns);
if (qb) {
if (fuse_nr) { // the q/gate split reads q straight out of the q|gate rows (stride 2 * HD)
native_qsa_rms_norm_rope(qfull_ + tb * NH * 2 * HD, (int) (2 * HD), (const float*) wqn->data,
@@ -2360,6 +2530,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
stamp(l, 7, grp);
mm(wk, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD));
mm(wv, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD));
if (has_qsa_l) {
loop_lora_add(xm, (int) N, kcur_ + (size_t) tb * NKV * HD, (int) (NKV * HD), pass, l,
LoopTarget::kQsaK, n, cs);
loop_lora_add(xm, (int) N, vcur_ + (size_t) tb * NKV * HD, (int) (NKV * HD), pass, l,
LoopTarget::kQsaV, n, cs);
}
if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV);
else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH);
if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp)
@@ -2627,11 +2803,17 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
stamp(l, 14, grp);
quant_in(attn32_ + tb * NH * HD, (int) (NH * HD));
mm(wo, bo_ + tb * N, (int) (NH * HD), (int) N);
if (has_qsa_l)
loop_lora_add(attn32_ + (size_t) tb * NH * HD, (int) (NH * HD), bo_ + (size_t) tb * N, (int) N,
pass, l, LoopTarget::kQsaO, n, cs);
}
} catch (const std::exception& e) {
err = "verify layer " + std::to_string(l) + ": " + e.what();
return false;
}
if (loop_on && loop_adapter().dual_coda) // strata_dual_coda_loop_v1: attn LoRA on the block's HC-mixed input, added to its output
loop_lora_add_gated(mixed_ + (size_t) tb * N, (int) N, bo_ + (size_t) tb * N, (int) N, pass, l,
LoopTarget::kAttn, n, cs, cd_omega_ + tb);
stamp(l, 16, grp);
const bool q8_ffn = gr_read_group(1, true, inj_, inj2_); // true: nat_xq_ holds the MoE input's q8_1 (STRATA_QFUSE)
stamp(l, 32, grp); // the profile only: the FFN-side read ends here, the router starts
@@ -2652,11 +2834,23 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
// the window's rows routed in 2 launches (one router GEMV reading the weight once, one
// top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old)
const WeightRef* w_router = v.get("ffn_gate_inp.weight");
const bool has_gate_l = loop_on && loop_adapter().has_lora(pass, l, LoopTarget::kMoeGate);
// S26 STRATA_LFUSE=1: the shared expert's gate row rides in the router GEMV launch, its sigmoid + row scale
// move into the combine, gate + up share one launch (all bitwise; resident combine path, 2-8 rows only)
const WeightRef* w_sgi = lfuse_on(n) && g_lfuse_gate() ? v.get("ffn_gate_inp_shexp.weight") : nullptr;
const WeightRef* w_sgi = (!has_gate_l && lfuse_on(n) && g_lfuse_gate()) ? v.get("ffn_gate_inp_shexp.weight") : nullptr;
bool sg_ready = false;
if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10) {
if (has_gate_l && w_router != nullptr) {
try {
bf16_gemv_fp32_mmvf_multi(mixed_ + tb * N, N, (const uint16_t*) w_router->data, logits_ + tb * NE, NE, N,
NE, n, cs);
loop_lora_add(mixed_ + (size_t) tb * N, (int) N, logits_ + (size_t) tb * NE, (int) NE, pass, l,
LoopTarget::kMoeGate, n, cs);
if (native_router_enabled() && NE == 512 && K == 10)
native_router_top10_multi(logits_ + tb * NE, ids_ + tb * K, w_ + tb * K, n, cs);
else
router_top10(logits_ + tb * NE, n, (int) NE, (int) K, ids_ + tb * K, w_ + tb * K, cs);
} catch (const std::exception& e) { err = "verify router (loop): " + std::string(e.what()); return false; }
} else if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled() && NE == 512 && K == 10) {
try {
if (w_sgi != nullptr)
sg_ready = bf16_gemv_fp32_mmvf_multi_aux(mixed_ + tb * N, N, (const uint16_t*) w_router->data,
@@ -2719,11 +2913,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
resident_plan(ids_ + tb * K, n * (int) K, (int) K, hits_.d_res + l * g.n_expert, (int) g.n_expert,
hits_.cache_base, slot_off_d_, (long long) hits_.blob,
plan_ + (size_t) grp * (size_t) (plan_i32_ + 16), (long long) max_t_ * K, skip_ + grp,
(uint32_t) ((l - lb_) * G + grp + 1), cs, nullptr, peer_autonomous_);
(uint32_t) ((int64_t) sidx * G + grp + 1), cs, nullptr, peer_autonomous_);
#if defined(STRATA_USE_HIP)
if (g_doorbell_store) // #649 A/B: the step's ring stored, not incremented over PCIe
doorbell_publish_value(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N,
m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs);
m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((int64_t) sidx * G + grp + 1), cs);
else
#endif
// #578: the helper GPUs reduce with the routing weights - publish them; set_always_publish: the rows
@@ -2770,7 +2964,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
shared_expert_multi(n, xm, sh_bf16_ + tb * N, nsw, (const uint16_t*) wgi->data, sh_gate_ + (size_t) tb * g.n_ff,
sh_up_ + (size_t) tb * g.n_ff, sh_g_ + tb, shared_ + tb * N, N, g.n_ff, sh_stream,
qdedup ? (const void*) (nat_xq_ + (size_t) tb * (N / 32) * 36) : nullptr,
(sg_ready ? 1 : 0) | (lfuse_on(n) && g_lfuse_pair() ? 2 : 0));
(sg_ready ? 1 : 0) | (lfuse_on(n) && g_lfuse_pair() ? 2 : 0),
loop_on ? pass : -1, loop_on ? l : -1);
sg_gated_[grp] = sg_ready;
} catch (const std::exception& e) {
err = std::string("verify shared expert: ") + e.what();
@@ -2804,11 +2999,14 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
const char* e = std::getenv("STRATA_FUSE_HEAD_GR");
return e && e[0] == '1';
}();
const bool fuse_head_gr = fuse_head_gr_env && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) &&
const bool fuse_head_gr = !loop_on && fuse_head_gr_env && (le_ == g.n_layers) && (head_ != nullptr && head_->loaded()) &&
!cvec().covers(g.n_layers - 1);
auto post = [&](int64_t l, int grp) -> bool {
auto post = [&](size_t sidx, int grp) -> bool {
const LoopStep& stp = loop_plan[sidx];
const int64_t l = stp.layer;
const int pass = stp.pass;
const int tb = tb_[grp], te = te_[grp], n = te - tb;
const uint32_t ring = (uint32_t) ((l - lb_) * G + grp + 1);
const uint32_t ring = (uint32_t) ((int64_t) sidx * G + grp + 1);
const int64_t cap = (int64_t) n * K, capx = (int64_t) max_t_ * K;
int32_t* pl = plan_ + (size_t) grp * (size_t) (plan_i32_ + 16);
const int32_t* p_counts = pl;
@@ -2892,7 +3090,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
wait_copy_i32_from_mapped(m_flagA_, ring, pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
} else {
if (m_bal_ != nullptr) // set_pcie_balance: the GPU's share starts as the plan arrives
wait_flag_ge_stamped(m_flagA_, ring, nullptr, m_bal_ + ((l - lb_) * 2 + grp) * 4, cs);
wait_flag_ge_stamped(m_flagA_, ring, nullptr, m_bal_ + ((int64_t) sidx * 2 + grp) * 4, cs);
else
wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan
copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs);
@@ -2903,7 +3101,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
stamp(l, 20, grp);
if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs);
else if (m_bal_ != nullptr) // set_pcie_balance: the PCIe part starts
wait_flag_ge_stamped(m_flagB_, ring, m_bal_ + ((l - lb_) * 2 + grp) * 4 + 1, nullptr, cs);
wait_flag_ge_stamped(m_flagB_, ring, m_bal_ + ((int64_t) sidx * 2 + grp) * 4 + 1, nullptr, cs);
else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped
if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging
const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs;
@@ -2936,7 +3134,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
const bool fuse_rows = fuse_rows_on() && !prof_on_ && !remote_opt_ && dec_batch && m_bal_ == nullptr; // 143-amdk
if (!fuse_rows) {
if (m_bal_ != nullptr) // set_pcie_balance: ... and ends as it waits for the CPU's rows
wait_flag_ge_stamped(m_flag_, ring, m_bal_ + ((l - lb_) * 2 + grp) * 4 + 2, nullptr, cs);
wait_flag_ge_stamped(m_flag_, ring, m_bal_ + ((int64_t) sidx * 2 + grp) * 4 + 2, nullptr, cs);
else
wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows
}
@@ -2988,8 +3186,45 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
}
if (remote_opt_) remote_opt_->combine(bo_ + tb * N, y_dummy_ + tb * N, tb, n,
device_plan_ ? skip_ + grp : nullptr, ring, cs);
if (loop_on && loop_adapter().dual_coda) // strata_dual_coda_loop_v1: mlp LoRA on the MoE's HC-mixed input, added to its output
loop_lora_add_gated(mixed_ + (size_t) tb * N, (int) N, bo_ + (size_t) tb * N, (int) N, pass, l,
LoopTarget::kMlp, n, cs, cd_omega_ + tb);
stamp(l, 24, grp);
if (tap_on_ && (!batch_rec_ || tap_batch_) && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0) {
// LoopCD-Hidden on this step's rows (the core's last layer on the last pass): a tap here takes the corrected rows
// after it, as the prompt path does. Always captured when loop_on so per-token thinking gating and per-request
// loop_cd_omega changes work without recapturing CUDA graphs (omega == 0.0f is an immediate bit-exact no-op).
const bool cd_here = loop_on && stp.save_mprev_after && pass == loop_adapter().num_passes - 1;
const bool tap_here = tap_on_ && (!batch_rec_ || tap_batch_) && l < (int64_t) tap_slot_.size() && tap_slot_[(size_t) l] >= 0 &&
loop_tap_pass(stp, loop_adapter(), bypass_loaded_);
auto tap_materialized = [&] { // the mean of the streams of rows already written (no pending FFN write)
const int64_t nt = (int64_t) tap_layers_.size();
#if defined(STRATA_HAVE_DFLASH2)
strata::kernels::df2_tap_rows(Rt(tb), tap_dev_ + ((size_t) tb * nt + (size_t) tap_slot_[(size_t) l]) * N, nt * N, N,
(int) HC, n, cs);
#else
for (int t = tb; t < te; ++t)
hc_mean_streams(Rt(t), tap_dev_ + ((size_t) t * nt + (size_t) tap_slot_[(size_t) l]) * N, N, (int) HC, cs);
#endif
};
// the core's materialized checkpoints after this step's write (and LoopCD on the last pass)
auto loop_after = [&] {
if (stp.save_anchor_after) {
cudaMemcpyAsync(R_anchor_ + (size_t) tb * HC * N, Rt(tb), (size_t) n * HC * N * sizeof(float),
cudaMemcpyDeviceToDevice, cs);
}
if (stp.save_mprev_after) {
if (pass == 0) {
cudaMemcpyAsync(R_m0_ + (size_t) tb * HC * N, Rt(tb), (size_t) n * HC * N * sizeof(float),
cudaMemcpyDeviceToDevice, cs);
}
if (cd_here)
loop_cd_hidden_per_tok(Rt(tb), R_m0_ + (size_t) tb * HC * N, Rt(tb), cd_omega_ + tb, n, cs);
cudaMemcpyAsync(R_mprev_ + (size_t) tb * HC * N, Rt(tb), (size_t) n * HC * N * sizeof(float),
cudaMemcpyDeviceToDevice, cs);
}
if (cd_here && tap_here) tap_materialized();
};
if (tap_here && !cd_here) {
// the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it), the mean of
// the hc streams, all rows of the group in one launch
const int64_t nt = (int64_t) tap_layers_.size();
@@ -3004,12 +3239,20 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
}
#endif
}
if (l == g.n_layers - 1) {
// the model's final step: the head reads the materialized rows (a core ending at the last layer runs its
// checkpoints and LoopCD on them first)
if (cyc ? (cvis->head && sidx + 1 == loop_plan.size()) : (l == g.n_layers - 1 && sidx + 1 == loop_plan.size())) {
if (!fuse_head_gr) {
if (dec_batch && !g_no_multi_gr) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs);
else for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);
if (loop_on && stp.materialize_after) loop_after();
}
} else if (loop_on && stp.materialize_after) {
if (dec_batch && !g_no_multi_gr) gr_write_multi(Rt(tb), bo_ + tb * N, inj2_ + tb * HC, gs, Rt(tb), n, cs);
else for (int t = tb; t < te; ++t) gr_write(Rt(t), bo_ + t * N, inj2_ + t * HC, gs, Rt(t), cs);
if (cvec().covers(l)) cvec_apply(Rt(tb), l, n, HC * N, nullptr, 0, nullptr, 0, false, cs);
loop_after();
} else if (cvec().covers(l)) {
cvec_apply(Rt(tb), l, n, HC * N, bo_ + tb * N, N, inj2_ + tb * HC, HC, true, cs);
}
@@ -3017,13 +3260,21 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) {
};
for (int grp = 0; grp < G; ++grp)
if (!pre(lb_, grp)) return false;
for (int64_t l = lb_; l < le_; ++l)
if (!pre(0, grp)) return false;
for (size_t sidx = 0; sidx < loop_plan.size(); ++sidx)
for (int grp = 0; grp < G; ++grp) {
if (!post(l, grp)) return false;
if (l + 1 < le_ && !pre(l + 1, grp)) return false;
if (!post(sidx, grp)) return false;
if (sidx + 1 < loop_plan.size() && !pre(sidx + 1, grp)) return false;
}
if (le_ < g.n_layers) { // a layer split's earlier stage: hand the residual on, no head
if (cyc && !cvis->head) { // a cyclic visit before the last: the materialized residual (and m_prev) on
float* hout = cyc_out_[(size_t) cyc_visit_];
copy_from_mapped(hout, R_, (int64_t) T * HC * N, cs);
copy_from_mapped(hout + (size_t) T * HC * N, bo_, (int64_t) T * N, cs);
copy_from_mapped(hout + (size_t) T * (HC + 1) * N, inj2_, (int64_t) T * HC, cs);
if (cvis->mprev_out) copy_from_mapped(hout + (size_t) T * HB, R_mprev_, (int64_t) T * HC * N, cs);
return true;
}
if (!cyc && le_ < g.n_layers) { // a layer split's earlier stage: hand the residual on, no head
float* hout = hand_out_ + (size_t) hrow0 * HB;
if (hflag_out_d_ != nullptr && !batch_rec_) { // the overlapped split: payload + the next stage's flag
handoff_publish(hout, R_, (int64_t) T * HC * N, bo_, (int64_t) T * N, inj2_, (int64_t) T * HC, hcount_d_,
@@ -3473,8 +3724,10 @@ bool Verifier::capture_commit(std::string& err) {
#else
static const bool commit_batch = [] { const char* e = std::getenv("STRATA_COMMIT_BATCH"); return !e || e[0] != '0'; }();
#endif
const bool commit_loop_on = loop_adapter().loaded() && !bypass_loaded_;
const bool commit_batch_eff = commit_batch && !commit_loop_on;
bool gdn_batched = false;
if (commit_batch) {
if (commit_batch_eff) {
int64_t n_gdn = 0;
bool norms_ok = true; // the per-layer loop checks each layer's ssm_norm.weight: keep that check
for (int64_t l = lb_; l < le_ && norms_ok; ++l)
@@ -3493,7 +3746,7 @@ bool Verifier::capture_commit(std::string& err) {
}
// the QSA layers' tail restore + indexer append, one launch for all of them (one block per layer)
bool qsa_batched = false;
if (commit_batch && ok && !g_no_batch_kv) {
if (commit_batch_eff && ok && !g_no_batch_kv) {
QsaIndexerLayers il;
int nq = 0;
int64_t mc = -1;
@@ -3518,13 +3771,19 @@ bool Verifier::capture_commit(std::string& err) {
qsa_batched = true;
}
}
for (int64_t l = lb_; l < le_ && ok; ++l) {
const auto commit_plan = (cyclic() && !bypass_loaded_)
? cyc_owner_steps()
: build_loop_schedule(g.n_layers, g.qsa_interval, lb_, le_, bypass_loaded_);
for (size_t sidx = 0; sidx < commit_plan.size() && ok; ++sidx) {
const LoopStep& stp = commit_plan[sidx];
const int64_t l = stp.layer;
const LayerView v(*wt_, l);
if (is_qsa_layer(g, l) && qsa_batched) {
++qsa_index;
} else if (!is_qsa_layer(g, l) && gdn_batched) {
++gdn_index;
} else if (!is_qsa_layer(g, l)) {
const int64_t gi = stp.gdn_slot;
if (MT > kVerifyMaxT) { // gdn_step_norm_multi takes kVerifyMaxT tokens; gdn_commit_layers takes more
err = "verify commit: windows past " + std::to_string(kVerifyMaxT) + " tokens (--lookup-max-t) need "
"the batched GDN commit (unset STRATA_COMMIT_BATCH=0, STRATA_GDN_SPLIT, STRATA_GDN_COMMIT_SPLIT=0)";
@@ -3533,27 +3792,28 @@ bool Verifier::capture_commit(std::string& err) {
}
const WeightRef* wnm = need(v, "ssm_norm.weight", err);
if (!wnm) { ok = false; break; }
float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
float* state = ss.gdn_state + (size_t) (gi - ss.gdn_ord0) * gdn_floats;
float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
const float* qkv = qkv_L_ + (size_t) gdn_index * MT * C;
const float* qkv = qkv_L_ + (size_t) gi * MT * C;
gdn_conv_commit(conv, qkv, (int) C, commit_, cs_);
gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C, (int) C, gate_L_ + (size_t) gdn_index * MT * HV,
beta_L_ + (size_t) gdn_index * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_,
gdn_step_norm_multi(state, h_L_ + (size_t) gi * MT * C, (int) C, gate_L_ + (size_t) gi * MT * HV,
beta_L_ + (size_t) gi * MT * HV, z_, (const float*) wnm->data, EPS, y_dummy_,
(int) g.ssm_k_heads, (int) HV, (int) MT, commit_, cs_,
(int) MT); // S26: t_out_begin = MT - the replay's outputs (y_dummy_) are never read
++gdn_index;
} else {
const QsaState& st = ss.qsa_states[qsa_index];
const int64_t qi = stp.qsa_slot;
const QsaState& st = ss.qsa_states[qi];
const WeightRef* wikn = need(v, "indexer.k_norm.weight", err);
if (!wikn) { ok = false; break; }
copy_from_mapped(st.idx_tail, tail_snap_ + (size_t) qsa_index * TS, TS, cs_);
copy_from_mapped(st.idx_tail, tail_snap_ + (size_t) qi * TS, TS, cs_);
const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos};
if (!g_no_batch_kv) {
native_qsa_indexer_append_steps(idx_raw_L_ + (size_t) qsa_index * MT * ID, commit_ + 2, 1, (int) MT, 0,
native_qsa_indexer_append_steps(idx_raw_L_ + (size_t) qi * MT * ID, commit_ + 2, 1, (int) MT, 0,
(const float*) wikn->data, EPS, ib, s, st.max_cells, rope_scaling(), cs_);
} else {
for (int64_t t = 0; t < MT; ++t)
native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0,
native_qsa_indexer_append(idx_raw_L_ + (size_t) (qi * MT + t) * ID, commit_ + 2 + t, 0,
(const float*) wikn->data, EPS, ib, s, st.max_cells,
rope_scaling(), cs_);
}
@@ -3597,6 +3857,13 @@ void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) {
for (int64_t h = 0; h < g.n_head_kv; ++h) pk[t * g.n_head_kv + h] = pos_t;
for (int64_t h = 0; h < g.idx_q_heads; ++h) pi[t * g.idx_q_heads + h] = pos_t;
}
if (h_cd_omega_ != nullptr) {
const auto& la = strata::kernels::loop_adapter();
const float om = (la.loaded() && !bypass_loaded_) ? (loop_req_set_ ? loop_cd_omega_ : la.cd_omega) : 0.0f;
const bool th = loop_req_set_ ? loop_cd_thinking_ : la.cd_thinking;
strata::kernels::loop_cd_fill_omega(tokens, T, om, th, la.think_start_id, la.think_end_id,
loop_cd_in_thinking_, h_cd_omega_);
}
*(volatile uint32_t*) h_seq_ = 0;
*(volatile uint32_t*) h_flag_ = 0;
*(volatile uint32_t*) h_flagA_ = 0;
@@ -3726,7 +3993,7 @@ bool Verifier::handoff_failed(std::string& err) const {
}
bool Verifier::chain_overlap() const {
return next_ != nullptr && hflag_out_h_ != nullptr && hflag_out_d_ != nullptr && hcount_d_ != nullptr &&
return next_ != nullptr && !cyclic() && hflag_out_h_ != nullptr && hflag_out_d_ != nullptr && hcount_d_ != nullptr &&
next_->hflag_in_h_ == hflag_out_h_ && next_->device_ != device_ && !next_->ple_stage();
}
@@ -3844,6 +4111,18 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
const OnDevice on_device(device_);
last_batch_ = false;
split_logits_materialized_ = false;
// a cyclic split: which hop of the itinerary this call runs (the caller enters at the first)
const int hop = (cyclic() && !bypass_loaded_) ? (cyc_entered_ ? cyc_hop_ : 0) : -1;
cyc_entered_ = false;
if (hop >= 0) {
if (hop >= (int) cyc_hops_->size() || (*cyc_hops_)[(size_t) hop].ver != this) {
err = "verify: the cyclic split's itinerary does not start on this stage";
return false;
}
cyc_visit_ = (*cyc_hops_)[(size_t) hop].visit;
cyc_select(cyc_visit_);
}
const LoopVisit* cvis = hop >= 0 ? &cyc_visits_[(size_t) cyc_visit_] : nullptr;
if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; }
// a layer split's hand-off buffers hold kVerifyMaxT rows
if (T > kVerifyMaxT && (next_ != nullptr || lb_ > 0)) { err = "verify: windows past 8 tokens need one stage"; return false; }
@@ -3871,7 +4150,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
const Clock::time_point t0 = Clock::now();
if (!pre && !staged_) stage_inputs(T, tokens, pos0);
staged_ = false;
const bool do_ple = ss.ple.ready() && ple_stage();
const bool do_ple = ss.ple.ready() && ple_stage() && (cvis == nullptr || cvis->ple);
uint32_t ple_rows[kVerifyLongT * PLE_N_HEADS];
if (do_ple) {
int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]};
@@ -4018,7 +4297,10 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
volatile uint32_t* const flag = h_flag_;
const int G = groups_[T] > 0 ? groups_[T] : 1;
const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T};
const int64_t steps = (le_ - lb_) * G;
const auto run_plan = cvis != nullptr ? cvis->steps
: strata::kernels::build_loop_schedule(g.n_layers, g.qsa_interval, lb_, le_,
bypass_loaded_);
const int64_t steps = (int64_t) run_plan.size() * G;
if (ar_on() && !test_stall) {
if (flag_raised) {
// up before the launch (early_ple_flag_mode)
@@ -4036,7 +4318,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
// PLE rows already gathered before graph and peer launch
} else
for (int64_t k = 0; k < steps; ++k) {
const int64_t l = lb_ + k / G;
const int64_t l = run_plan[(size_t) (k / G)].layer;
const int grp = (int) (k % G);
const uint32_t want = (uint32_t) (k + 1);
const Clock::time_point a = Clock::now();
@@ -4231,7 +4513,16 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
// own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to
// the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever
// the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw.
if (le_ < g.n_layers) { // a layer split's earlier stage: the hand-off is written (synced above)
if (cvis != nullptr && !cvis->head) { // a cyclic visit before the last: the next hop reads its hand-off
if (cvis->owner_first) ++windows;
Verifier* nv = (*cyc_hops_)[(size_t) hop + 1].ver;
nv->cyc_hop_ = hop + 1;
nv->cyc_entered_ = true;
if (!nv->run(T, tokens, pos0, pool, user, out, err)) return false;
if (hop == 0 && tap_split_ && !batch_rec_) tap_write(T, tokens, pos0);
return true;
}
if (cvis == nullptr && le_ < g.n_layers) { // a layer split's earlier stage: the hand-off is written (synced above)
++windows;
if (next_ != nullptr && !next_->run(T, tokens, pos0, pool, next_user_, out, err)) return false;
// a layer split's first stage owns STRATA_TAP_FILE: it writes once the rest of the chain has run
@@ -4340,9 +4631,13 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool,
VDBG("window done\n");
if (megakernel_stall_take()) {
megakernel_off();
if (hop >= 0) { // the replay is this hop's, not the itinerary's first
cyc_hop_ = hop;
cyc_entered_ = true;
}
return run(T, tokens, pos0, pool, user, out, err);
}
++windows;
if (cvis == nullptr || cvis->owner_first) ++windows;
progress_at("decode");
progress_beat();
return true;
@@ -4363,12 +4658,26 @@ void Verifier::megakernel_off() {
const OnDevice on(device_);
if (cs_) (void) cudaStreamSynchronize(cs_);
mk_in_graph_ = false;
const bool was_bypass = bypass_loaded_;
if (was_bypass) select_loop_bypass(false);
for (auto& row : exec_)
for (auto& e : row)
if (e != nullptr) { (void) cudaGraphExecDestroy(e); e = nullptr; }
for (auto& row : exec_nr_)
for (auto& e : row)
if (e != nullptr) { (void) cudaGraphExecDestroy(e); e = nullptr; }
for (size_t v = 0; v < cyc_graphs_.size(); ++v) {
if ((int) v == cyc_loaded_) { cyc_graphs_[v] = CycGraphs{}; continue; }
for (auto* tab : {&cyc_graphs_[v].exec, &cyc_graphs_[v].exec_nr})
for (auto& row : *tab)
for (auto& e : row)
if (e != nullptr) { (void) cudaGraphExecDestroy(e); e = nullptr; }
}
for (auto* tab : {&bypass_graphs_.exec, &bypass_graphs_.exec_nr})
for (auto& row : *tab)
for (auto& e : row)
if (e != nullptr) { (void) cudaGraphExecDestroy(e); e = nullptr; }
if (was_bypass) select_loop_bypass(true);
}
// set_pcie_balance: each stamped step's times into the model's fits (PcieModel::sample), solved once a window.
@@ -4629,6 +4938,11 @@ bool Verifier::commit(int n_keep, std::string& err) {
ss_->ple_prev[0] = ss_->ple_prev[1];
ss_->ple_prev[1] = last_tokens_[t];
}
if (h_cd_omega_ != nullptr) {
const auto& la = strata::kernels::loop_adapter();
loop_cd_in_thinking_ = strata::kernels::loop_think_state_after(
last_tokens_, n_keep, la.think_start_id, la.think_end_id, loop_cd_in_thinking_);
}
ms_commit += ms_since(t0);
return next_ == nullptr || next_->commit(n_keep, err);
}
@@ -4667,6 +4981,10 @@ bool Verifier::init_slots(const std::vector<SessionState*>& slots, std::string&
err = "verify: init_slots needs at least one session";
return false;
}
if (cyclic()) {
err = "verify: batch windows do not run on a cyclic layer split";
return false;
}
for (SessionState* x : slots) {
if (x == nullptr || x->layer_lo != ss_->layer_lo || x->layer_hi != ss_->layer_hi ||
x->max_cells != ss_->max_cells || x->gdn_ord0 != ss_->gdn_ord0 || x->qsa_ord0 != ss_->qsa_ord0) {
@@ -5133,6 +5451,24 @@ bool Verifier::drop_window_graphs(int& dropped, std::string& err) {
err = "verify: synchronizing before dropping the window graphs failed";
return false;
}
const bool was_bypass = bypass_loaded_;
if (was_bypass) select_loop_bypass(false);
auto drop_bank = [&](CycGraphs& bank, bool destroy) {
for (int s = 0; s < 2; ++s)
for (int t = 0; t <= strata::kernels::kVerifyLongT; ++t) {
if (destroy) {
for (cudaGraphExec_t* e : {&bank.exec[s][t], &bank.exec_nr[s][t]})
if (*e != nullptr) {
(void) cudaGraphExecDestroy(*e);
*e = nullptr;
++dropped;
}
} else {
bank.exec[s][t] = bank.exec_nr[s][t] = nullptr;
}
bank.launched[s][t] = bank.launched_nr[s][t] = false;
}
};
for (int s = 0; s < 2; ++s)
for (int t = 0; t <= strata::kernels::kVerifyLongT; ++t) {
for (cudaGraphExec_t* e : {&exec_[s][t], &exec_nr_[s][t]})
@@ -5143,6 +5479,9 @@ bool Verifier::drop_window_graphs(int& dropped, std::string& err) {
}
launched_[s][t] = launched_nr_[s][t] = false; // the next graph of that size is a cold first launch again
}
for (size_t v = 0; v < cyc_graphs_.size(); ++v) drop_bank(cyc_graphs_[v], (int) v != cyc_loaded_);
drop_bank(bypass_graphs_, true);
if (was_bypass) select_loop_bypass(true);
return true;
}
File diff suppressed because it is too large. Load diff
+14 -2
View File
@@ -19,6 +19,7 @@
// BF16 path affects only the scalar gate: it reads the original F32 input and uses pinned CUDA MMVF plus
// an FP32 sigmoid. Native projection overrides independently select CUDA Q8_1 MMVQ and FP32 SwiGLU.
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/loop_adapter.hpp"
#include "strata/kernels/fuse_decode.hpp"
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/bf16_bits.hpp"
@@ -215,8 +216,10 @@ bool fused_swiglu_q81_enabled() {
void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw,
const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd,
int64_t n_ff, void* stream, const void* x_q8_1_ready, int lfuse) {
int64_t n_ff, void* stream, const void* x_q8_1_ready, int lfuse, int loop_pass,
int64_t loop_layer) {
const bool gate_deferred = (lfuse & 1) != 0, pair = (lfuse & 2) != 0;
const bool has_sh_lora = loop_pass >= 0 && loop_layer >= 0 && loop_adapter().has_sh_lora(loop_pass, loop_layer);
if (n_tok < 1 || n_tok > kVerifyMaxT || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream)
throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens (16 in a wide build), native weights, scratch and a stream");
cudaStream_t cs = (cudaStream_t) stream;
@@ -242,8 +245,14 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, cons
native_mmvq(nw.gate_type, nw.gate_data, x_q8_1, gate, (int) n_embd, (int) n_ff, n_tok, stream);
native_mmvq(nw.up_type, nw.up_data, x_q8_1, up, (int) n_embd, (int) n_ff, n_tok, stream);
}
if (has_sh_lora) {
loop_lora_add(x, (int) n_embd, gate, (int) n_ff, loop_pass, loop_layer, LoopTarget::kShGate, n_tok, stream);
loop_lora_add(x, (int) n_embd, up, (int) n_ff, loop_pass, loop_layer, LoopTarget::kShUp, n_tok, stream);
}
const bool has_down_lora =
has_sh_lora && loop_adapter().has_lora(loop_pass, loop_layer, LoopTarget::kShDown);
const int n = (int) (n_ff * n_tok);
if (fused_swiglu_q81_enabled()) {
if (fused_swiglu_q81_enabled() && !has_down_lora) {
native_swiglu_quantize_q8_1(gate, up, nw.q8_1, (int) n_ff, n_tok, stream);
} else {
native_swiglu_kernel<<<(unsigned) ((n + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate, up, gate, n);
@@ -255,6 +264,9 @@ void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, cons
} else {
native_mmvq(nw.down_type, nw.down_data, nw.q8_1, out, (int) n_ff, (int) n_embd, n_tok, stream);
}
if (has_down_lora) {
loop_lora_add(gate, (int) n_ff, out, (int) n_embd, loop_pass, loop_layer, LoopTarget::kShDown, n_tok, stream);
}
if (gate_deferred) { // the caller computed g (raw) with the router and scales `out` in the combine
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) throw std::runtime_error(std::string("shared_expert_multi: ") + cudaGetErrorString(e));
+84
View File
@@ -0,0 +1,84 @@
// src/kernels/loop_adapter_stub.cpp - Unloaded no-op implementation of loop_adapter.hpp for backends that do not
// compile src/kernels/cuda/loop_adapter.cu (Metal, SYCL, CPU-only builds).
#include "strata/kernels/loop_adapter.hpp"
#include <stdexcept>
namespace strata::kernels {
const LoopLoraPair* LoopAdapter::lora(int, int64_t, LoopTarget) const { return nullptr; }
const LoopAdapter& loop_adapter() {
static const LoopAdapter none{};
return none;
}
bool loop_adapter_load(const std::string&, int, float, int64_t, int64_t, int64_t, std::string&, std::string& err, bool,
int32_t, int32_t) {
err = "loop_adapter: --loop-adapter is only supported on CUDA/HIP builds";
return false;
}
bool loop_adapter_replicate(std::string&) { return true; }
void loop_adapter_free() {}
int64_t loop_extra_gdn_slots(int64_t, int64_t, int64_t) { return 0; }
int64_t loop_extra_qsa_slots(int64_t, int64_t, int64_t) { return 0; }
std::vector<LoopStep> build_loop_schedule(int64_t, int64_t qsa_interval, int64_t layer_lo, int64_t layer_hi, bool) {
const int64_t I = qsa_interval > 0 ? qsa_interval : 4;
std::vector<LoopStep> out;
out.reserve((size_t) (layer_hi > layer_lo ? layer_hi - layer_lo : 0));
for (int64_t l = layer_lo; l < layer_hi; ++l) {
LoopStep s;
s.layer = l;
s.pass = 0;
s.core_step = -1;
if (l % I == I - 1) s.qsa_slot = l / I;
else s.gdn_slot = l - l / I;
out.push_back(s);
}
return out;
}
bool loop_split_cyclic(const std::vector<int64_t>&) { return false; }
std::vector<LoopVisit> build_loop_itinerary(int64_t, int64_t, const std::vector<int64_t>&) { return {}; }
void loop_workspace_entry(const float*, const float*, float*, int, int, void*) {
throw std::runtime_error("loop_workspace_entry: --loop-adapter is only supported on CUDA/HIP builds");
}
void loop_cross_pass_mixer(const float*, const float*, float*, int, int, int, void*) {
throw std::runtime_error("loop_cross_pass_mixer: --loop-adapter is only supported on CUDA/HIP builds");
}
void loop_lora_add(const float*, int, float*, int, int, int64_t, LoopTarget, int, void*) {
throw std::runtime_error("loop_lora_add: --loop-adapter is only supported on CUDA/HIP builds");
}
void loop_adapter_set_coda(const std::string&) {}
void loop_lora_add_gated(const float*, int, float*, int, int, int64_t, LoopTarget, int, void*, const float*) {
throw std::runtime_error("loop_lora_add_gated: --loop-adapter is only supported on CUDA/HIP builds");
}
void loop_lora_add_f16(const uint16_t*, int, float*, int, int, int64_t, LoopTarget, int, void*) {
throw std::runtime_error("loop_lora_add_f16: --loop-adapter is only supported on CUDA/HIP builds");
}
void loop_gdn_ab_epilogue(const float*, const float*, const float*, const float*, float*, float*, int, int, void*) {
throw std::runtime_error("loop_gdn_ab_epilogue: --loop-adapter is only supported on CUDA/HIP builds");
}
void loop_cd_hidden(const float*, const float*, float*, float, int, void*) {
throw std::runtime_error("loop_cd_hidden: --loop-adapter is only supported on CUDA/HIP builds");
}
void loop_cd_hidden_per_tok(const float*, const float*, float*, const float*, int, void*) {
throw std::runtime_error("loop_cd_hidden_per_tok: --loop-adapter is only supported on CUDA/HIP builds");
}
} // namespace strata::kernels
+268
View File
@@ -0,0 +1,268 @@
// src/kernels/loop_adapter_test.cpp - Host unit tests for LoopCD-Hidden <think> gating,
// loop cache key derivation, and T=1 vs T=N conversation-cache / spill / file isolation.
#include "strata/core/conversation_cache.hpp"
#include "strata/core/conversation_file.hpp"
#include "strata/core/conversation_spill.hpp"
#include "strata/kernels/loop_adapter.hpp"
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <string>
#include <vector>
namespace {
int g_checks = 0;
int g_failed = 0;
#define CHECK(cond) \
do { \
++g_checks; \
if (!(cond)) { \
++g_failed; \
std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \
} \
} while (0)
strata::core::SavedConversation make_saved(std::vector<int32_t> ids, uint64_t loop_key, bool cvec = true,
size_t kv_bytes = 64) {
strata::core::SavedConversation s;
s.cvec = cvec;
s.loop_key = loop_key;
s.live.ids = ids;
s.live.gdn.resize(16, uint8_t(loop_key & 0xffu));
strata::core::ConversationKv kv;
kv.cells = (int64_t) ids.size();
kv.k.resize(kv_bytes, uint8_t(loop_key & 0xffu));
kv.v.resize(kv_bytes, uint8_t((loop_key >> 8) & 0xffu));
s.kv.push_back(std::move(kv));
return s;
}
void test_think_mask_semantics() {
using namespace strata::kernels;
constexpr int32_t TS = 248068;
constexpr int32_t TE = 248069;
constexpr float W = 0.75f;
// Outside -> <think> (on) -> inside (on) -> </think> (off) -> answer (off)
// Matches vllm_looped_qwen38 compute_thinking_token_mask(default_thinking=False, include_end_token=False).
const std::vector<int64_t> seq = {10, 20, TS, 30, 40, TE, 50, 60, TE, TS, 70, TS, 80, TE, 90};
const std::vector<float> want = {0.0f, 0.0f, W, W, W, 0.0f, 0.0f, 0.0f, 0.0f, W, W, W, W, 0.0f, 0.0f};
std::vector<float> got(seq.size(), -1.0f);
const bool end_state = loop_cd_fill_omega(seq.data(), (int64_t) seq.size(), W, true, TS, TE, false, got.data());
CHECK(!end_state);
for (size_t i = 0; i < seq.size(); ++i) CHECK(got[i] == want[i]);
CHECK(loop_think_state_after(seq.data(), (int64_t) seq.size(), TS, TE, false) == false);
CHECK(loop_think_state_after(seq.data(), 4, TS, TE, false) == true); // after [10, 20, TS, 30]
CHECK(loop_think_state_after(seq.data(), 6, TS, TE, false) == false); // after [..., TE]
// Chunked prefill boundary equivalence across every chunk size 1..seq.size().
for (size_t chunk = 1; chunk <= seq.size(); ++chunk) {
std::vector<float> chunked(seq.size(), -1.0f);
bool st = false;
for (size_t pos = 0; pos < seq.size(); pos += chunk) {
const int64_t len = (int64_t) std::min(chunk, seq.size() - pos);
st = loop_cd_fill_omega(seq.data() + pos, len, W, true, TS, TE, st, chunked.data() + pos);
}
CHECK(st == end_state);
for (size_t i = 0; i < seq.size(); ++i) CHECK(chunked[i] == want[i]);
}
// Speculative decode verify window accept/reject rollback semantics.
// Suppose committed state is in_thinking=true and the drafted window is [101, </think>, 102, 103].
const int32_t win[4] = {101, TE, 102, 103};
float w_om[4] = {-1, -1, -1, -1};
const bool after_all = loop_cd_fill_omega(win, 4, W, true, TS, TE, true, w_om);
CHECK(!after_all);
CHECK(w_om[0] == W);
CHECK(w_om[1] == 0.0f);
CHECK(w_om[2] == 0.0f);
CHECK(w_om[3] == 0.0f);
// If verifier rejects draft </think> (commit n_keep=1), thinking state stays ON.
CHECK(loop_think_state_after(win, 1, TS, TE, true) == true);
// If verifier accepts </think> (commit n_keep=2), thinking state turns OFF.
CHECK(loop_think_state_after(win, 2, TS, TE, true) == false);
// Direct (enable_thinking=false) Qwen3.8 prompt ending with <think>\n\n</think>\n\n:
// Answer tokens after </think> all get 0.0f.
const std::vector<int64_t> direct_prompt = {1, 2, TS, 271, TE, 271};
const bool after_direct = loop_think_state_after(direct_prompt.data(), (int64_t) direct_prompt.size(), TS, TE, false);
CHECK(!after_direct);
const int32_t answer_toks[3] = {500, 501, 502};
float ans_om[3] = {-1, -1, -1};
CHECK(!loop_cd_fill_omega(answer_toks, 3, W, true, TS, TE, after_direct, ans_om));
for (float v : ans_om) CHECK(v == 0.0f);
// Unconditional legacy mode (cd_thinking=false): every token receives W.
std::vector<float> uncond(seq.size(), -1.0f);
CHECK(loop_cd_fill_omega(seq.data(), (int64_t) seq.size(), W, false, TS, TE, false, uncond.data()) == false);
for (float v : uncond) CHECK(v == W);
// Invalid think IDs (equal or negative) safely fall back to unconditional / no-op transition.
std::vector<float> bad(seq.size(), -1.0f);
CHECK(loop_cd_fill_omega(seq.data(), (int64_t) seq.size(), W, true, TS, TS, false, bad.data()) == false);
for (float v : bad) CHECK(v == W);
CHECK(loop_think_state_after(seq.data(), (int64_t) seq.size(), -1, TE, false) == false);
}
void test_loop_cache_keys() {
using namespace strata::kernels;
constexpr int32_t TS = 248068;
constexpr int32_t TE = 248069;
// Unloaded adapter always produces key 0.
CHECK(loop_cache_key_for(false, 1, 0.0f, false, TS, TE) == 0);
CHECK(loop_cache_key_for(false, 2, 1.0f, true, TS, TE) == 0);
// Loaded adapter with T=1 bypass always produces key 1, invariant to LoopCD knobs.
CHECK(loop_cache_key_for(true, 1, 0.0f, false, TS, TE) == 1);
CHECK(loop_cache_key_for(true, 1, 1.5f, true, TS, TE) == 1);
CHECK(loop_cache_key_for(true, 1, 0.5f, false, 10, 11) == 1);
// Loaded adapter with T >= 2 produces keys >= 2, distinguishing passes, omega, thinking gating, and think IDs.
const uint64_t k_t2_0_off = loop_cache_key_for(true, 2, 0.0f, false, TS, TE);
const uint64_t k_t2_0_on = loop_cache_key_for(true, 2, 0.0f, true, TS, TE);
const uint64_t k_t2_neg0 = loop_cache_key_for(true, 2, -0.0f, false, TS, TE);
const uint64_t k_t2_cd_off = loop_cache_key_for(true, 2, 0.5f, false, TS, TE);
const uint64_t k_t2_cd_on = loop_cache_key_for(true, 2, 0.5f, true, TS, TE);
const uint64_t k_t2_cd_other_ids = loop_cache_key_for(true, 2, 0.5f, true, 100, 101);
const uint64_t k_t2_cd1_on = loop_cache_key_for(true, 2, 1.0f, true, TS, TE);
const uint64_t k_t3_0 = loop_cache_key_for(true, 3, 0.0f, false, TS, TE);
CHECK(k_t2_0_off >= 2);
CHECK(k_t2_0_off == k_t2_0_on); // omega == 0 makes cd_thinking a no-op
CHECK(k_t2_0_off == k_t2_neg0); // -0.0f == +0.0f
CHECK(k_t2_0_off != k_t2_cd_off);
CHECK(k_t2_cd_off != k_t2_cd_on);
CHECK(k_t2_cd_on != k_t2_cd_other_ids);
CHECK(k_t2_cd_on != k_t2_cd1_on);
CHECK(k_t2_0_off != k_t3_0);
}
void test_cache_and_spill_isolation() {
using namespace strata::core;
using namespace strata::kernels;
const uint64_t k1 = loop_cache_key_for(true, 1, 0.0f, false, 248068, 248069);
const uint64_t k2 = loop_cache_key_for(true, 2, 0.5f, true, 248068, 248069);
CHECK(k1 == 1);
CHECK(k2 >= 2);
const std::vector<int32_t> prompt = {10, 20, 30, 40, 50, 60, 70, 80};
std::vector<int32_t> extended = prompt;
extended.push_back(90);
const std::vector<int64_t> extended64(extended.begin(), extended.end());
// 1. ConversationCache RAM tier isolation.
ConversationCache cache(4 * 1024 * 1024, 4);
CHECK(cache.put(make_saved(prompt, k1)));
CHECK(cache.put(make_saved(prompt, k2)));
CHECK(cache.size() == 2);
const auto m1 = cache.best(extended64, {}, true, k1);
const auto m2 = cache.best(extended64, {}, true, k2);
const auto m0 = cache.best(extended64, {}, true, 0);
CHECK(m1.tokens == (int64_t) prompt.size());
CHECK(m2.tokens == (int64_t) prompt.size());
CHECK(m1.serial != m2.serial);
CHECK(m0.tokens == 0);
// Dropping superseded entries for k1 must NOT drop k2.
CHECK(cache.drop_superseded(extended, {}, {}, true, nullptr, k1) == 1);
CHECK(cache.size() == 1);
CHECK(cache.best(extended64, {}, true, k1).tokens == 0);
CHECK(cache.best(extended64, {}, true, k2).tokens == (int64_t) prompt.size());
// Retained KV reuse must NOT cross loop_key boundaries.
auto make_kvs = [&]() {
std::vector<ConversationKv> kvs(1);
kvs[0].cells = (int64_t) prompt.size();
kvs[0].k.resize(32, 0xaa);
kvs[0].v.resize(32, 0xbb);
return kvs;
};
cache.retain(make_kvs(), (int64_t) prompt.size(), {}, prompt, k1);
CHECK(cache.has_reuse_for(prompt, k1));
CHECK(!cache.has_reuse_for(prompt, k2));
CHECK(cache.take_reuse_for(prompt, k2).kv.empty());
cache.retain(make_kvs(), (int64_t) prompt.size(), {}, prompt, k1);
CHECK(!cache.take_reuse_for(prompt, k1).kv.empty());
// 2. Session file round-trip (legacy loop_key=0 vs LOOPKEY1 tail for loop_key!=0).
const std::filesystem::path tmp_root =
std::filesystem::temp_directory_path() / ("strata_loop_adapter_test_" + std::to_string((long long) std::rand()));
std::error_code ec;
std::filesystem::remove_all(tmp_root, ec);
std::filesystem::create_directories(tmp_root, ec);
SessionFileIdentity id;
id.model = 0x1111222233334444ull;
id.config = 0x5555666677778888ull;
SessionReadLimits lim;
lim.max_file_bytes = 64ull << 20;
for (uint64_t lk : {uint64_t(0), k1, k2}) {
const std::filesystem::path p = tmp_root / ("sess_" + std::to_string(lk) + ".strata");
SavedConversation out = make_saved(prompt, lk);
std::string err;
size_t nbytes = 0;
CHECK(session_file_write(p.string(), out, id, nbytes, err));
SavedConversation in;
size_t rbytes = 0;
CHECK(session_file_read(p.string(), id, in, rbytes, err, lim));
CHECK(in.loop_key == lk);
CHECK(in.live.ids == prompt);
}
// 3. ConversationSpill SSD tier isolation + persistence reopen.
const std::filesystem::path spill_dir = tmp_root / "spill";
std::string serr;
{
ConversationSpill spill;
CHECK(spill.open(spill_dir, 16ull << 20, serr, nullptr, &id));
CHECK(spill.put(make_saved(prompt, k1), id, serr));
CHECK(spill.put(make_saved(prompt, k2), id, serr));
CHECK(spill.size() == 2);
const auto b1 = spill.best(extended64, {}, true, k1);
const auto b2 = spill.best(extended64, {}, true, k2);
const auto b0 = spill.best(extended64, {}, true, 0);
CHECK(b1.tokens == (int64_t) prompt.size());
CHECK(b2.tokens == (int64_t) prompt.size());
CHECK(b1.serial != b2.serial);
CHECK(b0.tokens == 0);
spill.close();
}
{
// Reopen persistent spill directory and confirm loop_key metadata survived SPM2 reload.
ConversationSpill spill;
size_t adopted = 0;
CHECK(spill.open(spill_dir, 16ull << 20, serr, nullptr, &id, &adopted));
CHECK(adopted == 2);
CHECK(spill.best(extended64, {}, true, k1).tokens == (int64_t) prompt.size());
CHECK(spill.best(extended64, {}, true, k2).tokens == (int64_t) prompt.size());
CHECK(spill.best(extended64, {}, true, 0).tokens == 0);
// Supersede k1 only; k2 must remain on SSD.
CHECK(spill.drop_superseded(extended, {}, true, k1).size() == 1);
CHECK(spill.best(extended64, {}, true, k1).tokens == 0);
CHECK(spill.best(extended64, {}, true, k2).tokens == (int64_t) prompt.size());
spill.close();
}
std::filesystem::remove_all(tmp_root, ec);
}
} // namespace
int main() {
test_think_mask_semantics();
test_loop_cache_keys();
test_cache_and_spill_isolation();
std::printf("loop_adapter_test: %d checks, %d failed\n", g_checks, g_failed);
return g_failed == 0 ? 0 : 1;
}
+382 -50
View File
@@ -59,6 +59,7 @@
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/kv_stream.hpp"
#include "strata/kernels/cvec.hpp"
#include "strata/kernels/loop_adapter.hpp"
#include "strata/kernels/kv_q4.hpp"
#include "strata/core/layer.hpp"
#include "strata/core/native_dense.hpp"
@@ -1118,6 +1119,20 @@ struct Alloc {
} // namespace
// A cyclic layer split (Prefill::set_cyclic): the itinerary, every stage's path, and a run's progress - per visit, the
// chunks it has finished. Visit g of chunk c waits for visit g - 1 of chunk c (its rows), and a visit that hands rows
// on waits until the readers of what its stage handed on two chunks ago (the same buffer) have finished.
struct Prefill::Cyc {
std::vector<strata::kernels::LoopVisit> visits;
std::vector<Prefill*> paths;
std::mutex mu;
std::condition_variable cv;
std::vector<int64_t> done;
int64_t limit = 0; ///< the chunks this run reads (stop_at_chunk lowers it)
bool failed = false;
std::string err;
};
// Step 4 of the prompt-speed plan: the experts the arena could not pin (a third of the streamed ones on IQ3_S) are
// copied into pinned buffers by these threads, ahead of the launches. Copied in line by the launching thread they
// left the GPU without queued work while each ~2 MB memcpy ran (~15 s of a 32K prompt on IQ3_S). Job j - a layer's
@@ -1554,6 +1569,8 @@ struct Prefill::Impl {
std::vector<void*> owned;
// chunk buffers
float *emb = nullptr, *R = nullptr, *xn = nullptr, *lo = nullptr, *gated = nullptr, *inj = nullptr;
float *R_anchor = nullptr, *R_mprev = nullptr, *R_m0 = nullptr; // Looped adapter residual checkpoints
float *cd_omega = nullptr; // Looped adapter per-token LoopCD omega [T]
float* grs = nullptr; // F-1: the hyper-connection read's row scales (T x 4)
uint16_t *xn16 = nullptr, *lo16 = nullptr;
float* mixed = nullptr;
@@ -1702,6 +1719,8 @@ struct Prefill::Impl {
// layer split: the device, and the hand-off to the next stage (two pinned chunk buffers, used in turn)
int device = -1;
float* hand[2] = {};
float* hand_mp[2] = {}; // a cyclic split: the m_prev rows relayed beside them (set_cyclic)
int64_t hand_rows = 0; // the rows each hand-off buffer holds
// STRATA_HANDOFF_PIPE: per hand-off buffer, "the chunk's work is done" and one "landed" event per piece
int hand_pieces = 0;
cudaEvent_t hand_done[2] = {};
@@ -1842,6 +1861,7 @@ void Prefill::release() {
}
for (int b = 0; b < 2; ++b) {
if (impl_->hand[b]) cudaFreeHost(impl_->hand[b]);
if (impl_->hand_mp[b]) cudaFreeHost(impl_->hand_mp[b]);
if (impl_->hand_done[b]) cudaEventDestroy(impl_->hand_done[b]);
for (cudaEvent_t& e : impl_->hand_ev[b])
if (e) cudaEventDestroy(e);
@@ -2485,11 +2505,25 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co
}
// the CPU share's staged-chunk limit, before the ring is sized below (a caller that sizes loans first armed it)
arm_cpu_share(cpu_pool_ != nullptr);
for (int b = 0; next_ != nullptr && b < 2; ++b)
// a cyclic split: a stage hands rows on from each visit but the final one (and relays m_prev where one says so)
bool cyc_writes = false, cyc_relays = false;
if (cyc_ != nullptr)
for (const strata::kernels::LoopVisit& v : cyc_->visits)
if (v.owner == cyc_stage_ && !v.head) {
cyc_writes = true;
cyc_relays = cyc_relays || v.mprev_out;
}
for (int b = 0; (next_ != nullptr || cyc_writes) && b < 2; ++b)
if (!m.hand[b] && cudaHostAlloc((void**) &m.hand[b], (size_t) chunk * D * 4, cudaHostAllocPortable) != cudaSuccess) {
err = "prefill: the layer split's hand-off buffers";
return false;
}
for (int b = 0; cyc_relays && b < 2; ++b)
if (!m.hand_mp[b] && cudaHostAlloc((void**) &m.hand_mp[b], (size_t) chunk * D * 4, cudaHostAllocPortable) != cudaSuccess) {
err = "prefill: the cyclic layer split's m_prev hand-off buffers";
return false;
}
m.hand_rows = chunk;
if (next_ != nullptr && handoff_pipe_pieces() > 0 && m.hand_pieces == 0) { // events only: no device memory
bool ok = true;
auto make = [](cudaEvent_t& e) { return e != nullptr || cudaEventCreateWithFlags(&e, cudaEventDisableTiming) == cudaSuccess; };
@@ -2764,6 +2798,14 @@ bool Prefill::carve(size_t T, void* alloc) {
core::SessionState& ss = *m.ss;
bool ok = true;
m.emb = o.take<float>(T * N, ok); m.R = o.take<float>(T * D, ok);
if (strata::kernels::loop_adapter().loaded()) {
m.R_anchor = o.take<float>(T * D, ok);
m.R_mprev = o.take<float>(T * D, ok);
m.R_m0 = o.take<float>(T * D, ok);
m.cd_omega = o.take<float>(T, ok);
} else {
m.R_anchor = m.R_mprev = m.R_m0 = m.cd_omega = nullptr;
}
m.xn = gr_unfused() ? o.take<float>(T * D, ok) : nullptr; // F-1: not needed (gr_mix_r reads R)
m.grs = o.take<float>(T * HC, ok);
const bool hcr = pf_hc_region(); // STRATA_PF_HC_REGION: xn16 / lo / lo16 / gated (and their _lo) are taken in the region
@@ -3734,10 +3776,13 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se
// still bounds-checks - but it under-sizes every loan, so every chunk the scan picks is one step smaller.
if (ring_bytes_on()) {
f(T * N); f(T * D);
if (strata::kernels::loop_adapter().loaded()) { f(T * D); f(T * D); f(T * D); f(T); }
if (gr_unfused()) f(T * D);
f(T * HC);
} else { // STRATA_RING_BYTES=0: 0.1.39's count
f(T * N); f(T * D); f(T * D);
f(T * N); f(T * D);
if (strata::kernels::loop_adapter().loaded()) { f(T * D); f(T * D); f(T * D); f(T); }
f(T * D);
}
const bool hcr = pf_hc_region();
if (!hcr) { o.take<uint16_t>(T * (D + (hc_pad() ? XN_PAD : 0)), ok); f(T * LR); o.take<uint16_t>(T * LR, ok); f(T * D); }
@@ -4300,7 +4345,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// pool would decide which experts the CPU computed (other bits) - timing, where the chunks are a function of n
const bool pipe_chunked = hand_in_ == nullptr ? (forced > 0 ? forced_planned : planned_C > 0 && C < std::min(n, m.T))
: pipe_chunked_;
const bool helped = single_chunk && bind_stage_helper(n);
const bool helped = single_chunk && cyc_vis_ == nullptr && bind_stage_helper(n);
if (helped) std::swap(m.pp, m.help_pp);
struct HelpScope {
Impl& m;
@@ -4324,7 +4369,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// The PLE rows of a chunk are read from the model file on the host (an SSD read per missed row): the chunk
// after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows
// depend only on the tokens (the two before a position name its n-grams), so this is the same data.
const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE;
const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE && (cyc_vis_ == nullptr || cyc_vis_->ple);
// the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token);
// STRATA_PLE_BATCH=0 keeps the per-token block (the A/B)
const bool ple_batch_env = ple_batch_enabled();
@@ -4376,6 +4421,17 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
for (size_t i = 0; i < tap_local_.size(); ++i) tap_slot[(size_t) tap_local_[i]] = (int) i;
}
#endif
const auto& la_pf = strata::kernels::loop_adapter();
const bool loop_on = la_pf.loaded() && !loop_bypass_;
const float eff_cd_omega = loop_on ? (loop_req_set_ ? loop_cd_omega_ : la_pf.cd_omega) : 0.0f;
const bool eff_cd_thinking = loop_req_set_ ? loop_cd_thinking_ : la_pf.cd_thinking;
std::vector<float> cd_omega_host;
if (eff_cd_omega != 0.0f && cyc_cd_omega_ == nullptr) {
cd_omega_host.resize((size_t) n, 0.0f);
strata::kernels::loop_cd_fill_omega(tokens, n, eff_cd_omega, eff_cd_thinking, la_pf.think_start_id,
la_pf.think_end_id, loop_cd_in_thinking_, cd_omega_host.data());
}
bool chunk_think_state = loop_cd_in_thinking_;
for (int64_t c0 = 0; c0 < n; c0 += C) {
if (should_stop && should_stop()) { err = "cancelled"; return false; }
// the first stage: end the run before this chunk (every chunk before it is handed on; the caller's drain
@@ -4419,7 +4475,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
#else
const int64_t tap_t0 = 0, tap_rows = 0;
#endif
++stats_.chunks;
if (cyc_vis_ == nullptr || cyc_vis_->owner_first) ++stats_.chunks;
pt.mark(kPfStart, cs);
const auto tsetup = Clock::now();
// ---- embeddings, broadcast to the four streams - or, in a later stage of a layer split, the rows the
@@ -4462,6 +4518,15 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
return false;
}
}
// a cyclic visit on a later pass: the previous pass's core output - the handed-in rows themselves on the wrap
// into the core's first stage, else relayed beside them (the workspace entry overwrites R: never an alias)
if (cyc_vis_ != nullptr && cyc_vis_->mprev_in != 0 &&
(cyc_vis_->mprev_in == 1
? cudaMemcpyAsync(m.R_mprev, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToDevice, m.cs)
: cudaMemcpyAsync(m.R_mprev, cyc_mprev_in_, (size_t) T * D * 4, cudaMemcpyHostToDevice, m.cs)) != cudaSuccess) {
err = "prefill: the cyclic layer split's m_prev upload failed";
return false;
}
// C-4: the whole chunk's rows in one gather (the same per-element arithmetic as the per-token path, so the
// same bits); a chunk with picture rows, or a token outside the table, takes the per-token path
bool batched = hand_in_ == nullptr && m.tok_dev != nullptr;
@@ -4591,11 +4656,27 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
return false;
}
const bool chunk_think_before = chunk_think_state;
if (next_ != nullptr && cyc_vis_ == nullptr && loop_on && eff_cd_thinking) {
chunk_think_state = strata::kernels::loop_think_state_after(
tokens + c0, T, la_pf.think_start_id, la_pf.think_end_id, chunk_think_before);
}
if (eff_cd_omega != 0.0f && m.cd_omega != nullptr) {
const float* src_om = cyc_cd_omega_ != nullptr ? cyc_cd_omega_ : (cd_omega_host.data() + c0);
if (cudaMemcpyAsync(m.cd_omega, src_om, (size_t) T * sizeof(float), cudaMemcpyHostToDevice, m.cs) !=
cudaSuccess) {
err = "prefill: LoopCD per-token omega upload failed";
return false;
}
}
const auto loop_plan =
cyc_vis_ != nullptr ? cyc_vis_->steps
: strata::kernels::build_loop_schedule(g.n_layers, g.qsa_interval, LB, LE, loop_bypass_);
int64_t qsa_index = 0, gdn_index = 0;
for (int64_t l = 0; l < LB; ++l) (core::is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1;
int64_t kv_pending = -1;
auto kv_prefetch_after = [&](int64_t layer, int64_t ordinal) -> bool {
if (!kv_prefetch || p0 <= 0) return true;
if (!kv_prefetch || p0 <= 0 || loop_on) return true;
if (kv_pending >= 0) return true; // one staging pool: the pending prefetch has not been consumed yet
for (int64_t l = layer; l < LE; ++l) {
if (!core::is_qsa_layer(g, l)) continue;
@@ -4655,9 +4736,9 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
++P.p_issued;
}
};
auto p_release_to = [&](int64_t l, int32_t e_stop, cudaStream_t ps) {
auto p_release_to = [&](size_t sidx_arg, int32_t e_stop, cudaStream_t ps) {
PeerPrefill& P = *m.pp;
while (P.pk < P.pseq_start[(size_t) l + 1] && P.pseq[P.pk].e < e_stop) {
while (P.pk < P.pseq_start[sidx_arg + 1] && P.pseq[P.pk].e < e_stop) {
cudaEventRecord(P.pused[P.pk % (size_t) P.RP], ps);
++P.pk;
p_issue_until(P.pk + (size_t) P.RP);
@@ -4668,11 +4749,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
std::vector<size_t> seq_start;
size_t issued = 0, consumed = 0;
if (stream_all) {
seq_start.assign((size_t) g.n_layers + 1, 0);
seq_start.assign(loop_plan.size() + 1, 0);
std::vector<Stager::Job> js;
if (ps_on) {
m.pp->pseq.clear();
m.pp->pseq_start.assign((size_t) g.n_layers + 1, 0);
m.pp->pseq_start.assign(loop_plan.size() + 1, 0);
m.pp->ps_flag.assign((size_t) g.n_layers * m.g->n_expert, 0);
m.pp->p_issued = m.pp->pk = 0;
}
@@ -4681,13 +4762,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// transfer plan is where the avoidable cost lives (the research handoff's "expert transfers must be
// skipped too"). `kva_skips_layer` is the one place the two conditions meet.
auto kva_skips_layer = [&](int64_t l) {
return kva_approx && l >= kva_split &&
return kva_approx && !loop_on && l >= kva_split &&
(kva.only == KvaConfig::Only::All ||
(kva.only == KvaConfig::Only::Gdn) == !core::is_qsa_layer(g, l));
};
for (int64_t l = LB; l < LE; ++l) {
seq_start[(size_t) l] = seq.size();
if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();
for (size_t si = 0; si < loop_plan.size(); ++si) {
const int64_t l = loop_plan[si].layer;
seq_start[si] = seq.size();
if (ps_on) m.pp->pseq_start[si] = m.pp->pseq.size();
if (kva_skips_layer(l)) continue; // no transfer for a layer whose MoE half is skipped
for (int32_t e = 0; e < m.g->n_expert; ++e) {
if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
@@ -4717,10 +4799,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
seq.push_back({(int32_t) l, e, b, job});
}
}
for (int64_t l = LE; l <= g.n_layers; ++l) {
seq_start[(size_t) l] = seq.size();
if (ps_on) m.pp->pseq_start[(size_t) l] = m.pp->pseq.size();
}
seq_start[loop_plan.size()] = seq.size();
if (ps_on) m.pp->pseq_start[loop_plan.size()] = m.pp->pseq.size();
m.stager->start(std::move(js));
}
struct StagerDone {
@@ -4776,7 +4856,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// before the issuer thread, so they outlive it on every return (IssuerJoin joins it first).
static const bool rs_env = routed_stream::enabled_from(std::getenv("STRATA_PREFILL_ROUTED_STREAM"));
static const int rs_depth = routed_stream::depth_from(std::getenv("STRATA_PREFILL_ROUTED_STREAM_DEPTH"));
const bool rs_on = rs_env && routed_stream::eligible(
const bool rs_on = !loop_on && rs_env && routed_stream::eligible(
stream_all, issuer_on, m.pp != nullptr, copy_event_every, copy_wait_dedupe);
routed_stream::RouteGate rs_gate;
size_t rs_dropped = 0;
@@ -4974,8 +5054,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
const char* v = std::getenv("STRATA_STOP_LAYERS");
return v == nullptr || std::atoi(v) != 0;
}();
for (int64_t l = LB; l < LE; ++l) {
if (l > LB && stop_in_chunk && should_stop && should_stop()) {
for (size_t sidx = 0; sidx < loop_plan.size(); ++sidx) {
const strata::kernels::LoopStep& stp = loop_plan[sidx];
const int64_t l = stp.layer;
const int pass = stp.pass;
if (sidx > 0 && stop_in_chunk && should_stop && should_stop()) {
a_stop.store(true, std::memory_order_release);
if (issuer.joinable()) issuer.join();
if (stream_all) m.stager->finish();
@@ -4991,12 +5074,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
return false;
}
core::progress_beat(); // the serve watchdog: a prompt chunk of 8192 tokens is still moving
if (l > LB) pf_step("reading the prompt (batched, step sync): the experts and the rest of layer", l - 1);
if (sidx > 0) pf_step("reading the prompt (batched, step sync): the experts and the rest of layer", loop_plan[sidx - 1].layer);
core::progress_at("reading the prompt (batched): layer", l, p0); // #251: a stall names layer and chunk
const core::LayerView v(*m.wt, l);
// STRATA_KVA: `kva_layer` means this layer's output has no consumer left for this chunk, so only its
// state advances; `kva_subst` means the block input itself is replayed from a capture (oracle mode).
const bool kva_layer = kva_approx && l >= kva_split &&
const bool kva_layer = kva_approx && !loop_on && l >= kva_split &&
(kva.only == KvaConfig::Only::All ||
(kva.only == KvaConfig::Only::Gdn) == !core::is_qsa_layer(g, l));
// STRATA_KVA_SKIP=moe: the layer's attention half (GDN or QSA, outputs included) runs in full and only the MoE
@@ -5004,13 +5087,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
const bool kva_moe_only = kva_layer && kva.skip == KvaConfig::Skip::Moe;
const bool kva_state_only = kva_layer && !kva_moe_only;
const bool kva_subst = kva_layer && kva.mode == KvaConfig::Mode::Oracle;
const bool kva_cap_layer = kva.capture && LB == 0 && (LE < 0 || LE == g.n_layers) && l >= kva_split;
if (l == std::max<int64_t>(LB, 1)) { // the PLE rows, read from layer 1 on (a wait for the SSD read of the first chunk lands on "ple")
const bool kva_cap_layer = !loop_on && kva.capture && LB == 0 && (LE < 0 || LE == g.n_layers) && l >= kva_split;
if (pass == 0 && l == std::max<int64_t>(LB, 1)) { // the PLE rows, read from layer 1 on (a wait for the SSD read of the first chunk lands on "ple")
pt.mark(kPfPle, cs);
if (!ple_land()) return false;
}
// ---- the PLE block at layer 1, token by token (its conv reads the previous tokens' rows)
if (l == 1 && ple_on && ple_batch) {
if (l == 1 && pass == 0 && ple_on && ple_batch) {
// the whole chunk at once, in sub-batches carved from the idle scratch region: the key and value
// projections as GEMMs (a token at a time they re-read ~52 MB of BF16 key per token on the IQ
// files), the rest with the per-token kernels' arithmetic (native_ple_postops_batch)
@@ -5049,7 +5132,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
} catch (const std::exception& e) { err = std::string("prefill PLE: ") + e.what(); return false; }
}
stats_.ms_ple += ms_since(tp);
} else if (l == 1 && ple_on) {
} else if (l == 1 && pass == 0 && ple_on) {
pt.mark(kPfPle, cs);
const auto tp = Clock::now();
for (int64_t t = 0; t < T; ++t) {
@@ -5071,13 +5154,24 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (!kva_oracle.read(l, m.R, T, p0, D, cs)) { err = kva_oracle.err; return false; }
normed = false; // the previous half's norm of R is stale once the input is replaced
}
if (stp.save_anchor_before) {
cudaMemcpyAsync(m.R_anchor, m.R, (size_t) T * D * sizeof(float), cudaMemcpyDeviceToDevice, m.cs);
}
if (stp.run_workspace_entry) {
strata::kernels::loop_workspace_entry(m.R_anchor, m.R_mprev, m.R, pass - 1, (int) T, m.cs);
normed = false;
}
if (stp.run_cross_pass_mixer) {
strata::kernels::loop_cross_pass_mixer(m.R, m.R_mprev, m.R, pass - 1, stp.core_step, (int) T, m.cs);
normed = false;
}
for (int half = 0; half < 2; ++half) {
if (kva_moe_only && half == 1) {
// KVA moe-skip: the attention half wrote its output into R; this layer's MoE half has no consumer
// left for an approximated chunk, so it (and its expert transfers) is skipped. R is not normed for
// it (the write after the attention half normed it with this layer's FFN weights).
normed = false;
consumed = std::max(consumed, seq_start[(size_t) l + 1]);
consumed = std::max(consumed, seq_start[sidx + 1]);
give_back(consumed);
break;
}
@@ -5177,9 +5271,11 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
*wsa = need(v, "ssm_a", err);
if (!wqkv || !wg || !wo || !wa || !wb || !wc || !wnm || !wdt || !wsa) return false;
pt.mark(kPfGdn, cs);
float* state = ss.gdn_state + (size_t) (gdn_index - ss.gdn_ord0) * gdn_floats;
const int64_t gi = stp.gdn_slot;
float* state = ss.gdn_state + (size_t) (gi - ss.gdn_ord0) * gdn_floats;
float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size;
if (!native_proj(m.gemm, wqkv, m.mixed_h, m.qkv, T, v.name("attn_qkv.weight"), err)) return false;
if (loop_on) strata::kernels::loop_lora_add(m.mixed, (int) N, m.qkv, (int) C, pass, l, strata::kernels::LoopTarget::kGdnQkv, (int) T, m.cs);
// KVA: the gate projection feeds only the output normalization, which a state-only layer skips
// (STRATA_KVA_GDN_NORM=1 keeps the full recurrence as the A/B control for the state-only one)
static const bool kva_gdn_norm = [] {
@@ -5188,8 +5284,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}();
if ((!kva_state_only || kva_gdn_norm) &&
!native_proj(m.gemm, wg, m.mixed_h, m.z, T, v.name("attn_gate.weight"), err)) return false;
if (loop_on && (!kva_state_only || kva_gdn_norm))
strata::kernels::loop_lora_add(m.mixed, (int) N, m.z, (int) ZV, pass, l, strata::kernels::LoopTarget::kGdnZ, (int) T, m.cs);
if (!bf16_proj(m.gemm, wa, m.mixed_bf, m.ab, T, v.name("ssm_alpha.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
if (loop_on) strata::kernels::loop_lora_add(m.mixed, (int) N, m.ab, (int) (2 * HV), pass, l, strata::kernels::LoopTarget::kGdnA, (int) T, m.cs);
if (!bf16_proj(m.gemm, wb, m.mixed_bf, m.ab + HV, T, v.name("ssm_beta.weight"), err, 2 * HV, m.mixed_bf_lo)) return false;
if (loop_on) strata::kernels::loop_lora_add(m.mixed, (int) N, m.ab + HV, (int) (2 * HV), pass, l, strata::kernels::LoopTarget::kGdnB, (int) T, m.cs);
pt.mark(kPfGdnConv, cs); // "gdn" is the projections in; the rest on their own lines
gdn_gates(m.ab, (const float*) wdt->data, (const float*) wsa->data, m.gate, m.beta, T, m.cs);
const int64_t ld_y = pf_pad() && T >= std::max<int64_t>(pf_switch_min_t(), 64) ? ZV + ZV_PAD : 0;
@@ -5209,19 +5309,22 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
gdn_recurrence(state, m.hbuf, m.gate, m.beta, m.z, (const float*) wnm->data, EPS, m.y, m.y_h, T, m.cs,
ld_y);
pt.mark(kPfGdnOut, cs);
if (!kva_state_only) // KVA: the out projection feeds only the residual write and the MoE half
if (!kva_state_only) { // KVA: the out projection feeds only the residual write and the MoE half
if (!native_proj(m.gemm, wo, m.y_h, m.bo, T, v.name("ssm_out.weight"), err, 0, ld_y)) return false;
if (loop_on) strata::kernels::loop_lora_add_f16(m.y_h, (int) (ld_y ? ld_y : ZV), m.bo, (int) N, pass, l, strata::kernels::LoopTarget::kGdnOut, (int) T, m.cs);
}
++gdn_index;
if (kva_state_only) {
// the layer consumed no expert: its stream entries must still be released, or the issuer
// thread fills the ring and the next fully computed layer waits for a copy that never comes
consumed = std::max(consumed, seq_start[(size_t) l + 1]);
consumed = std::max(consumed, seq_start[sidx + 1]);
give_back(consumed);
break; // state advanced: no gated residual write, no MoE half of this layer
}
} else if (half == 0) {
// ======================= QSA =======================
const core::QsaState& st = ss.qsa_states[qsa_index];
const int64_t qi = stp.qsa_slot;
const core::QsaState& st = ss.qsa_states[qi];
const core::WeightRef *wq = need(v, "attn_q.weight", err), *wk = need(v, "attn_k.weight", err),
*wv = need(v, "attn_v.weight", err), *wo = need(v, "attn_output.weight", err),
*wik = need(v, "indexer.k_proj.weight", err),
@@ -5232,9 +5335,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false;
pt.mark(kPfQsa, cs);
if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false;
if (loop_on) strata::kernels::loop_lora_add(m.mixed, (int) N, m.Kc, kKvW, pass, l, strata::kernels::LoopTarget::kQsaK, (int) T, m.cs);
if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false;
if (loop_on) strata::kernels::loop_lora_add(m.mixed, (int) N, m.Vc, kKvW, pass, l, strata::kernels::LoopTarget::kQsaV, (int) T, m.cs);
// KVA: the query projections have no consumer when only the KV/indexer state advances
if (!kva_state_only && !native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false;
if (loop_on && !kva_state_only) strata::kernels::loop_lora_add(m.mixed, (int) N, m.Qf, kQFull, pass, l, strata::kernels::LoopTarget::kQsaQ, (int) T, m.cs);
pt.mark(kPfQsaIdxG, cs); // STRATA_PREFILL_TIMING: "qsa proj" is the k, v and q projections
if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
if (!kva_state_only && !bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) return false;
@@ -5347,7 +5453,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
++qsa_index;
if (!kv_prefetch_after(l + 1, qsa_index)) return false;
// no expert is consumed here: release the stream entries so the issuer cannot stall
consumed = std::max(consumed, seq_start[(size_t) l + 1]);
consumed = std::max(consumed, seq_start[sidx + 1]);
give_back(consumed);
break;
}
@@ -5572,6 +5678,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
pt.mark(kPfQsa, cs);
if (!gated) gate_attn(m.attn, m.Qf, m.attn_h, T, m.cs, ld_a);
if (!native_proj(m.gemm, wo, m.attn_h, m.bo, T, v.name("attn_output.weight"), err, 0, ld_a)) return false;
if (loop_on) strata::kernels::loop_lora_add_f16(m.attn_h, (int) (ld_a ? ld_a : kQW), m.bo, (int) N, pass, l, strata::kernels::LoopTarget::kQsaO, (int) T, m.cs);
++qsa_index;
if (!kv_prefetch_after(l + 1, qsa_index)) return false;
} else {
@@ -5584,6 +5691,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
if (!wr || !wgi || !wsg || !wsu || !wsd) return false;
pt.mark(kPfRouter, cs);
if (!bf16_proj(m.gemm, wr, m.mixed_bf, m.logits, T, v.name("ffn_gate_inp.weight"), err, 0, m.mixed_bf_lo)) return false;
if (loop_on) strata::kernels::loop_lora_add(m.mixed, (int) N, m.logits, (int) m.g->n_expert, pass, l, strata::kernels::LoopTarget::kMoeGate, (int) T, m.cs);
route(m.logits, m.ids, m.w, T, m.g->n_expert, m.cs);
// RESEARCH HOOK (141-research, opt-in, never on by default): STRATA_DBG_FEAT=<file> dumps, per MoE layer and chunk,
// the routed ids + weights (and for the layers in STRATA_DBG_FEAT_LAYERS the router-input hidden state, bf16);
@@ -5648,9 +5756,12 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// the shared expert and its scalar gate
auto shared_expert = [&]() -> bool {
if (!native_proj(m.gemm, wsg, m.mixed_h, m.sgate, T, v.name("ffn_gate_shexp.weight"), err)) return false;
if (loop_on) strata::kernels::loop_lora_add(m.mixed, (int) N, m.sgate, kFF, pass, l, strata::kernels::LoopTarget::kShGate, (int) T, m.cs);
if (!native_proj(m.gemm, wsu, m.mixed_h, m.sup, T, v.name("ffn_up_shexp.weight"), err)) return false;
if (loop_on) strata::kernels::loop_lora_add(m.mixed, (int) N, m.sup, kFF, pass, l, strata::kernels::LoopTarget::kShUp, (int) T, m.cs);
swiglu_pair(m.sgate, m.sup, m.sh_h, T, m.cs);
if (!native_proj(m.gemm, wsd, m.sh_h, m.shared, T, v.name("ffn_down_shexp.weight"), err)) return false;
if (loop_on) strata::kernels::loop_lora_add_f16(m.sh_h, kFF, m.shared, (int) N, pass, l, strata::kernels::LoopTarget::kShDown, (int) T, m.cs);
if (wgi->kind != core::WeightKind::Bf16InF32) { err = "prefill: shared gate is not BF16"; return false; }
m.gemm.bf16(m.mixed_bf, (const uint16_t*) wgi->data, m.sg, T, 1, N);
if (m.mixed_bf_lo) m.gemm.bf16(m.mixed_bf_lo, (const uint16_t*) wgi->data, m.sg, T, 1, N, 0, 1.0f);
@@ -5779,8 +5890,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
// of which at most a third of the ring streamed: the next batch's blobs arrive while one computes.
// An expert the routing did not pick has no tiles; its ring slot is given back with its batch.
const size_t per = (size_t) std::max(1, m.ring / 3);
size_t k = seq_start[(size_t) l];
const size_t kend = seq_start[(size_t) l + 1];
size_t k = seq_start[sidx];
const size_t kend = seq_start[sidx + 1];
// STRATA_PF_BATCH=N (opt-in): experts per launch (the same rows, so the same bits; a launch is one
// persistent grid, so fewer launches leave fewer grid tails) - at most kMaxBatch, or up to
// kBatchRoom in a WideBatch on the native NT = 256 kernels (STRATA_PF_FUSED_NT=256 or _F16=1) or
@@ -6154,7 +6265,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
const int32_t* layer_res = m.host_res && m.cache ? m.host_res + (size_t) l * m.g->n_expert : nullptr;
if (detail::mmq_resident_sort_eligible(tier_sort || ((sort_all || sort_full) && on_peer.empty()), use_mmq, lay.native,
m.cache != nullptr, layer_res, m.g->n_expert, stream_all,
!stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1], tier_sort)) {
!stream_all || seq_start[sidx] == seq_start[sidx + 1], tier_sort)) {
std::vector<char> layer_pin;
if (tier_sort && !stream_all && m.src != nullptr) {
layer_pin.assign((size_t) m.g->n_expert, 0);
@@ -6550,7 +6661,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
lay.native && m.cache != nullptr && m.host_res != nullptr && !wmma_l &&
!mmq_plan().direct[(size_t) l] && lay.fmt[(size_t) l].up_off == mmq_gub / 2 &&
order_peer.empty() && rows_cpu == 0 && rows_local == T * K && !m.fused_bufs && m.group_cap == 0 &&
(!stream_all || seq_start[(size_t) l] == seq_start[(size_t) l + 1]) && !had_gu && !had_d &&
(!stream_all || seq_start[sidx] == seq_start[sidx + 1]) && !had_gu && !had_d &&
!lay.fmt[(size_t) l].tail_off && !mmq::fp4_activations(mmq_gt) &&
!mmq::fp4_activations(mmq_dt) && mmq::swiglu_quant_ok(mmq_dt) &&
ws::supported(mmq_gt, mmq_dt) && ws::faster(mmq_gt, ws_u) && ws::faster(mmq_dt, ws_u)) {
@@ -6753,8 +6864,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
const uint8_t* bd = nullptr;
int psl = -1;
if (on_peer[(size_t) e] == 2) { // from the peer's ring
p_release_to(l, e, ps);
if (P.pk >= P.pseq_start[(size_t) l + 1] || P.pseq[P.pk].e != e) {
p_release_to(sidx, e, ps);
if (P.pk >= P.pseq_start[sidx + 1] || P.pseq[P.pk].e != e) {
err = "prefill: a peer-streamed expert is not next in the peer's ring";
cudaSetDevice(prevd);
return false;
@@ -6995,7 +7106,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
int pd = 0;
cudaGetDevice(&pd);
cudaSetDevice(m.pp->dev);
p_release_to(l, (int32_t) m.g->n_expert, m.pp->s);
p_release_to(sidx, (int32_t) m.g->n_expert, m.pp->s);
cudaSetDevice(pd);
}
// STRATA_PREFILL_GROUP_GATHER=0: one gather, one wait and one record per expert.
@@ -7534,8 +7645,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
} else {
// the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not
// pick only gives its slot back
size_t k = seq_start[(size_t) l];
const size_t kend = seq_start[(size_t) l + 1];
size_t k = seq_start[sidx];
const size_t kend = seq_start[sidx + 1];
// STRATA_I8_DEFER=1 (opt-in, the int8 expert groups only): a streamed entry the routing did not pick no longer
// launches the open int8 group early. Without it, every such entry while an int8 group holds ring slots runs the
// experts gathered so far as a launch of their own (MMQ's flush only gathers, its GEMM still waits for the full
@@ -7655,18 +7766,25 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
}
}
if (loop_on && strata::kernels::loop_adapter().dual_coda) // strata_dual_coda_loop_v1: the block's LoRA on its HC-mixed input, added to its output
strata::kernels::loop_lora_add_gated(m.mixed, (int) N, m.bo, (int) N, pass, l,
half == 0 ? strata::kernels::LoopTarget::kAttn : strata::kernels::LoopTarget::kMlp,
(int) T, m.cs, m.cd_omega);
pt.mark(kPfHcWrite, cs); // the write-back (and the next half's norm) on its own line; it used to be charged to the phase before
// ---- the hyper-connection write of this half; F-2: fused with the next half's norm when nothing else
// touches R in between (not the stage's last half, not before the PLE block of layer 1, not under a
// control vector)
const int64_t nl = half == 0 ? l : l + 1;
const bool next_exists = (half == 0) || (sidx + 1 < loop_plan.size());
const int64_t nl = half == 0 ? l : (next_exists ? loop_plan[sidx + 1].layer : LE);
const bool steered = half == 1 && strata::kernels::cvec().covers(l);
const bool loop_mat = half == 1 && loop_on && stp.materialize_after;
const float *cv_dir = nullptr, *cv_s = nullptr;
const int* cv_on = nullptr;
const bool cv_fused = steered && cvec_fuse() && !gr_unfused() && nl < LE && !(nl == 1 && ple_on) &&
const bool cv_fused = steered && !loop_mat && cvec_fuse() && !gr_unfused() && next_exists &&
!(nl == 1 && ple_on) &&
strata::kernels::cvec().n_embd == N && strata::kernels::cvec().hc == HC &&
strata::kernels::cvec_tables(&cv_dir, &cv_s, &cv_on);
const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && (!steered || cv_fused);
const bool fuse = !gr_unfused() && !loop_mat && next_exists && !(half == 1 && nl == 1 && ple_on) && (!steered || cv_fused);
const core::WeightRef* wnn = nullptr;
if (fuse) {
const core::LayerView vn(*m.wt, nl);
@@ -7719,8 +7837,23 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
if (steered && !cv_fused) // --control-vector-scaled
strata::kernels::cvec_apply(m.R, l, T, D, nullptr, 0, nullptr, 0, false, m.cs);
if (loop_mat) {
if (stp.save_anchor_after) {
cudaMemcpyAsync(m.R_anchor, m.R, (size_t) T * D * sizeof(float), cudaMemcpyDeviceToDevice, m.cs);
}
if (stp.save_mprev_after) {
if (pass == 0 && eff_cd_omega != 0.0f) {
cudaMemcpyAsync(m.R_m0, m.R, (size_t) T * D * sizeof(float), cudaMemcpyDeviceToDevice, m.cs);
}
if (pass == la_pf.num_passes - 1 && eff_cd_omega != 0.0f) {
strata::kernels::loop_cd_hidden_per_tok(m.R, m.R_m0, m.R, m.cd_omega, (int) T, m.cs);
}
cudaMemcpyAsync(m.R_mprev, m.R, (size_t) T * D * sizeof(float), cudaMemcpyDeviceToDevice, m.cs);
}
}
#if defined(STRATA_HAVE_DFLASH2)
if (half == 1 && tap_rows > 0 && tap_slot[(size_t) l] >= 0) // DFlash2: this layer's completed output, mean of the streams
if (half == 1 && tap_rows > 0 && tap_slot[(size_t) l] >= 0 && // DFlash2: this layer's completed output, mean of the streams
strata::kernels::loop_tap_pass(stp, la_pf, loop_bypass_)) // (a looped core: its final pass)
strata::kernels::df2_tap_rows(m.R + (size_t) tap_t0 * D, tap_dev_ + (size_t) tap_slot[(size_t) l] * N, (int64_t) tap_local_.size() * N, N,
(int) HC, (int) tap_rows, m.cs);
#endif
@@ -7742,9 +7875,28 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
std::fprintf(stderr, "strata prefill copies: %lld slot waits, %lld skipped as the same release event\n",
(long long) iss_waits, (long long) iss_dedup);
}
stats_.tokens += T;
if (cyc_vis_ == nullptr || cyc_vis_->owner_first) stats_.tokens += T;
core::progress_at("reading the prompt (batched): finishing the chunk from token", p0);
pt.mark(kPfStart, cs);
if (cyc_vis_ != nullptr && !cyc_vis_->head) {
// a cyclic split's visit before the final one: its rows (and the m_prev it relays) to its hand-off, which
// the next visit's stage reads once this returns (run_cyclic); the stage's taps and its checkpoint part
// after its last visit of the chunk
bool ok = cudaMemcpyAsync(cyc_out_, m.R, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) == cudaSuccess;
if (ok && cyc_mprev_out_ != nullptr)
ok = cudaMemcpyAsync(cyc_mprev_out_, m.R_mprev, (size_t) T * D * 4, cudaMemcpyDeviceToHost, m.cs) == cudaSuccess;
if (!ok || cudaStreamSynchronize(m.cs) != cudaSuccess) {
err = std::string("prefill: the cyclic layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
if (cyc_vis_->owner_last) {
#if defined(STRATA_HAVE_DFLASH2)
if (tap_rows > 0 && on_taps && !on_taps(tap_dev_, tap_rows, p0 + tap_t0, err)) return false;
#endif
if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false;
}
continue;
}
if (next_ != nullptr) {
// The current hand-off slot was used two chunks ago.
float* h = m.hand[hand_buf_];
@@ -7794,6 +7946,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
err = std::string("prefill: the layer split's hand-off: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
#if defined(STRATA_HAVE_DFLASH2)
// this stage's DFlash2 prompt taps: the landing waits for every tapping stage's rows (a looped adapter only:
// the stock split keeps its 0.2.23 behaviour)
if (tap_rows > 0 && on_taps && strata::kernels::loop_adapter().loaded()) {
if (cudaStreamSynchronize(m.cs) != cudaSuccess) { err = std::string("prefill: ") + cudaGetErrorString(cudaGetLastError()); return false; }
if (!on_taps(tap_dev_, tap_rows, p0 + tap_t0, err)) return false;
}
#endif
// Wait only for the DIRECT successor's previous chunk. That successor
// may already have forwarded its older chunk to later GPUs.
if (on_stage_chunk && !on_stage_chunk(p0 + T, err)) return false;
@@ -7818,6 +7978,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
next_->hand_pieces_ = hp;
next_->single_chunk_ = single_chunk;
next_->pipe_chunked_ = pipe_chunked;
next_->loop_cd_in_thinking_ = chunk_think_before;
if (handoff_pipe_worker()) {
if (!m.hand_worker) m.hand_worker = std::make_unique<HandWorker>();
next_run_ = m.hand_worker->submit(std::packaged_task<bool()>([this, tokens, c0, T, p0] {
@@ -7902,8 +8063,10 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
}
// Do not drain the successor here. This is the overlap: an intermediate
// stage can return while later GPUs are still processing the previous chunk.
ss.ple_prev[0] = prev[0];
ss.ple_prev[1] = prev[1];
if (cyc_vis_ == nullptr || cyc_vis_->owner_first) { // (a cyclic stage's later visits read the same tokens again)
ss.ple_prev[0] = prev[0];
ss.ple_prev[1] = prev[1];
}
if (std::getenv("STRATA_DBG_NAN") != nullptr) { // debug: the state the prompt leaves for the token path
cudaStreamSynchronize(m.cs);
auto bad = [&](const float* d, int64_t n) {
@@ -8417,6 +8580,7 @@ bool Prefill::run_multi(const std::vector<Seg>& segs, std::string& err) {
for (const Seg& sg : segs) total += sg.n;
std::string why;
if (hand_in_ != nullptr || !impl_) { err = "prefill: multi-prompt read declined (chunk hand-off in use)"; return false; }
if (cyc_ != nullptr) { err = "prefill: multi-prompt read declined (a cyclic layer split)"; return false; }
if (!tap_layers_.empty()) { err = "prefill: multi-prompt read declined (the DFlash2 prompt taps are for one prompt)"; return false; }
for (Prefill* q = this; q != nullptr; q = q->next_) q->lm_force_ = true;
struct ForceOff { Prefill* h; ~ForceOff() { for (Prefill* q = h; q != nullptr; q = q->next_) q->lm_force_ = false; } } force_off{this};
@@ -9589,6 +9753,173 @@ bool Prefill::lm_run(const std::vector<Seg>& segs, int depth, const std::vector<
return true;
}
void Prefill::set_cyclic(const std::vector<Prefill*>& paths, const std::vector<int64_t>& stage_begin,
const core::ModelGeometry& g) {
std::shared_ptr<Cyc> cy;
if (!paths.empty()) {
cy = std::make_shared<Cyc>();
cy->paths = paths;
cy->visits = strata::kernels::build_loop_itinerary(g.n_layers, g.qsa_interval, stage_begin);
}
for (size_t s = 0; s < paths.size(); ++s) {
paths[s]->cyc_ = cy;
paths[s]->cyc_stage_ = (int) s;
}
}
void Prefill::set_loop_request(int passes, float cd_omega, bool cd_thinking, bool in_thinking) {
const auto& la = strata::kernels::loop_adapter();
const bool bypass = la.loaded() && passes == 1;
auto apply = [&](Prefill* p) {
if (p == nullptr) return;
p->loop_req_set_ = true;
p->loop_bypass_ = bypass;
p->loop_cd_omega_ = cd_omega;
p->loop_cd_thinking_ = cd_thinking;
p->loop_cd_in_thinking_ = in_thinking;
};
if (cyc_ != nullptr) {
for (Prefill* p : cyc_->paths) apply(p);
}
for (Prefill* p = this; p != nullptr; p = p->next_) apply(p);
}
bool Prefill::run_cyclic(const int64_t* tokens, int64_t n, int64_t pos0, std::string& err) {
Cyc& cy = *cyc_;
const int S = (int) cy.paths.size();
if (cy.visits.empty() || S < 2 || cy.paths[0] != this) { err = "prefill: the cyclic layer split has no itinerary"; return false; }
const auto& la_cy = strata::kernels::loop_adapter();
const float eff_cd_omega = la_cy.loaded() ? (loop_req_set_ ? loop_cd_omega_ : la_cy.cd_omega) : 0.0f;
const bool eff_cd_thinking = loop_req_set_ ? loop_cd_thinking_ : la_cy.cd_thinking;
std::vector<float> cd_omega_all;
if (eff_cd_omega != 0.0f) {
cd_omega_all.resize((size_t) n, 0.0f);
strata::kernels::loop_cd_fill_omega(tokens, n, eff_cd_omega, eff_cd_thinking, la_cy.think_start_id,
la_cy.think_end_id, loop_cd_in_thinking_, cd_omega_all.data());
}
const int64_t forced = std::exchange(force_chunk_, 0);
const bool forced_single = force_single_, forced_planned = force_planned_;
const int64_t planned = forced > 0 ? 0 : plan_chunk(n);
int64_t C = forced > 0 ? forced : planned > 0 ? planned : impl_->T;
// run_impl's rule: a read the pipe chunked (here, or the engine's planned segment) takes no CPU share
const bool plan_chunked = forced > 0 ? forced_planned : planned > 0 && planned < std::min(n, impl_->T);
for (const Prefill* p : cy.paths) {
C = std::min(C, p->impl_->T);
if (p->impl_->hand_rows > 0) C = std::min(C, p->impl_->hand_rows);
}
if (C < 1) { err = "prefill: the cyclic layer split has no chunk"; return false; }
const int64_t nch = (n + C - 1) / C;
const size_t NV = cy.visits.size();
{
std::lock_guard<std::mutex> lk(cy.mu);
cy.done.assign(NV, 0);
cy.limit = nch;
cy.failed = false;
cy.err.clear();
}
stopped_at_ = -1;
auto fail = [&cy](const std::string& e) {
{
std::lock_guard<std::mutex> lk(cy.mu);
if (!cy.failed) { cy.failed = true; cy.err = e; }
}
cy.cv.notify_all();
};
// chunk c's visit gv may run: its rows are there, and its stage's hand-off buffer of this parity has been read
auto ready = [&cy, NV](size_t gv, int64_t c) {
if (gv > 0 && cy.done[gv - 1] <= c) return false;
if (c < 2 || cy.visits[gv].head) return true;
const int s = cy.visits[gv].owner;
for (size_t h = 0; h + 1 < NV; ++h)
if (cy.visits[h].owner == s && cy.done[h + 1] < c - 1) return false;
return true;
};
auto stage_body = [&, C, n, nch](int s) {
Prefill& P = *cy.paths[(size_t) s];
std::string e;
for (int64_t c = 0;; ++c)
for (size_t gv = 0; gv < NV; ++gv) {
const strata::kernels::LoopVisit& v = cy.visits[gv];
if (v.owner != s) continue;
{
std::unique_lock<std::mutex> lk(cy.mu);
cy.cv.wait(lk, [&] { return cy.failed || c >= cy.limit || ready(gv, c); });
if (cy.failed || c >= cy.limit) return;
}
if (gv == 0 && c > 0 && stop_at_chunk && stop_at_chunk()) { // the first stage ends the run before chunk c
{
std::lock_guard<std::mutex> lk(cy.mu);
cy.limit = c;
}
cy.cv.notify_all();
return;
}
const int64_t c0 = c * C, T = std::min(C, n - c0);
const int pb = (int) (c & 1);
const Impl* prev = gv > 0 ? cy.paths[(size_t) cy.visits[gv - 1].owner]->impl_.get() : nullptr;
P.cyc_vis_ = &v;
P.hand_in_ = v.embed ? nullptr : prev->hand[pb];
P.hand_ev_ = nullptr;
P.hand_pieces_ = 0;
P.cyc_mprev_in_ = v.mprev_in == 2 ? prev->hand_mp[pb] : nullptr;
P.cyc_out_ = v.head ? nullptr : P.impl_->hand[pb];
P.cyc_mprev_out_ = v.mprev_out ? P.impl_->hand_mp[pb] : nullptr;
P.cyc_cd_omega_ = cd_omega_all.empty() ? nullptr : (cd_omega_all.data() + c0);
P.single_chunk_ = nch == 1;
P.pipe_chunked_ = plan_chunked;
if (v.embed) P.force_chunk(T, nch == 1 ? (forced > 0 ? forced_single : true) : false, plan_chunked);
const bool ok = (v.embed || P.hand_in_ != nullptr) && (v.head || P.cyc_out_ != nullptr) &&
(v.mprev_in != 2 || P.cyc_mprev_in_ != nullptr) && (!v.mprev_out || P.cyc_mprev_out_ != nullptr) &&
P.run_impl(tokens + c0, T, pos0 + c0, e);
P.cyc_vis_ = nullptr;
if (!ok) {
fail(e.empty() ? std::string("prefill: the cyclic layer split's hand-off buffers are missing") : e);
return;
}
{
std::lock_guard<std::mutex> lk(cy.mu);
cy.done[gv] = c + 1;
}
cy.cv.notify_all();
}
};
// one exception boundary for every stage (a throwing callback or allocation): the run fails, the waiters wake
auto stage_loop = [&](int s) {
try {
stage_body(s);
} catch (const std::exception& ex) {
fail(std::string("prefill: the cyclic layer split: ") + ex.what());
} catch (...) {
fail("prefill: the cyclic layer split: an unknown exception");
}
cy.paths[(size_t) s]->cyc_vis_ = nullptr;
};
std::vector<std::thread> th;
try {
th.reserve((size_t) S - 1);
for (int s = 1; s < S; ++s)
th.emplace_back([&stage_loop, s] {
strata::platform::name_this_thread("strata-cyc");
strata::aux_cpus::pin_current_thread();
stage_loop(s);
});
} catch (const std::exception& ex) {
fail(std::string("prefill: the cyclic layer split could not start its stage threads: ") + ex.what());
}
stage_loop(0); // (returns at once when the start failed)
for (std::thread& t : th) t.join();
for (Prefill* p : cy.paths) {
p->cyc_vis_ = nullptr;
p->hand_in_ = nullptr;
p->cyc_mprev_in_ = nullptr;
p->cyc_out_ = p->cyc_mprev_out_ = nullptr;
p->cyc_cd_omega_ = nullptr;
}
if (cy.failed) { err = cy.err; return false; }
if (cy.limit < nch) stopped_at_ = cy.limit * C;
return true;
}
bool Prefill::drain_pipeline(std::string& err) {
bool ok = true;
@@ -9656,7 +9987,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
#endif
// layer-major prefill: STRATA_PREFILL_LAYER_MAJOR=1 / 0 win; unset, it is off everywhere (sm120_series.hpp prefill_layer_major_default: a layer split
// reads 32K prompts 37-55% sooner chunk-major, owner's yes 2026-11-02; the single-card small-cache rule sets the variable itself)
if (hand_in_ == nullptr && impl_ &&
if (hand_in_ == nullptr && impl_ && !strata::kernels::loop_adapter().loaded() &&
strata::prefill_layer_major_resolve(lm_env_text(), lm_hip, stage_count(), strata::qwen_defaults_026())) {
const bool by_default = !lm_env_explicit();
for (Prefill* p = this; p != nullptr; p = p->next_) p->lm_by_default_ = by_default;
@@ -9702,6 +10033,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e
(long long) off_in_row, why.c_str());
}
}
if (cyc_ != nullptr && cyc_stage_ == 0 && !loop_bypass_) return run_cyclic(tokens, n, pos0, err);
const bool body_ok = run_impl(tokens, n, pos0, err);
std::string drain_err;
+289 -42
View File
@@ -162,6 +162,7 @@
#endif
#include "strata/program/pipe_probe.hpp"
#include "strata/kernels/cvec.hpp"
#include "strata/kernels/loop_adapter.hpp"
#include "strata/core/progress.hpp"
#include "strata/core/stream_watch.hpp"
#include "strata/core/gpu_pause_time.hpp"
@@ -1207,6 +1208,14 @@ struct Options {
int cvec_first = -1, cvec_last = -1; ///< llama.cpp's defaults: 1 .. the last layer
int cvec_mode = 1; ///< 0 = project, 1 = add (llama.cpp's default)
int cvec_single = -1; ///< --cvec-dir single:L (project mode): layer L's direction everywhere
/// Looped Qwen3.8-Flash-Next recurrent core adapter (strata/kernels/loop_adapter.hpp). Opt-in.
std::string loop_adapter; ///< --loop-adapter FILE (.safetensors, optional sibling .json)
int loop_passes = 0; ///< --loop-passes N (default 2 when --loop-adapter is given)
std::string loop_coda = "universal"; ///< --loop-coda universal|compact: the dual-coda file's coda LoRA set (compact for the Compact tier)
float loop_cd_omega = 0.0f; ///< --loop-cd-omega F (optional LoopCD-Hidden weight, default 0.0)
bool loop_cd_thinking = false; ///< --loop-cd-thinking (gate LoopCD-Hidden to active <think>...</think> spans)
int32_t loop_cd_think_start = 248068; ///< --loop-cd-think-ids START END (<think>, default Qwen3.8-Flash-Next)
int32_t loop_cd_think_end = 248069; ///< --loop-cd-think-ids START END (</think>, default Qwen3.8-Flash-Next)
};
void usage() {
@@ -1376,6 +1385,12 @@ void usage() {
" --control-vector-layer-range A B the layers it follows (inclusive; default 1 .. the last)\n"
" --cvec-mode add|project h += s v (default) or h -= s (h.v) v with v unit\n"
" --cvec-dir per-layer|single:L each layer's own direction (default) or layer L's everywhere (project)\n"
" --loop-adapter FILE Looped Qwen3.8-Flash-Next recurrent adapter (.safetensors + optional sibling .json)\n"
" --loop-passes N recurrent core passes T when --loop-adapter is set (default 2; supports 2..8; 2..3 for the Qwen4 dual-coda file)\n"
" --loop-coda SET Qwen4-35B-A3B-Loop.safetensors only: universal (Ultra / Balanced / GGUF, default) or compact (the Compact tier)\n"
" --loop-cd-omega F optional ratio-preserving LoopCD-Hidden weight after final pass (default 0.0)\n"
" --loop-cd-thinking opt-in: gate LoopCD-Hidden to active <think>...</think> spans only\n"
" --loop-cd-think-ids START END <think> and </think> token IDs (default 248068 248069; implies --loop-cd-thinking)\n"
" --no-token-graph A/B: two graphs per layer (the host launches each) instead of one per token\n"
" --no-fused-gr A/B: the six-kernel hyper-connection read and a separate write (native)\n"
" --prefill CHUNK batched prompt processing in chunks of CHUNK tokens (needs --native); auto =\n"
@@ -4315,6 +4330,16 @@ int main(int argc, char** argv) {
else if (d.rfind("single:", 0) == 0) o.cvec_single = std::atoi(d.c_str() + 7);
else { std::fprintf(stderr, "--cvec-dir: per-layer or single:L, got '%s'\n", d.c_str()); return 2; }
}
else if (a == "--loop-adapter") o.loop_adapter = next("--loop-adapter");
else if (a == "--loop-passes") o.loop_passes = std::atoi(next("--loop-passes"));
else if (a == "--loop-coda") o.loop_coda = next("--loop-coda");
else if (a == "--loop-cd-omega") o.loop_cd_omega = std::strtof(next("--loop-cd-omega"), nullptr);
else if (a == "--loop-cd-thinking") o.loop_cd_thinking = true;
else if (a == "--loop-cd-think-ids") {
o.loop_cd_think_start = (int32_t) std::atoi(next("--loop-cd-think-ids"));
o.loop_cd_think_end = (int32_t) std::atoi(next("--loop-cd-think-ids"));
o.loop_cd_thinking = true;
}
else if (a == "--no-spec-split") o.spec_split = false;
else if (a == "--eos-ids") {
std::string e;
@@ -5202,6 +5227,13 @@ int main(int argc, char** argv) {
o.lookup_max_t = fix.lookup_max_t;
}
}
// --loop-adapter: the batched GDN commit is off (each extra pass replays its own states), so a window cannot be wider than
// kVerifyMaxT rows: the 12-token lookup default is clamped instead of ending the engine on the first request.
if (!o.loop_adapter.empty() && o.lookup_max_t > (int) strata::kernels::kVerifyMaxT) {
std::fprintf(stderr, "strata generate: --loop-adapter: --lookup-max-t %d is clamped to %d (no batched GDN commit under the loop)\n",
o.lookup_max_t, (int) strata::kernels::kVerifyMaxT);
o.lookup_max_t = (int) strata::kernels::kVerifyMaxT;
}
if (o.lookup_max_t > 0 && o.suffix_draft > 0 && o.spec >= 2) {
if (o.mtp_max_t == 0) o.mtp_max_t = o.spec;
o.spec = std::max(o.spec, std::min(o.lookup_max_t, strata::kernels::kVerifyLongT));
@@ -5974,6 +6006,23 @@ int main(int argc, char** argv) {
// room; STRATA_STAGE_TRIM=0, STRATA_SPLIT_EARLY_OFF=1 or STRATA_SPILL_OFF=1 keeps the old path.
// Dynamic drafter VRAM reserve: Q2_0 S2 stays at kDrafterMib (1000 MiB); larger native packs (e.g. Q4_0 / IQ4_NL:
// ~1675 MiB) scale up by their extra expert bytes so layer-split sizing keeps accurate VRAM headroom.
if (!o.loop_adapter.empty()) {
if (o.batch > 0) {
std::fprintf(stderr, "strata generate: --loop-adapter does not support --batch > 0 yet\n");
return 2;
}
const int passes = o.loop_passes > 0 ? o.loop_passes : 2;
std::string loop_sum, loop_err;
strata::kernels::loop_adapter_set_coda(o.loop_coda);
if (!strata::kernels::loop_adapter_load(o.loop_adapter, passes, o.loop_cd_omega, g.n_layers, g.n_embd, g.hc,
loop_sum, loop_err, o.loop_cd_thinking, o.loop_cd_think_start,
o.loop_cd_think_end)) {
std::fprintf(stderr, "strata generate: %s\n", loop_err.c_str());
return 2;
}
std::fprintf(stderr, "strata generate: loop adapter loaded (%s) from %s\n", loop_sum.c_str(),
o.loop_adapter.c_str());
}
const int64_t mtp_drafter_mib =
!o.mtp.empty() ? strata::core::MtpDrafter::reserve_mib(o.mtp, strata::program::stage_reserve::kDrafterMib)
: strata::program::stage_reserve::kDrafterMib;
@@ -6054,7 +6103,11 @@ int main(int argc, char** argv) {
std::vector<int64_t> at;
std::string ks;
int64_t run = 0;
for (int i = 0; i + 1 < nd; ++i) { run += share[(size_t) i]; at.push_back(run); ks += (ks.empty() ? "" : ",") + std::to_string(run); }
for (int i = 0; i + 1 < nd; ++i) {
run += share[(size_t) i];
at.push_back(run);
ks += (ks.empty() ? "" : ",") + std::to_string(run);
}
std::fprintf(stderr, "strata generate: short of GPU memory: CUDA%d has %.2f GiB free and a layer split card needs about %.2f GiB beside a full copy of the dense weights "
"(%.2f GiB): the split is chosen from what each card has free (--layer-split %s) and every card loads only the dense weights of its own layers "
"(STRATA_STAGE_TRIM=0 keeps the copies)\n",
@@ -6721,6 +6774,7 @@ int main(int argc, char** argv) {
: batch_blocks_pw ? "not with --batch slots (STRATA_PW_WITH_BATCH=1 keeps it for the solo path)"
: o.peer_device >= 1 ? "not with --peer-device"
: helpers ? "not with the helper caches (--expert-cache-device1..3, --remote-expert-opt)"
: strata::kernels::loop_adapter().loaded() ? "not with --loop-adapter (a cut inside the recurrent core visits the stages in turn)"
: nullptr;
if (off != nullptr) {
std::fprintf(stderr, "strata generate: --pipeline-windows %d is off: %s\n", o.pipeline_windows, off);
@@ -6821,6 +6875,10 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: layer split, CUDA%d: %s\n", st.dev, err.c_str());
return 1;
}
if (strata::kernels::loop_adapter().loaded() && !strata::kernels::loop_adapter_replicate(err)) {
std::fprintf(stderr, "strata generate: layer split, CUDA%d: %s\n", st.dev, err.c_str());
return 1;
}
// --vision: this device's image-position table (the identity until a picture request), read by every rope
// kernel its stage runs - set before any of its graphs is captured
if (o.vision) {
@@ -7184,6 +7242,18 @@ int main(int argc, char** argv) {
return native_pack ? strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(l), slot_guard)
: (int64_t) lay.max_blob;
};
// --loop-adapter: a window runs the recurrent core's layers once per pass, so a stage's work is its layers plus
// (passes - 1) x its core layers, and a core layer's misses are paid on every pass. A cut inside the core is a
// cyclic split (the window visits the stages in turn); two equal cards balance at the core's middle.
const auto& lad = strata::kernels::loop_adapter();
auto loop_w = [&](int64_t l) -> double {
return lad.loaded() && l >= lad.core_start && l < lad.core_end ? (double) lad.num_passes : 1.0;
};
auto work = [&](int64_t lb, int64_t le) -> double {
if (!lad.loaded()) return (double) (le - lb);
const int64_t in_core = std::max<int64_t>(0, std::min<int64_t>(le, lad.core_end) - std::max<int64_t>(lb, lad.core_start));
return (double) (le - lb) + (double) (lad.num_passes - 1) * (double) in_core;
};
// the predicted window time (ms) of a placement, and the routed mass its caches hold
std::vector<int64_t> held_cnt((size_t) ns, 0); // per-stage fill count, for the startability gate
const int64_t kAutoLendPct = [] {
@@ -7212,12 +7282,12 @@ int main(int argc, char** argv) {
const int64_t l = profile[r].first;
int st = 0;
while (st + 1 < ns && l >= at[(size_t) st]) ++st;
mass_i[(size_t) st] += mass[r];
mass_i[(size_t) st] += mass[r] * loop_w(l);
if (full[(size_t) st]) continue;
if (used[(size_t) st] + cost(l) > capr[(size_t) st]) { full[(size_t) st] = true; continue; } // as the fill
used[(size_t) st] += cost(l);
held_mass += mass[r];
held_i[(size_t) st] += mass[r];
held_i[(size_t) st] += mass[r] * loop_w(l);
++held;
++held_cnt[(size_t) st];
}
@@ -7229,7 +7299,7 @@ int main(int argc, char** argv) {
std::max(total_mass, 1e-9);
for (int i = 0; i < ns; ++i) {
const int64_t lb = i == 0 ? 0 : at[(size_t) i - 1], le = i + 1 < ns ? at[(size_t) i] : g.n_layers;
ms += (double) (le - lb) * layer_ms[(size_t) i];
ms += work(lb, le) * layer_ms[(size_t) i];
}
return ms;
};
@@ -7248,7 +7318,7 @@ int main(int argc, char** argv) {
double m = 0;
for (int i = 0; i < ns; ++i) {
const int64_t lb = i == 0 ? 0 : cuts[(size_t) i - 1], le = i + 1 < ns ? cuts[(size_t) i] : g.n_layers;
m = std::max(m, (double) (le - lb) * layer_ms[(size_t) i]);
m = std::max(m, work(lb, le) * layer_ms[(size_t) i]);
}
return m;
};
@@ -7404,8 +7474,13 @@ int main(int argc, char** argv) {
double acc = 0;
for (int i = 0; i + 1 < ns; ++i) {
acc += 1.0 / layer_ms[(size_t) i];
at[(size_t) i] = std::clamp<int64_t>((int64_t) std::llround(acc / total * (double) L),
i == 0 ? 2 : at[(size_t) i - 1] + 1, L - (ns - 1 - i));
int64_t k = (int64_t) std::llround(acc / total * (double) L);
if (lad.loaded()) { // the cut where the stages before it hold their share of the window's work
const double want = acc / total * work(0, L);
k = 1;
while (k < L && work(0, k) + 0.5 * loop_w(k) <= want) ++k;
}
at[(size_t) i] = std::clamp<int64_t>(k, i == 0 ? 2 : at[(size_t) i - 1] + 1, L - (ns - 1 - i));
}
consider();
};
@@ -7444,21 +7519,29 @@ int main(int argc, char** argv) {
std::vector<double> held_mass_at((size_t) ns * (size_t) L * stride, -1.0);
std::vector<int64_t> held_at(held_mass_at.size(), 0);
std::vector<int64_t> used_at(held_mass_at.size(), 0); // the fill's byte total, for the startability gate
std::vector<double> miss_w_at(lad.loaded() ? held_mass_at.size() : 0, 0.0); // --loop-adapter: pass-weighted missed mass
auto range_hold = [&](int i, int64_t lb, int64_t le) -> size_t {
const size_t key = ((size_t) i * (size_t) L + (size_t) lb) * stride + (size_t) le;
if (held_mass_at[key] < 0.0) {
// one stage's own carve, exactly as `predict` prices it
const int64_t room = stage_left(i, lb, le);
double hm = 0;
// one stage's own carve, exactly as `predict` prices it (--loop-adapter: with predict's trim credit too;
// the stock search keeps its own rule)
const int64_t room = miss_w_at.empty() ? stage_left(i, lb, le)
: stage_left(i, lb, le) + strata::program::split_rules::trim_credit(i, trim_frees(lb, le));
double hm = 0, mw = 0, hw = 0;
int64_t used = 0, cnt = 0;
bool stop = false;
for (size_t r = 0; r < profile.size(); ++r) {
const int64_t l = profile[r].first;
if (l < lb || l >= le) continue;
if (used + cost(l) > room) break; // the fill stops exactly where predict's does
mw += mass[r] * loop_w(l);
if (stop) continue;
if (used + cost(l) > room) { stop = true; if (miss_w_at.empty()) break; continue; } // the fill stops exactly where predict's does
used += cost(l);
hm += mass[r];
hw += mass[r] * loop_w(l);
++cnt;
}
if (!miss_w_at.empty()) miss_w_at[key] = mw - hw;
held_mass_at[key] = hm;
held_at[key] = cnt;
used_at[key] = used;
@@ -7472,9 +7555,14 @@ int main(int argc, char** argv) {
const size_t a = range_hold(0, 0, k1), b = range_hold(1, k1, k2);
const size_t c = range_hold(2, k2, k3), d = range_hold(3, k3, L);
const double hm = held_mass_at[a] + held_mass_at[b] + held_mass_at[c] + held_mass_at[d];
const double ms = miss_ms * (1.0 - hm / denom) +
(double) k1 * layer_ms[0] + (double) (k2 - k1) * layer_ms[1] +
(double) (k3 - k2) * layer_ms[2] + (double) (L - k3) * layer_ms[3];
const double ms = miss_w_at.empty()
? miss_ms * (1.0 - hm / denom) +
(double) k1 * layer_ms[0] + (double) (k2 - k1) * layer_ms[1] +
(double) (k3 - k2) * layer_ms[2] + (double) (L - k3) * layer_ms[3]
: miss_ms * (link_scale[0] * miss_w_at[a] + link_scale[1] * miss_w_at[b] +
link_scale[2] * miss_w_at[c] + link_scale[3] * miss_w_at[d]) / denom +
work(0, k1) * layer_ms[0] + work(k1, k2) * layer_ms[1] +
work(k2, k3) * layer_ms[2] + work(k3, L) * layer_ms[3];
if (min_stage_layers > 1 &&
strata::program::split_rules::smallest_stage({k1, k2, k3}, L) < min_stage_layers) continue;
if (!stage_floors.empty() && strata::program::split_rules::below_floors({k1, k2, k3}, L, stage_floors)) continue;
@@ -13131,6 +13219,20 @@ int main(int argc, char** argv) {
strata::prefill::Prefill* room_path = nullptr;
auto init_prompt_paths = [&]() -> int { // 0: ready; 1: failed (err set); 2: failed with "do not fit"
room_path = nullptr;
if (multi_gpu && !stages.empty()) { // --loop-adapter, a cut inside the core: the paths read a chunk's visits in turn
std::vector<int64_t> sbeg{0};
sbeg.insert(sbeg.end(), split_at.begin(), split_at.end());
if (strata::kernels::loop_split_cyclic(sbeg)) {
std::vector<strata::prefill::Prefill*> paths{&sp};
for (size_t i = 0; i < stages.size(); ++i) {
GpuStage& st = *stages[i];
st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr);
paths.push_back(&st.sp);
}
sp.set_stage(0, split_at[0], &stages[0]->sp);
strata::prefill::Prefill::set_cyclic(paths, sbeg, g);
}
}
for (size_t i = 0; i < stages.size(); ++i) {
GpuStage& st = *stages[i];
st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr);
@@ -13375,6 +13477,7 @@ int main(int argc, char** argv) {
// (--split-device 0: the second stage on this GPU, sharing its weights, session and cache - the A/B.)
strata::core::Verifier ver_same;
SplitDrive split_drive;
std::vector<strata::core::Verifier::CycHop> cyc_hops; // a cyclic split's itinerary (every stage's verifier points at it)
auto stage_ver = [&](int st) -> strata::core::Verifier& {
return st == 0 ? ver : split_same ? ver_same : stages[(size_t) st - 1]->ver;
};
@@ -13481,8 +13584,18 @@ int main(int argc, char** argv) {
const char* v = std::getenv("STRATA_SPLIT_OVERLAP");
return v != nullptr && std::atoi(v) != 0;
}();
// --loop-adapter with a cut inside the recurrent core: the window visits the stages in turn (a cyclic split)
std::vector<int64_t> stage_begin{0};
stage_begin.insert(stage_begin.end(), split_at.begin(), split_at.end());
const bool cyc_split = strata::kernels::loop_split_cyclic(stage_begin);
if (cyc_split && split_same) {
std::fprintf(stderr, "strata serve: --loop-adapter: a cut inside the recurrent core needs each stage on its own GPU (not --split-device 0)\n");
return 1;
}
// --pipeline-windows (#859) runs its own overlapped loop with its own hand-offs: the two do not mix
const bool overlap = overlap_asked && !split_same && o.pipeline_windows == 0;
const bool overlap = overlap_asked && !split_same && o.pipeline_windows == 0 && !cyc_split;
if (overlap_asked && cyc_split)
std::fprintf(stderr, "strata serve: STRATA_SPLIT_OVERLAP is off on a cyclic layer split (--loop-adapter)\n");
if (overlap_asked && o.pipeline_windows > 0)
std::fprintf(stderr, "strata serve: STRATA_SPLIT_OVERLAP is off beside --pipeline-windows %d "
"(that loop overlaps the stages itself)\n", o.pipeline_windows);
@@ -13516,6 +13629,35 @@ int main(int argc, char** argv) {
split_drive.cache_slot_off[st] = drive.d.cache_slot_off;
split_drive.pcie_num[st] = pcie_num_of(o.pcie_frac);
}
size_t cyc_visits = 0;
if (cyc_split) {
// one hand-in per stage, read by each of its visits but the first (the visits run one after another);
// a visit's hand-out is the next visit's stage's hand-in
const auto itin = strata::kernels::build_loop_itinerary(g.n_layers, g.qsa_interval, stage_begin);
const size_t hbc = (size_t) hrows * (size_t) strata::core::Verifier::cyclic_handoff_floats(g) * sizeof(float);
std::vector<float*> cyc_in((size_t) n_stages, nullptr);
for (float*& h : cyc_in) {
float* hh = nullptr;
if (cudaHostAlloc((void**) &hh, hbc, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess ||
cudaHostGetDevicePointer((void**) &h, hh, 0) != cudaSuccess) {
std::fprintf(stderr, "strata serve: the cyclic layer-split hand-off allocation failed\n");
return 1;
}
std::memset(hh, 0, hbc);
}
std::vector<std::vector<strata::kernels::LoopVisit>> per((size_t) n_stages);
std::vector<std::vector<float*>> outs((size_t) n_stages);
cyc_hops.clear();
for (size_t j = 0; j < itin.size(); ++j) {
const int s = itin[j].owner;
cyc_hops.push_back({&stage_ver(s), (int) per[(size_t) s].size()});
per[(size_t) s].push_back(itin[j]);
outs[(size_t) s].push_back(itin[j].head ? nullptr : cyc_in[(size_t) itin[j + 1].owner]);
}
for (int st = 0; st < n_stages; ++st)
stage_ver(st).set_cyclic(std::move(per[(size_t) st]), std::move(outs[(size_t) st]), cyc_in[(size_t) st], &cyc_hops);
cyc_visits = itin.size();
}
for (int st = 1; st < n_stages; ++st) {
bool ok_s = false;
if (split_same) {
@@ -13553,6 +13695,10 @@ int main(int argc, char** argv) {
" (CUDA" + std::to_string(split_same ? 0 : stages[(size_t) st - 1]->dev) + ")";
std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window%s\n", plan_s.c_str(),
overlap ? " (overlapped: STRATA_SPLIT_OVERLAP=1)" : "");
if (cyc_split)
std::fprintf(stderr, "strata serve: layer split: the cut is inside the looped core [%d,%d): each window visits the "
"stages %zu times in turn (T=%d)\n", strata::kernels::loop_adapter().core_start,
strata::kernels::loop_adapter().core_end, cyc_visits, strata::kernels::loop_adapter().num_passes);
}
// --pipeline-windows: the odd windows' verifiers and their hand-off (initialized before `ver`, which stays the
// watchdog's verifier), and the drafter's own row buffer, which either parity's rows are copied into
@@ -13981,6 +14127,9 @@ int main(int argc, char** argv) {
// checkpoints taken inside it
ConvCheckpoint::PromptPlan seg_plan;
bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with
uint64_t loop_key_cached = strata::kernels::loop_cache_key(
strata::kernels::loop_adapter().num_passes, strata::kernels::loop_adapter().cd_omega,
strata::kernels::loop_adapter().cd_thinking); // looped execution mode the live session and checkpoints were read with
// without --mtp the conversation cache stays on: a parked image carries the draft layer's K/V only when there is one
// (the snapshots accept a null draft)
// #3493: no --conversation-cache-mib given: size the cache for agent use from the RAM that is free now that the model is
@@ -14163,6 +14312,12 @@ int main(int argc, char** argv) {
{"keep_canonical", o.keep_canonical}, {"no_fused_gr", o.no_fused_gr},
{"no_fast_attn", o.no_fast_attn}, {"no_fused_gdn", o.no_fused_gdn},
{"no_fast_select", o.no_fast_select}, {"vision", o.vision}};
if (strata::kernels::loop_adapter().loaded()) {
const auto& lad = strata::kernels::loop_adapter();
c.switches.push_back({"loop_passes", lad.num_passes});
c.switches.push_back({"loop_core_start", lad.core_start});
c.switches.push_back({"loop_core_end", lad.core_end});
}
config_fp = strata::core::session_config_fingerprint(c);
}
id.model = *model_fp;
@@ -14329,6 +14484,7 @@ int main(int argc, char** argv) {
const std::vector<ImgKey>& imgs;
std::vector<ConvCheckpoint>& checks; ///< moved apart into stage parts for the capture, put back after
bool cvec;
uint64_t loop_key;
strata::core::SessionState& session; ///< stage 0's
std::vector<strata::core::SessionState*> stage_sessions; ///< the later stages', in stage order (stages[k]->dev)
const strata::core::QsaState* draft0; ///< the draft layer's K/V saved with stage 0's image (or none)
@@ -14413,14 +14569,14 @@ int main(int argc, char** argv) {
// nothing the outgoing chain does not, apart from the tail this conversation rewrote)
{
std::vector<size_t> gone;
const size_t dropped = conversations.drop_superseded(src.ids, src.imgs, src.checks, src.cvec, &gone);
const size_t dropped = conversations.drop_superseded(src.ids, src.imgs, src.checks, src.cvec, &gone, src.loop_key);
if (dropped)
std::fprintf(stderr, "strata serve: conversation cache: dropped %zu superseded cop%s of this "
"conversation; parked=%zu\n", dropped, dropped == 1 ? "y" : "ies", conversations.size());
// a longer snapshot of the same conversation makes the older ones useless, in RAM and on the SSD tier alike
// (never spilled, and a spilled one is deleted with its index file)
if (spill.enabled()) {
const auto on_ssd = spill.drop_superseded(src.ids, src.imgs, src.cvec);
const auto on_ssd = spill.drop_superseded(src.ids, src.imgs, src.cvec, src.loop_key);
gone.insert(gone.end(), on_ssd.begin(), on_ssd.end());
}
for (const size_t n : gone)
@@ -14442,11 +14598,11 @@ int main(int argc, char** argv) {
strata::core::ConversationCheckpointSplit& cs; std::vector<ConvCheckpoint>& checks; bool on;
~MergeBack() { if (on && !strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear(); }
} merge_back{cs, checks, n_st > 0};
const strata::core::ConversationView view{src.ids, src.imgs, n_st > 0 ? cs.stage0 : checks, src.cvec};
const strata::core::ConversationView view{src.ids, src.imgs, n_st > 0 ? cs.stage0 : checks, src.cvec, src.loop_key};
const int64_t retained_n = src.with_reuse ? conversations.retained_tokens() : 0;
// a batch slot's image carries no retained K/V (it describes the main session's conversation), and the
// main session's stays retained for its own park
auto reuse = src.with_reuse ? conversations.take_reuse_for(src.ids) // never another conversation's K/V
auto reuse = src.with_reuse ? conversations.take_reuse_for(src.ids, src.loop_key) // never another conversation's K/V
: strata::core::ConversationKvReuse{};
if (retained_n > 0 && reuse.unchanged_tokens < retained_n)
std::fprintf(stderr, "strata serve: conversation cache: retained K/V reused for %lld of its %lld tokens "
@@ -14460,7 +14616,7 @@ int main(int argc, char** argv) {
for (size_t k = 0; k < n_st; ++k) {
auto& st = stages[k];
const strata::core::OnDevice on(st->dev);
const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec};
const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec, src.loop_key};
size_t b = 0;
if (!strata::core::conversation_snapshot_bytes(view_k, *src.stage_sessions[k], g, draft_of(k), b, err)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (stage CUDA%d: %s)\n",
@@ -14611,7 +14767,7 @@ int main(int argc, char** argv) {
auto& st = stages[k];
const strata::core::OnDevice on(st->dev);
if (cudaDeviceSynchronize() != cudaSuccess) { err = "stage sync failed"; return false; }
const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec};
const strata::core::ConversationView view_k{src.ids, src.imgs, cs.parts[k], src.cvec, src.loop_key};
strata::core::SavedConversation part;
if (!strata::core::conversation_snapshot_save(part, view_k, *src.stage_sessions[k], g, draft_of(k), err,
std::move(stage_reuse[k]), &reused_bytes))
@@ -14656,7 +14812,7 @@ int main(int argc, char** argv) {
auto park_current_body = [&](size_t held) -> bool {
if (!conversations.enabled() || !live_ok || live.empty()) return true;
const size_t n_st = stages.size();
ParkSource src{live, live_imgs, checks, cvec_cached, ss, {},
ParkSource src{live, live_imgs, checks, cvec_cached, loop_key_cached, ss, {},
(n_st > 0 && !mtp_first) || !use_mtp ? nullptr : &mtp.kv_state(),
use_mtp && !mtp_first && n_st > 0 ? &mtp.kv_state() : nullptr, true, ""};
for (auto& st : stages) src.stage_sessions.push_back(&st->ss);
@@ -14972,7 +15128,8 @@ int main(int argc, char** argv) {
part_at.erase(part_at.begin(), part_at.upper_bound(done));
}
bool complete = parts.size() == stages.size() + 1;
for (const ConvCheckpoint& k : parts) complete = complete && !k.gdn.empty();
// a saved part holds the prefix's ids (a stage of QSA layers only has no GDN bytes); a failed copy left it empty
for (const ConvCheckpoint& k : parts) complete = complete && (int64_t) k.ids.size() == done;
saved = !complete || checkpoint_at(done, &parts); // an incomplete set: no checkpoint here
} else {
saved = checkpoint_at(done, nullptr, tail_checkpoint && !periodic_checkpoint);
@@ -16333,6 +16490,14 @@ int main(int argc, char** argv) {
slots_all += remote_experts[(size_t) r].resident();
mib_all += (int64_t) (remote_experts[(size_t) r].gib() * 1024.0);
}
std::string loop_info_s;
if (strata::kernels::loop_adapter().loaded()) {
const auto& lad = strata::kernels::loop_adapter();
char lbuf[160];
std::snprintf(lbuf, sizeof lbuf, " loop_passes=%d loop_cd_omega=%g loop_cd_thinking=%d",
lad.num_passes, (double) lad.cd_omega, lad.cd_thinking ? 1 : 0);
loop_info_s = lbuf;
}
// (#5012: experts = every routed (layer, expert) pair, so the Monitor shows "slots / experts" as a share)
std::printf("INFO logit_bias=1 context=%lld kv=%s kv_resident=%lld expert_slots=%lld experts=%lld expert_cache_mib=%lld "
"expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d "
@@ -16340,7 +16505,7 @@ int main(int argc, char** argv) {
"spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d "
"conversation_cache_min_free_mib=%lld conversation_cache_min_tokens=%lld "
"tail_role_token=%lld vram_elastic=%d "
"prefill_cap=%lld prefill_stages=%d stream_all_min=%lld prefill_pipe=%g%s engine=" STRATA_VERSION "\n",
"prefill_cap=%lld prefill_stages=%d stream_all_min=%lld prefill_pipe=%g%s%s engine=" STRATA_VERSION "\n",
(long long) o.max_context, o.kv.c_str(),
(long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1
? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0),
@@ -16361,7 +16526,8 @@ int main(int argc, char** argv) {
o.batch > 0 ? (" batch_slots=" + std::to_string(o.batch) +
" slot_cache=" + std::to_string(o.prompt_cache > 0 ? 1 : 0) +
" batch_groups=" + std::to_string(o.batch_groups) +
" slot_read=" + std::to_string(slot_read_cap ? 1 : 0)).c_str() : "");
" slot_read=" + std::to_string(slot_read_cap ? 1 : 0)).c_str() : "",
loop_info_s.c_str());
if (strata::core::manifest::enabled()) { // STRATA_MANIFEST: engine choice and budgets (a diagnostic; off by default)
auto& M = strata::core::manifest::instance();
M.engine("version", STRATA_VERSION);
@@ -16524,6 +16690,7 @@ int main(int argc, char** argv) {
} else {
strata::core::session_zero(ss, g, nullptr, main_cs);
cudaStreamSynchronize(main_stream);
ver.set_loop_cd_in_thinking(false);
}
drive.d.layers = 0;
drive.d.experts = 0;
@@ -17227,7 +17394,7 @@ int main(int argc, char** argv) {
}
const size_t n_st = stages.size();
static const std::vector<ImgKey> no_imgs;
ParkSource src{sl.ids, no_imgs, sl.checks, sl.cvec, *bslot_ss[0][(size_t) b], {},
ParkSource src{sl.ids, no_imgs, sl.checks, sl.cvec, 0, *bslot_ss[0][(size_t) b], {},
(n_st > 0 && !mtp_first) || !batch_mtp || batch_df2 ? nullptr : &slot_mtp[(size_t) b]->kv_state(),
batch_mtp && !batch_df2 && !mtp_first && n_st > 0 ? &slot_mtp[(size_t) b]->kv_state() : nullptr, false,
" from slot " + std::to_string(b)};
@@ -18828,7 +18995,7 @@ int main(int argc, char** argv) {
continue;
}
kept = disk_checks.size();
const strata::core::ConversationView view{live, live_imgs, disk_checks, cvec_cached};
const strata::core::ConversationView view{live, live_imgs, disk_checks, cvec_cached, loop_key_cached};
strata::core::SavedConversation meta;
std::vector<strata::core::SessionKvSource> sources;
// the live running state comes off the device in one synchronous copy
@@ -18926,6 +19093,7 @@ int main(int argc, char** argv) {
checks = std::move(image.checkpoints);
for (const ConvCheckpoint& c : checks) check_clock = std::max(check_clock, c.used);
cvec_cached = image.cvec;
loop_key_cached = image.loop_key;
live_ok = true;
if (nan_flush) { // #879: the file replaced the poisoned session; the parked ones go (no slots here)
nan_flush = false;
@@ -18970,6 +19138,15 @@ int main(int argc, char** argv) {
std::string req_bias_text;
bool req_bias_present = false;
int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent)
// Looped adapter per-request overrides (absent = engine start-up defaults):
// loop_passes=N: 1 (stock 48-layer bypass) or the loaded --loop-passes N
// loop_cd_omega=F: per-request LoopCD-Hidden extrapolation weight (0.0 disables)
// loop_cd_thinking=0|1: per-request <think>-only LoopCD-Hidden gating toggle
const auto& req_la = strata::kernels::loop_adapter();
int req_loop_passes = req_la.loaded() ? req_la.num_passes : 1;
bool req_loop_passes_set = false;
float req_loop_cd_omega = req_la.loaded() ? req_la.cd_omega : 0.0f;
bool req_loop_cd_thinking = req_la.loaded() ? req_la.cd_thinking : false;
// logprobs=K (0..20): after each "T id" an "LP logprob id:logprob ..." line.
// -1 (absent) = no LP lines, so a server that never asks sees today's output.
int req_logprobs = -1;
@@ -19023,6 +19200,9 @@ int main(int argc, char** argv) {
if (key == "logit_bias") { req_bias_text = tok.substr(eq + 1); req_bias_present = true; }
else if (key == "pen_from") req_pen_from = std::atoll(tok.c_str() + eq + 1);
else if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1);
else if (key == "loop_passes") { req_loop_passes = std::atoi(tok.c_str() + eq + 1); req_loop_passes_set = true; }
else if (key == "loop_cd_omega") req_loop_cd_omega = fv;
else if (key == "loop_cd_thinking") req_loop_cd_thinking = std::atoi(tok.c_str() + eq + 1) != 0;
else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0;
else if (key == "prefill") req_prefill_only = std::atoi(tok.c_str() + eq + 1) != 0;
else if (key == "pin") req_pin = std::max<long long>(0, std::atoll(tok.c_str() + eq + 1));
@@ -19078,6 +19258,26 @@ int main(int argc, char** argv) {
}
}
strata::prefill::Prefill::set_pipe_request(req_pipe); // every request sets it: none carries over
if (req_loop_passes_set) {
if (!req_la.loaded()) {
if (req_loop_passes != 1) {
std::printf("ERR loop_passes: engine was started without --loop-adapter (only 1 is valid, got %d)\n",
req_loop_passes);
continue;
}
} else if (req_loop_passes != 1 && req_loop_passes != req_la.num_passes) {
std::printf("ERR loop_passes: expected 1 (stock single-pass) or %d (loaded --loop-passes), got %d\n",
req_la.num_passes, req_loop_passes);
continue;
}
}
if (!std::isfinite(req_loop_cd_omega)) {
std::printf("ERR loop_cd_omega: expected a finite number\n");
continue;
}
if (!req_la.loaded() || req_loop_passes <= 1) {
req_loop_cd_omega = 0.0f;
}
bool req_df2 = use_df2; // --draft auto: this request's drafter, decided once the prompt is parsed (below)
std::vector<float> req_bias;
std::string bias_error;
@@ -19284,6 +19484,8 @@ int main(int argc, char** argv) {
return imgs_below(req_imgs, L) == pre_imgs;
};
const bool want_cvec = strata::kernels::cvec().loaded() ? req_cvec != 0 : true;
const uint64_t want_loop_key =
strata::kernels::loop_cache_key(req_loop_passes, req_loop_cd_omega, req_loop_cd_thinking);
// the last request's final commit may still be running on the verifier's stream (set_commit_async):
// everything below reads, restores or zeroes the session from other streams and the host (the end of the
// last request waited already; this covers a request that ended on an error path)
@@ -19417,7 +19619,7 @@ int main(int argc, char** argv) {
}
int64_t resume = 0;
bool from_live = false;
if (o.prompt_cache > 0 && want_cvec == cvec_cached) {
if (o.prompt_cache > 0 && want_cvec == cvec_cached && want_loop_key == loop_key_cached) {
if (live_ok && starts_with(live, live_imgs)) { resume = (int64_t) live.size(); from_live = true; }
for (const ConvCheckpoint& c : checks)
if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) {
@@ -19431,7 +19633,7 @@ int main(int argc, char** argv) {
// of a slot's checkpoint this request moved into `checks` (from the slot it is admitted to), -1: none
int lent_slot = -1;
int64_t moved_in = -1;
if (slot_ckpt_move_env() && o.prompt_cache > 0 && want_cvec == cvec_cached && live_ok)
if (slot_ckpt_move_env() && o.prompt_cache > 0 && want_cvec == cvec_cached && want_loop_key == loop_key_cached && live_ok)
for (int b = 0; b < (int) bs.size(); ++b) {
if (bs[(size_t) b].cvec != cvec_cached || bs[(size_t) b].tainted) continue; // (#879)
for (const ConvCheckpoint& c : bs[(size_t) b].checks) {
@@ -19511,7 +19713,7 @@ int main(int argc, char** argv) {
k + 1, (long long) (k < now.size() ? now[k].start : -1));
}
}
const auto parked = conversations.best(ids, req_imgs, want_cvec);
const auto parked = conversations.best(ids, req_imgs, want_cvec, want_loop_key);
// STRATA_SLOT_READ (opt-in: =1, with STRATA_PIPED_MTP; asked for by the server with slot_read=1, which then
// takes DONE and BADM without a token): the next turn of the conversation an idle slot holds is read IN
// that slot - its new tokens as rows of the slot's own windows in the pipelined groups, all kept - instead
@@ -19662,7 +19864,7 @@ int main(int argc, char** argv) {
const int64_t floor_tokens = std::max({resume, slot_tokens, parked.tokens});
int64_t held = 0;
spill_writer->for_each_held([&](const strata::core::SavedConversation& s) {
held = std::max(held, strata::core::conversation_image_prefix(s, ids, req_imgs, want_cvec).first);
held = std::max(held, strata::core::conversation_image_prefix(s, ids, req_imgs, want_cvec, want_loop_key).first);
});
if (held > floor_tokens) {
const auto t0 = Clock::now();
@@ -19671,7 +19873,7 @@ int main(int argc, char** argv) {
size_t at = SIZE_MAX;
std::pair<int64_t, bool> m{0, false};
for (size_t i = 0; i < done.size(); ++i) {
const auto mi = strata::core::conversation_image_prefix(done[i].item, ids, req_imgs, want_cvec);
const auto mi = strata::core::conversation_image_prefix(done[i].item, ids, req_imgs, want_cvec, want_loop_key);
if (mi.first > m.first) { m = mi; at = i; }
}
if (at != SIZE_MAX && m.first > floor_tokens) {
@@ -19688,7 +19890,7 @@ int main(int argc, char** argv) {
}
spill_reclaim(); // what the writer finished meanwhile is on the SSD tier: its RAM goes back before this request parks
if (!from_ssd && spill.enabled() && spill.size() > 0 && stages.empty()) {
const auto sp = spill.best(ids, req_imgs, want_cvec);
const auto sp = spill.best(ids, req_imgs, want_cvec, want_loop_key);
const auto sp_entry = sp.tokens > 0 ? spill.find(sp.serial) : std::nullopt;
if (sp_entry && sp.tokens > std::max({resume, slot_tokens, parked.tokens}) && spill_id) {
const auto t0 = Clock::now();
@@ -19832,7 +20034,7 @@ int main(int argc, char** argv) {
// conversation, a parked one coming back, a batch slot, a borrow, another cvec) parks as before.
bool reply_replaced = false;
if (!from_live && !incoming && !borrow && slot_source < 0 && lent_slot < 0 && live_ok && !pin_sibling &&
want_cvec == cvec_cached && resume > 0) {
want_cvec == cvec_cached && want_loop_key == loop_key_cached && resume > 0) {
std::vector<int64_t> live_pictures;
for (const ImgKey& k : live_imgs) live_pictures.push_back((int64_t) k.start);
for (const ConvCheckpoint& c : checks)
@@ -19851,7 +20053,7 @@ int main(int argc, char** argv) {
// it still holds this conversation's prefix, and re-parking writes the whole snapshot only for the next
// turn to drop it again. 0 (the default) parks every turn, as before.
const size_t park_held = o.conversation_cache_park_gain > 0
? conversations.parked_prefix_tokens(live, live_imgs, checks, cvec_cached)
? conversations.parked_prefix_tokens(live, live_imgs, checks, cvec_cached, loop_key_cached)
: 0;
const bool park_worth = o.conversation_cache_park_gain <= 0 || park_held == 0 ||
(int64_t) live.size() >= (int64_t) park_held + o.conversation_cache_park_gain;
@@ -19877,14 +20079,15 @@ int main(int argc, char** argv) {
"live; %lld past the resume point are not kept)\n",
(long long) resume, (long long) live.size(), (long long) (live.size() - resume));
// STRATA_PARK_ASYNC: the checkpoints this request drops after its park - all of them when another state
// comes in (a parked conversation, a borrow, a batch slot) or the cvec changes, else the ones off this
// comes in (a parked conversation, a borrow, a batch slot) or the cvec / loop mode changes, else the ones off this
// prompt's path (off_path below) - move into the parked image
struct ParkDrops {
std::function<bool(const ConvCheckpoint&)>& f;
~ParkDrops() { f = nullptr; }
} park_drops_reset{park_drops};
if (park_async_env()) {
const bool drops_all = incoming.has_value() || borrow || slot_source >= 0 || want_cvec != cvec_cached;
const bool drops_all = incoming.has_value() || borrow || slot_source >= 0 || want_cvec != cvec_cached ||
want_loop_key != loop_key_cached;
park_drops = [&, drops_all](const ConvCheckpoint& c) {
return drops_all || (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs);
};
@@ -19897,7 +20100,7 @@ int main(int argc, char** argv) {
if (swap_block_bytes != 0 && incoming && !from_ssd && taken.live &&
taken.tokens == (int64_t) incoming->live.ids.size() &&
!borrow && !keep_branch && !reply_replaced && park_worth && live_ok && !live.empty() &&
conversations.wants((int64_t) live.size()) && !conversations.has_reuse_for(live) &&
conversations.wants((int64_t) live.size()) && !conversations.has_reuse_for(live, loop_key_cached) &&
stages.empty() && o.batch == 0 && !kvg.on) {
swap_t0 = Clock::now();
struct SwapStage {
@@ -19905,7 +20108,7 @@ int main(int argc, char** argv) {
~SwapStage() { strata::core::progress_at("request"); strata::core::progress_beat(); }
} swap_stage;
try {
const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached};
const strata::core::ConversationView view{live, live_imgs, checks, cvec_cached, loop_key_cached};
strata::core::ConversationSwapPlan plan;
if (strata::core::conversation_snapshot_swap_prepare(plan, *incoming, view, ss, g,
use_mtp ? &mtp.kv_state() : nullptr, swap_block_bytes, err)) {
@@ -20114,6 +20317,7 @@ int main(int argc, char** argv) {
for (const ConvCheckpoint& c : checks)
if ((int64_t) c.ids.size() == parked.tokens) { live = c.ids; live_imgs = c.imgs; }
cvec_cached = donor->cvec;
loop_key_cached = donor->loop_key;
resume = parked.tokens;
from_live = false;
conversations.count_borrow();
@@ -20168,12 +20372,14 @@ int main(int argc, char** argv) {
if (!strata::core::conversation_checkpoints_merge(std::move(cs), checks)) checks.clear();
}
cvec_cached = incoming->cvec;
loop_key_cached = incoming->loop_key;
resume = taken.tokens; // (parked.tokens unless the image came from the SSD tier)
from_live = taken.live;
if (!swapped_parked && std::getenv("STRATA_SNAPSHOT_FULL_CAPTURE") == nullptr) {
std::vector<std::vector<strata::core::ConversationKv>> stage_kv; // every stage's, for its next park
for (auto& si : incoming->stage_images) stage_kv.push_back(std::move(si.kv));
conversations.retain(std::move(incoming->kv), int64_t(live.size()), std::move(stage_kv), live);
conversations.retain(std::move(incoming->kv), int64_t(live.size()), std::move(stage_kv), live,
loop_key_cached);
}
incoming.reset(); // Running-state/checkpoint copies are no longer needed.
lent_slot = -1; // (the main session holds the parked conversation now)
@@ -20182,10 +20388,11 @@ int main(int argc, char** argv) {
std::chrono::duration<double, std::milli>(Clock::now() - t0).count(),
conversations.size(), conversations.bytes());
}
if (want_cvec != cvec_cached) {
if (want_cvec != cvec_cached || want_loop_key != loop_key_cached) {
live_ok = false;
checks.clear();
cvec_cached = want_cvec;
loop_key_cached = want_loop_key;
}
if (strata::kernels::cvec().loaded()) strata::kernels::cvec_set_enabled(want_cvec);
// this request rewrites every cell from `resume` on, so a checkpoint past it (or not on this prompt's
@@ -20548,11 +20755,20 @@ int main(int argc, char** argv) {
std::fflush(stdout);
return true;
};
auto think_before = [&](int64_t pos) {
return req_la.loaded()
? strata::kernels::loop_think_state_after(ids.data(), pos, req_la.think_start_id,
req_la.think_end_id, false)
: false;
};
// tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals
auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool {
// (STRATA_LOGPOS reads every window's logits: the serial loop)
// the pipelined prompt read stays two-stage (three or more stages read serially; only the decode overlaps)
if (pipe && n_stages == 2 && pl_pw >= 1 && std::getenv("STRATA_LOGPOS") == nullptr) return read_windows_pl(a, b, e);
if (req_la.loaded() &&
!ver.set_loop_request(req_loop_passes, req_loop_cd_omega, req_loop_cd_thinking, think_before(a), e))
return false;
strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched"
// every token is committed and the picks are discarded: no head sampling (see set_head_sampling)
struct NoHeadSampling {
@@ -20974,7 +21190,12 @@ int main(int argc, char** argv) {
segs.push_back(sg);
used.push_back(&c);
}
if (segs.size() < 2) return sp.run(lead.tokens, lead.n, lead.pos0, ce);
if (segs.size() < 2) {
if (req_la.loaded())
sp.set_loop_request(req_loop_passes, req_loop_cd_omega, req_loop_cd_thinking,
think_before(lead.pos0));
return sp.run(lead.tokens, lead.n, lead.pos0, ce);
}
for (const CoReq* c : used) {
park_slot(c->slot); // the conversation the slot holds, before this read overwrites it
for (size_t k = 0; k < bslot_ss.size(); ++k) {
@@ -20992,6 +21213,9 @@ int main(int argc, char** argv) {
if (ce.rfind("prefill: multi-prompt read declined", 0) == 0) { // nothing was read: the usual run
std::fprintf(stderr, "strata batch: co-read of %zu prompt(s) declined (%s)\n", used.size(), ce.c_str());
ce.clear();
if (req_la.loaded())
sp.set_loop_request(req_loop_passes, req_loop_cd_omega, req_loop_cd_thinking,
think_before(lead.pos0));
return sp.run(lead.tokens, lead.n, lead.pos0, ce);
}
return false;
@@ -21019,6 +21243,9 @@ int main(int argc, char** argv) {
co_tried = true;
run_ok = co_run(q, r, e);
} else {
if (req_la.loaded())
sp.set_loop_request(req_loop_passes, req_loop_cd_omega, req_loop_cd_thinking,
think_before(q));
run_ok = sp.run(ids.data() + q, r - q, q, e);
}
if (run_ok && q == 0 && sp.kva_floor() > 0) { // KVA approximated the start of this prompt: remember which tokens
@@ -21329,6 +21556,9 @@ int main(int argc, char** argv) {
conc_thread_cpus();
try { // (an exception leaving a std::thread ends the process: a failed read instead)
if (planned) sp.force_chunk(plan.chunk, plan_single, plan.chunked);
if (req_la.loaded())
sp.set_loop_request(req_loop_passes, req_loop_cd_omega, req_loop_cd_thinking,
think_before(q0));
read_ok = sp.run(ids.data() + q0, b0 - q0, q0, read_err);
} catch (const std::exception& x) {
read_ok = false;
@@ -22799,6 +23029,11 @@ int main(int argc, char** argv) {
auto draft_df2 = [&](int) -> bool { return false; };
#endif
if (df2_trace != nullptr) std::fprintf(df2_trace, "# request prompt %lld df2 %d spec %d\n", (long long) n, req_df2 ? 1 : 0, S_mtp);
if (req_la.loaded() && !pl_ran && !cancelled &&
!ver.set_loop_request(req_loop_passes, req_loop_cd_omega, req_loop_cd_thinking, think_before(p), err)) {
std::printf("ERR %s\n", err.c_str());
return 1;
}
while (!pl_ran && !cancelled && produced_n < cap_now()) {
int T = 1;
policy.set_context(p);
@@ -24947,6 +25182,18 @@ int main(int argc, char** argv) {
return true;
};
int64_t p = spec_pos;
if (strata::kernels::loop_adapter().loaded()) {
const auto& cli_la = strata::kernels::loop_adapter();
const int64_t n_pr = std::min<int64_t>(p, (int64_t) o.tokens.size());
bool cli_th = strata::kernels::loop_think_state_after(
o.tokens.data(), n_pr, cli_la.think_start_id, cli_la.think_end_id, false);
if (p > n_pr && !produced.empty()) {
const int64_t n_gen = std::min<int64_t>(p - n_pr, (int64_t) produced.size());
cli_th = strata::kernels::loop_think_state_after(
produced.data(), n_gen, cli_la.think_start_id, cli_la.think_end_id, cli_th);
}
ver.set_loop_cd_in_thinking(cli_th);
}
int32_t x = (int32_t) tok;
std::vector<int32_t> drafts((size_t) o.spec, 0);
std::vector<float> dprob((size_t) o.spec, 1.0f);
+46 -9
View File
@@ -26,6 +26,11 @@ endif()
message(STATUS "strata-q4-lite version ${Q4LITE_VERSION}")
set(Q4LITE_CUDA_ARCH "86" CACHE STRING "CUDA architectures (semicolon list)")
option(Q4LITE_HIP "Build for AMD (HIP, wave32 RDNA2 / RDNA3 / RDNA4) instead of CUDA" OFF)
set(Q4LITE_HIP_ARCH "gfx1201" CACHE STRING "HIP architectures (semicolon list)")
if(Q4LITE_HIP)
set(CMAKE_HIP_ARCHITECTURES ${Q4LITE_HIP_ARCH}) # before the first target
endif()
option(Q4LITE_VENDORED_ZSTD "Link the bundled zstd decoder even when the system has libzstd (release packages)" OFF)
find_package(Threads REQUIRED)
@@ -68,33 +73,65 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$" AND NOT MSVC)
endif()
# --- the GPU part ---
set(CMAKE_CUDA_ARCHITECTURES ${Q4LITE_CUDA_ARCH})
set(CMAKE_CUDA_STANDARD 17)
enable_language(CUDA)
find_package(CUDAToolkit REQUIRED)
set(_ling ${engine_root}/src/ling32)
if(Q4LITE_HIP)
# AMD wave32 RDNA (gfx1030 .. gfx1201): the same sources through the hip_compat shim, as src/ling32 does (LING32_HIP)
set(CMAKE_HIP_STANDARD 17)
enable_language(HIP)
find_package(hip CONFIG REQUIRED)
set(_hc "${engine_root}/include/strata/hip_compat")
file(GLOB _q4_cu_files CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/*.cu" "${_ling}/*.cu")
set_source_files_properties(${_q4_cu_files} ${engine_root}/src/kernels/cuda/mla_latent_attn.cu PROPERTIES LANGUAGE HIP)
add_library(q4lite_hip_rt INTERFACE)
target_include_directories(q4lite_hip_rt BEFORE INTERFACE "${_hc}" "${engine_root}/include")
target_compile_definitions(q4lite_hip_rt INTERFACE STRATA_USE_HIP=1 STRATA_WMMA_GFX11=1)
file(TO_CMAKE_PATH "${_hc}/cuda_runtime.h" _hc_force)
file(TO_CMAKE_PATH "${_hc}/cuda_fp16.h" _hc_force_fp16)
target_compile_options(q4lite_hip_rt INTERFACE "$<$<COMPILE_LANGUAGE:CXX>:-include>" "$<$<COMPILE_LANGUAGE:CXX>:${_hc_force}>"
"$<$<COMPILE_LANGUAGE:HIP>:-include>" "$<$<COMPILE_LANGUAGE:HIP>:${_hc_force}>" "$<$<COMPILE_LANGUAGE:HIP>:-w>")
target_link_libraries(q4lite_hip_rt INTERFACE hip::host)
set(_q4_rt q4lite_hip_rt)
else()
set(CMAKE_CUDA_ARCHITECTURES ${Q4LITE_CUDA_ARCH})
set(CMAKE_CUDA_STANDARD 17)
enable_language(CUDA)
find_package(CUDAToolkit REQUIRED)
set(_q4_rt CUDA::cudart)
endif()
add_library(q4lite_gpu STATIC
# Ling's generic kernels (S_K GEMV / GEMM, FWHT, Q8_1, routed experts, grouped experts), compiled unchanged
${_ling}/ling32_kernels.cu ${_ling}/ling32_layers.cu ${_ling}/ling32_moe_tc.cu ${_ling}/ling32_mla_exp.cu ${_ling}/ling32_mla_exp_hip.cu
${engine_root}/src/kernels/cuda/mla_latent_attn.cu
# Qwen4
q4_model.cu q4_glue.cu q4_gemv.cu q4_moe.cu q4_engine.cu q4_tier.cu)
q4_model.cu q4_glue.cu q4_gemv.cu q4_hc.cu q4_moe.cu q4_engine.cu q4_tier.cu)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/q4_mixers_fn.cu")
# the token mixers: Flash-Next kernels at the q4_lite geometry + q4_gdn / q4_attn (q4_mixer_sources.cmake)
include(${CMAKE_CURRENT_SOURCE_DIR}/q4_mixer_sources.cmake)
if(Q4LITE_HIP)
set_source_files_properties(${Q4_MIXER_KERNELS} PROPERTIES LANGUAGE HIP) # the same files, compiled as HIP through the hip_compat shim
endif()
target_sources(q4lite_gpu PRIVATE q4_mixers_fn.cu ${Q4_MIXER_KERNELS})
target_compile_definitions(q4lite_gpu PUBLIC ${Q4_MIXER_DEFS})
set_source_files_properties(${Q4_MIXER_FASTMATH} PROPERTIES COMPILE_OPTIONS "--use_fast_math")
if(Q4LITE_HIP)
# clang has no --use_fast_math (left out: the HIP mixers run in plain float math); gdn_chunk.cu takes __half from the shim's cuda_fp16.h
set_source_files_properties(${engine_root}/src/prefill/gdn_chunk.cu PROPERTIES COMPILE_OPTIONS "-include;${_hc_force_fp16}")
else()
set_source_files_properties(${Q4_MIXER_FASTMATH} PROPERTIES COMPILE_OPTIONS "--use_fast_math")
endif()
target_include_directories(q4lite_gpu PRIVATE ${engine_root}/third_party/ggml)
else()
target_sources(q4lite_gpu PRIVATE q4_mixers_stub.cpp)
endif()
target_include_directories(q4lite_gpu PUBLIC ${engine_root}/include ${CMAKE_CURRENT_SOURCE_DIR} ${_ling})
target_compile_options(q4lite_gpu PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--expt-relaxed-constexpr;-lineinfo>)
target_link_libraries(q4lite_gpu PUBLIC q4lite_core CUDA::cudart)
set_target_properties(q4lite_gpu PROPERTIES CUDA_RUNTIME_LIBRARY Shared)
target_link_libraries(q4lite_gpu PUBLIC q4lite_core ${_q4_rt})
if(NOT Q4LITE_HIP)
set_target_properties(q4lite_gpu PROPERTIES CUDA_RUNTIME_LIBRARY Shared)
endif()
add_executable(strata-q4-lite q4_main.cpp)
target_compile_definitions(strata-q4-lite PRIVATE Q4LITE_VERSION="${Q4LITE_VERSION}")
target_link_libraries(strata-q4-lite PRIVATE q4lite_gpu)
set_target_properties(strata-q4-lite PROPERTIES CUDA_RUNTIME_LIBRARY Shared)
if(NOT Q4LITE_HIP)
set_target_properties(strata-q4-lite PROPERTIES CUDA_RUNTIME_LIBRARY Shared)
endif()
@@ -0,0 +1,62 @@
# q4lite HIP tests (Q4-HIP lane): the KEXP routed-expert kernels (src/q4lite/q4_moe.cu), compiled as HIP through Ling's hip_compat shim (wave32 RDNA, gfx1030 .. gfx1201), their CPU
# reference and tests. Standalone like kexp_tests:
#
# cmake -S engine/src/q4lite/hip_tests -B build-q4h -G Ninja -DQ4H_HIP_ARCH="gfx1201" -DCMAKE_HIP_COMPILER=<rocm>/llvm/bin/clang++ ...
# cmake --build build-q4h -j && ctest --test-dir build-q4h --output-on-failure
cmake_minimum_required(VERSION 3.24)
project(q4_hip LANGUAGES C CXX)
set(Q4H_HIP_ARCH "gfx1201" CACHE STRING "HIP architectures (semicolon list)")
set(CMAKE_HIP_ARCHITECTURES ${Q4H_HIP_ARCH})
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Threads REQUIRED)
get_filename_component(engine_root "${CMAKE_CURRENT_SOURCE_DIR}/../../.." ABSOLUTE)
set(q4_src "${engine_root}/src/q4lite")
set(l32_src "${engine_root}/src/ling32")
set(tests_dir "${engine_root}/tests/q4lite")
set(_zd "${engine_root}/third_party/zstd-dec")
add_library(strata_zstd_dec STATIC
${_zd}/common/debug.c ${_zd}/common/entropy_common.c ${_zd}/common/error_private.c ${_zd}/common/fse_decompress.c
${_zd}/common/xxhash.c ${_zd}/common/zstd_common.c ${_zd}/decompress/huf_decompress.c ${_zd}/decompress/zstd_ddict.c
${_zd}/decompress/zstd_decompress.c ${_zd}/decompress/zstd_decompress_block.c)
target_include_directories(strata_zstd_dec PUBLIC ${_zd} ${_zd}/common ${_zd}/decompress)
target_compile_definitions(strata_zstd_dec PRIVATE ZSTD_DISABLE_ASM=1)
add_library(q4k_core STATIC ${engine_root}/src/artifact/strata_reader.cpp ${engine_root}/src/platform/direct_file.cpp ${q4_src}/q4_moe_cpu.cpp ${l32_src}/ling32_cpu_expert.cpp)
target_include_directories(q4k_core PUBLIC ${engine_root}/include ${q4_src} ${l32_src})
target_link_libraries(q4k_core PUBLIC strata_zstd_dec Threads::Threads)
set_source_files_properties(${l32_src}/ling32_cpu_expert.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c;-ffp-contract=off")
set_source_files_properties(${q4_src}/q4_moe_cpu.cpp PROPERTIES COMPILE_OPTIONS "-mfma;-ffp-contract=off")
enable_testing()
add_executable(q4_codec_test ${tests_dir}/q4_codec_test.cpp)
target_link_libraries(q4_codec_test PRIVATE q4k_core)
add_test(NAME q4_codec_test COMMAND q4_codec_test ${tests_dir}/data/golden_codec.bin $ENV{Q4_COMPACT_FILE})
set(CMAKE_HIP_STANDARD 17)
enable_language(HIP)
find_package(hip CONFIG REQUIRED)
set(_hc "${engine_root}/include/strata/hip_compat")
set_source_files_properties(${q4_src}/q4_moe.cu PROPERTIES LANGUAGE HIP)
add_library(q4h_hip_rt INTERFACE)
target_include_directories(q4h_hip_rt BEFORE INTERFACE "${_hc}" "${engine_root}/include")
target_compile_definitions(q4h_hip_rt INTERFACE STRATA_USE_HIP=1 STRATA_WMMA_GFX11=1)
file(TO_CMAKE_PATH "${_hc}/cuda_runtime.h" _hc_force)
target_compile_options(q4h_hip_rt INTERFACE "$<$<COMPILE_LANGUAGE:CXX>:-include>" "$<$<COMPILE_LANGUAGE:CXX>:${_hc_force}>"
"$<$<COMPILE_LANGUAGE:HIP>:-include>" "$<$<COMPILE_LANGUAGE:HIP>:${_hc_force}>" "$<$<COMPILE_LANGUAGE:HIP>:-w>")
target_link_libraries(q4h_hip_rt INTERFACE hip::host)
add_library(q4k_gpu STATIC ${q4_src}/q4_moe.cu)
target_include_directories(q4k_gpu PUBLIC ${engine_root}/include ${q4_src} ${l32_src})
target_link_libraries(q4k_gpu PUBLIC q4k_core q4h_hip_rt)
foreach(_t q4_moe_test q4_moe_bench)
if(EXISTS ${tests_dir}/${_t}.cpp)
add_executable(${_t} ${tests_dir}/${_t}.cpp)
target_link_libraries(${_t} PRIVATE q4k_gpu)
endif()
endforeach()
if(EXISTS ${tests_dir}/q4_moe_test.cpp)
add_test(NAME q4_moe_test COMMAND q4_moe_test ${tests_dir}/data/golden_codec.bin $ENV{Q4_COMPACT_FILE})
endif()
+52
View File
@@ -19,6 +19,7 @@
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include <vector>
namespace strata::q4lite {
@@ -301,6 +302,57 @@ bool attn_run(const AttnShape& s, const AttnWeights& w, const AttnState& st, Att
return launch_ok(err, "attn_run");
}
// ---- graph-capturable decode
namespace {
__global__ void decode_pos_kernel(int32_t* pos, int32_t* steps, int p, int budget, int ixb) {
const int i = threadIdx.x;
if (i < 16) pos[i] = p;
if (i == 0) {
const int n_kv = p + 1;
steps[K::kStepPos] = p;
steps[K::kStepNKv] = n_kv;
steps[K::kStepNBid] = n_kv / ixb;
steps[K::kStepWidth] = min(n_kv, budget + n_kv % ixb);
}
}
} // namespace
size_t attn_decode_dev_bytes() { return 128; }
bool attn_decode_dev_assign(void* base, AttnDecodeDev& o) {
if (!base) return false;
o.pos = (int32_t*) base;
o.steps = (int32_t*) ((uint8_t*) base + 64);
return true;
}
void attn_decode_set_pos(const AttnShape& s, const AttnDecodeDev& d, int pos, cudaStream_t stream) {
decode_pos_kernel<<<1, 32, 0, stream>>>(d.pos, d.steps, pos, s.ix_budget, s.ixb);
}
bool attn_decode_dev(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const AttnDecodeDev& d, const float* q_proj, const float* k_proj,
const float* v_proj, const float* idx_qk, float* out, cudaStream_t stream, std::string& err) {
if (!shape_ok(s, err)) return false;
if (s.nh > 16 || s.nkv > 16 || s.ixh > 16) { err = "attn_decode_dev: more than 16 rows per token"; return false; }
const K::QsaShapes q = qshapes(s);
const int qw = s.ixh * s.ixd;
try {
K::native_qsa_rms_norm_rope(q_proj, 2 * s.hd, w.q_g, sc.q, s.nh, s.hd, s.n_rot, kEps, K::rope_scaling(), d.pos, stream);
K::native_qsa_rms_norm_rope(k_proj, s.hd, w.k_g, sc.k, s.nkv, s.hd, s.n_rot, kEps, K::rope_scaling(), d.pos, stream);
split_idx_kernel<<<(unsigned) ((qw + s.ixd + 255) / 256), 256, 0, stream>>>(idx_qk, sc.qi, sc.raw, 1, qw, s.ixd);
K::native_qsa_rms_norm_rope(sc.qi, s.ixd, w.ixq_g, sc.qi, s.ixh, s.ixd, s.n_rot, kEps, K::rope_scaling(), d.pos, stream);
K::kv_append_step(st.k_pool, st.v_pool, st.page_table, d.steps, sc.k, v_proj, q, stream);
const K::QsaIndexerBuffers ib{st.ix_tail, st.ix_dead, st.ix_pooled, st.ix_block_pos};
K::native_qsa_indexer_append(sc.raw, d.steps + K::kStepPos, 0, w.ixk_g, kEps, ib, q, st.max_ctx, K::rope_scaling(), stream);
K::qsa_block_scores(st.ix_pooled, st.ix_dead, sc.qi, d.steps, 1, sc.max_blocks, q, sc.sel_scores, stream); // capacity grid (active = -1)
K::qsa_block_topk(sc.sel_scores, d.steps, 1, sc.max_blocks, sc.cap, q, sc.sel_ids, stream);
K::qsa_decode_attn_batch(sc.q, pools_of(st), sc.sel_ids, d.steps, sc.cap, q, sc.attn_scratch, sc.attn, 1, stream);
K::native_qsa_gate_apply(sc.attn, q_proj, out, s.nh, s.hd, stream);
} catch (const std::exception& e) {
err = std::string("attn_decode_dev: ") + e.what();
return false;
}
return launch_ok(err, "attn_decode_dev");
}
bool attn_rollback(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, AttnVerifyBuf& vb, int n_keep, cudaStream_t stream, std::string& err,
const AttnOptions& opt) {
if (n_keep < 0 || n_keep > vb.n) { err = "attn_rollback: n_keep out of range"; return false; }
+14
View File
@@ -99,6 +99,20 @@ struct AttnOptions {
bool attn_run(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const float* q_proj, const float* k_proj, const float* v_proj,
const float* idx_qk, int N, int pos0, float* out, cudaStream_t stream, std::string& err, const AttnOptions& opt = AttnOptions(),
AttnVerifyBuf* vb = nullptr);
// ---- graph-capturable single-token decode. Everything that depends on the position lives in DEVICE memory (a step record {pos, n_kv, n_bid, width} and the rope
// positions of the rows), written by attn_decode_set_pos BEFORE each graph launch (one 1-thread kernel launch outside the graph); attn_decode_dev then launches
// only kernels whose arguments and grids are constant for the whole context (capacity-sized grids, counts read from the step record), so it can be captured once
// and replayed for every token. Needs a warm-up call outside the capture (lazy kernel attributes): attn_decode_dev once, eagerly, before the first capture.
struct AttnDecodeDev {
int32_t* pos = nullptr; // [16] the position, repeated (rope positions of the 16 query rows)
int32_t* steps = nullptr; // [4] step record of the token
};
size_t attn_decode_dev_bytes();
bool attn_decode_dev_assign(void* base, AttnDecodeDev& out);
void attn_decode_set_pos(const AttnShape& s, const AttnDecodeDev& d, int pos, cudaStream_t stream);
bool attn_decode_dev(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, const AttnDecodeDev& d, const float* q_proj, const float* k_proj,
const float* v_proj, const float* idx_qk, float* out, cudaStream_t stream, std::string& err);
// the state after the first n_keep tokens of the window attn_run(..., vb) processed (0 <= n_keep <= vb.n): KV needs nothing (positions are overwritten), the indexer's
// tail is restored and the kept tokens' raw keys re-appended
bool attn_rollback(const AttnShape& s, const AttnWeights& w, const AttnState& st, AttnScratch& sc, AttnVerifyBuf& vb, int n_keep, cudaStream_t stream,
+44 -17
View File
@@ -3,6 +3,7 @@
#include "q4_glue.hpp"
#include "q4_mixers.hpp"
#include "q4_hc.hpp"
#include "q4_moe.hpp"
#include "ling32_kernels.hpp"
#include "strata/kernels/ngram.hpp"
@@ -54,7 +55,8 @@ void moe_routed(const GpuModel& m, MoeScratch& ms, int grouped_min_n, int il, in
} // namespace
struct Q4Engine::Impl {
cudaStream_t s = nullptr;
cudaStream_t s = nullptr, s2 = nullptr; // s2: the shared expert runs beside the router and the routed experts
cudaEvent_t ev_fork = nullptr, ev_join = nullptr;
std::unique_ptr<Mixers> mix;
strata::kernels::PleTable* ple = nullptr;
PleHash hash;
@@ -94,6 +96,9 @@ bool Q4Engine::init(GpuModel& model, const EngineOptions& o, strata::kernels::Pl
I.V = c.V;
I.ple = ple;
if (!cu_ok(cudaStreamCreateWithFlags(&I.s, cudaStreamNonBlocking), "stream", err)) return false;
if (!cu_ok(cudaStreamCreateWithFlags(&I.s2, cudaStreamNonBlocking), "stream 2", err) || !cu_ok(cudaEventCreateWithFlags(&I.ev_fork, cudaEventDisableTiming), "event", err) ||
!cu_ok(cudaEventCreateWithFlags(&I.ev_join, cudaEventDisableTiming), "event", err))
return false;
const size_t M = opt.max_tokens, D = c.D, HD = c.hcD();
bool ok = dalloc(&I.d_ids, M, "ids", err) && dalloc(&I.h, M * HD, "h", err) && dalloc(&I.hn, M * HD, "hn", err) && dalloc(&I.u, M * HD, "u", err) &&
dalloc(&I.x, M * D, "x", err) && dalloc(&I.y, M * D, "y", err) && dalloc(&I.t, M * c.hc_rank, "t", err) && dalloc(&I.raw, M * c.hc, "raw", err) &&
@@ -156,6 +161,9 @@ void Q4Engine::destroy() {
if (I.h_embstage) { cudaFreeHost(I.h_embstage); I.h_embstage = nullptr; }
if (I.ridx) { cudaFree(I.ridx); I.ridx = nullptr; }
if (I.s) { cudaStreamDestroy(I.s); I.s = nullptr; }
if (I.s2) { cudaStreamDestroy(I.s2); I.s2 = nullptr; }
if (I.ev_fork) { cudaEventDestroy(I.ev_fork); I.ev_fork = nullptr; }
if (I.ev_join) { cudaEventDestroy(I.ev_join); I.ev_join = nullptr; }
m_ = nullptr;
}
@@ -234,30 +242,42 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
gpu::hc_repeat(I.xr, N, c.hc, D, I.h, st);
};
// hyper-connection read: h -> x (the mixed input of the sub-layer) and raw (the inject weights); optionally xr = fwht128(x)
static const bool no_fuse = std::getenv("STRATA_Q4_NOFUSE") != nullptr;
auto f_hc_read = [&](const HcWeights& hw, bool want_xr, cudaStream_t st) {
gpu::hc_norm(I.h, hw.norm, N, c.hc, D, c.eps, I.hn, st);
L::fwht128(I.hn, I.rot, N, HD, st);
gemv_dense(hw.down, I.rot, N, I.t, c.hc_rank, st);
gpu::hc_down_act(I.t, N, c.hc_rank, c.hc, st);
L::fwht128(I.t, I.trot, N, c.hc_rank, st);
gemv_dense(hw.up, I.trot, N, I.u, HD, st);
gpu::hc_mix(I.u, I.hn, N, c.hc, D, I.x, st);
if (hw.inject.p) gemv_dense(hw.inject, I.rot, N, I.raw, c.hc, st);
if (!no_fuse && N == 1 && hw.down.qp && hw.up.qp && (!hw.inject.p || hw.inject.qp) && gpu::hc_fused_ok(c.hc, D, c.hc_rank, HD)) {
gpu::hc_read_fused(I.h, hw.norm, hw.down.qp, hw.down.ep, hw.up.qp, hw.up.ep, hw.inject.p ? hw.inject.qp : nullptr, hw.inject.p ? hw.inject.ep : nullptr, c.hc, D, c.hc_rank, c.eps, I.hn,
I.rot, I.t, I.raw, I.x, st);
} else {
gpu::hc_norm(I.h, hw.norm, N, c.hc, D, c.eps, I.hn, st);
L::fwht128(I.hn, I.rot, N, HD, st);
gemv_dense(hw.down, I.rot, N, I.t, c.hc_rank, st);
gpu::hc_down_act(I.t, N, c.hc_rank, c.hc, st);
L::fwht128(I.t, I.trot, N, c.hc_rank, st);
gemv_dense(hw.up, I.trot, N, I.u, HD, st);
gpu::hc_mix(I.u, I.hn, N, c.hc, D, I.x, st);
if (hw.inject.p) gemv_dense(hw.inject, I.rot, N, I.raw, c.hc, st);
}
if (want_xr) L::fwht128(I.x, I.xr, N, D, st);
};
auto f_inject = [&](cudaStream_t st) { gpu::hc_inject(I.h, I.y, I.raw, N, c.hc, D, st); };
auto f_moe = [&](int il, cudaStream_t st) {
const MoeLayer& e = m_->layers[il].moe;
L::fwht128(I.x, I.xr, N, D, st); // x in the FWHT-128 domain: the shared expert's dense weights and the routed experts read it
// the shared expert on a second stream (fork / join with events: also inside a captured graph) beside the router and the routed experts
const bool two = !opt.profile && I.s2 && !std::getenv("STRATA_Q4_ONE_STREAM");
cudaStream_t s2 = two ? I.s2 : st;
if (two) { cudaEventRecord(I.ev_fork, st); cudaStreamWaitEvent(s2, I.ev_fork, 0); }
L::gemv2_swiglu_s8(e.sh_gate.p, e.sh_up.p, c.I_shared, D, I.xr, N, 0.0f, false, I.sh_a, c.I_shared, s2);
L::fwht128(I.sh_a, I.shr, N, c.I_shared, s2);
gemv_dense(e.sh_down, I.shr, N, I.sh_y, D, s2);
L::gemv_f32(e.sh_gate_w, 1, D, I.x, N, I.sg, s2); // BF16 tensors are plain (unrotated x)
if (two) cudaEventRecord(I.ev_join, s2);
L::gemv_f32(e.gate, c.n_exp, D, I.x, N, I.rlog, st);
gpu::route_topk(I.rlog, N, c.n_exp, c.top_k, c.norm_topk, I.ridx, I.rw, st);
L::fwht128(I.x, I.xr, N, D, st); // x in the FWHT-128 domain: the shared expert's dense weights and the routed experts read it
L::gemv2_swiglu_s8(e.sh_gate.p, e.sh_up.p, c.I_shared, D, I.xr, N, 0.0f, false, I.sh_a, c.I_shared, st);
L::fwht128(I.sh_a, I.shr, N, c.I_shared, st);
gemv_dense(e.sh_down, I.shr, N, I.sh_y, D, st);
L::gemv_f32(e.sh_gate_w, 1, D, I.x, N, I.sg, st); // BF16 tensors are plain (unrotated x)
if (opt.profile) sec("router_shared");
moe_routed(*m_, I.moe, opt.moe_tc_min_n, il, N, I.ridx, I.xr, I.gu, I.act, I.ye, st);
if (opt.profile) sec("moe_routed");
if (two) cudaStreamWaitEvent(st, I.ev_join, 0);
gpu::moe_merge(I.ye, I.rw, I.sh_y, I.sg, N, c.top_k, D, I.y, st);
};
auto f_final = [&](cudaStream_t st) {
@@ -316,6 +336,9 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
bool first = true; // the first segment starts with the embedding
auto seg_begin_layer = [&](int il) {};
(void)seg_begin_layer;
// attention layers inside the graph (device-side position, constant-grid kernels) when the mixers support it: the only eager point left is the PLE gather
const bool attn_in_graph = I.mix->decode_graph_ok() && !std::getenv("STRATA_Q4_ATTN_EAGER");
if (attn_in_graph && !I.mix->set_decode_pos(pos_, s, err)) return false;
int il = 0;
bool carry_sub1 = false; // layer il's attention mixer has just run eagerly: its inject and the mlp half come first in the next segment
while (il < c.n_layers && ok) {
@@ -328,7 +351,7 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
std::vector<int> layers_here;
for (int l = il; l < c.n_layers; ++l) {
layers_here.push_back(l);
if (m_->layers[l].is_full && !(l == il && carry)) { stop_attn = l; break; }
if (!attn_in_graph && m_->layers[l].is_full && !(l == il && carry)) { stop_attn = l; break; }
if (l + 1 < c.n_layers && m_->layers[l + 1].ple.present && I.ple) break; // the next layer needs a PLE gather first
}
ok = run_seg([&](cudaStream_t st) -> bool {
@@ -339,8 +362,12 @@ bool Q4Engine::forward(const int* ids, int N, int n_logits, std::vector<float>*
const Layer& Ly = m_->layers[l];
if (!(k == 0 && carry)) {
f_hc_read(Ly.hc_attn, true, st);
if (Ly.is_full) break; // the segment ends before the attention mixer
if (!I.mix->gdn(l, I.x, I.xr, N, pos_, I.y, st, err)) return false;
if (Ly.is_full) {
if (!attn_in_graph) break; // the segment ends before the attention mixer
if (!I.mix->attn_decode(l, I.x, I.xr, I.y, st, err)) return false;
} else if (!I.mix->gdn(l, I.x, I.xr, N, pos_, I.y, st, err)) {
return false;
}
}
f_inject(st);
f_hc_read(Ly.hc_mlp, false, st);
+4
View File
@@ -185,7 +185,11 @@ bool gdn_run(const GdnShape& s, const GdnWeights& w, const GdnState& st, GdnScra
conv_hist_kernel<<<(C + 127) / 128, 128, 0, stream>>>(st.hist, qkv, N, C);
if (!launch_ok(err, "gdn_run(conv)")) return false;
// the 64-token chunks (FP32 chunk-parallel scan, prefill/gdn_chunk.cu) then the remainder through the window kernels in groups of <= 16
#if defined(STRATA_USE_HIP)
const int T64 = 0; // HIP: the 64-token chunk scan (prefill/gdn_chunk.cu) is CUDA only; the window kernels below take every token
#else
const int T64 = N / 64 * 64;
#endif
if (T64 > 0) {
strata::prefill::gdn_chunk_recurrence(st.S, sc.h, sc.gate, sc.beta, sc.oc, T64, stream);
out_norm_kernel<<<T64 * s.hv, S, 0, stream>>>(sc.oc, z, w.norm, y, kEps);
+136
View File
@@ -0,0 +1,136 @@
// src/q4lite/q4_hc.cu - the fused hyper-connection read (Qwen4MoeTextGatedResidual): 4 launches instead of 9 per sub-layer.
//
// hc_norm_rot h -> hn (group RMS, 1 + w) and rot = FWHT-128(hn) (was hc_norm + fwht128)
// s8_split2 down(rot) and inject(rot): two packed S8_K matrices over the same input, one launch (was 2 GEMVs)
// hc_up_mix t -> silu(t / hc) -> FWHT-128 -> up GEMV -> sigmoid -> mean over the branches of (m * hn) -> x
// (was hc_down_act + fwht128 + GEMV + hc_mix)
// All arithmetic is float32 with the same operations as the separate kernels; only the summation order of the GEMV differs from Ling's (as gemv_s8_split).
#include "q4_hc.hpp"
#include "ling32_dev.cuh"
#include <cstdint>
namespace strata::q4lite::gpu {
namespace dk = strata::ling32::gpu::dev;
namespace {
__device__ __forceinline__ float sigmoidf_(float x) { return 1.0f / (1.0f + expf(-x)); }
__device__ __forceinline__ float siluf_(float x) { return x / (1.0f + expf(-x)); }
// grid (hc, N), block 256: one group of D = 2048 values per block (D must be 2048: 8 warps x 2 slices x 128)
__global__ void __launch_bounds__(256) k_hc_norm_rot(const float* __restrict__ h, const float* __restrict__ w, int hc, int D, float eps, float* __restrict__ hn, float* __restrict__ rot) {
__shared__ float sh[32];
__shared__ float tile[2048];
const size_t base = (static_cast<size_t>(blockIdx.y) * hc + blockIdx.x) * D;
const size_t wb = static_cast<size_t>(blockIdx.x) * D;
float ss = 0.0f;
for (int d = threadIdx.x; d < D; d += blockDim.x) { const float v = h[base + d]; ss += v * v; }
for (int off = 16; off >= 1; off >>= 1) ss += __shfl_xor_sync(0xFFFFFFFFu, ss, off);
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
if (lane == 0) sh[warp] = ss;
__syncthreads();
float tot = 0.0f;
for (int i = 0; i < (blockDim.x >> 5); ++i) tot += sh[i]; // fixed order
const float r = rsqrtf(tot / static_cast<float>(D) + eps);
for (int d = threadIdx.x; d < D; d += blockDim.x) {
const float v = h[base + d] * r * (1.0f + w[wb + d]);
hn[base + d] = v;
tile[d] = v;
}
__syncthreads();
for (int sl = warp; sl < D / 128; sl += (blockDim.x >> 5)) {
float v[4];
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] = tile[sl * 128 + lane * 4 + i];
dk::fwht128_warp(v, lane);
#pragma unroll
for (int i = 0; i < 4; ++i) rot[base + sl * 128 + lane * 4 + i] = v[i];
}
}
// one row per block of 4 warps over a packed S8_K matrix with nsb = K / 256 superblocks split over the 4 warps; block b < rows_a reads matrix A, else matrix B
__global__ void __launch_bounds__(128) k_s8_split2(const int8_t* __restrict__ qa, const float* __restrict__ epa, int rows_a, const int8_t* __restrict__ qb, const float* __restrict__ epb, int K,
const float* __restrict__ x, float* __restrict__ out_a, float* __restrict__ out_b) {
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
const bool isb = static_cast<int>(blockIdx.x) >= rows_a;
const int row = isb ? blockIdx.x - rows_a : blockIdx.x;
const int8_t* qr = (isb ? qb : qa) + static_cast<size_t>(row) * K;
const float* er = (isb ? epb : epa) + static_cast<size_t>(row) * (K >> 6);
const int nsb = K >> 8, g = lane >> 3, idx0 = g * 64 + (lane & 7) * 8;
float acc = 0.0f;
#pragma unroll 8
for (int sb = warp; sb < nsb; sb += 4) {
const float eff = er[sb * 4 + g];
const uint2 w = *reinterpret_cast<const uint2*>(qr + sb * 256 + idx0);
const float4* xp = reinterpret_cast<const float4*>(x + sb * 256 + idx0);
const float4 xa = xp[0], xb = xp[1];
const float xs[8] = {xa.x, xa.y, xa.z, xa.w, xb.x, xb.y, xb.z, xb.w};
const uint32_t ww[2] = {w.x, w.y};
float s = 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) s += static_cast<float>(static_cast<int8_t>((ww[j >> 2] >> (8 * (j & 3))) & 0xFFu)) * xs[j];
acc += eff * s;
}
#pragma unroll
for (int off = 16; off >= 1; off >>= 1) acc += __shfl_xor_sync(0xFFFFFFFFu, acc, off);
__shared__ float part[4];
if (lane == 0) part[warp] = acc;
__syncthreads();
if (threadIdx.x == 0) (isb ? out_b : out_a)[row] = ((part[0] + part[1]) + part[2]) + part[3];
}
// grid (D / 2), block 256 (8 warps = 2 output positions d x 4 branches c). t [rank = 256] (the down GEMV output). up: packed S8_K [hc * D rows, K = rank = 256].
__global__ void __launch_bounds__(256) k_hc_up_mix(const float* __restrict__ t, const int8_t* __restrict__ qu, const float* __restrict__ epu, const float* __restrict__ hn, int hc, int D, float inv_hc,
float* __restrict__ x) {
__shared__ float trot[256];
__shared__ float part[8];
const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
if (warp < 2) { // silu(t / hc) then FWHT-128 of each half
float v[4];
#pragma unroll
for (int i = 0; i < 4; ++i) v[i] = siluf_(t[warp * 128 + lane * 4 + i] * inv_hc);
dk::fwht128_warp(v, lane);
#pragma unroll
for (int i = 0; i < 4; ++i) trot[warp * 128 + lane * 4 + i] = v[i];
}
__syncthreads();
const int dloc = warp >> 2, c = warp & 3;
const int d = blockIdx.x * 2 + dloc;
const int row = c * D + d;
const int g = lane >> 3, idx0 = g * 64 + (lane & 7) * 8;
const float eff = epu[static_cast<size_t>(row) * 4 + g];
const uint2 w = *reinterpret_cast<const uint2*>(qu + static_cast<size_t>(row) * 256 + idx0);
const uint32_t ww[2] = {w.x, w.y};
float s = 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) s += static_cast<float>(static_cast<int8_t>((ww[j >> 2] >> (8 * (j & 3))) & 0xFFu)) * trot[idx0 + j];
float acc = eff * s;
#pragma unroll
for (int off = 16; off >= 1; off >>= 1) acc += __shfl_xor_sync(0xFFFFFFFFu, acc, off);
if (lane == 0) part[warp] = sigmoidf_(acc) * hn[static_cast<size_t>(c) * D + d];
__syncthreads();
if (threadIdx.x < 2) {
const int dd = blockIdx.x * 2 + threadIdx.x;
float sum = 0.0f;
for (int cc = 0; cc < 4; ++cc) sum += part[threadIdx.x * 4 + cc]; // fixed order over the branches (hc == 4)
x[dd] = sum / static_cast<float>(hc);
}
}
} // namespace
bool hc_fused_ok(int hc, int D, int rank, int K) { return hc == 4 && D == 2048 && rank == 256 && K == hc * D; }
// N == 1 only
void hc_read_fused(const float* h, const float* norm_w, const int8_t* q_down, const float* e_down, const int8_t* q_up, const float* e_up, const int8_t* q_inj, const float* e_inj, int hc, int D, int rank,
float eps, float* hn, float* rot, float* t, float* raw, float* x, cudaStream_t s) {
k_hc_norm_rot<<<dim3(hc, 1), 256, 0, s>>>(h, norm_w, hc, D, eps, hn, rot);
if (q_inj) k_s8_split2<<<rank + hc, 128, 0, s>>>(q_down, e_down, rank, q_inj, e_inj, hc * D, rot, t, raw);
else k_s8_split2<<<rank, 128, 0, s>>>(q_down, e_down, rank, q_down, e_down, hc * D, rot, t, raw);
k_hc_up_mix<<<D / 2, 256, 0, s>>>(t, q_up, e_up, hn, hc, D, 1.0f / static_cast<float>(hc), x);
}
} // namespace strata::q4lite::gpu
+18
View File
@@ -0,0 +1,18 @@
// src/q4lite/q4_hc.hpp - see q4_hc.cu
#pragma once
#include <cuda_runtime.h>
#include <cstdint>
namespace strata::q4lite::gpu {
// the fused read supports hc = 4, D = 2048, rank = 256, K = hc * D (Qwen4-35B-A3B)
bool hc_fused_ok(int hc, int D, int rank, int K);
// One token. h [hc*D] -> x [D] (mixed input), raw [hc] (inject weights, when q_inj != null), through packed S8_K matrices (q int8 + ep fp32 scales).
// scratch: hn [hc*D], rot [hc*D], t [rank]. Same math as hc_norm + fwht128 + down GEMV + hc_down_act + fwht128 + up GEMV + hc_mix + inject GEMV.
void hc_read_fused(const float* h, const float* norm_w, const int8_t* q_down, const float* e_down, const int8_t* q_up, const float* e_up, const int8_t* q_inj, const float* e_inj, int hc, int D, int rank,
float eps, float* hn, float* rot, float* t, float* raw, float* x, cudaStream_t s);
} // namespace strata::q4lite::gpu
+1 -1
View File
@@ -9,4 +9,4 @@ set(Q4_MIXER_KERNELS
${engine_root}/src/prefill/gdn_chunk.cu
${engine_root}/src/q4lite/q4_gdn.cu ${engine_root}/src/q4lite/q4_attn.cu)
set(Q4_MIXER_FASTMATH ${_kc}/native_rope.cu ${_kc}/native_qsa.cu ${_kc}/native_qsa_indexer.cu ${_kc}/native_qsa_score.cu)
set(Q4_MIXER_DEFS STRATA_GDN_PAIR_GROUPED=1)
set(Q4_MIXER_DEFS STRATA_GDN_PAIR_GROUPED=1 STRATA_VERIFY_MAX_T=16)
+7
View File
@@ -31,6 +31,13 @@ public:
virtual size_t state_bytes() const { return 0; }
// after a run of CUDA-graph decode steps (the GDN layers were not called on the host): bring the GDN layers' host position counters to `pos`
virtual void sync_gdn_pos(int pos) { (void)pos; }
// CUDA-graph decode (N = 1): decode_graph_ok() says the attention layers can be captured. Before EVERY graph launch (also the first) call set_decode_pos(pos, s) on the
// launch stream (one tiny kernel: the position and step record live in device memory); attn_decode() is attn() for N = 1 at that device position: it launches only kernels
// with constant arguments and grids, so it may be inside a stream capture and replayed for every token (the host position argument is gone). Do the first call eagerly
// (warm-up) before capturing; Mixers::init already warms the kernels up once.
virtual bool decode_graph_ok() const { return false; }
virtual bool set_decode_pos(int pos, cudaStream_t s, std::string& err) { (void)pos; (void)s; err = "decode graphs are not supported by these mixers"; return false; }
virtual bool attn_decode(int il, const float* x, const float* xr, float* y, cudaStream_t s, std::string& err) { (void)il; (void)x; (void)xr; (void)y; (void)s; err = "attn_decode: not supported"; return false; }
};
// Defined by the implementation (q4_mixers_fn.cu): a new instance of the production mixers
+52 -3
View File
@@ -51,7 +51,7 @@ public:
size_t per_attn = al(attn_state_bytes(as_, max_ctx_)) + al((size_t) (2 * as_.hd + 2 * as_.ixd) * 4) + al(attn_verify_bytes(as_));
int n_g = 0, n_a = 0;
for (int il = 0; il < nl; ++il) (c.is_full[il] ? n_a : n_g)++;
total = proj + gsc + asc + per_gdn * n_g + per_attn * n_a;
total = proj + gsc + asc + al(attn_decode_dev_bytes()) + per_gdn * n_g + per_attn * n_a;
MX_CK(cudaMalloc(&arena_, total), err);
arena_bytes_ = total;
uint8_t* p = (uint8_t*) arena_;
@@ -69,6 +69,7 @@ public:
pj_r_ = (float*) take((size_t) maxn_ * c.val_dim() * 4);
gdn_assign_scratch(take(gsc));
if (!attn_scratch_assign(as_, maxn_, max_ctx_, take(asc), asc_)) { err = "attn scratch"; return false; }
if (!attn_decode_dev_assign(take(attn_decode_dev_bytes()), dec_)) { err = "attn decode buffers"; return false; }
for (int il = 0; il < nl; ++il) {
if (!c.is_full[il]) {
G& g = gdn_[il];
@@ -93,11 +94,30 @@ public:
}
}
MX_CK(cudaDeviceSynchronize(), err);
// warm-up of the graph-capturable decode kernels (lazy attributes / statics must not first run inside a stream capture)
{
int first = -1;
for (int il = 0; il < nl && first < 0; ++il) if (c.is_full[il]) first = il;
if (first >= 0) {
cudaMemset(pj_q_, 0, (size_t) 2 * c.q_dim() * 4); cudaMemset(pj_k_, 0, (size_t) c.kv_dim() * 4); cudaMemset(pj_v_, 0, (size_t) c.kv_dim() * 4);
cudaMemset(pj_ix_, 0, (size_t) as_.ix_width() * 4);
attn_decode_set_pos(as_, dec_, 0, 0);
if (!attn_decode_dev(as_, attn_[first].w, attn_[first].st, asc_, dec_, pj_q_, pj_k_, pj_v_, pj_ix_, pj_o_, 0, err)) {
std::fprintf(stderr, "q4lite: graph-capturable attention decode unavailable (%s): attention layers stay eager\n", err.c_str());
err.clear();
cudaGetLastError();
dec_ok_ = false;
} else {
MX_CK(cudaDeviceSynchronize(), err);
}
}
}
reset();
MX_CK(cudaDeviceSynchronize(), err);
return true;
}
bool dec_ok_ = true; // the device-position decode attention passed its warm-up
void destroy() override {
if (arena_) { cudaDeviceSynchronize(); cudaFree(arena_); arena_ = nullptr; }
if (global_) { attn_global_release(); global_ = false; }
@@ -123,7 +143,7 @@ public:
pos_[il] += pending_n_[il];
g.pending = false;
}
if (pos0 != pos_[il]) { err = "gdn: position " + std::to_string(pos0) + " does not continue layer " + std::to_string(il) + " at " + std::to_string(pos_[il]); return false; }
// (no position check for GDN layers: graph decode replays them without the host)
if (N < 1 || N > maxn_) { err = "gdn: N out of range"; return false; }
const GdnLayer& W = m_->layers[il].gdn;
const Q4Cfg& c = m_->cfg;
@@ -150,7 +170,7 @@ public:
A& a = attn_[il];
if (!a.st.k_pool) { err = "attn: layer " + std::to_string(il) + " is not an attention layer"; return false; }
if (a.pending) { a.pending = false; pos_[il] += pending_n_[il]; } // previous window accepted in full
if (pos0 != pos_[il]) { err = "attn: position " + std::to_string(pos0) + " does not continue layer " + std::to_string(il) + " at " + std::to_string(pos_[il]); return false; }
if (pos0 != pos_[il]) { err = "attn: position " + std::to_string(pos0) + " does not continue layer " + std::to_string(il) + " at " + std::to_string(pos_[il]) + " (after graph decode steps call set_decode_pos for each token)"; return false; }
if (N < 1 || N > maxn_) { err = "attn: N out of range"; return false; }
const AttnLayer& W = m_->layers[il].attn;
const Q4Cfg& c = m_->cfg;
@@ -167,6 +187,34 @@ public:
return true;
}
bool decode_graph_ok() const override { return m_ != nullptr && !verify_mode_ && dec_ok_; }
// the position of the next decode token goes to the device (one 1-thread kernel); the host trackers move to the position after it
bool set_decode_pos(int pos, cudaStream_t s, std::string& err) override {
if (!m_ || pos < 0 || pos >= max_ctx_) { err = "set_decode_pos: position out of range (max_ctx " + std::to_string(max_ctx_) + ")"; return false; }
attn_decode_set_pos(as_, dec_, pos, s);
for (size_t il = 0; il < pos_.size(); ++il) pos_[il] = pos + 1;
return true;
}
// attn() for N = 1 at the device position: capturable (see q4_attn.hpp), the host position argument is gone
bool attn_decode(int il, const float* x, const float* xr, float* y, cudaStream_t s, std::string& err) override {
namespace L = strata::ling32::gpu;
A& a = attn_[il];
if (!a.st.k_pool) { err = "attn_decode: layer " + std::to_string(il) + " is not an attention layer"; return false; }
const AttnLayer& W = m_->layers[il].attn;
const Q4Cfg& c = m_->cfg;
(void) x;
gemv_dense(W.q, xr, 1, pj_q_, 2 * c.q_dim(), s);
gemv_dense(W.k, xr, 1, pj_k_, c.kv_dim(), s);
gemv_dense(W.v, xr, 1, pj_v_, c.kv_dim(), s);
gemv_dense(W.ix_qk, xr, 1, pj_ix_, as_.ix_width(), s);
if (!attn_decode_dev(as_, a.w, a.st, asc_, dec_, pj_q_, pj_k_, pj_v_, pj_ix_, pj_o_, s, err)) return false;
L::fwht128(pj_o_, pj_r_, 1, c.q_dim(), s);
gemv_dense(W.o, pj_r_, 1, y, D_, s);
return true;
}
void sync_gdn_pos(int pos) override {
for (size_t il = 0; il < gdn_.size(); ++il)
if (gdn_[il].st.S) { pos_[il] = pos; gdn_[il].pending = false; }
@@ -211,6 +259,7 @@ private:
AttnOptions opt_;
GdnScratch gsc_;
AttnScratch asc_;
AttnDecodeDev dec_;
std::vector<G> gdn_;
std::vector<A> attn_;
std::vector<int> pos_;
+1 -1
View File
@@ -280,7 +280,7 @@ set(_kernel_files "")
foreach(k IN LISTS _kernel_cu)
list(APPEND _kernel_files src/kernels/cuda/${k}.cu)
endforeach()
strata_resolve(_kernels ${_kernel_files} src/kernels/ngram.cpp src/ngram/ple_reader.cpp src/platform/direct_file.cpp)
strata_resolve(_kernels ${_kernel_files} src/kernels/ngram.cpp src/kernels/loop_adapter_stub.cpp src/ngram/ple_reader.cpp src/platform/direct_file.cpp)
list(APPEND _kernels ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cuda/qsa_prompt_attn_xmx.dp.cpp) # port-only: the XMX prompt attention
list(APPEND _kernels ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cuda/qsa_prompt_attn_esimd.dp.cpp) # port-only: the int8 DPAS (ESIMD) prompt attention
list(APPEND _kernels ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cuda/weight_permute.dp.cpp)
@@ -314,7 +314,10 @@ bool fused_swiglu_q81_enabled() {
void shared_expert_multi(int n_tok, const float* x, const uint16_t* x_bf16, const NativeSharedWeights& nw,
const uint16_t* gate_inp_bf16, float* gate, float* up, float* g, float* out, int64_t n_embd,
int64_t n_ff, void* stream, const void* x_q8_1_ready, int lfuse) {
int64_t n_ff, void* stream, const void* x_q8_1_ready, int lfuse, int loop_pass,
int64_t loop_layer) {
(void) loop_pass;
(void) loop_layer;
const bool gate_deferred = (lfuse & 1) != 0, pair = (lfuse & 2) != 0;
if (n_tok < 1 || n_tok > 8 || !nw.q8_1 || !nw.gate_data || !nw.up_data || !nw.down_data || !stream)
throw std::invalid_argument("shared_expert_multi: needs 1..8 tokens, native weights, scratch and a stream");
+17 -10
View File
@@ -187,7 +187,7 @@ def gdn_ref(qkv, z, a, b, conv_w, A_log, dt_bias, norm_w, conv_state, S_state, c
# ------------------------------------------------------------------ QSA attention + indexer (single sequence, whole stream at once)
def attn_ref(q_proj, k_proj, v_proj, idx_qk, q_w, k_w, iq_w, ik_w, with_sel=True):
def attn_ref(q_proj, k_proj, v_proj, idx_qk, q_w, k_w, iq_w, ik_w, with_sel=True, override=None):
"""The stream of L tokens at positions 0..L-1 -> out [L, 4096] (attention * sigmoid(gate), before o_proj), plus per-query selection data.
q_proj [L, 16*512] per head [q | gate], k_proj, v_proj [L, 512], idx_qk [L, 640]; *_w are the RAW norm weights (the norms apply 1 + w)."""
L = q_proj.shape[0]
@@ -223,7 +223,7 @@ def attn_ref(q_proj, k_proj, v_proj, idx_qk, q_w, k_w, iq_w, ik_w, with_sel=True
if cg_ > 0:
sc = F.relu(torch.einsum("hd,gd->hg", qi[p], pooled[:cg_])).sum(0) / math.sqrt(IXD)
kk = min(width, cg_)
top = torch.topk(sc, kk).indices
top = torch.sort(sc, descending=True, stable=True).indices[:kk] # HF select_topk_indices(deterministic=True): ties -> lowest index (what the GPU does)
srt = torch.sort(sc, descending=True).values
cut[p, 0] = srt[kk - 1]
cut[p, 1] = srt[kk] if kk < cg_ else float("-inf")
@@ -231,6 +231,8 @@ def attn_ref(q_proj, k_proj, v_proj, idx_qk, q_w, k_w, iq_w, ik_w, with_sel=True
grp = torch.sort(top).values
toks = (grp[:, None] * IXB + torch.arange(IXB)[None, :]).reshape(-1).tolist()
toks += list(range(cg_ * IXB, n_kv)) # the unfinished group's tokens
if override is not None and p in override:
toks = override[p]
t = torch.tensor(toks, dtype=torch.long)
sel[p, : len(toks)] = t.to(torch.int32)
kt = k[t] # [T, 2, 256]
@@ -402,12 +404,7 @@ def cmp_(args):
print(f"op{i} {op['kind']} n={n}: NON-FINITE OUTPUT")
worst = [float("inf")] * 3
continue
e = err_line("y", ygpu, yref)
key = (op["kind"], n if n in (1, 4, 16, 64, 1000) else "other")
cur = per_kind.setdefault(key, [0.0, 0.0, 0.0])
for j in range(3):
cur[j] = max(cur[j], e[j])
worst[j] = max(worst[j], e[j])
same = np.ones(keep, bool) # attention: queries whose selected token set equals the reference's (the others are listed, not averaged in)
if man["scenario"] == "attn":
cap = 2051
selref = rd(d, f"op{i}.selref.i32", np.int32, (keep, IXBUDGET + IXB - 1))
@@ -423,10 +420,11 @@ def cmp_(args):
total_q += 1
if a_ != b_:
sel_mism_q += 1
same[r] = False
diff = a_.symmetric_difference(b_)
groups = {x // IXB for x in diff}
# explained by a tie (or a near tie within float32 score noise) at the cut-off
tol = 1e-4 * max(1.0, abs(cut[r, 0]))
# explained by a tie (or a near tie within the key rounding / TF32 score noise: the GPU's pooled keys come from fp16 raw keys) at the cut-off
tol = 2e-3 * max(1.0, abs(cut[r, 0]))
ok = all(abs(float(gs[r, gi]) - cut[r, 0]) <= tol or abs(float(gs[r, gi]) - cut[r, 1]) <= tol for gi in groups if gi < gs.shape[1]) and all(
(x // IXB) < gs.shape[1] for x in diff)
if ok:
@@ -435,6 +433,15 @@ def cmp_(args):
real += 1
if real <= 5:
print(f" REAL selection mismatch op{i} q{p}: only-gpu {sorted(a_ - b_)[:8]} only-ref {sorted(b_ - a_)[:8]} cut={cut[r]} ")
if same.any():
e = err_line("y", ygpu[same], yref[same])
if os.environ.get("CMP_VERBOSE"):
print(f" op{i} {op['kind']:6s} n={n:4d} keep={keep:4d} rows {op['row']}..{op['row'] + keep - 1} rms_rel={e[2]:.2e} max_abs={e[0]:.2e} (rows compared {int(same.sum())})")
key = (op["kind"], n if n in (1, 4, 16, 64, 1000) else "other")
cur = per_kind.setdefault(key, [0.0, 0.0, 0.0])
for j in range(3):
cur[j] = max(cur[j], e[j])
worst[j] = max(worst[j], e[j])
print("---- error table: max abs, max abs / max|ref|, rms / rms(ref)")
for key in sorted(per_kind, key=str):
e = per_kind[key]
+78 -2
View File
@@ -69,14 +69,50 @@ static std::vector<Op> parse_ops(const std::string& man, std::string& scenario)
return ops;
}
// --graph: single-token runs go through ONE captured graph of attn_decode_dev, replayed for every token with only set_pos + input copies outside it
static cudaGraphExec_t g_exec = nullptr;
static AttnDecodeDev g_dev;
static float *g_q = nullptr, *g_k = nullptr, *g_v = nullptr, *g_ix = nullptr;
static bool graph_step(const AttnShape& s, const AttnWeights& w, const AttnState& state, AttnScratch& sc, const float* q, const float* k, const float* v,
const float* ix, int pos, float* out, cudaStream_t st, std::string& err) {
const size_t nq = (size_t) s.nh * 2 * s.hd, nk = (size_t) s.nkv * s.hd, nix = (size_t) s.ix_width();
if (!g_exec) {
CK(cudaMalloc(&g_q, nq * 4)); CK(cudaMalloc(&g_k, nk * 4)); CK(cudaMalloc(&g_v, nk * 4)); CK(cudaMalloc(&g_ix, nix * 4));
void* dm = nullptr;
CK(cudaMalloc(&dm, attn_decode_dev_bytes()));
attn_decode_dev_assign(dm, g_dev);
CK(cudaMemcpyAsync(g_q, q, nq * 4, cudaMemcpyDeviceToDevice, st)); CK(cudaMemcpyAsync(g_k, k, nk * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(g_v, v, nk * 4, cudaMemcpyDeviceToDevice, st)); CK(cudaMemcpyAsync(g_ix, ix, nix * 4, cudaMemcpyDeviceToDevice, st));
attn_decode_set_pos(s, g_dev, pos, st);
if (!attn_decode_dev(s, w, state, sc, g_dev, g_q, g_k, g_v, g_ix, out, st, err)) return false; // warm-up, eager
CK(cudaStreamSynchronize(st));
CK(cudaStreamBeginCapture(st, cudaStreamCaptureModeThreadLocal));
const bool ok = attn_decode_dev(s, w, state, sc, g_dev, g_q, g_k, g_v, g_ix, out, st, err);
cudaGraph_t g = nullptr;
CK(cudaStreamEndCapture(st, &g));
if (!ok) return false;
CK(cudaGraphInstantiate(&g_exec, g, 0));
cudaGraphDestroy(g);
std::printf("graph captured\n");
}
CK(cudaMemcpyAsync(g_q, q, nq * 4, cudaMemcpyDeviceToDevice, st)); CK(cudaMemcpyAsync(g_k, k, nk * 4, cudaMemcpyDeviceToDevice, st));
CK(cudaMemcpyAsync(g_v, v, nk * 4, cudaMemcpyDeviceToDevice, st)); CK(cudaMemcpyAsync(g_ix, ix, nix * 4, cudaMemcpyDeviceToDevice, st));
attn_decode_set_pos(s, g_dev, pos, st);
CK(cudaGraphLaunch(g_exec, st));
return true;
}
int main(int argc, char** argv) {
if (argc < 2) { std::fprintf(stderr, "usage: q4_attn_test DIR [--no-tc] [--fp32-indexer] [--time]\n"); return 2; }
DIR = argv[1];
bool no_tc = false, fp32_ix = false, do_time = false;
bool no_tc = false, fp32_ix = false, do_time = false, use_graph = false;
int bench_ctx = 0;
for (int i = 2; i < argc; ++i) {
if (!std::strcmp(argv[i], "--no-tc")) no_tc = true;
else if (!std::strcmp(argv[i], "--fp32-indexer")) fp32_ix = true;
else if (!std::strcmp(argv[i], "--time")) do_time = true;
else if (!std::strcmp(argv[i], "--graph")) use_graph = true;
else if (!std::strcmp(argv[i], "--bench") && i + 1 < argc) bench_ctx = std::atoi(argv[++i]);
}
MKDIR((DIR + "/gpu").c_str());
auto mb = readfile(DIR + "/manifest.json");
@@ -182,7 +218,8 @@ int main(int argc, char** argv) {
std::string p = "op" + std::to_string(i);
float* q = upload(p + ".q.f32"); float* k = upload(p + ".k.f32"); float* v = upload(p + ".v.f32"); float* ix = upload(p + ".idx.f32");
bool ok;
if (o.kind == "run") ok = attn_run(s, w, state, sc, q, k, v, ix, o.n, pos, out, st, err, opt);
if (o.kind == "run" && o.n == 1 && use_graph) ok = graph_step(s, w, state, sc, q, k, v, ix, pos, out, st, err);
else if (o.kind == "run") ok = attn_run(s, w, state, sc, q, k, v, ix, o.n, pos, out, st, err, opt);
else {
ok = attn_run(s, w, state, sc, q, k, v, ix, o.n, pos, out, st, err, opt, &vb);
if (ok) ok = attn_rollback(s, w, state, sc, vb, o.keep, st, err, opt);
@@ -205,6 +242,45 @@ int main(int argc, char** argv) {
float ms; cudaEventElapsedTime(&ms, e0, e1);
std::printf("TIME attention decode step at ctx %d (norm+rope, kv, indexer, select, attn, gate; 1 layer): %.1f us\n", ctx, ms * 1000.0f / 100);
}
if (bench_ctx > 0 && !bad) { // timing only: fill a long context with the first op's inputs repeated (random data), then time decode steps at its end
const int mc = (bench_ctx + 64 + 3) / 4 * 4;
attn_global_init(s, mc, e2);
void* stm2 = nullptr; void* scm2 = nullptr;
CK(cudaMalloc(&stm2, attn_state_bytes(s, mc)));
CK(cudaMalloc(&scm2, attn_scratch_bytes(s, max_n, mc)));
AttnState st2; AttnScratch sc2;
attn_state_assign(s, mc, stm2, st2);
attn_state_reset(s, st2, st);
attn_scratch_assign(s, max_n, mc, scm2, sc2);
float* q = upload("op0.q.f32"); float* k = upload("op0.k.f32"); float* v = upload("op0.v.f32"); float* ix = upload("op0.idx.f32");
int p = 0;
const int chunk = ops[0].n; // op0 is a run of n tokens
while (p + chunk <= bench_ctx) {
if (!attn_run(s, w, st2, sc2, q, k, v, ix, chunk, p, out, st, err, opt)) { std::printf("bench fill failed: %s\n", err.c_str()); bad = 1; break; }
p += chunk;
}
while (!bad && p < bench_ctx) {
if (!attn_run(s, w, st2, sc2, q, k, v, ix, 1, p, out, st, err, opt)) { std::printf("bench fill failed: %s\n", err.c_str()); bad = 1; break; }
++p;
}
CK(cudaStreamSynchronize(st));
if (g_exec) { cudaGraphExecDestroy(g_exec); g_exec = nullptr; }
if (!bad) {
cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
for (int rep = 0; rep < 10; ++rep) (use_graph ? graph_step(s, w, st2, sc2, q, k, v, ix, bench_ctx - 1, out, st, err) : attn_run(s, w, st2, sc2, q, k, v, ix, 1, bench_ctx - 1, out, st, err, opt));
cudaEventRecord(e0, st);
for (int rep = 0; rep < 100; ++rep) (use_graph ? graph_step(s, w, st2, sc2, q, k, v, ix, bench_ctx - 1, out, st, err) : attn_run(s, w, st2, sc2, q, k, v, ix, 1, bench_ctx - 1, out, st, err, opt));
cudaEventRecord(e1, st); cudaEventSynchronize(e1);
float ms; cudaEventElapsedTime(&ms, e0, e1);
std::printf("TIME attention decode step at ctx %d: %.1f us (1 layer; norm+rope, kv append, indexer append, scores, top-k, attention, gate)\n", bench_ctx, ms * 1000.0f / 100);
// prefill speed of the chunk path at this context depth: one chunk of `chunk` tokens
cudaEventRecord(e0, st);
for (int rep = 0; rep < 5; ++rep) attn_run(s, w, st2, sc2, q, k, v, ix, chunk, bench_ctx - chunk, out, st, err, opt);
cudaEventRecord(e1, st); cudaEventSynchronize(e1);
cudaEventElapsedTime(&ms, e0, e1);
std::printf("TIME attention prefill chunk of %d tokens ending at ctx %d: %.1f us per layer (%.0f tokens/s per layer)\n", chunk, bench_ctx, ms * 1000.0f / 5, chunk / (ms / 5 / 1000.0f));
}
}
}
CK(cudaStreamSynchronize(st));
std::printf(bad ? "RUN FAILED\n" : "RUN DONE\n");
+57
View File
@@ -0,0 +1,57 @@
# Qwen4-35B-A3B exactness harness (lane Q4-REF)
Two single-file Python tools (numpy only, run with `python -I -B`):
- `q4_drift.py` reproduces the owner's quant-vs-BF16 drift numbers of a `.strata` tier from his golden file (`golden_qwen4_drift_ref.npz`, 36 probes p00..p35).
This is THE exactness gate for the engine lanes: our decode of a tier must give his top-1 / KL for that tier.
- `q4_exact.py` is the generic Ling-style gate (top-1 %, mean / max KL, greedy identical x of y, NaN, GATE lines) against any reference that holds logits in
npz / npy / safetensors / json / pt / raw f32 / Ling `.tf.bin`. Use it when a same-quant reference (not BF16) exists, and for the long-prompt and picture runs
with prompt sets of our own (`q4_exact.py inspect PATH` shows what a file holds).
Both have `selftest` (synthetic data, no model). The golden itself is not in git (private data, `*.npz` is ignored): `phaseA-tests/qwen4/evals/`.
## What the engine has to produce (q4_drift.py)
Jobs: `python -I -B q4_drift.py make-jobs GOLDEN.npz jobs.jsonl [--probes p00,p01] [--ids-dir DIR]` writes one line per probe
`{"id":"p00","full_ids":[...],"cont_offset":126,"rows":160,"dump_r39":true,"prompt_ids":[...],"cont_ids":[...],"gen":0,"tf":160}`
(and `DIR/p00.ids.txt`, the comma separated `full_ids`, for an `--ids` style command line). `full_ids` is the prompt plus 160 teacher-forced tokens; no tokenizer.
For each probe, teacher-force `full_ids` (ONE prefill pass over all of it, as the BF16 reference did; chunked prefill is fine; if you teacher-force by decode steps say so in the log)
and write into the output directory:
| file | content |
|---|---|
| `<id>.tf.bin` | int32 P, int32 K; int32 ids[P,K]; float32 logits[P,K]; float32 lse[P]. The Ling `--jobs` layout. P = 160 rows = positions `cont_offset .. cont_offset+159` (row j predicts `full_ids[cont_offset+j+1]`). K >= 128, 256 advised; ids descending by logit; `lse` = logsumexp over the FULL padded vocab (248320) of the final logits |
| or `<id>.logits.f32` / `.f16` / `.npy` | the full `[160, 248320]` logits (little endian), exact tail bucket; 159 MB per probe in f32, use for a few probes |
| `<id>.R39.f32` | 8192 float32 = the 4 hyper-connection streams x 2048 after layer 39 at the LAST position of `full_ids` (optional; cosine is informational) |
| `<id>.gen.json` | `{"id":"p00","nan":false}`; a true NaN flag fails GATE-NAN (optional) |
Rows may also be written for every position (P = len(full_ids)) or with a `positions` array; the harness aligns by absolute position and prints the rule it used.
A K-row file cannot give the engine's logit for a BF16 top-128 id that is not in its own top-K: the harness uses the K-th logit (an upper bound, so KL comes out slightly low)
and prints `INFO the engine's top-K covers only ...` when that matters. With K=256 it normally does not; check it on Compact (the biggest drift).
## Run
```
python -I -B q4_drift.py drift --golden GOLDEN.npz --engine OUTDIR --tier compact --owner drift_report_compact_v2.json [--probes p00,p01] [--json out.json]
```
Prints per probe: top-1, owner's top-1, KL, owner's KL, ratio, top-5 (two readings), p>=0.9 flips, R39 cosine; then the all-probe line, KL variants, and GATE lines:
`GATE-DRIFT-TOP1` (+-0.5 points of the owner's tier number), `GATE-DRIFT-KL` (+-10 %), `GATE-DRIFT-PROBES` (per probe close, provisional), `GATE-NAN`, `GATE-COVERAGE`, `GATE-Q4-DRIFT`.
Exit code 0 = pass. Owner tier numbers are built in (Compact 0.89288 / 0.213052, Balanced 0.96788 / 0.026649, Ultra 0.97622 / 0.013379); `--owner` takes his
`drift_report_<tier>_v2.json` (R2 `qwen4-35b-a3b/evals/`) for the per-probe numbers.
## Prompt sets (q4_prompts.py, data/)
Ling's short set (chat, code, JSON/YAML, tool calls, prose, one 1500-token HTML probe) plus low/high/xhigh effort variants, a 4K document prompt (frozen `data/doc_corpus.txt`) and a
picture prompt (`data/pic_448.png`, 196 image tokens), tokenised with Qwen4's own encoder: `python -I -B q4_prompts.py tokenize --hf HFDIR --out tokenized.json` (HFDIR = tiktoken.model,
encoding_qwen4.py, tokenizer_config.json of the HF repo). `selfcheck` reproduces the ids printed in the HF README, and the framing of effort `off` matches the golden's own prompts
(`...<|im_start|>assistant\n<think></think>`). These have no reference logits yet: use them for engine-vs-engine checks (backends, KV precision, long prompt) or, once a same-quant
reference exists, with `q4_exact.py make-jobs --prompts tokenized.json` / `compare`. The picture prompt needs the vision tower and `Qwen4-35B-A3B-Vision.strata`.
## Definitions (inferred, see phaseA-tests/notes-q4-ref.md)
KL(BF16 || engine) over the BF16 top-128 plus one tail bucket; top-1 = argmax equal to the BF16 top-1; flip rate = among the 4659 of 5760 positions where BF16 p(top-1) >= 0.9, the
share where the engine's top-1 differs (this denominator reproduces the owner's 0.03692, 0.00129 and 0.00043 exactly). Variants that cannot be settled without an engine
run (top-5 direction, KL without the tail bucket, renormalised, reverse) are printed next to the headline so a lane can see which one matches the owner.
+564
View File
@@ -0,0 +1,564 @@
<p align="center">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="app/host/public/brand/strata-lockup-dark.svg">
<img src="app/host/public/brand/strata-lockup-light.svg" alt="Strata" width="340">
</picture>
</p>
<h3 align="center">Run powerful AI on your own computer.</h3>
<p align="center">Chat, code and work with images, locally.</p>
<p align="center">
<a href="#models">Models</a> · <a href="#install"><b>Install</b></a> ·
<a href="#hardware">Hardware</a> · <a href="#tools">Tools</a> ·
<a href="#help">Help</a> · <a href="#support-strata">Support</a>
</p>
<p align="center">
<a href="https://github.com/Niko1221/Strata/releases/latest"><img src="https://img.shields.io/github/v/release/Niko1221/Strata?label=download&color=0ab887" alt="Download Strata"></a>
<a href="LICENSE"><img src="https://img.shields.io/github/license/Niko1221/Strata" alt="MIT license"></a>
<a href="https://github.com/sponsors/Niko1221"><img src="https://img.shields.io/badge/Sponsor-EA4AAA?logo=githubsponsors&logoColor=fff" alt="Sponsor Strata on GitHub Sponsors"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://img.shields.io/badge/Buy_me_a_coffee-FFDD00?logo=buymeacoffee&logoColor=000" alt="Support Strata on Buy Me a Coffee"></a>
</p>
<p align="center"><sub><b>English</b> · <a href="docs/lang/README.zh-CN.md">简体中文</a> · <a href="docs/lang/README.ja.md">日本語</a> · <a href="docs/lang/README.de.md">Deutsch</a> · <a href="docs/lang/README.fr.md">Français</a> · <a href="docs/lang/README.es.md">Español</a> · <a href="docs/lang/README.pt-BR.md">Português</a> · <a href="docs/lang/README.pl.md">Polski</a></sub></p>
**Free, open source, and yours to run.** Use Strata on your desktop or with your favorite coding tools. No account needed.
## Models
We recommend **ISTA-DASLab first**, then **Unsloth** and other providers, where a compatible model fits.
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.8-Flash-Next</b></summary>
| Provider | Choices |
| --- | --- |
| **ISTA-DASLab · recommended** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) for coding. |
| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 |
| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Lower memory use but slower. |
| **Other options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) |
[Compare sizes, memory needs and compatibility](docs/MODELS.md).
</details>
<details>
<summary><img src="docs/media/models/hunyuan.svg" width="22" alt="" align="middle"> &nbsp;<b>Tencent Hy4-Flash</b></summary>
| Pack | Your RAM | Graphics card |
| --- | --- | --- |
| **SQ-64** | 64 GiB | 8, 12 or 16 GiB |
| **SQ-96** | 96 GiB | 8 or 12 GiB |
| **SQ-128** | 128 GiB | 8 or 12 GiB |
The number in the name is the RAM the pack is made for.
[Hy4-Flash packs on Hugging Face](https://huggingface.co/strata-engine/Hy4-Flash-Strata)
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Qwen3.6-35B-A3B</b></summary>
**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. These are the currently documented packs for this model.
[Model guide and compatibility](docs/QWEN36.md).
</details>
<details>
<summary><img src="docs/media/models/qwen.svg" width="22" alt="" align="middle"> &nbsp;<b>Ornith-1.5-35B-A3B</b></summary>
**Ornith AI (MIT):** Q4_K_M, Q5_K_M, Q6_K, Q8_0. The same architecture and engine path as Qwen3.6-35B-A3B. Catalog entry from eSPiYa's patch.
[Sizes and setup](docs/MODELS.md#ornith-15-35b-a3b).
</details>
<details>
<summary><picture><source media="(prefers-color-scheme: dark)" srcset="docs/media/models/thinking-machines-white.png"><img src="docs/media/models/thinking-machines.png" height="22" alt="Thinking Machines" align="middle"></picture> &nbsp;<b>Inkling 2 Mini</b></summary>
| Provider | Choices |
| --- | --- |
| **Strata** | SQ-20 (19.37 GB), SQ-15 (14.35 GB), SQ-10 (10.47 GB) |
| **GSQ-RCO** | IQ3\_S (11.43 GB) |
| **Unsloth** | UD-Q4\_K\_XL (17.63 GB) |
SQ-20 is made for a 24 GiB graphics card, SQ-15 for 16 GiB and SQ-10 for 12 GiB. A 4 GiB card is enough to start.
[Strata packs on Hugging Face](https://huggingface.co/strata-engine/Inkling-2-Mini-Strata) · [GSQ-RCO GGUF file](https://huggingface.co/ISTA-DASLab/Inkling-2-Mini-GSQ-RCO-GGUF) · [Unsloth GGUF files](https://huggingface.co/unsloth/Inkling-2-Mini-GGUF)
</details>
<a id="the-other-sizes"></a>
Not sure what fits? [Choose a model for your computer](docs/MODELS.md#pick-by-memory).
## Install
<a id="option-a-the-strata-app"></a>
### Desktop app
**[Download Strata for Windows, Linux or Mac →](https://github.com/Niko1221/Strata/releases/latest)**
Install the app, choose a model, and start chatting. There is one installer for each system. On first start the app
downloads the engine for your graphics card. [Help with the installer](docs/INSTALL.md#the-app).
<sub>Files: `Strata-0.2.25-windows-x64-setup.exe` · `Strata-0.2.25-linux-x86_64.AppImage` · `Strata-0.2.25-macos-arm64.dmg`</sub>
<p align="center">
<img src="docs/media/app-chat.png" width="900" alt="Strata desktop app with a chat and live code preview side by side">
<br><sub>Chat, files and a live preview in one window.</sub>
</p>
<a id="option-b-the-terminal-one-line"></a>
### Terminal app
Prefer the terminal? Install Strata, then run **`strata launch`**.
<details open>
<summary><b>Install commands</b></summary>
**Linux / Mac**
```sh
curl -fsSL --connect-timeout 15 --max-time 120 https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh
```
**Windows PowerShell**
```powershell
irm -TimeoutSec 120 https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex
```
On Windows, open a new terminal afterwards. Then:
```sh
strata launch
```
Follow the prompts to download and start a model. [Terminal guide](docs/TERMINAL_LAUNCH.md).
</details>
<p align="center">
<img src="docs/media/terminal-monitor.png" width="900" alt="Strata terminal app showing model activity, speed, memory and recent requests">
<br><sub>Watch your model and hardware while it runs.</sub>
</p>
<a id="build-from-source"></a>
[Build from source](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Full install guide](docs/INSTALL.md)
<a id="what-you-need"></a>
## Hardware
| Supported hardware | Guide |
| --- | --- |
| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 series** | [NVIDIA setup](docs/INSTALL.md#what-you-need) |
| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD setup](docs/AMD_HIP.md) |
| **AMD Radeon RX 6800 / 6900 · experimental** | [RX 6000 setup](docs/AMD_HIP.md#rdna2-gfx1030) |
| **Intel Arc · Linux** | [Intel setup](docs/INTEL_ARC.md) |
| **Apple Silicon · M1 or newer** | [Mac setup](docs/MAC.md) |
| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo setup](docs/STRIX_HALO.md) |
| **NVIDIA DGX Spark · Linux** | [DGX Spark setup](docs/DGX_SPARK_LINUX.md) |
<a id="using-it"></a>
## Tools
**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, and more through the OpenAI- and Anthropic-compatible APIs.
Run **`strata connect`** to see setup instructions for your tool. [Connection guide](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect).
<a id="guides"></a>
<a id="how-fast-is-it"></a>
<a id="how-does-it-work"></a>
<a id="something-went-wrong"></a>
## Help
[All guides](docs) · [Troubleshooting](docs/TROUBLESHOOTING.md) · [Report a bug](https://github.com/Niko1221/Strata/issues/new/choose) ·
[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [How it works](docs/HOW_IT_WORKS.md) · [Contribute](.github/CONTRIBUTING.md)
## Sponsors of Strata
<!-- Sponsor logos: one centred row with room for five, each 130 px wide. Add the next sponsor after Olares, with &nbsp;&nbsp;&nbsp;&nbsp; between two logos. -->
<p align="center">
<a href="https://heylinger.com"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/media/sponsors/linger-logo-white.svg"><img src="docs/media/sponsors/linger-logo-color.svg" alt="Linger" title="Linger" width="130" align="middle"></picture></a>
&nbsp;&nbsp;&nbsp;&nbsp;
<a href="https://www.olares.com/one"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/media/sponsors/olares-logo-white.svg"><img src="docs/media/sponsors/olares-logo-color.svg" alt="Olares" title="Olares" width="130" align="middle"></picture></a>
</p>
## Support Strata
**Help keep local AI open to everyone.** A GitHub sponsorship or a coffee helps fund development and testing on more hardware.
<a href="https://github.com/sponsors/Niko1221"><img src="https://img.shields.io/badge/Sponsor_on_GitHub-EA4AAA?style=for-the-badge&logo=githubsponsors&logoColor=white" alt="GitHub Sponsors: sponsor Strata" height="48"></a>
<a href="https://buymeacoffee.com/strataengine"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me a Coffee: support Strata" height="48"></a>
### Loyal supporters
Thank you to everyone who supports Strata.
<!-- supporters:start (generated from the public GitHub sponsors: one row per level, the biggest supporters first and largest; private sponsors are not listed) -->
<a href="https://github.com/codeconduit-official"><img src="https://images.weserv.nl/?url=github.com/codeconduit-official.png&w=240&h=240&fit=cover&mask=circle&output=png" width="120" height="120" alt="codeconduit-official" title="codeconduit-official"></a>
<a href="https://github.com/kod88vn"><img src="https://images.weserv.nl/?url=github.com/kod88vn.png&w=160&h=160&fit=cover&mask=circle&output=png" width="80" height="80" alt="kod88vn" title="kod88vn"></a>
<a href="https://github.com/router0mail"><img src="https://images.weserv.nl/?url=github.com/router0mail.png&w=160&h=160&fit=cover&mask=circle&output=png" width="80" height="80" alt="router0mail" title="router0mail"></a>
<a href="https://github.com/kingdonb"><img src="https://images.weserv.nl/?url=github.com/kingdonb.png&w=160&h=160&fit=cover&mask=circle&output=png" width="80" height="80" alt="kingdonb" title="kingdonb"></a>
<a href="https://github.com/Daisame"><img src="https://images.weserv.nl/?url=github.com/Daisame.png&w=160&h=160&fit=cover&mask=circle&output=png" width="80" height="80" alt="Daisame" title="Daisame"></a>
<a href="https://github.com/ryan4yin"><img src="https://images.weserv.nl/?url=github.com/ryan4yin.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="ryan4yin" title="ryan4yin"></a>
<a href="https://github.com/themactep"><img src="https://images.weserv.nl/?url=github.com/themactep.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="themactep" title="themactep"></a>
<a href="https://github.com/macintog"><img src="https://images.weserv.nl/?url=github.com/macintog.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="macintog" title="macintog"></a>
<a href="https://github.com/bisonbet"><img src="https://images.weserv.nl/?url=github.com/bisonbet.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="bisonbet" title="bisonbet"></a>
<a href="https://github.com/vizv"><img src="https://images.weserv.nl/?url=github.com/vizv.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="vizv" title="vizv"></a>
<a href="https://github.com/seoulworker"><img src="https://images.weserv.nl/?url=github.com/seoulworker.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="seoulworker" title="seoulworker"></a>
<a href="https://github.com/jaceknoga"><img src="https://images.weserv.nl/?url=github.com/jaceknoga.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="jaceknoga" title="jaceknoga"></a>
<a href="https://github.com/jackyini"><img src="https://images.weserv.nl/?url=github.com/jackyini.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="jackyini" title="jackyini"></a>
<a href="https://github.com/moruku36"><img src="https://images.weserv.nl/?url=github.com/moruku36.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="moruku36" title="moruku36"></a>
<a href="https://github.com/hrkgk"><img src="https://images.weserv.nl/?url=github.com/hrkgk.png&w=112&h=112&fit=cover&mask=circle&output=png" width="56" height="56" alt="hrkgk" title="hrkgk"></a>
<!-- supporters:end -->
All supporters and how to support Strata: [SUPPORTERS.md](SUPPORTERS.md)
[MIT license](LICENSE) · [Credits and model licenses](docs/HOW_IT_WORKS.md#credits) · [Privacy](docs/SAFETY.md)
<a id="option-c-let-your-ai-set-it-up"></a>
<sub>For AI tools and automated readers: <a href="AGENTS.md">technical reference</a> · <a href="docs/AI_SETUP.md">setup instructions</a>.</sub>
**Sponsorships, hardware partnerships or collaborations:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com).
===== FILE: docs/MULTI_GPU.md =====
# Strata on two or more GPUs (layer split)
This page is for people with two or more graphics cards of the same make in one PC. A layer split puts one model on
several cards. NVIDIA is described here; AMD limits and measurements are in [AMD_HIP.md](AMD_HIP.md).
> **On this page:** [Using it](#using-it) · [Main, Helper, Off](#main-helper-off) · [How the split works](#how-the-split-works) ·
> [Tuning options](#tuning-options) · [Pipeline windows](#pipeline-windows) · [Two models on two cards](#two-models-on-two-cards) ·
> [Limits](#limits) · [History](#history--older-measurements)
## Using it
**Desktop app:** choose Main, Helper or Off for each card. **Terminal:** run `strata launch` and use the Cards step, or name
the cards:
```sh
strata launch --gpu 0,1
strata launch --gpu-roles 1=main,0=helper # cards you do not name are Off
```
Choose a model that fits the combined memory. A split can add capacity without adding speed.
**Source checkout only:** `START-HERE.bat` and `./setup.sh` have their own card picker. Their flags are not `strata launch` flags:
| Source setup flag | Meaning |
| --- | --- |
| `--gpus 0,2` | These cards together, numbered as `nvidia-smi` numbers them. Strata puts the faster card last. Remembered. |
| `--gpus all` | Every card that can share the model. |
| `--gpu 0` | One card (at a start: for that start only). |
| `--layer-split auto` | The default. Or the first layer of each later card, for example `18` or `16,32`. |
| `--gpu-roles 1=main,0=helper` | Roles, saved. |
Or edit an existing run config (`strata-*.json`) and restart. Merge these fields into the config; this is not a complete config:
```json
{
"gpu": [0, 2],
"layer_split": "auto"
}
```
Docker: `GPU_ROLES=1=main,0=helper` is passed as `--gpu-roles` ([DOCKER.md](DOCKER.md)).
## Main, Helper, Off
Every card has one of three roles.
| Role | What it does |
| --- | --- |
| **Main** | Runs the last stage of the split: the output head, the draft layer and the check of its guesses. A prompt chunk waits on it. Exactly one card is Main. |
| **Helper** | Holds a share of the layers and of the expert cache, so more of the model sits on graphics cards instead of being read from the drive. The effect on speed depends on the cards and the workload. |
| **Off** | Strata does not touch the card (a game, the screen, a card that is too small). |
The Main card is the last card in the engine's order. The first card runs the first layers and, by default, the picture reader.
**Recommended roles** (the same rule in the app, `strata launch` and setup; `terminal/strata_control/gpu_roles.py`):
- The faster card is Main. Speed is multiprocessors x max clock. Cards within 5% count as the same card, and the one with more memory wins, then the lower number. Of two identical cards the highest number is Main. A card with clearly more memory beats a faster one that is at least half as fast.
- Every other card starts as Helper, except a card with 8 GB or less when a bigger card is present (Off; with only 8 GB cards the second one is a Helper), built-in graphics beside a card with memory of its own (Off), and a card the engine cannot run (Off).
- A role is one click (app), one key (`strata launch`: M, H, O; R restores the recommendation) or one line (above).
Only a few things are warned about, one short line each: built-in graphics as Main, a card the engine cannot run, and too
little memory for the chosen setup. All cards Off is allowed. The CUDA, HIP and SYCL engines cannot start without a card and
say so; the Mac engine says "Performance is degraded on CPU only." and goes on.
**In the run config** (what the app writes). Merge these fields into the existing config:
```json
{
"gpu_roles": {"1": "main", "0": "helper", "2": "off"},
"gpu": [0, 1],
"gpu_order": "as_given"
}
```
`gpu` is the same choice for older engines and the Monitor: the Helpers (slowest first), then the Main card, Off cards left out.
The server reads `gpu_roles`. If `gpu` was edited by hand and no longer matches, `gpu` wins and the log says so. A file with only
`"gpu": [1, 0]` shows as Main = the last card, Helper = the first, the rest Off. The recommendation is not saved, so a card you
add later is recommended again; a card you add after choosing roles starts Off.
**Which cards count** (`terminal/strata_control/gpu_fit.py` holds the memory arithmetic): not an integrated chip beside a real card; at
least 4 GB of graphics memory to be listed; 8 GB or less starts Off beside a bigger card. Each extra card of a split costs an
estimated 2 GB of its own buffers.
**Not supported** (setup says so and names the cards that can be used):
- A card older than the RTX 20 series (compute capability below 7.5). Pascal and Volta cards are admitted when you name them
with `--gpus` (or `--gpu`, `--cuda 12`) and then run the experimental CUDA 12 engine ([OLDER_GPUS.md](OLDER_GPUS.md)).
- A card with less than 8 GB of VRAM together with others, because each card holds a copy of the dense weights and its own
prompt buffers. If you name it with `--gpus`, setup states the risk and asks (`--yes` goes ahead).
- Intel GPUs in a split, and a mix of NVIDIA and AMD cards. An engine drives one make of card. The app, `strata launch` and setup
offer only the cards the engine can drive, and say so when the other make has the bigger card. AMD cards share a model among
themselves: `./setup.sh --backend hip --gpus 1,0` ([AMD_HIP.md](AMD_HIP.md)).
A prompt read on one card and an answer made on another, with the session handed over in RAM, is a different opt-in: [SPLIT_SERVE.md](SPLIT_SERVE.md).
## How the split works
The layers are cut into contiguous ranges, one per card. The first card runs layers 0 to K-1, the next runs K onward, and the
last card also runs the output head and the draft (MTP) layer. Each card keeps an expert cache for its own layers only, so two
cards hold about twice the experts one card holds.
This is pipeline parallelism, not tensor parallelism. A token crosses from one card to the next once per verify window (a few
hundred KB through pinned RAM). No NVLink or peer-to-peer access is needed, cards on x4 or x1 slots work, and each card's PCIe
share is probed on its own link. A `--pcie-frac` you give applies to every card and skips those probes.
**What each card holds**
- Every card: a copy of the dense weights, its own session state (the KV cache of the full context), its verify window, its
prompt-path buffers, and an expert cache for its layers filled from the expert profile.
- The last card: also the output head and the draft layer (about 0.8 GB).
- Host RAM: the expert arena once, shared by all cards. The CPU pool computes whatever no card holds.
Prompts are read in chunks that flow through the cards in turn: while a later card reads chunk c, the first card reads chunk c+1.
Conversation checkpoints save and restore every card's state.
**`"layer_split"`** is `"auto"` (placed by each card's free VRAM) or the first layer of each later card: one rising number per
card after the first, not a count per card. With four cards and a 48-layer model, `"24,36,42"` puts layers 0-23 on the first
card, 24-35 on the second, 36-41 on the third and 42-47 on the last. The server checks the value before the start and says what
is wrong.
**`auto`** tries every placement for two, three or four cards (proportional to free VRAM beyond that) and keeps the one whose
caches hold the most of the expert profile, hottest pairs weighted most. Ties go to the placement that leaves the fullest card
the most room. The startup log prints the choice:
```
strata generate: layer split auto: K=19 - the caches hold 11767 of 12288 profiled pairs (fullest device 100%)
strata serve: layer split: layers 0-18 (CUDA0), 19-47 (CUDA1), one hand-off per window
```
**Card order with `auto`:** the faster card goes last, because the last stage runs the head, the draft layer and the verify, and
a prompt chunk waits on it. Cards within 5% keep your order, and so does a manual split. `"gpu_order": "as_given"` keeps your
order under `auto` as well. The log line `layer split: card order ...` says when the order changed.
**Unequal cards under `auto`.** The search asks for at least 3 layers per card and, on two cards, first for a placement in which
each card owns at least its share of the layers by its room for experts. The log line says which rule chose the split. Prefill
that stays flat from 4K to 16K tokens is the sign of an idle card. On an unequal pair, sweep `"layer_split"` once, because a
4K-only benchmark cannot see it. On x16 plus x4 rigs the link-miss scaling can move `auto` off the balanced placement;
`STRATA_SPLIT_UNIFORM=1` (with `"gpu_order": "as_given"`) prices every link the same.
## Tuning options
These are engine flags and environment variables. Put flags in the config's `"args"` and variables in its `"env"` object, then
restart. Defaults are off unless the table says otherwise.
| Setting | What it does | Notes |
| --- | --- | --- |
| `"split_skip_if_fits": true` (flag `--split-skip-if-fits`) | Runs on the first card alone when it holds every profiled expert plus the context's KV, the draft layer and the reserve. Otherwise the split stays. | Opt-in. Needs `--layer-split auto`. |
| `STRATA_SPLIT_OWN=1` or `auto` | Gives every card its own prompt buffers. `auto` does it only where the buffers are at most 12% of each card's VRAM. | Output differs from the default's (stable and coherent). |
| `STRATA_PREFILL_HELP=1` | The idle card computes a share of the streamed experts of a one-chunk prompt. `STRATA_PREFILL_HELP_FRAC=f` fixes the share. | Helps prompts up to about 3.3K tokens on slow links only; not bit-identical; native packs on the MMQ prompt path only. |
| `STRATA_SPLIT_MTP_BATCH=1` | The last card fills the draft layer's prompt K/V in batches, as on one card. | Needs a `--native` pack and a paged or ring draft K/V; says why once if it declines. |
| `--vram-reserve-later-mib N` | A separate VRAM reserve for the later cards (default: `--vram-reserve-mib`). Use it when the display sits on the last card. | `--vram-reserve-mib 300 --vram-reserve-later-mib 1800` gives the first card that VRAM. |
| `--prefill-pipe R` (or `STRATA_PREFILL_PIPE=R`) | Reads each prompt in the chunk count with the least pipeline time for b/a = R tokens. `1` evens out today's chunk count. | Opt-in. `./setup.sh --calibrate` measures it per PC and writes it to the config. |
| `STRATA_SPLIT_RING=N` | Sets the prompt path's streamed ring to N slots (`0`: the pinned-share rule). A split uses 96 when at least 75% of the (layer, expert) pairs sit in some card's cache. | The startup line `lend sizing: ...` shows the result. |
| `STRATA_SPLIT_CHUNK16K=1` | Keeps the 16384-token auto chunk on AMD gfx12 splits (default 8192); on NVIDIA it keeps the raised ceiling of 32768. | 2x RTX 5090 (PCIe 4.0 x2 + x8), UD-Q4_K_XL, 73% of the experts on the cards: 16K prompt 11.2 -> 8.7 s, 32K 20.0 -> 12.0 s, decode and 4K unchanged. A split that holds all its experts keeps the 8192 default. |
| `STRATA_SPLIT_LINK_MIN=r` | The gap (fastest card's link / this card's) from which a slow link scales the auto split's miss cost (default 4). | A x8 beside a x2 slot is a gap of 3.9 and was left unscaled: auto put 24 layers on the x2 card. With `=3` the x2 card gets fewer layers. |
| `STRATA_SPLIT_OVERLAP=1` | Overlapped hand-off between stages on different cards. | Helps AMD; no gain on NVIDIA. See [below](#overlapped-hand-off). |
| `--split-device D1[,D2..]` | The later stages' devices (default: the next visible ones). `--layer-split K --split-device 0` runs both stages on one card; a bit-exact hand-off check, not a speed mode. | |
**The resident RAM mode works on a split.** `--resident-experts` (the low-RAM mode) leaves out of the RAM copy the experts any
card's cache holds. An adaptive swap copies the evicted expert back into RAM from the card that owns its layer. A RAM budget
(`--resident-budget-gib`) works on a split as well ([UNSLOTH_Q4.md](UNSLOTH_Q4.md)). With `--pcie-frac 0 --adapt-every 0` the
split's greedy output is the same in either mode.
**Under WDDM (Windows and WSL2)** only 8 GiB of the expert arena is pinned on a multi-GPU run; the rest streams through the
pinned staging ring. Linux pins the whole arena. `STRATA_ARENA_PIN_GIB=N` pins at most N GiB, `0` the whole arena, on any OS.
### Turning a default off
| Setting | What it does | Notes |
| --- | --- | --- |
| `STRATA_STAGE_TRIM=0` (or `--no-trim-stage-weights`) | Every card of a layer split keeps the dense weights of all the layers, as before. By default each card, explicit split or `auto`, loads only its own layers' dense weights and the freed VRAM goes to its expert cache. | Output can differ slightly from the default, which caches more experts. |
### Overlapped hand-off
By default each verify window runs the stages one after another. `STRATA_SPLIT_OVERLAP=1` (stages on different cards only) gives
the hand-off a ready flag, so the next stage's graph is launched while the earlier stage still runs and waits on the flag on
its GPU. It takes one stream sync and one graph launch per window off the critical path. Batch windows keep the serial order, and
it is off beside `--pipeline-windows`. The wait is bounded by `STRATA_SPLIT_WAIT_MS` (default 30000, `0` = no bound); on timeout
the window fails with an error naming the setting and the server restarts the engine.
## Pipeline windows
`--pipeline-windows 2` lets the first card start the next verify window while the last card still verifies this one. The next
window is a guess: that this window is accepted whole and that its bonus token is the one the draft layer predicts. If the guess
holds, half of the next window is already done. If not, the first card restores its state and builds the window from the real
tokens. The tokens are the serial loop's, up to CPU rounding.
- **Default:** on for AMD RDNA4 (gfx1200 / gfx1201) with `--serve`, the draft layer, and a split of two or more stages when the
drafter can sit on the first card, otherwise three or more. The log says "is on by default for a layer split of N stages".
`--pipeline-windows 0` or `STRATA_PIPELINE_AUTO=0` turns it off. NVIDIA builds keep it opt-in (`--pipeline-windows 2`).
The Intel Arc engine turns it on for exactly two Arc B-series (Battlemage) cards, with `--serve` and the draft layer (`--spec 2`
or more): on 2x Arc Pro B65 decode is 17% to 23% faster, and setup writes `--spec 2` for those cards ([INTEL_ARC.md](INTEL_ARC.md)).
It runs exactly two cards, so one card, Arc A-series cards and three or more cards stay serial.
- **Draft layer placement:** with the pipeline on, the draft layer loads on the first card, whose window has finished when the
chain starts. `STRATA_MTP_STAGE0=0` keeps the old place.
- **Off, with one log line saying why:** `--batch` slots, `--peer-device`, the helper caches (`--expert-cache-device1..3`, which
`--remote-expert-opt` builds on), a split onto one GPU, no draft layer, and on three or more stages `--pipeline-windows 1` and
`--adapt-async 1`. A request with repetition penalties or coupled draft sampling decodes serially.
- **Cost:** a second verify window on each card, 160 MiB less expert cache per card, plus two copies of the first card's
recurrent state (about 3 MiB per GDN layer it runs).
- **Config:** `"args": [ ..., "--pipeline-windows", "2" ]` with `"layer_split": "20"`.
`--remote-expert-opt` does something only with a helper cache; on a plain layer split it is inert.
The `STRATA_PIPELINE_*` tuning and test variables are read only with `STRATA_PIPELINE_DEBUG=1`.
## Two models on two cards
The other way to use two cards is two models, one per card, each answering on its own. In the app, turn on **Run multiple
models** on the Models page. The card list then says which card a loaded model uses ("In use by ..."), starts that card as Off
for the next model, and explains a failed start on a card that is taken. Two models at once on two makes is not supported.
**Measured on:** a PC with two of four Radeon AI PRO R9700 cards, Linux, AMD build, Q2_0 on one card and IQ3_XXS on the other.
Both loaded (33 s and 59 s with the files cached, 114 s the first time) and answered chats at about 60 tokens/s each. Unloading
one left the other answering. The same app code drives NVIDIA cards, but two models on two NVIDIA cards were not run.
## Small cards: what a split gives up when it is short of memory
Two 8 GB cards used to stop at the start ("expert cache: no room", "the GPU has too little free VRAM for the prompt path"): every card loads a copy of the
dense weights (3.5 GiB for IQ3_S) beside its session, its share of the head and the draft layer, a working expert cache and the prompt path's buffers. A split now
walks the same steps a single card does, per card, mildest first, and says each one in one line (`short of GPU memory: ...`). The context you asked for and the
number of requests are never changed; the cost is speed. A card with room never takes a step. Cards that hold every expert of their layers (two 96 GB cards) give the same
greedy answers as before (5 of 5 hashes); a card that holds only part of them has a cache 256 MiB smaller (the last paragraph), which can change the last bits.
1. **Trim**: a card that is too short for a full copy of the dense weights loads only the weights of its own layers (`--trim-stage-weights`, bit-exact in itself). Under `auto`
the split is then chosen from what each card has free, so every card gets the same cache bytes per layer. `STRATA_STAGE_TRIM=0` keeps the copies.
2. **KV window**: when no placement can start the prompt path, the search runs again with 20480, 8192, then 4096 cells of the KV window in VRAM (the rest streams from RAM).
3. **Drafter**: the draft layer (or DFlash2) is dropped on the card that holds it when that card cannot hold it and a working cache. `STRATA_MTP_KEEP=1` keeps it.
4. **Prompt buffers**: a stage whose cache cannot lend the prompt path a 256-token chunk keeps 16 slots behind the loan instead of 128; CUDA0 reads prompts with its own small buffers.
5. **Head**: the output head moves to pinned host memory on the card that holds it (about 3x slower logits), only when the cache would otherwise have no room.
6. **Fewer cards**: under `auto`, a card with under 3 GiB free is left out of the split, and so is the card with the least room when even the whole walk cannot pay for every
layer on the cards that are left; with none left, the start is the single card's, with the rest of the experts in RAM.
A later stage also keeps 256 MiB free for what it allocates after its cache (cuBLAS, the MMQ pool, as the single card has done since 0.2.7): two 16 GB cards used to start and then
run out of memory in the first long prompt. `STRATA_SPILL_OFF=1` turns every step off; `STRATA_DEFAULTS=026` keeps the 0.2.6 reserve.
When a start still ends because a card ran out of memory, `strata launch` and the server repeat it once without a drafter (never with the MTP in place of DFlash2, which takes more
memory), and the last line shown is the engine's own reason.
## Limits
- Every card needs compute capability 7.5 (RTX 20 or newer), unless you opt into the CUDA 12 engine for older cards.
- Works across cards: images (`--vision`), control vectors, KV streaming (`--kv-resident`) and mid-prompt checkpoints
(`--prompt-cache-every`). Each card keeps its own part.
- The older helper-GPU caches (`--expert-cache-device1..3`, [SECOND_GPU.md](SECOND_GPU.md)) take the visible GPUs no stage runs on.
A weak helper can make decoding slower, because its per-layer round trip costs more than the CPU pool needs for those experts.
- `--mmap-experts` needs a canonical pack (`experts.bin`); a native (IQ) pack says so at start.
- The prompt path has its own buffers on every card (1.5 GB each at the default 2048-token chunk; `--prefill 1024` halves that).
An explicit `--expert-cache` on the first card is capped to leave room for them.
- More cards pay off when the model's routed experts do not fit the faster ones. An extra slow card costs its own round per
window and can make a good pair slower.
With `--layer-split auto`, the engine prints a `FEWER CARDS` line when its cost model predicts a decode window that is at
least 20% shorter without the first cards. The placement does not change. `STRATA_SPLIT_FEWER_PCT` sets the threshold in
percent, and 0 disables the line. The line names the exact setting to try: `--gpu N` without `--layer-split` for one card, the
other cards hidden with `CUDA_VISIBLE_DEVICES` and `--layer-split auto` kept for several, and in the Terminal the card roles
(`strata launch --gpu-roles`, a card set to Off). Nothing is removed for you. The model predicts decode only, so measure the
prompt read before you remove a card.
- **The split pays most when the CPU pool is the bottleneck.** On two identical RTX 2080 Ti 22 GB over a dual-socket Xeon E5-2696 v4 (AVX2 only,
88 logical CPUs), a plain split moved decode from 35.2 to 51.0 tok/s (+45%) and an 11.6K-token prompt from 672 to 908 tok/s (+35%) at 180 W,
engine 0.1.49, six 300-token coding prompts. `STRATA_DECODE_TIMING=1` shows why: the window fell from 70.06 to 37.96 ms, almost entirely
because the CPU pool fell from 9.52 to 0.79 ms per window. The 5080 + 3090 measurement below, where decode with the second card is on par
with the 5080 alone, was taken over a fast CPU (Ryzen 9 9950X3D). When the CPU pool is what the window waits on, moving half the layers to a
second identical card removes that work. This is one pair of cards and one CPU, so there is no threshold, and the window breakdown from the
engine log is not the same statistic as the decode numbers beside it. Setup splits across two cards by itself; with two identical older cards
on a slow workstation CPU, compare one card against the split and tell us in [#3930](https://github.com/Niko1221/Strata/pull/3930).
- For several conversations at once, `--batch N --batch-groups G --trim-stage-weights` pipelines them through the cards
([BATCHING.md](BATCHING.md)).
## History / older measurements
Dated numbers behind the settings above. Each row is one machine; none is a claim about yours.
<a id="measured"></a>
**Layer split, Coder model.** Measured on: RTX 5080 + RTX 3090, Ryzen 9 9950X3D, Coder, 32K context, engine 0.1.20-era
(`docs/bench-results/2026-09-29-layer-split/`).
| Setup | Prompt 16K / 28K tok/s | Decode story / code tok/s |
| --- | --- | --- |
| 5080 alone | 1,726-2,017 / 1,970 | 83-87 / 88-105 |
| 5080 + 3090, best split (K=26) | 2,039 / 2,357 | 84 / 110 |
| 5080 + 3090, auto (K=22) | 2,037 / 2,073 | 80 / 109 |
A third card (RTX 2080 Ti) made that pair slower: 68 / 90 tok/s decode.
**Option measurements**
| Setting | Measured on | Result |
| --- | --- | --- |
| Unequal pair, `auto` rule | 2x RTX A4000 made unequal, IQ3_XXS, 14.5K prompt, 5 interleaved pairs | prompt 945 -> 1,441 tok/s (+52%), decode 50.2 -> 65.9 (+31%) |
| Unequal pair, hand sweep of `"layer_split"` | 4060 Ti 16 GB + 3060 12 GB, IQ3_S | K=12/18/24/28/32: 582 / 693 / 762 / 802 / 803 prompt tok/s; the old rule chose K=3: 452 |
| x16 + x4 link scaling | 2x RTX 3090, x16 + x4 | K=31: 114-119 tok/s decode, K=27: 130-136 |
| `split_skip_if_fits` | R9700 32 GB + RX 9070 XT, Coder | 4K prompts 1,244 -> 1,776 tok/s, decode ~51 -> ~60; 16K prompts ~5% slower |
| `STRATA_SPLIT_OWN=1` | R9700 + RX 9070 XT | 2K prompts 1,450 and 16K 2,227 tok/s (default 1,265 and 1,950) |
| `STRATA_PREFILL_HELP=1` | 2x RTX 3090, UD-Q4_K_XL, no P2P | prompt tok/s without / with: 1.1K 496 / 723, 2K 878 / 1,128, 3K 1,260 / 1,440; 4K and 8K unchanged |
| `STRATA_PREFILL_HELP=1` | 2x R9700 (16 GB each), Q2_0, PCIe 4.0 x16 | 700 tokens 638 -> 672; 1.5K 839 -> 809; 3K 1,105 -> 929; slower from 1.5K, so it stays off |
| `STRATA_SPLIT_MTP_BATCH=1` | 2x RTX 3080 20 GB, Xeon E5-2696 v4, UD-Q4_K_XL, `--layer-split 23` | prompt read +6.7% at 25K, +4.3% at 51K, +3.3% at 104K; decode not shown unchanged (about 3% lower, within restart noise) |
| `STRATA_STAGE_TRIM=1` | 2x MI50 16 GB, Coder | experts in VRAM 8,819 -> 10,626; decode 39.2 -> 41.7 tok/s |
| Prompt chunk on a split, AMD gfx12 | 2x / 3x / 4x R9700 | 16K prompt +36% / +45% / +53%; 32K +18% / +21% / +29%; 64K +4% / +12% / +17% |
| `STRATA_SPLIT_OVERLAP=1` | 2x RX 7900 XTX, Swift 1.5 IQ3_XXS, 128K, median of 8 | code decode 53 -> 70.1 tok/s (one card ~70); prose 45 -> 55.9 (one card ~68) |
| `STRATA_SPLIT_OVERLAP=1` | 2x RTX A4000, IQ3_XXS | +0.3% story, +2.1% code, -0.3% facts, inside the noise |
| Two Tesla P40, layer split | community report, IQ2_XS (#1028), experimental | decode 19.6 tok/s on one card, 34.8 on both |
**Resident RAM mode on a split.** Measured on: RTX 4060 Ti (layers 0-19) + RTX 5080 (20-47), i9-14900KF, 32 GB RAM, Windows 11,
Swift 1.5 IQ3_XXS, 160K context, four greedy prompts at a time, decode tok/s.
| Setup | First four prompts | After three more rounds |
| --- | ---: | ---: |
| 5080 alone, `--resident-experts` | 25 | 29 |
| split, `--mmap-experts` | 32 | 64 |
| split, `--resident-experts` (22 GiB locked in RAM) | 71 | 69 |
**Prompt chunks for the pipeline (`--prefill-pipe`).** Prompt tok/s, fresh prompts, two interleaved rounds per row.
| Prompt tokens | `--prefill auto` | `--prefill 2048` | `--prefill-pipe 1024` (chunk) |
| ---: | ---: | ---: | ---: |
| 2,013 | 180.9 | 181.4 | 228.0 (1024) |
| 3,865 | 207.6 | 276.5 | 312.4 (1024) |
| 10,041 | 261.1 | 433.0 | 432.6 (2048) |
| 28,998 | 475.7 | 554.1 | 559.7 (3328) |
Measured on: four GP100 dies (PH402 SKU 200), `--layer-split 12,24,36`, Flash-Next IQ3_XXS, 64K context. On 2x RTX 3090 Ti
(Swift 1.5 IQ3_XXS, 1M context) calibration kept it off, and a fixed 1024 chunk read 19-24% slower there and 22-36% slower on
2x RTX 4090 (community report).
On 2x RX 6900 XT (HIP, gfx1030, `--layer-split auto` = two stages, Flash-Next IQ3_S, 256K context
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

+539
View File
@@ -0,0 +1,539 @@
[
{
"id": "code_1",
"category": "code",
"messages": [
{
"role": "user",
"content": "Write a Python function merge_intervals(intervals) that merges overlapping [start, end] intervals and returns them sorted. Include a docstring and three assert-based tests."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "code_2",
"category": "code",
"messages": [
{
"role": "user",
"content": "Implement a thread-unsafe LRU cache class in C++17 with get(key) and put(key, value) in O(1) using std::list and std::unordered_map. Show the full class and a tiny main()."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "code_3",
"category": "code",
"messages": [
{
"role": "user",
"content": "Given tables orders(id, customer_id, region, total) and customers(id, name), write a SQL query that returns the top 3 customers by total order value in each region, using window functions."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "code_4",
"category": "code",
"messages": [
{
"role": "user",
"content": "This JavaScript is supposed to debounce a function but it never fires. Find the bug and give the corrected code:\n\nfunction debounce(fn, ms) {\n let t;\n return function(...args) {\n clearTimeout(t);\n setTimeout(() => fn.apply(this, args), ms);\n };\n}"
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "prose_1",
"category": "prose",
"messages": [
{
"role": "user",
"content": "Write a clear, engaging explanation of why the sea is salty, in about 150 words, for a curious teenager."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "prose_2",
"category": "prose",
"messages": [
{
"role": "user",
"content": "Describe how the printing press changed European society in the 15th and 16th centuries. Write three well-organised paragraphs."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "prose_3",
"category": "prose",
"messages": [
{
"role": "user",
"content": "Write the opening paragraph of a short story about a lighthouse keeper who finds a message in a bottle."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "json_1",
"category": "json",
"messages": [
{
"role": "user",
"content": "Return ONLY a JSON object (no prose, no code fence) with keys: name (string), age (integer), skills (array of exactly 3 strings), address (object with city and country). Invent a fictional software engineer."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "json_2",
"category": "json",
"messages": [
{
"role": "user",
"content": "Convert this CSV to a JSON array of objects, numbers as numbers. Output only the JSON.\n\nid,name,price,in_stock\n1,Widget,9.99,true\n2,Gadget,24.5,false\n3,Doohickey,3,true"
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "json_3",
"category": "json",
"messages": [
{
"role": "user",
"content": "Write a YAML configuration for a web service with three environments (dev, staging, prod). Each environment needs: replicas, cpu_limit, memory_limit and a list of two feature flags. Output only the YAML."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "tool_1",
"category": "tool",
"messages": [
{
"role": "user",
"content": "What's the weather in Paris right now? Use celsius."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
},
"required": [
"city"
]
}
}
},
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web and return result titles.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string"
},
"num_results": {
"type": "integer"
}
},
"required": [
"query"
]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate an arithmetic expression exactly.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string"
}
},
"required": [
"expression"
]
}
}
}
],
"effort": "off",
"max_new": 128
},
{
"id": "tool_2",
"category": "tool",
"messages": [
{
"role": "user",
"content": "Search the web for the latest stable PyTorch release and give me 3 results."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
},
"required": [
"city"
]
}
}
},
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web and return result titles.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string"
},
"num_results": {
"type": "integer"
}
},
"required": [
"query"
]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate an arithmetic expression exactly.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string"
}
},
"required": [
"expression"
]
}
}
}
],
"effort": "off",
"max_new": 128
},
{
"id": "tool_3",
"category": "tool",
"messages": [
{
"role": "user",
"content": "Please compute 1234 * 5678 with the calculator tool."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
},
"required": [
"city"
]
}
}
},
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web and return result titles.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string"
},
"num_results": {
"type": "integer"
}
},
"required": [
"query"
]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate an arithmetic expression exactly.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string"
}
},
"required": [
"expression"
]
}
}
}
],
"effort": "off",
"max_new": 128
},
{
"id": "chat_1",
"category": "chat",
"messages": [
{
"role": "user",
"content": "Hi! How are you today?"
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "chat_2",
"category": "chat",
"messages": [
{
"role": "user",
"content": "What is the capital of Australia?"
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "chat_3",
"category": "chat",
"messages": [
{
"role": "user",
"content": "Give me three quick tips for sleeping better."
}
],
"tools": null,
"effort": "off",
"max_new": 128
},
{
"id": "x_html",
"category": "extra",
"messages": [
{
"role": "user",
"content": "Create a complete single-file HTML page for a to-do list app: an input box, an Add button, a list with check boxes and delete buttons, and some CSS. Put the JavaScript in a script tag. Output only the HTML."
}
],
"tools": null,
"effort": "off",
"max_new": 1500
},
{
"id": "chat_2_high",
"category": "chat",
"messages": [
{
"role": "user",
"content": "What is the capital of Australia?"
}
],
"tools": null,
"effort": "high",
"max_new": 128
},
{
"id": "code_1_low",
"category": "code",
"messages": [
{
"role": "user",
"content": "Write a Python function merge_intervals(intervals) that merges overlapping [start, end] intervals and returns them sorted. Include a docstring and three assert-based tests."
}
],
"tools": null,
"effort": "low",
"max_new": 128
},
{
"id": "tool_1_high",
"category": "tool",
"messages": [
{
"role": "user",
"content": "What's the weather in Paris right now? Use celsius."
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
},
"required": [
"city"
]
}
}
},
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web and return result titles.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string"
},
"num_results": {
"type": "integer"
}
},
"required": [
"query"
]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "Evaluate an arithmetic expression exactly.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string"
}
},
"required": [
"expression"
]
}
}
}
],
"effort": "high",
"max_new": 128
},
{
"id": "json_1_xhigh",
"category": "json",
"messages": [
{
"role": "user",
"content": "Return ONLY a JSON object (no prose, no code fence) with keys: name (string), age (integer), skills (array of exactly 3 strings), address (object with city and country). Invent a fictional software engineer."
}
],
"tools": null,
"effort": "xhigh",
"max_new": 128
}
]
+372
View File
@@ -0,0 +1,372 @@
#!/usr/bin/env python3
"""q4_drift.py - reproduce the owner's quant-vs-BF16 drift numbers of a Qwen4-35B-A3B tier with the Strata engine (lane Q4-REF).
The golden (phaseA-tests/qwen4/evals/golden_qwen4_drift_ref.npz) holds, for 36 probes p00..p35, the BF16 model's teacher-forced numbers:
pNN_full_ids int32 [L+160] prompt + 160 continuation tokens, already tokenised (no tokenizer needed)
pNN_cont_offset int32 [1] = L-1: logits row j is the position cont_offset+j and predicts full_ids[cont_offset+j+1], j = 0..159
pNN_top128_idx int32 [160,128] BF16 top-128 token ids (descending)
pNN_top128_lp float16 [160,128] their log-probs
pNN_tail_prob float32 [160] probability mass outside the top-128 (1e-12 where it rounds to zero)
pNN_last_R39 float16 [4,2048] the 4 hyper-connection streams after layer 39 at the last position
The engine side: teacher-force full_ids through the quantised tier (ONE prefill pass of all of full_ids, as the reference did; a decode-step teacher
force is allowed too, say so in the log) and write per probe, in an output directory (see README.md):
<id>.tf.bin int32 P,K ; int32 ids[P,K] ; float32 logits[P,K] ; float32 lse[P] (Ling layout; P = 160 rows from position cont_offset, K >= 128, 256 advised)
or <id>.logits.f32 / .f16 / .npy [160, 248320] full logits (exact tail; the big files, use for a few probes)
<id>.R39.f32 8192 float32, the 4 x 2048 residual streams after layer 39 at the LAST position of full_ids (optional, cosine only)
<id>.gen.json {"nan": false} (optional; a true NaN flag fails GATE-NAN)
python -I q4_drift.py make-jobs GOLDEN.npz OUT.jsonl [--probes p00,p01] [--ids-dir DIR] jobs for the engine (and pNN.ids.txt, comma separated)
python -I q4_drift.py drift --golden GOLDEN.npz --engine DIR --tier compact|balanced|ultra [--owner drift_report_compact_v2.json]
[--probes p00,p01] [--json OUT.json]
python -I q4_drift.py selftest
Metrics, per position over the 160 rows (the owner's definitions, inferred from the numbers: see notes-q4-ref.md; the variants that are not certain are printed too):
top-1 engine argmax == BF16 top-1 id (top128_idx[:,0])
KL KL(BF16 || engine) over the BF16 top-128 plus ONE tail bucket: sum_i p_i (lp_i - q_i) + t_ref (ln t_ref - ln t_eng), p_i = exp(lp_i),
q_i = the engine's log-prob of that id (logit - full-vocabulary lse), t_eng = 1 - sum_i exp(q_i) (floored at 1e-12), t_ref = tail_prob.
Also printed: top-128 without the tail bucket, and the two renormalised top-128 distributions.
top-5 (a) BF16 top-1 within the engine's top-5 (b) engine top-1 within the BF16 top-5
flip rate among the positions where BF16 p(top-1) >= 0.9 (4659 of 5760): the fraction where the engine's top-1 differs (the denominator that reproduces the owner's 0.03692 etc.)
R39 cosine of the engine's 4x2048 streams with the golden's (informational; a quantised tier is not expected to be 1.0)
Per probe and mean (mean over all tokens = mean over probes, every probe has 160 rows). suite means: p00..p20 loktar21, p21..p35 canary15.
Gates (the coordinator's brief): GATE-DRIFT-TOP1 within +-0.5 points of the owner's tier number, GATE-DRIFT-KL within +-10 %, GATE-DRIFT-PROBES the
per-probe numbers close (|dKL| <= max(20 % of the owner's, 0.005) and |dtop-1| <= 0.03 on >= 90 % of the probes; provisional, set by --tol-*), GATE-NAN, GATE-COVERAGE.
A probe subset (--probes) is compared with the owner's per-probe numbers of the same probes; the overall gates then use their mean over the subset.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import sys
import tempfile
from pathlib import Path
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import q4_exact as qx # noqa: E402
# the owner's per-tier means over the 5760 tokens (Q4-LAUNCH-BRIEF.md, v2_top1_upgrade_summary.json)
OWNER = {
"compact": {"top1": 0.89288, "kl": 0.213052, "top5": 0.99514, "flip": 0.03692},
"balanced": {"top1": 0.96788, "kl": 0.026649, "top5": 0.99983, "flip": 0.00129},
"ultra": {"top1": 0.97622, "kl": 0.013379, "top5": 1.0, "flip": 0.00043},
}
EPS_TAIL = 1e-12
def load_golden(path: str) -> dict:
z = np.load(path, allow_pickle=False)
meta = {m["key"]: m for m in json.loads(bytes(z[" metadata_json"]).decode("utf-8"))} if " metadata_json" in z.files else {}
keys = sorted({k.split("_", 1)[0] for k in z.files if k.startswith("p") and "_" in k and k.split("_", 1)[0][1:].isdigit()})
out = {}
for k in keys:
s = qx.Seq(k)
ids = z[k + "_full_ids"].astype(np.int64)
off = int(z[k + "_cont_offset"][0])
idx = z[k + "_top128_idx"].astype(np.int64)
s.full_ids = ids
s.cont_offset = off
s.prompt_ids = ids[: off + 1]
s.cont_ids = ids[off + 1:]
s.top_ids = idx
s.top_logits = z[k + "_top128_lp"].astype(np.float64) # log-probs: lse 0 below makes them logits of a normalised distribution
s.lse = np.zeros(idx.shape[0])
s.positions = off + np.arange(idx.shape[0], dtype=np.int64)
s.tail = z[k + "_tail_prob"].astype(np.float64)
s.r39 = z[k + "_last_R39"].astype(np.float64).reshape(-1) if (k + "_last_R39") in z.files else None
s.meta = meta.get(k, {})
out[k] = s
return out
def _lse(x):
m = x.max(axis=1, keepdims=True)
return (m + np.log(np.exp(x - m).sum(axis=1, keepdims=True)))[:, 0]
def probe_rows(g, e, block: int = 32):
"""per-row arrays of engine e against golden g; engine rows aligned by qx.align_rows (positions, 160 rows, or absolute rows)"""
ra, ea, n, note = qx.align_rows(g, e)
res = {k: [] for k in ("kl_tail", "kl_top", "kl_renorm", "kl_rev", "top1", "top5a", "top5b", "conf", "flip", "cov")}
nonfin = 0
for a in range(0, max(n, 0), block):
b = min(a + block, n)
r_ids = g.top_ids[ra + a: ra + b]
r_lp = g.top_logits[ra + a: ra + b]
tail = np.maximum(g.tail[ra + a: ra + b], EPS_TAIL)
if e.full is not None:
x = e.full.block(ea + a, ea + b)
nonfin += int((~np.isfinite(x)).sum())
x = np.nan_to_num(x, nan=-1e30, posinf=1e30, neginf=-1e30)
lse = _lse(x.astype(np.float64))
q = np.take_along_axis(x, r_ids, 1).astype(np.float64) - lse[:, None]
arg = x.argmax(axis=1)
ref1 = np.take_along_axis(x, r_ids[:, :1], 1)
top5a = ((x > ref1).sum(axis=1) < 5)
top5b = (r_ids[:, :5] == arg[:, None]).any(1)
cov = np.ones(len(arg))
else:
e_ids, e_lg, e_lse = e.topk_block(ea + a, ea + b, e.K)
nonfin += int((~np.isfinite(e_lg)).sum()) + int((~np.isfinite(e_lse)).sum())
e_lg = np.nan_to_num(e_lg, nan=-1e30, posinf=1e30, neginf=-1e30)
eq = r_ids[:, :, None] == e_ids[:, None, :]
hit = eq.any(2)
j = eq.argmax(2)
v = np.where(hit, np.take_along_axis(e_lg, j, 1), e_lg[:, -1:]) # an id below the engine's top-K: its K-th logit (an upper bound)
q = v - e_lse[:, None]
arg = e_ids[:, 0]
top5a = hit[:, 0] & (j[:, 0] < 5)
top5b = (r_ids[:, :5] == arg[:, None]).any(1)
p = np.exp(r_lp)
cov = (p * hit).sum(1) / p.sum(1) # share of the BF16 top-128 mass that the engine's top-K covers
p = np.exp(r_lp)
d = r_lp - q
kl_top = (p * d).sum(1)
tq = np.maximum(1.0 - np.exp(q).sum(1), EPS_TAIL)
kl_tail = kl_top + tail * (np.log(tail) - np.log(tq))
kl_rev = (np.exp(q) * (q - r_lp)).sum(1) + tq * (np.log(tq) - np.log(tail)) # KL(engine || BF16), in case the owner's direction is the other one
zp, zq = p.sum(1), np.exp(q).sum(1)
kl_renorm = (p / zp[:, None] * (np.log(p / zp[:, None] + 1e-300) - np.log(np.exp(q) / zq[:, None] + 1e-300))).sum(1)
top1 = arg == r_ids[:, 0]
conf = p[:, 0] >= 0.9
for k, v_ in (("kl_tail", kl_tail), ("kl_top", kl_top), ("kl_renorm", kl_renorm), ("kl_rev", kl_rev), ("top1", top1), ("top5a", top5a), ("top5b", top5b), ("conf", conf),
("flip", conf & ~top1), ("cov", cov)):
res[k].append(np.asarray(v_))
out = {k: (np.concatenate(v) if v else np.zeros(0)) for k, v in res.items()}
out["n"] = n
out["nonfinite"] = nonfin
out["note"] = note
return out
def cos(a, b):
na, nb = np.linalg.norm(a), np.linalg.norm(b)
return float(a @ b / (na * nb)) if na > 0 and nb > 0 else float("nan")
def run_drift(args) -> int:
gold = load_golden(args.golden)
eng = qx.load_set(args.engine, args.vocab, {}, "eng")
keys = sorted(gold)
if args.probes:
keys = [k for k in keys if k in set(args.probes.split(","))]
owner_pp, owner_sum = {}, None
if args.owner:
o = json.loads(Path(args.owner).read_text(encoding="utf-8"))
gd = o.get("golden_drift") or o.get("golden_drift_summary") or o
for r in gd.get("per_probe", []):
owner_pp[r["id"]] = r
owner_sum = gd
exp = OWNER.get(args.tier, {}) if args.tier else {}
if owner_sum and "mean_kld" in owner_sum:
exp = {"top1": owner_sum["top1_agreement"], "kl": owner_sum["mean_kld"], "top5": owner_sum.get("top5_coverage"), "flip": owner_sum.get("high_conf_p09_flip_rate")}
rows, missing = [], []
for k in keys:
g, e = gold[k], eng.get(k)
if e is None or (e.full is None and e.top_ids is None):
missing.append(k)
continue
r = probe_rows(g, e)
if r["n"] <= 0:
missing.append(k)
continue
row = {"key": k, "id": g.meta.get("id", k), "suite": g.meta.get("suite", ""), "prompt_len": len(g.prompt_ids), "n": r["n"], "note": r["note"],
"top1": float(r["top1"].mean()), "top5a": float(r["top5a"].mean()), "top5b": float(r["top5b"].mean()), "kl": float(r["kl_tail"].mean()),
"kl_top": float(r["kl_top"].mean()), "kl_renorm": float(r["kl_renorm"].mean()), "kl_rev": float(r["kl_rev"].mean()), "conf": int(r["conf"].sum()), "flips": int(r["flip"].sum()),
"cov_min": float(r["cov"].min()), "nonfinite": r["nonfinite"] + (e.nonfinite() if e.full is None else 0), "nan_flag": e.nan_flag, "cos": None, "rel_l2": None}
if e.r39 is not None and g.r39 is not None and e.r39.size == g.r39.size:
row["cos"] = cos(e.r39, g.r39)
row["cos_streams"] = [cos(e.r39.reshape(4, -1)[i], g.r39.reshape(4, -1)[i]) for i in range(4)]
row["rel_l2"] = float(np.linalg.norm(e.r39 - g.r39) / max(np.linalg.norm(g.r39), 1e-30))
ow = owner_pp.get(row["id"])
if ow:
row["owner_kl"], row["owner_top1"] = ow["kld"], ow["top1"]
rows.append(row)
print(f"HARNESS q4_drift.py golden={args.golden} engine={args.engine} tier={args.tier or '?'}")
print(f"{'probe':<5}{'len':>6}{'top1':>8}{'(owner)':>9}{'KL':>9}{'(owner)':>9}{'ratio':>7}{'top5a':>7}{'top5b':>7}{'flip/conf':>10}{'R39 cos':>9} id")
for r in rows:
ok = ""
print(f"{r['key']:<5}{r['prompt_len']:>6}{r['top1']:>8.4f}{r.get('owner_top1', float('nan')):>9.4f}{r['kl']:>9.4f}{r.get('owner_kl', float('nan')):>9.4f}"
f"{(r['kl'] / r['owner_kl']) if r.get('owner_kl') else float('nan'):>7.2f}{r['top5a']:>7.3f}{r['top5b']:>7.3f}{r['flips']:>5}/{r['conf']:<4}"
f"{(format(r['cos'], '.4f') if r['cos'] is not None else '-'):>9} {r['id']}{ok}{' NaN' if (r['nonfinite'] or r['nan_flag']) else ''}"
f"{(' [' + r['note'] + ']') if r['note'] else ''}")
for k in missing:
print(f"{k:<5} MISSING in engine output")
if not rows:
print("GATE-COVERAGE FAIL no probe compared")
return 1
tok = sum(r["n"] for r in rows)
mean = lambda f: sum(r[f] * r["n"] for r in rows) / tok # noqa: E731
conf, flips = sum(r["conf"] for r in rows), sum(r["flips"] for r in rows)
agg = {"top1": mean("top1"), "kl": mean("kl"), "top5a": mean("top5a"), "top5b": mean("top5b"), "kl_top": mean("kl_top"), "kl_renorm": mean("kl_renorm"), "kl_rev": mean("kl_rev"),
"flip": flips / max(1, conf)}
for suite in ("loktar21", "canary15"):
sr = [r for r in rows if r["suite"] == suite]
if sr:
agg[suite + "_kl"] = sum(r["kl"] * r["n"] for r in sr) / sum(r["n"] for r in sr)
full = len(rows) == len(gold)
print(f"ALL {len(rows)}/{len(gold)} probes, {tok} tokens: top-1 {agg['top1']:.5f} KL {agg['kl']:.6f} top-5 (a) {agg['top5a']:.5f} (b) {agg['top5b']:.5f} "
f"flip rate {agg['flip']:.5f} ({flips}/{conf})" + "".join(f" {s} KL {agg[s + '_kl']:.6f}" for s in ("loktar21", "canary15") if s + "_kl" in agg))
print(f"INFO KL variants: with tail bucket {agg['kl']:.6f}, top-128 only {agg['kl_top']:.6f}, renormalised top-128 {agg['kl_renorm']:.6f}, reverse direction KL(engine||BF16) {agg['kl_rev']:.6f}")
covm = min(r["cov_min"] for r in rows)
if covm < 0.999:
print(f"INFO the engine's top-K covers only {covm:.4f} of the BF16 top-128 mass at the worst position: KL is biased low; dump more candidates (K=256 or full logits)")
cs = [r["cos"] for r in rows if r["cos"] is not None]
if cs:
print(f"INFO R39 cosine vs the golden: mean {np.mean(cs):.4f} min {np.min(cs):.4f} on {len(cs)} probes; relative L2 mean {np.mean([r['rel_l2'] for r in rows if r['rel_l2'] is not None]):.4f}")
gates = []
def gate(name, ok, text):
gates.append(ok)
print(f"GATE-{name} {'PASS' if ok else 'FAIL'} {text}")
gate("COVERAGE", not missing, f"{len(rows)}/{len(keys)} probes have engine output" + (f"; missing {','.join(missing)}" if missing else ""))
sub = {}
if owner_pp and not full:
sel = [owner_pp[r["id"]] for r in rows if r["id"] in owner_pp]
if sel:
sub = {"top1": float(np.mean([x["top1"] for x in sel])), "kl": float(np.mean([x["kld"] for x in sel]))}
ref = sub or (exp if full else {})
if not full and not sub:
print("GATE-DRIFT SKIP subset run without --owner: the tier means cover all 36 probes (give --owner drift_report_<tier>_v2.json for the subset's own numbers)")
elif ref.get("top1") is not None:
d = agg["top1"] - ref["top1"]
gate("DRIFT-TOP1", abs(d) <= args.tol_top1, f"top-1 {agg['top1']:.5f} vs owner {ref['top1']:.5f}: {100 * d:+.2f} points (tolerance +-{100 * args.tol_top1:.1f}){' [subset mean]' if sub else ''}")
rel = agg["kl"] / ref["kl"] - 1.0
gate("DRIFT-KL", abs(rel) <= args.tol_kl, f"KL {agg['kl']:.6f} vs owner {ref['kl']:.6f}: {100 * rel:+.1f} % (tolerance +-{100 * args.tol_kl:.0f} %){' [subset mean]' if sub else ''}")
else:
print("GATE-DRIFT SKIP no owner numbers (give --tier or --owner)")
if exp.get("top5") is not None and full:
print(f"INFO top-5 owner {exp['top5']:.5f}: ours (a) {agg['top5a']:.5f} (b) {agg['top5b']:.5f}; flip rate owner {exp['flip']:.5f}: ours {agg['flip']:.5f}")
pp = [r for r in rows if "owner_kl" in r]
if pp:
good = [r for r in pp if abs(r["kl"] - r["owner_kl"]) <= max(args.tol_probe_kl * r["owner_kl"], 0.005) and abs(r["top1"] - r["owner_top1"]) <= args.tol_probe_top1]
bad = [r["key"] for r in pp if r not in good]
gate("DRIFT-PROBES", len(good) >= args.probe_frac * len(pp), f"{len(good)}/{len(pp)} probes within |dKL| <= max({100 * args.tol_probe_kl:.0f} % of the owner's, 0.005) and |dtop-1| <= {args.tol_probe_top1}"
+ (f"; outside: {','.join(bad)}" if bad else "") + " (provisional)")
nan_total = sum(r["nonfinite"] for r in rows) + sum(1 for r in rows if r["nan_flag"])
gate("NAN", nan_total == 0, f"NaN/Inf count in the engine output: {nan_total}")
ok = all(gates)
print(f"GATE-Q4-DRIFT {'PASS' if ok else 'FAIL'} ({sum(gates)}/{len(gates)} gates){' (subset run)' if not full else ''}")
if args.json:
Path(args.json).write_text(json.dumps({"tier": args.tier, "aggregate": agg, "owner": exp, "probes": rows, "missing": missing}, indent=1, default=float))
return 0 if ok else 1
def run_make_jobs(args) -> int:
gold = load_golden(args.golden)
keys = [k for k in sorted(gold) if not args.probes or k in set(args.probes.split(","))]
if args.ids_dir:
Path(args.ids_dir).mkdir(parents=True, exist_ok=True)
with open(args.out, "w") as f:
for k in keys:
g = gold[k]
f.write(json.dumps({"id": k, "full_ids": g.full_ids.tolist(), "cont_offset": g.cont_offset, "rows": int(g.top_ids.shape[0]), "dump_r39": True,
"prompt_ids": g.prompt_ids.tolist(), "cont_ids": g.cont_ids.tolist(), "gen": 0, "tf": int(g.top_ids.shape[0])}) + "\n")
if args.ids_dir:
(Path(args.ids_dir) / f"{k}.ids.txt").write_text(",".join(str(int(i)) for i in g.full_ids))
print(f"{len(keys)} jobs -> {args.out}" + (f"; comma separated ids in {args.ids_dir}" if args.ids_dir else ""))
return 0
def run_selftest(_args) -> int:
rng = np.random.default_rng(3)
V, R = 3000, 40
tmp = Path(tempfile.mkdtemp(prefix="q4_drift_selftest_"))
gz, ed = tmp / "gold.npz", tmp / "eng"
ed.mkdir()
arrs, meta, truth = {}, [], {}
fails = []
for i, (L, suite) in enumerate(((30, "loktar21"), (50, "canary15"))):
k = f"p{i:02d}"
ids = rng.integers(0, V, L + R)
bf = (rng.standard_normal((R, V)) * 3).astype(np.float32)
bf[:, 0] += 6 * (np.arange(R) % 2) # make some rows confident
lse = _lse(bf.astype(np.float64))
idx = np.argsort(-bf, axis=1)[:, :128]
lp = (np.take_along_axis(bf, idx, 1) - lse[:, None]).astype(np.float16)
tail = np.maximum(1.0 - np.exp(np.take_along_axis(bf, idx, 1) - lse[:, None]).sum(1), 1e-12).astype(np.float32)
arrs.update({k + "_full_ids": ids.astype(np.int32), k + "_cont_offset": np.array([L - 1], np.int32), k + "_top128_idx": idx.astype(np.int32),
k + "_top128_lp": lp, k + "_tail_prob": tail, k + "_last_R39": rng.standard_normal((4, 2048)).astype(np.float16)})
meta.append({"key": k, "id": f"{suite}::t{i}", "suite": suite, "prompt_len": L, "gen_len": R})
q = bf + (rng.standard_normal(bf.shape) * 0.3).astype(np.float32) # the "quantised" engine
# brute-force truth: bucket KL on the stored (fp16) reference numbers
p = np.exp(lp.astype(np.float64))
qlse = _lse(q.astype(np.float64))
qi = np.take_along_axis(q, idx, 1).astype(np.float64) - qlse[:, None]
tq = np.maximum(1 - np.exp(qi).sum(1), 1e-12)
t = np.maximum(tail.astype(np.float64), 1e-12)
kl = (p * (lp.astype(np.float64) - qi)).sum(1) + t * (np.log(t) - np.log(tq))
truth[k] = (float(kl.mean()), float((q.argmax(1) == idx[:, 0]).mean()))
if i == 0:
q.astype("<f4").tofile(ed / f"{k}.logits.f32")
else:
order = np.argsort(-q, axis=1)[:, :256]
vals = np.take_along_axis(q, order, 1)
with open(ed / f"{k}.tf.bin", "wb") as f:
import struct
f.write(struct.pack("<ii", R, 256) + order.astype(np.int32).tobytes() + vals.astype(np.float32).tobytes() + qlse.astype(np.float32).tobytes())
(ed / f"{k}.R39.f32").write_bytes((arrs[k + "_last_R39"].astype(np.float32).reshape(-1) + rng.standard_normal(8192).astype(np.float32) * 0.05).astype("<f4").tobytes())
arrs[" metadata_json"] = np.frombuffer(json.dumps(meta).encode(), np.uint8)
np.savez(gz, **arrs)
ns = argparse.Namespace(golden=str(gz), engine=str(ed), tier="compact", owner=None, probes=None, json=str(tmp / "o.json"), vocab=V, tol_top1=0.005, tol_kl=0.10,
tol_probe_kl=0.20, tol_probe_top1=0.03, probe_frac=0.9)
import contextlib
import io
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
run_drift(ns)
out = buf.getvalue()
print(out)
res = json.loads((tmp / "o.json").read_text())
for r in res["probes"]:
tk, tt = truth[r["key"]]
if abs(r["kl"] - tk) > 2e-3 * max(1.0, tk) or abs(r["top1"] - tt) > 1e-9:
fails.append(f"{r['key']}: kl {r['kl']:.6f} vs brute force {tk:.6f}, top1 {r['top1']} vs {tt}")
if r["cos"] is None or r["cos"] < 0.99:
fails.append(f"{r['key']}: R39 cosine {r['cos']}")
if "GATE-NAN PASS" not in out or "GATE-COVERAGE PASS" not in out:
fails.append("NaN or coverage gate line missing")
bad = np.fromfile(ed / "p00.logits.f32", "<f4")
bad[5] = np.nan
bad.astype("<f4").tofile(ed / "p00.logits.f32")
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
run_drift(ns)
if "GATE-NAN FAIL" not in buf.getvalue():
fails.append("NaN not caught")
print("selftest:", "FAIL " + "; ".join(fails) if fails else "PASS (golden npz, f32 full logits, tf.bin K=256, R39, brute-force KL and top-1, NaN)")
return 1 if fails else 0
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sp = ap.add_subparsers(dest="cmd", required=True)
d = sp.add_parser("drift")
d.add_argument("--golden", required=True)
d.add_argument("--engine", required=True)
d.add_argument("--tier", choices=sorted(OWNER))
d.add_argument("--owner", help="drift_report_<tier>_v2.json of the owner (per-probe numbers and the tier means)")
d.add_argument("--probes")
d.add_argument("--json")
d.add_argument("--vocab", type=int, default=qx.DEFAULT_VOCAB)
d.add_argument("--tol-top1", type=float, default=0.005)
d.add_argument("--tol-kl", type=float, default=0.10)
d.add_argument("--tol-probe-kl", type=float, default=0.20)
d.add_argument("--tol-probe-top1", type=float, default=0.03)
d.add_argument("--probe-frac", type=float, default=0.9)
j = sp.add_parser("make-jobs")
j.add_argument("golden")
j.add_argument("out")
j.add_argument("--probes")
j.add_argument("--ids-dir")
sp.add_parser("selftest")
a = ap.parse_args()
return {"drift": run_drift, "make-jobs": run_make_jobs, "selftest": run_selftest}[a.cmd](a)
if __name__ == "__main__":
sys.exit(main())
+960
View File
@@ -0,0 +1,960 @@
#!/usr/bin/env python3
"""q4_exact.py - exactness check of the Strata Qwen4-35B-A3B engine against reference logits (the Qwen4 counterpart of the Ling golden gate,
engine/tests/ling32/golden_compare.py, but format-flexible because the reference data of the Qwen4 quant is not fixed yet).
python -I q4_exact.py inspect PATH [PATH ...] what a reference / engine file holds: keys, shapes, dtypes, ids found
python -I q4_exact.py make-jobs --ref PATH [--prompts P.json] OUT.jsonl [--gen 128] [--tf 64]
the engine's jobs file (Ling format: id, prompt_ids, cont_ids, gen, tf)
python -I q4_exact.py compare --ref PATH --engine DIR [--also bf16=PATH ...] [--json OUT.json] [options]
top-1 %, mean / max KL, greedy identical x of y, NaN count, GATE lines
python -I q4_exact.py selftest synthetic round trip through every format (no model needed)
REFERENCE (--ref) and ENGINE (--engine) can each be a directory (one set of files per prompt id) or one file that holds all ids. Formats:
.npz / .npy / .safetensors (F32, F16, BF16, ints; own reader, no safetensors package needed) / .json / .jsonl / .pt (if torch is installed) /
raw float32 (.f32, .bin with --vocab) / the Ling engine files <id>.tf.bin + <id>.gen.json.
Per prompt the reader looks for (synonyms are accepted, see ALIASES; --map KEY=NAME adds one):
prompt_ids int [L] the rendered, tokenised prompt
cont_ids int [C] the reference's greedy continuation (the teacher-forced tokens come from it)
logits float [P,V] FULL next-token logits per position, or
top_ids [P,K] + top_logits [P,K] (+ lse [P]) the Ling golden layout (logprobs instead of logits: give lse = 0 or leave it out)
positions int [P] absolute positions of the rows, if the file does not start at position 0
gen_ids / nan / decode_tok_s (engine side, <id>.gen.json)
Position p of a row set = the logits that predict the token after tokens[0..p] of prompt_ids + cont_ids (Ling convention: the last prompt
position predicts cont_ids[0]). If the engine holds fewer rows than the reference and carries no positions, the alignment is printed:
1 row = the first-token logits (reference row L-1), otherwise the TAIL of the reference.
Gates (Ling P1 numbers for the short set; the long set (prompt > --long-len tokens, default 2048 = the Qwen4 indexer budget, so the sparse top-k
attention is active) has its own numbers that are PROVISIONAL until the owner's reference noise is known):
GATE-TOP1 teacher-forced top-1 >= 99.8 % over all positions of the short prompts (--top1)
GATE-KL mean KL(ref || engine) < 5e-4 (--kl)
GATE-GREEDY the greedy continuation equals the reference's for the first >= 32 tokens on most prompts (--greedy-prefix)
GATE-NAN no NaN / Inf in the engine's logits or gen.json
GATE-LONG-TOP1 / GATE-LONG-KL the same for long prompts: >= 99.0 % and < 2e-3 until measured otherwise (--long-top1, --long-kl)
GATE-COVERAGE every reference prompt has engine output
GATE-QUANTFLOOR (with --also LABEL=PATH, e.g. the BF16 evals) engine KL vs that reference <= 1.5 x (primary reference vs the same reference) + 1e-4
KL = sum_i p_ref(i) (log p_ref(i) - log p_eng(i)). Full-vocabulary when both sides hold full logits; otherwise over the reference top-K support (Ling's
rule: an id missing from the engine's top-K takes the engine's K-th logit, so the estimate can only be too small by the tail).
Top-1 is tie aware: an engine argmax whose reference logit equals the reference maximum counts as agreement (bf16 dumps tie often); the strict figure
is printed as well. Exit code 0 = every gate passes.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import os
import struct
import sys
import tempfile
from pathlib import Path
import numpy as np
DEFAULT_VOCAB = 248320 # Qwen4 padded vocab (config.json vocab_size)
ALIASES = {
"prompt_ids": ["prompt_ids", "input_ids", "prompt_tokens", "prompt", "ids_prompt", "prompt_token_ids"],
"cont_ids": ["cont_ids", "continuation_ids", "cont", "completion_ids", "output_ids", "generated_ids", "greedy_ids", "gen_ids", "tf_ids"],
"gen_ids": ["gen_ids", "generated_ids", "output_ids", "greedy_ids", "completion_ids", "cont_ids"],
"logits": ["logits", "tf_logits", "full_logits", "all_logits", "logits_all", "lm_logits", "pos_logits", "first_logits", "next_logits"],
"logprobs": ["logprobs", "log_probs", "tf_logprobs", "full_logprobs"],
"top_ids": ["tf_top_ids", "top_ids", "topk_ids", "topk_indices", "top_indices", "top_k_ids", "top_tokens"],
"top_logits": ["tf_top_logits", "top_logits", "topk_logits", "topk_values", "top_values", "top_k_logits"],
"top_logprobs": ["tf_top_logprobs", "top_logprobs", "topk_logprobs", "top_k_logprobs"],
"lse": ["tf_lse", "lse", "logsumexp", "log_sum_exp"],
"positions": ["positions", "pos", "position_ids", "token_positions"],
"nan": ["nan", "has_nan"],
"decode_tok_s": ["decode_tok_s"],
"r39": ["r39", "R39", "last_R39", "last_r39", "resid_last", "last_resid"],
}
IGNORE_SUFFIX = (".routes.npz", ".meta.json", ".lookahead.json", ".layers.f32")
EXTS = (".npz", ".npy", ".safetensors", ".json", ".jsonl", ".pt", ".pth", ".f32", ".f16", ".bin")
# --------------------------------------------------------------------------------------------------------------------------------- matrices
class Mat:
"""A [P,V] logits matrix read lazily in row blocks as float32."""
shape: tuple
def block(self, a: int, b: int) -> np.ndarray: # pragma: no cover - interface
raise NotImplementedError
class ArrMat(Mat):
def __init__(self, arr: np.ndarray):
self.arr = arr
self.shape = tuple(arr.shape)
def block(self, a, b):
return np.asarray(self.arr[a:b], dtype=np.float32)
class Bf16Mat(Mat):
def __init__(self, raw: np.ndarray, shape):
self.raw = raw
self.shape = tuple(shape)
def block(self, a, b):
u = np.asarray(self.raw[a:b]).astype(np.uint32) << 16
return u.view(np.float32)
_ST_DT = {"F64": np.float64, "F32": np.float32, "F16": np.float16, "I64": np.int64, "I32": np.int32, "I16": np.int16, "I8": np.int8, "U8": np.uint8,
"U16": np.uint16, "U32": np.uint32, "U64": np.uint64, "BOOL": np.bool_}
def _to_array(x):
"""Mat -> ndarray (small things only: ids, lse), ndarray -> ndarray."""
if isinstance(x, Mat):
return x.block(0, x.shape[0])
return np.asarray(x)
def read_safetensors(path: Path) -> dict:
with open(path, "rb") as f:
n = struct.unpack("<Q", f.read(8))[0]
hdr = json.loads(f.read(n).decode("utf-8"))
base = 8 + n
out = {}
size = path.stat().st_size
mm = np.memmap(path, mode="r", dtype=np.uint8, offset=base, shape=(size - base,)) if size > base else np.zeros(0, np.uint8)
for name, meta in hdr.items():
if name == "__metadata__":
continue
s, e = meta["data_offsets"]
shape = tuple(meta["shape"])
dt = meta["dtype"]
raw = mm[s:e]
if dt == "BF16":
u16 = raw.view(np.uint16).reshape(shape)
out[name] = Bf16Mat(u16, shape) if len(shape) == 2 else u16.astype(np.uint32).__lshift__(16).view(np.float32).reshape(shape)
else:
if dt not in _ST_DT:
continue
a = raw.view(_ST_DT[dt]).reshape(shape)
out[name] = ArrMat(a) if (a.ndim == 2 and a.dtype.kind == "f") else np.array(a)
return out
def read_raw_f32(path: Path, vocab: int) -> dict:
"""raw little-endian float32 (.f32, .bin) or float16 (.f16) rows of --vocab values; <id>.R39.f32 is the flat residual dump instead"""
a = np.fromfile(path, dtype="<f2" if path.suffix.lower() == ".f16" else "<f4")
parts = path.name.split(".")
if len(parts) >= 3 and parts[1].lower() == "r39":
return {"r39": a.astype(np.float32)}
if a.size % vocab:
raise SystemExit(f"{path}: {a.size} values is not a multiple of --vocab {vocab}")
return {"logits": ArrMat(a.reshape(-1, vocab))}
def read_tf_bin(path: Path) -> dict:
b = path.read_bytes()
P, K = struct.unpack_from("<ii", b, 0)
off = 8
ids = np.frombuffer(b, np.int32, P * K, off).reshape(P, K)
off += P * K * 4
vals = np.frombuffer(b, np.float32, P * K, off).reshape(P, K)
off += P * K * 4
lse = np.frombuffer(b, np.float32, P, off)
return {"top_ids": ids, "top_logits": vals, "lse": lse}
def _topk_from_py(rows):
"""per position a list of {id|token_id|token: ..., logprob|logit: ...} or a dict {id: value}; -> (ids [P,K], vals [P,K], is_logprob)"""
ids, vals, lp = [], [], False
for r in rows:
if isinstance(r, dict) and not any(k in r for k in ("id", "token_id", "token", "logprob", "logit")):
items = sorted(((int(str(k).replace("token_id:", "")), float(v)) for k, v in r.items()), key=lambda t: -t[1])
else:
items = []
for e in r:
tid = e.get("id", e.get("token_id", e.get("token")))
if isinstance(tid, str):
tid = int(tid.replace("token_id:", ""))
if "logprob" in e:
lp = True
items.append((int(tid), float(e.get("logprob", e.get("logit")))))
items.sort(key=lambda t: -t[1])
ids.append([t[0] for t in items])
vals.append([t[1] for t in items])
k = min(len(x) for x in ids)
return np.array([x[:k] for x in ids], np.int32), np.array([x[:k] for x in vals], np.float64), lp
def _py_to_arrays(d: dict) -> dict:
out = {}
for k, v in d.items():
if isinstance(v, (list, tuple)):
if v and isinstance(v[0], (list, tuple, dict)) and k in ALIASES["top_ids"] + ALIASES["top_logprobs"] + ["top", "top_k"]:
try:
ids, vals, lp = _topk_from_py(v)
out["top_ids"] = ids
out["top_logprobs" if lp else "top_logits"] = vals
continue
except Exception:
pass
try:
out[k] = np.array(v)
except Exception:
out[k] = v
elif isinstance(v, (int, float, bool)):
out[k] = np.array(v)
else:
out[k] = v
return out
def read_json(path: Path) -> dict:
txt = path.read_text(encoding="utf-8")
if path.suffix == ".jsonl":
recs = [json.loads(ln) for ln in txt.splitlines() if ln.strip()]
return {"__records__": recs}
d = json.loads(txt)
if isinstance(d, list):
return {"__records__": d}
if isinstance(d, dict) and "summary" in d and "prompts" in d:
return {}
return _py_to_arrays(d)
def read_pt(path: Path) -> dict:
try:
import torch # noqa: PLC0415
except ImportError:
raise SystemExit(f"{path}: reading .pt needs torch (not installed); save the tensors as .npz or .safetensors")
d = torch.load(path, map_location="cpu", weights_only=True)
out = {}
for k, v in (d.items() if isinstance(d, dict) else [("logits", d)]):
if hasattr(v, "dtype") and str(v.dtype) == "torch.bfloat16":
v = v.float()
out[k] = ArrMat(v.numpy()) if (hasattr(v, "ndim") and v.ndim == 2 and v.is_floating_point()) else (v.numpy() if hasattr(v, "numpy") else v)
return out
def read_file(path: Path, vocab: int) -> dict:
n = path.name
if n.endswith(".tf.bin"):
return read_tf_bin(path)
suf = path.suffix.lower()
if suf == ".npz":
z = np.load(path, allow_pickle=False)
out = {}
for k in z.files:
a = z[k]
out[k] = ArrMat(a) if (a.ndim == 2 and a.dtype.kind == "f") else a
return out
if suf == ".npy":
a = np.load(path, mmap_mode="r", allow_pickle=False)
return {"logits": ArrMat(a.reshape(-1, a.shape[-1]))} if a.dtype.kind == "f" else {"prompt_ids": np.asarray(a)}
if suf == ".safetensors":
return read_safetensors(path)
if suf in (".json", ".jsonl"):
return read_json(path)
if suf in (".pt", ".pth"):
return read_pt(path)
if suf in (".f32", ".f16", ".bin"):
return read_raw_f32(path, vocab)
raise SystemExit(f"{path}: unknown format")
# ------------------------------------------------------------------------------------------------------------------------ normalisation
class Seq:
"""One prompt's normalised data: full logits (Mat) or top-K (ids, logits, lse)."""
def __init__(self, sid: str):
self.id = sid
self.prompt_ids = None
self.cont_ids = None
self.gen_ids = None
self.full: Mat | None = None
self.top_ids = None
self.top_logits = None
self.lse = None
self.positions = None
self.nan_flag = False
self.decode_tok_s = None
self.r39 = None
self.source = ""
@property
def P(self) -> int:
if self.full is not None:
return self.full.shape[0]
return 0 if self.top_ids is None else self.top_ids.shape[0]
@property
def K(self) -> int:
return 0 if self.top_ids is None else self.top_ids.shape[1]
def nonfinite(self) -> int:
n = 0
if self.full is not None:
for a in range(0, self.P, 64):
n += int((~np.isfinite(self.full.block(a, min(a + 64, self.P)))).sum())
if self.top_logits is not None:
n += int((~np.isfinite(self.top_logits)).sum())
if self.lse is not None:
n += int((~np.isfinite(self.lse)).sum())
return n
def topk_block(self, a: int, b: int, k: int):
"""(ids [n,k], logits [n,k] float64, lse [n] float64), descending."""
if self.full is not None:
x = self.full.block(a, b)
kk = min(k, x.shape[1])
idx = np.argpartition(-x, kk - 1, axis=1)[:, :kk]
v = np.take_along_axis(x, idx, 1)
order = np.argsort(-v, axis=1, kind="stable")
idx = np.take_along_axis(idx, order, 1)
v = np.take_along_axis(v, order, 1).astype(np.float64)
m = x.max(axis=1).astype(np.float64)
lse = m + np.log(np.exp(x.astype(np.float64) - m[:, None]).sum(axis=1))
return idx.astype(np.int64), v, lse
kk = min(k, self.K)
return (self.top_ids[a:b, :kk].astype(np.int64), self.top_logits[a:b, :kk].astype(np.float64), self.lse[a:b].astype(np.float64))
def _find(flat: dict, canon: str):
for name in ALIASES[canon]:
if name in flat:
return flat[name]
return None
def _normalise(sid: str, flat: dict, vocab: int, extra_map: dict, role: str) -> Seq:
flat = dict(flat)
for k, v in extra_map.items():
if v in flat:
flat[k] = flat[v]
s = Seq(sid)
pi = _find(flat, "prompt_ids")
if pi is not None:
s.prompt_ids = _to_array(pi).astype(np.int64).reshape(-1)
if role == "ref":
ci = _find(flat, "cont_ids")
else:
ci = flat.get("cont_ids")
if ci is not None:
s.cont_ids = _to_array(ci).astype(np.int64).reshape(-1)
gi = None
for name in (["gen_ids", "generated_ids", "output_ids", "greedy_ids", "completion_ids"] if role == "eng" else []):
if name in flat:
gi = flat[name]
break
if gi is not None:
s.gen_ids = _to_array(gi).astype(np.int64).reshape(-1)
lg = _find(flat, "logits")
lp = _find(flat, "logprobs")
ti, tl, tp, ls = _find(flat, "top_ids"), _find(flat, "top_logits"), _find(flat, "top_logprobs"), _find(flat, "lse")
if lg is not None or lp is not None:
m = lg if lg is not None else lp
if isinstance(m, Mat):
shape = m.shape
else:
m = ArrMat(np.asarray(m)) if np.asarray(m).ndim >= 1 else None
shape = m.shape
if len(shape) == 1:
m = ArrMat(np.asarray(m.arr).reshape(1, -1))
elif len(shape) == 3:
m = ArrMat(np.asarray(m.arr).reshape(-1, shape[-1]))
s.full = m
elif ti is not None and (tl is not None or tp is not None):
ids = _to_array(ti).astype(np.int64)
vals = _to_array(tl if tl is not None else tp).astype(np.float64)
if ids.ndim == 3:
ids, vals = ids.reshape(-1, ids.shape[-1]), vals.reshape(-1, vals.shape[-1])
elif ids.ndim == 1:
ids, vals = ids[None], vals[None]
s.top_ids = ids
s.top_logits = vals
s.lse = _to_array(ls).astype(np.float64).reshape(-1) if ls is not None else np.zeros(ids.shape[0])
if ls is None and tl is not None:
# logits without a lse: the top-K logprob mass is unknown, so the KL cannot be normalised; treat as logprobs and say so
s.source += " (top logits without lse: taken as logprobs)"
pos = _find(flat, "positions")
if pos is not None:
s.positions = _to_array(pos).astype(np.int64).reshape(-1)
nn = _find(flat, "nan")
if nn is not None:
s.nan_flag = bool(np.asarray(nn).any())
dt = _find(flat, "decode_tok_s")
if dt is not None:
s.decode_tok_s = float(np.asarray(dt).reshape(-1)[0])
r39 = _find(flat, "r39")
if r39 is not None:
s.r39 = _to_array(r39).astype(np.float64).reshape(-1)
return s
def _group_flat(flat: dict) -> dict:
"""one big flat dict with names like 'chat_1.logits', 'chat_1/top_ids', 'logits.chat_1' -> {id: {key: value}}"""
known = set(sum(ALIASES.values(), [])) | {"cont_ids", "gen_ids"}
grouped: dict = {}
for name, v in flat.items():
for sep in (".", "/", "::", "__", "-"):
if sep in name:
head, _, tail = name.rpartition(sep)
if tail in known:
grouped.setdefault(head, {})[tail] = v
break
head, _, tail = name.partition(sep)
if head in known:
grouped.setdefault(tail, {})[head] = v
break
else:
return {}
return grouped
def _stem_id(name: str) -> str:
return name.split(".")[0]
def load_set(path: str, vocab: int, extra_map: dict, role: str) -> dict[str, Seq]:
"""-> {id: Seq}. PATH is a directory (<id>.* files) or one file (one prompt: id = stem; or many: grouped keys / records)."""
p = Path(path)
if not p.exists():
raise SystemExit(f"{path}: not found")
flats: dict[str, dict] = {}
srcs: dict[str, list] = {}
if p.is_dir():
for f in sorted(p.iterdir()):
if not f.is_file() or f.name.endswith(IGNORE_SUFFIX) or not (f.name.endswith(".tf.bin") or f.suffix.lower() in EXTS):
continue
if f.name in ("jobs.jsonl", "lookahead.json", "summary.json", "index.json"):
continue
try:
d = read_file(f, vocab)
except SystemExit:
raise
except Exception as e: # noqa: BLE001
print(f"WARN {f.name}: unreadable ({e})", file=sys.stderr)
continue
if "__records__" in d:
for i, r in enumerate(d["__records__"]):
rid = str(r.get("id", f"{_stem_id(f.name)}_{i}")) if isinstance(r, dict) else f"{_stem_id(f.name)}_{i}"
flats.setdefault(rid, {}).update(_py_to_arrays(r))
srcs.setdefault(rid, []).append(f.name)
continue
sid = _stem_id(f.name)
grouped = _group_flat(d)
if grouped and not any(k in d for k in sum(ALIASES.values(), [])):
for gid, gd in grouped.items():
flats.setdefault(gid, {}).update(gd)
srcs.setdefault(gid, []).append(f.name)
continue
# <id>.logits.npy : a bare array named by its second part
parts = f.name.split(".")
if f.suffix.lower() == ".npy" and len(parts) >= 3:
key = parts[1]
arr = d.get("logits") or d.get("prompt_ids")
d = {key: arr}
flats.setdefault(sid, {}).update(d)
srcs.setdefault(sid, []).append(f.name)
else:
d = read_file(p, vocab)
if "__records__" in d:
for i, r in enumerate(d["__records__"]):
rid = str(r.get("id", f"{p.stem}_{i}")) if isinstance(r, dict) else f"{p.stem}_{i}"
flats[rid] = _py_to_arrays(r)
srcs[rid] = [p.name]
else:
grouped = _group_flat(d) if not any(k in d for k in sum(ALIASES.values(), [])) else {}
if grouped:
flats = grouped
srcs = {k: [p.name] for k in grouped}
else:
flats = {_stem_id(p.name): d}
srcs = {_stem_id(p.name): [p.name]}
out = {}
for sid, fl in flats.items():
s = _normalise(sid, fl, vocab, extra_map, role)
s.source = ",".join(srcs[sid]) + s.source
out[sid] = s
return out
# ------------------------------------------------------------------------------------------------------------------------------ metrics
def _logsumexp_rows(x: np.ndarray) -> np.ndarray:
m = x.max(axis=1, keepdims=True)
return (m + np.log(np.exp(x - m).sum(axis=1, keepdims=True)))[:, 0]
def _kl_support(r_ids, r_lg, r_lse, e_ids, e_lg, e_lse):
"""KL over the reference support; engine logit of an id missing from its top-K = its K-th logit."""
eq = r_ids[:, :, None] == e_ids[:, None, :]
hit = eq.any(2)
j = eq.argmax(2)
v = np.take_along_axis(e_lg, j, 1)
v = np.where(hit, v, e_lg[:, -1:])
lr = r_lg - r_lse[:, None]
le = v - e_lse[:, None]
return (np.exp(lr) * (lr - le)).sum(axis=1), np.exp(lr).sum(axis=1)
def align_rows(ref: Seq, eng: Seq):
"""-> (ref_row_start, eng_row_start, n, note)"""
pr, pe = ref.P, eng.P
r0 = int(ref.positions[0]) if ref.positions is not None else 0 # absolute position of reference row 0
if eng.positions is not None:
e0 = int(eng.positions[0])
s = max(r0, e0)
return s - r0, s - e0, min(r0 + pr, e0 + pe) - s, (f"engine rows start at position {e0}" if e0 else "")
if pe == pr:
return 0, 0, pr, ""
if pe == 1 and ref.prompt_ids is not None and 0 <= len(ref.prompt_ids) - 1 - r0 < pr:
return len(ref.prompt_ids) - 1 - r0, 0, 1, f"first-token logits (engine 1 row) vs reference row {len(ref.prompt_ids) - 1 - r0}"
if pe >= r0 + pr: # the engine holds every position from 0 (prefill rows + decode rows)
return 0, r0, pr, f"engine rows are absolute positions 0..{pe - 1}; reference rows start at {r0}"
if pe < pr:
return pr - pe, 0, pe, f"engine has {pe} rows, reference {pr}: comparing the TAIL of the reference"
return 0, pe - pr, pr, f"engine has {pe} rows, reference {pr}: comparing the TAIL of the engine rows"
def compare_pair(ref: Seq, eng: Seq, k: int, tie_eps: float, block: int = 64):
"""per-prompt numbers of eng against ref (rows aligned by align_rows)"""
ra, ea, n, note = align_rows(ref, eng)
if n <= 0:
return {"positions": 0, "note": note or "no common positions"}
kls = np.zeros(n)
top1_strict = top1 = 0
mism = []
dlp_med, dlp_max = [], 0.0
mass = []
mode = "full" if (ref.full is not None and eng.full is not None) else "top%d" % k
nonfin = 0
for a in range(0, n, block):
b = min(a + block, n)
rs, re_, es, ee = ra + a, ra + b, ea + a, ea + b
r_ids, r_lg, r_lse = ref.topk_block(rs, re_, k)
if eng.full is not None:
x = eng.full.block(es, ee)
nonfin += int((~np.isfinite(x)).sum())
x = np.nan_to_num(x, nan=-1e30, posinf=1e30, neginf=-1e30)
e_arg = x.argmax(axis=1)
if ref.full is not None:
y = ref.full.block(rs, re_).astype(np.float64)
xd = x.astype(np.float64)
lr = y - _logsumexp_rows(y)[:, None]
le = xd - _logsumexp_rows(xd)[:, None]
kl = (np.exp(lr) * (lr - le)).sum(axis=1)
msum = np.ones(b - a)
else:
e_lse = _logsumexp_rows(x.astype(np.float64))
e_lg = np.take_along_axis(x, r_ids, 1).astype(np.float64)
lr = r_lg - r_lse[:, None]
le = e_lg - e_lse[:, None]
kl = (np.exp(lr) * (lr - le)).sum(axis=1)
msum = np.exp(lr).sum(axis=1)
e_top1_lg_at_ref = np.take_along_axis(x, e_arg[:, None], 1)[:, 0]
e_lp_at_ref = (np.take_along_axis(x, r_ids, 1).astype(np.float64) - _logsumexp_rows(x.astype(np.float64))[:, None])
else:
kk = min(k, eng.K)
e_ids, e_lg, e_lse = eng.topk_block(es, ee, kk)
nonfin += int((~np.isfinite(e_lg)).sum()) + int((~np.isfinite(e_lse)).sum())
e_lg = np.nan_to_num(e_lg, nan=-1e30, posinf=1e30, neginf=-1e30)
kl, msum = _kl_support(r_ids, r_lg, r_lse, e_ids, e_lg, e_lse)
e_arg = e_ids[:, 0]
e_top1_lg_at_ref = None
eq = r_ids[:, :, None] == e_ids[:, None, :]
hit = eq.any(2)
jj = eq.argmax(2)
e_lp_at_ref = np.where(hit, np.take_along_axis(e_lg, jj, 1), e_lg[:, -1:]) - e_lse[:, None]
kls[a:b] = kl
mass.extend(msum.tolist())
# top-1, strict and tie aware (engine argmax has the reference's maximum logit)
r1 = r_ids[:, 0]
strict = e_arg == r1
top1_strict += int(strict.sum())
ok = strict.copy()
for i in np.where(~strict)[0]:
# reference logit of the engine's argmax
hit_i = np.where(r_ids[i] == e_arg[i])[0]
if len(hit_i) and r_lg[i, hit_i[0]] >= r_lg[i, 0] - tie_eps:
ok[i] = True
top1 += int(ok.sum())
for i in np.where(~ok)[0]:
gap = float(r_lg[i, 0] - r_lg[i, 1]) if r_lg.shape[1] > 1 else float("nan")
mism.append({"pos": int(rs + i), "ref": int(r1[i]), "eng": int(e_arg[i]), "ref_gap": gap})
lp_ref = r_lg - r_lse[:, None]
d = np.abs(lp_ref - e_lp_at_ref)
dlp_med.append(float(np.median(d)))
dlp_max = max(dlp_max, float(d.max()))
return {"positions": n, "top1": top1, "top1_strict": top1_strict, "top1_pct": 100.0 * top1 / n, "kl_mean": float(kls.mean()), "kl_max": float(kls.max()),
"kl_sum": float(kls.sum()), "kl_mode": mode, "support_mass_min": float(min(mass)) if mass else 1.0, "dlogprob_median": float(np.median(dlp_med)),
"dlogprob_max": dlp_max, "mismatches": mism[:12], "n_mismatch": len(mism), "nonfinite": nonfin, "note": note}
def greedy_cmp(ref_cont, eng_gen):
if ref_cont is None or eng_gen is None:
return None
a, b = eng_gen.tolist(), ref_cont.tolist()
same = 0
for x, y in zip(a, b):
if x != y:
break
same += 1
return {"same_prefix": same, "len_engine": len(a), "len_ref": len(b), "identical": same == min(len(a), len(b)) and len(a) == len(b)}
# ---------------------------------------------------------------------------------------------------------------------------------- compare
def run_compare(args) -> int:
emap = dict(x.split("=", 1) for x in (args.map or []))
ref = load_set(args.ref, args.vocab, emap, "ref")
eng = load_set(args.engine, args.vocab, emap, "eng")
ids = sorted(ref)
if args.ids:
want = set(args.ids.split(","))
ids = [i for i in ids if i in want]
if args.skip_ids:
ids = [i for i in ids if i not in set(args.skip_ids.split(","))]
if not ids:
print(f"no reference prompts found in {args.ref} (ids seen: {sorted(ref)[:10]})")
print("GATE-COVERAGE FAIL no reference prompts")
return 1
also = {}
for item in args.also or []:
lab, _, pth = item.partition("=")
also[lab] = load_set(pth, args.vocab, emap, "ref")
rows, missing = [], []
for pid in ids:
r = ref[pid]
e = eng.get(pid)
if e is None or (e.full is None and e.top_ids is None and e.gen_ids is None):
missing.append(pid)
continue
plen = len(r.prompt_ids) if r.prompt_ids is not None else (len(e.prompt_ids) if e.prompt_ids is not None else 0)
row = {"id": pid, "prompt_len": plen, "long": plen > args.long_len or pid.startswith("long")}
if (r.full is not None or r.top_ids is not None) and (e.full is not None or e.top_ids is not None):
row.update(compare_pair(r, e, args.k, args.tie_eps))
else:
row["positions"] = 0
row["note"] = "no logits on one side"
g = greedy_cmp(r.cont_ids, e.gen_ids if e.gen_ids is not None else None)
row["greedy"] = g
row["nan_flag"] = e.nan_flag
row["engine_nonfinite"] = row.get("nonfinite", 0) + (e.nonfinite() if e.full is None else 0)
row["decode_tok_s"] = e.decode_tok_s
row["source"] = e.source
for lab, aset in also.items():
a = aset.get(pid)
if a is None:
continue
ex = compare_pair(a, e, args.k, args.tie_eps) if (a.full is not None or a.top_ids is not None) else None
fl = compare_pair(a, r, args.k, args.tie_eps) if (a.full is not None or a.top_ids is not None) else None
row.setdefault("also", {})[lab] = {"engine": ex, "ref": fl}
rows.append(row)
def grp(sel):
rs = [r for r in rows if r["positions"] and sel(r)]
pos = sum(r["positions"] for r in rs)
return {"prompts": len(rs), "positions": pos, "top1_pct": 100.0 * sum(r["top1"] for r in rs) / max(1, pos),
"top1_strict_pct": 100.0 * sum(r["top1_strict"] for r in rs) / max(1, pos), "kl_mean": sum(r["kl_sum"] for r in rs) / max(1, pos),
"kl_max": max([r["kl_max"] for r in rs], default=0.0)}
short, long_ = grp(lambda r: not r["long"]), grp(lambda r: r["long"])
allg = [r for r in rows if r.get("greedy")]
ge = sum(1 for r in allg if r["greedy"]["same_prefix"] >= min(args.greedy_prefix, r["greedy"]["len_ref"]))
ident = sum(1 for r in allg if r["greedy"]["identical"])
nan_total = sum(r["engine_nonfinite"] for r in rows) + sum(1 for r in rows if r["nan_flag"])
print(f"HARNESS q4_exact.py sha256={hashlib.sha256(Path(__file__).read_bytes()).hexdigest()[:16]} ref={args.ref} engine={args.engine}")
print(f"{'id':<14}{'len':>6}{'pos':>6}{'top1 %':>9}{'strict %':>9}{'KL mean':>11}{'KL max':>10}{'dlogp med/max':>16} greedy same prefix / ref / engine")
for r in rows:
if not r["positions"]:
g = r.get("greedy")
print(f"{r['id']:<14}{r['prompt_len']:>6} (no logits compared: {r.get('note','')})" + (f" greedy {g['same_prefix']} / {g['len_ref']} / {g['len_engine']}" if g else ""))
continue
g = r.get("greedy")
gs = f"{g['same_prefix']:>5} / {g['len_ref']} / {g['len_engine']}{' identical' if g['identical'] else ''}" if g else " (no greedy ids)"
print(f"{r['id']:<14}{r['prompt_len']:>6}{r['positions']:>6}{100.0 * r['top1'] / r['positions']:>9.2f}{100.0 * r['top1_strict'] / r['positions']:>9.2f}"
f"{r['kl_mean']:>11.2e}{r['kl_max']:>10.2e}{r['dlogprob_median']:>9.1e}/{r['dlogprob_max']:<8.1e} {gs}{' LONG' if r['long'] else ''}"
f"{' NaN' if (r['nan_flag'] or r['engine_nonfinite']) else ''}{(' [' + r['note'] + ']') if r.get('note') else ''}")
if args.verbose and r["mismatches"]:
for m in r["mismatches"]:
print(f" top-1 mismatch at position {m['pos']}: ref {m['ref']} engine {m['eng']} (ref gap to 2nd {m['ref_gap']:.3f})")
for pid in missing:
print(f"{pid:<14} MISSING in engine output")
modes = sorted({r["kl_mode"] for r in rows if r.get("kl_mode")})
print(f"KL mode: {', '.join(modes) or 'n/a'}; support mass of the reference top-{args.k} (min over positions): "
f"{min([r['support_mass_min'] for r in rows if r.get('support_mass_min') is not None], default=1.0):.4f}")
gates = []
def gate(name, ok, text):
gates.append(ok)
print(f"GATE-{name} {'PASS' if ok else 'FAIL'} {text}")
gate("COVERAGE", not missing, f"{len(rows)}/{len(ids)} reference prompts have engine output" + (f"; missing {','.join(missing)}" if missing else ""))
if short["positions"]:
gate("TOP1", short["top1_pct"] >= args.top1, f"short prompts: top-1 {short['top1_pct']:.3f} % (strict {short['top1_strict_pct']:.3f} %) over {short['positions']} positions of {short['prompts']} prompts, need >= {args.top1}")
gate("KL", short["kl_mean"] < args.kl, f"short prompts: mean KL {short['kl_mean']:.2e} (max per-position {short['kl_max']:.2e}), need < {args.kl:g}")
else:
print("GATE-TOP1 SKIP no short prompt with logits")
if long_["positions"]:
gate("LONG-TOP1", long_["top1_pct"] >= args.long_top1, f"long prompts: top-1 {long_['top1_pct']:.3f} % (strict {long_['top1_strict_pct']:.3f} %) over {long_['positions']} positions of {long_['prompts']} prompts, need >= {args.long_top1} (provisional)")
gate("LONG-KL", long_["kl_mean"] < args.long_kl, f"long prompts: mean KL {long_['kl_mean']:.2e} (max per-position {long_['kl_max']:.2e}), need < {args.long_kl:g} (provisional)")
else:
print("GATE-LONG SKIP no long prompt with logits (a prompt above --long-len tokens, id long*)")
if allg:
gate("GREEDY", ge > len(allg) / 2, f"greedy identical {ident} of {len(allg)} prompts; >= {args.greedy_prefix} identical tokens on {ge} of {len(allg)} (need most)")
else:
print("GATE-GREEDY SKIP no greedy ids on both sides")
gate("NAN", nan_total == 0, f"NaN/Inf count in the engine output: {nan_total}")
for lab in also:
pe = [(r["also"][lab]["engine"], r["also"][lab]["ref"]) for r in rows if lab in r.get("also", {}) and r["also"][lab]["engine"] and r["also"][lab]["engine"].get("positions")]
if pe:
n = sum(x["positions"] for x, _ in pe)
ke = sum(x["kl_sum"] for x, _ in pe) / n
kf = sum(y["kl_sum"] for _, y in pe if y and y.get("positions")) / max(1, sum(y["positions"] for _, y in pe if y and y.get("positions")))
te = 100.0 * sum(x["top1"] for x, _ in pe) / n
tf = 100.0 * sum(y["top1"] for _, y in pe if y and y.get("positions")) / max(1, sum(y["positions"] for _, y in pe if y and y.get("positions")))
print(f"INFO vs {lab}: engine top-1 {te:.3f} % KL {ke:.2e}; primary reference vs {lab}: top-1 {tf:.3f} % KL {kf:.2e} ({n} positions)")
gate("QUANTFLOOR", ke <= 1.5 * kf + 1e-4, f"engine-vs-{lab} KL {ke:.2e} <= 1.5 x quant floor {kf:.2e} + 1e-4")
ok = all(gates) and bool(rows)
print(f"GATE-Q4-EXACT {'PASS' if ok else 'FAIL'} ({sum(gates)}/{len(gates)} gates)")
if args.json:
Path(args.json).write_text(json.dumps({"short": short, "long": long_, "greedy_identical": ident, "greedy_ge_prefix": ge, "greedy_total": len(allg),
"nan": nan_total, "missing": missing, "prompts": rows}, indent=1, default=float))
return 0 if ok else 1
# ------------------------------------------------------------------------------------------------------------------------------ jobs, inspect
def run_make_jobs(args) -> int:
emap = dict(x.split("=", 1) for x in (args.map or []))
ref = load_set(args.ref, args.vocab, emap, "ref") if args.ref else {}
prompts = {}
if args.prompts:
for p in json.loads(Path(args.prompts).read_text(encoding="utf-8")):
if p.get("prompt_ids"):
prompts[p["id"]] = p
ids = sorted(set(ref) | set(prompts))
n = 0
with open(args.out, "w") as f:
for pid in ids:
r = ref.get(pid)
pi = prompts[pid]["prompt_ids"] if pid in prompts else (r.prompt_ids.tolist() if r is not None and r.prompt_ids is not None else None)
if pi is None:
print(f"skip {pid}: no prompt_ids (give --prompts a tokenised prompt file)")
continue
ci = r.cont_ids.tolist() if r is not None and r.cont_ids is not None else []
if r is not None and r.prompt_ids is not None and pid in prompts and list(r.prompt_ids) != list(pi):
print(f"WARN {pid}: tokenised prompt differs from the reference's prompt_ids ({len(pi)} vs {len(r.prompt_ids)} tokens); the reference rows will not line up")
f.write(json.dumps({"id": pid, "prompt_ids": pi, "cont_ids": ci, "gen": (args.gen if args.gen > 0 else len(ci)), "tf": args.tf}) + "\n")
n += 1
print(f"{n} jobs -> {args.out}")
return 0
def describe(v) -> str:
if isinstance(v, Mat):
return f"matrix {list(v.shape)} ({type(v).__name__})"
if isinstance(v, np.ndarray):
s = f"array {list(v.shape)} {v.dtype}"
if v.size and v.dtype.kind in "iu":
s += f" range [{v.min()}, {v.max()}]"
elif v.size and v.dtype.kind == "f":
fin = np.isfinite(v)
s += f" finite {int(fin.sum())}/{v.size}" + (f" range [{float(v[fin].min()):.4g}, {float(v[fin].max()):.4g}]" if fin.any() else "")
return s
return type(v).__name__ + (f" len {len(v)}" if hasattr(v, "__len__") else "")
def run_inspect(args) -> int:
for path in args.paths:
p = Path(path)
files = sorted(x for x in p.iterdir() if x.is_file()) if p.is_dir() else [p]
print(f"== {path}: {len(files)} file(s)")
shown = 0
for f in files:
if f.name.endswith(IGNORE_SUFFIX) or not (f.name.endswith(".tf.bin") or f.suffix.lower() in EXTS):
if shown < 40:
print(f" {f.name} ({f.stat().st_size} bytes, skipped by the loader)")
shown += 1
continue
if shown >= args.max_files:
print(" ...")
break
shown += 1
print(f" {f.name} ({f.stat().st_size} bytes)")
try:
d = read_file(f, args.vocab)
except SystemExit as e:
print(f" {e}")
continue
except Exception as e: # noqa: BLE001
print(f" unreadable: {e}")
continue
if "__records__" in d:
recs = d["__records__"]
print(f" {len(recs)} records; first: {json.dumps(recs[0])[:300] if recs else ''}")
continue
for k, v in list(d.items())[: args.max_keys]:
tag = [c for c, names in ALIASES.items() if k in names]
print(f" {k:<40} {describe(v)}" + (f" -> {'/'.join(tag)}" if tag else " (not a known key)"))
if len(d) > args.max_keys:
print(f" ... {len(d)} keys in all")
try:
sets = load_set(path, args.vocab, {}, "ref")
print(f" loader: {len(sets)} prompt id(s): {', '.join(sorted(sets)[:12])}{' ...' if len(sets) > 12 else ''}")
for sid in sorted(sets)[:3]:
s = sets[sid]
kind = f"full logits {list(s.full.shape)}" if s.full is not None else (f"top-{s.K} x {s.P} positions" if s.top_ids is not None else "no logits")
print(f" {sid}: prompt {None if s.prompt_ids is None else len(s.prompt_ids)} tok, cont {None if s.cont_ids is None else len(s.cont_ids)} tok, {kind}")
except SystemExit as e:
print(f" loader: {e}")
return 0
# ------------------------------------------------------------------------------------------------------------------------------- selftest
def _write_safetensors(path: Path, tensors: dict):
hdr, blobs, off = {}, [], 0
for k, a in tensors.items():
if a.dtype == np.float32 and k.endswith("__bf16"):
u = (np.ascontiguousarray(a).view(np.uint32) >> 16).astype(np.uint16)
raw, dt, name = u.tobytes(), "BF16", k[: -len("__bf16")]
else:
name = k
dt = {np.dtype(np.float32): "F32", np.dtype(np.int64): "I64", np.dtype(np.int32): "I32"}[a.dtype]
raw = np.ascontiguousarray(a).tobytes()
hdr[name] = {"dtype": dt, "shape": list(a.shape), "data_offsets": [off, off + len(raw)]}
blobs.append(raw)
off += len(raw)
h = json.dumps(hdr).encode()
path.write_bytes(struct.pack("<Q", len(h)) + h + b"".join(blobs))
def run_selftest(_args) -> int:
rng = np.random.default_rng(7)
V, K = 4000, 64
tmp = Path(tempfile.mkdtemp(prefix="q4_exact_selftest_"))
ref_dir, eng_dir = tmp / "ref", tmp / "eng"
ref_dir.mkdir()
eng_dir.mkdir()
fails = []
seqs = {}
for sid, L, C in (("chat_1", 20, 8), ("code_1", 33, 8), ("long_4k", 40, 6)):
P = L + C
lg = (rng.standard_normal((P, V)) * 2.0).astype(np.float32)
seqs[sid] = (rng.integers(0, V, L), rng.integers(0, V, C), lg)
# reference in three formats: full npz, safetensors (bf16 rounded), top-64 npz (Ling layout)
def topk(lg):
idx = np.argsort(-lg, axis=1)[:, :K]
v = np.take_along_axis(lg, idx, 1)
m = lg.max(1, keepdims=True).astype(np.float64)
lse = (m + np.log(np.exp(lg - m).sum(1, keepdims=True)))[:, 0]
return idx.astype(np.int32), v, lse.astype(np.float32)
pi, ci, lg = seqs["chat_1"]
np.savez(ref_dir / "chat_1.npz", prompt_ids=pi, cont_ids=ci, logits=lg)
pi2, ci2, lg2 = seqs["code_1"]
ti, tv, tl = topk(lg2)
np.savez(ref_dir / "code_1.npz", prompt_ids=pi2, cont_ids=ci2, tf_top_ids=ti, tf_top_logits=tv, tf_lse=tl)
pi3, ci3, lg3 = seqs["long_4k"]
_write_safetensors(ref_dir / "long_4k.safetensors", {"prompt_ids": pi3.astype(np.int64), "cont_ids": ci3.astype(np.int64), "logits__bf16": lg3})
lg3_bf16 = (np.ascontiguousarray(lg3).view(np.uint32) >> 16 << 16).view(np.float32)
def noisy(a, s):
return a + (rng.standard_normal(a.shape) * s).astype(np.float32)
# engine: chat_1 as full .npy with tiny noise, code_1 as Ling tf.bin, long_4k as full f32 raw (+ gen.json)
e1 = noisy(lg, 1e-4)
np.save(eng_dir / "chat_1.logits.npy", e1)
(eng_dir / "chat_1.gen.json").write_text(json.dumps({"gen_ids": ci.tolist(), "nan": False}))
e2 = noisy(lg2, 1e-4)
ei, ev, el = topk(e2)
with open(eng_dir / "code_1.tf.bin", "wb") as f:
P = ei.shape[0]
f.write(struct.pack("<ii", P, K) + ei.tobytes() + ev.astype(np.float32).tobytes() + el.tobytes())
(eng_dir / "code_1.gen.json").write_text(json.dumps({"gen_ids": ci2.tolist()[:5] + [1, 2], "nan": False}))
noisy(lg3_bf16, 1e-4).astype("<f4").tofile(eng_dir / "long_4k.f32")
(eng_dir / "long_4k.gen.json").write_text(json.dumps({"gen_ids": ci3.tolist(), "nan": False}))
ns = argparse.Namespace(ref=str(ref_dir), engine=str(eng_dir), also=None, map=None, vocab=V, ids=None, skip_ids=None, json=str(tmp / "out.json"), k=K, tie_eps=0.0,
long_len=2048, top1=99.8, kl=5e-4, long_top1=99.0, long_kl=2e-3, greedy_prefix=32, verbose=True)
import contextlib
import io
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = run_compare(ns)
out = buf.getvalue()
if rc != 1 and "GATE-GREEDY" not in out:
fails.append("expected the greedy mismatch of code_1 to show")
print(out)
for needle in ("GATE-TOP1 PASS", "GATE-KL PASS", "GATE-NAN PASS", "GATE-COVERAGE PASS"):
if needle not in out:
fails.append(f"missing {needle}")
# greedy: chat_1 identical, code_1 diverges at 5, long_4k identical; 2 of 3 have >= min(32, len) = 8/6 prefix? code_1 has 5 < 8 -> 2 of 3 pass -> GATE-GREEDY PASS
if "greedy identical 2 of 3" not in out:
fails.append("greedy identical count wrong")
# NaN must fail
bad = lg.copy()
bad[3, 5] = np.nan
np.save(eng_dir / "chat_1.logits.npy", bad)
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = run_compare(ns)
if "GATE-NAN FAIL" not in buf.getvalue() or rc == 0:
fails.append("NaN was not caught")
# a real error must fail KL / top-1
np.save(eng_dir / "chat_1.logits.npy", noisy(lg, 0.5))
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
rc = run_compare(ns)
if "GATE-KL FAIL" not in buf.getvalue() and "GATE-TOP1 FAIL" not in buf.getvalue():
fails.append("a noisy engine passed")
# first-token alignment: one row of chat_1 against the reference's row L-1
one = tmp / "one"
one.mkdir()
np.save(one / "chat_1.npy", lg[len(pi) - 1])
ns2 = argparse.Namespace(**{**vars(ns), "engine": str(one), "ids": "chat_1"})
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
run_compare(ns2)
if "first-token logits" not in buf.getvalue() or "KL mean" not in buf.getvalue():
fails.append("first-token alignment")
print("selftest:", "FAIL " + "; ".join(fails) if fails else "PASS (npz, npy, safetensors bf16, tf.bin, raw f32, gen.json, NaN, noise, first-token)")
return 1 if fails else 0
# --------------------------------------------------------------------------------------------------------------------------------- main
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sp = ap.add_subparsers(dest="cmd", required=True)
c = sp.add_parser("compare")
c.add_argument("--ref", required=True)
c.add_argument("--engine", required=True)
c.add_argument("--also", action="append", help="LABEL=PATH: a second reference (e.g. bf16=...) for the quant-floor gate")
c.add_argument("--map", action="append", help="KEY=NAME: treat NAME in the files as the canonical KEY (prompt_ids, cont_ids, logits, top_ids, top_logits, lse)")
c.add_argument("--vocab", type=int, default=DEFAULT_VOCAB, help="row width of raw float32 files")
c.add_argument("--ids")
c.add_argument("--skip-ids")
c.add_argument("--json")
c.add_argument("--k", type=int, default=64, help="top-K support of the KL when a side has no full logits")
c.add_argument("--tie-eps", type=float, default=0.0, help="reference logit slack that still counts a different argmax as agreement")
c.add_argument("--long-len", type=int, default=2048)
c.add_argument("--top1", type=float, default=99.8)
c.add_argument("--kl", type=float, default=5e-4)
c.add_argument("--long-top1", type=float, default=99.0)
c.add_argument("--long-kl", type=float, default=2e-3)
c.add_argument("--greedy-prefix", type=int, default=32)
c.add_argument("--verbose", "-v", action="store_true")
j = sp.add_parser("make-jobs")
j.add_argument("--ref")
j.add_argument("--prompts", help="tokenised prompt file from q4_prompts.py (prompt_ids per id)")
j.add_argument("--map", action="append")
j.add_argument("--vocab", type=int, default=DEFAULT_VOCAB)
j.add_argument("out")
j.add_argument("--gen", type=int, default=0)
j.add_argument("--tf", type=int, default=64)
i = sp.add_parser("inspect")
i.add_argument("paths", nargs="+")
i.add_argument("--vocab", type=int, default=DEFAULT_VOCAB)
i.add_argument("--max-files", type=int, default=12)
i.add_argument("--max-keys", type=int, default=24)
sp.add_parser("selftest")
args = ap.parse_args()
return {"compare": run_compare, "make-jobs": run_make_jobs, "inspect": run_inspect, "selftest": run_selftest}[args.cmd](args)
if __name__ == "__main__":
sys.exit(main())
+190
View File
@@ -0,0 +1,190 @@
#!/usr/bin/env python3
"""q4_prompts.py - the Qwen4 prompt sets of the exactness lane, tokenised with Qwen4's own chat encoder (encoding_qwen4.py + tiktoken.model of the HF repo).
python -I -B q4_prompts.py tokenize --hf HFDIR --out tokenized.json [--doc-tokens 4096]
python -I -B q4_prompts.py selfcheck --hf HFDIR the HF README's example (high effort) must give the published ids
python -I -B q4_prompts.py make-image data/pic_448.png the deterministic picture of the picture prompt
HFDIR holds tiktoken.model, encoding_qwen4.py and tokenizer_config.json of Qwen/Qwen4-35B-A3B (revision 849378c8..., public; Q4-INTAKE vendors them).
Needs python 3.10+ with `tiktoken` (and numpy for make-image); no transformers.
Sets (data/): prompts_short.json = the Ling short set (3 chat, 4 code, 3 json/yaml, 3 tool calls, 3 prose, 1 HTML) + four effort variants (low/high/xhigh);
a 4K document prompt built from the frozen data/doc_corpus.txt (README + docs/MULTI_GPU.md of int-0226) by cutting lines until the rendered prompt is <= --doc-tokens;
a picture prompt: data/pic_448.png (448x448, merge unit 32 px -> 14x14 = 196 image tokens) + "Describe this image." The text encoder renders ONE <|image_pad|>; the processor
(processing_qwen4.replace_image_token) expands it to prod(image_grid_thw) // merge_size^2 = 28*28 // 4 = 196 pads, done here so prompt_ids carries the final count.
Effort: the prompt's "effort" goes to reasoning_effort (off, low, high, xhigh); add_generation_prompt is on, so `off` ends with <think></think> and the others with <think>.
Output: a JSON list of {id, category, effort, prompt_ids, n_prompt_tokens, max_new, image?}; q4_exact.py make-jobs --prompts takes it.
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import struct
import sys
import zlib
from pathlib import Path
HERE = Path(__file__).resolve().parent
DATA = HERE / "data"
# the HF README's published ids for apply_chat_template(user "Write a Python function to merge two sorted linked lists. <think>", reasoning_effort=high, preserve_thinking)
README_IDS = [248045, 8678, 198, 24342, 286, 4879, 369, 716, 310, 1496, 13, 248046, 198, 248045, 846, 198, 7734, 264, 12654, 709, 310, 10562, 1330, 10300, 10278, 11140,
13, 361, 26003, 29, 248046, 198, 248045, 74455, 198, 248068]
class Shim:
"""TokenizerProtocol of encoding_qwen4.py on top of tiktoken (what tokenization_qwen4.Qwen4Tokenizer does, without transformers)."""
PAT = (r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+|\p{N}| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+")
RESERVED = 276
def __init__(self, hf: Path):
import tiktoken
from tiktoken.load import load_tiktoken_bpe
ranks = load_tiktoken_bpe(str(hf / "tiktoken.model"))
cfg = json.loads((hf / "tokenizer_config.json").read_text(encoding="utf-8"))
known = {int(k): v["content"] for k, v in cfg.get("added_tokens_decoder", {}).items()}
first = len(ranks)
specials = {known.get(i, f"<|reserved_token_{i}|>"): i for i in range(first, first + self.RESERVED)}
self.model = tiktoken.Encoding(name="qwen4", pat_str=self.PAT, mergeable_ranks=ranks, special_tokens=specials)
if self.model.n_vocab != 248320:
raise SystemExit(f"unexpected vocabulary size {self.model.n_vocab}")
def tokenize_segment(self, text: str, *, allow_special: bool = False) -> list[int]:
return self.model.encode(text, allowed_special="all") if allow_special else self.model.encode(text, disallowed_special=())
def decode(self, ids, **kw) -> str:
return self.model.decode(ids if isinstance(ids, list) else [ids])
def load_encoder(hf: Path):
spec = importlib.util.spec_from_file_location("encoding_qwen4", hf / "encoding_qwen4.py")
mod = importlib.util.module_from_spec(spec)
sys.modules["encoding_qwen4"] = mod
spec.loader.exec_module(mod)
return mod.Qwen4ChatEncoder(Shim(hf)), Shim(hf)
def render(enc, messages, tools, effort) -> list[int]:
return enc.render_tokens(messages, tools or None, add_generation_prompt=True, reasoning_effort=effort, preserve_thinking=True)
def doc_prompt(enc, target: int, effort: str = "off"):
lines = (DATA / "doc_corpus.txt").read_text(encoding="utf-8").split("\n")
head = "Below is the documentation of a software project. Read it carefully and then answer the question at the end.\n"
tail = "\n\n===== END OF DOCUMENTATION =====\nQuestion: In 5 short bullet points, what does this project do and what are its main features?"
def build(n):
return head + "\n".join(lines[:n]) + tail
def ntok(n):
return len(render(enc, [{"role": "user", "content": build(n)}], None, effort))
lo, hi = 1, len(lines)
if ntok(hi) <= target:
raise SystemExit(f"the frozen corpus has only {ntok(hi)} tokens, need more than {target}")
while lo < hi:
mid = (lo + hi + 1) // 2
if ntok(mid) <= target:
lo = mid
else:
hi = mid - 1
return build(lo), ntok(lo)
def picture_prompt(enc, hf: Path):
png = DATA / "pic_448.png"
w = h = 448
pads = (h // 16) * (w // 16) // 4 # image_grid_thw prod // merge_size^2 (t = 1)
msgs = [{"role": "user", "content": [{"type": "image", "image": "data/pic_448.png"}, {"type": "text", "text": "Describe this image."}]}]
ids = render(enc, msgs, None, "off")
pad_id = enc.tok.model.encode("<|image_pad|>", allowed_special="all")
assert len(pad_id) == 1
out, done = [], False
for t in ids:
if t == pad_id[0] and not done:
out.extend([t] * pads)
done = True
else:
out.append(t)
return out, pads, png.name
def cmd_selfcheck(a) -> int:
enc, _ = load_encoder(Path(a.hf))
ids = render(enc, [{"role": "user", "content": "Write a Python function to merge two sorted linked lists. <think>"}], None, "high")
ok = ids == README_IDS
print("README example:", "PASS" if ok else f"FAIL\n got {ids}\n want {README_IDS}")
return 0 if ok else 1
def cmd_tokenize(a) -> int:
enc, _ = load_encoder(Path(a.hf))
out = []
for p in json.loads((DATA / "prompts_short.json").read_text(encoding="utf-8")):
ids = render(enc, p["messages"], p["tools"], p["effort"])
out.append({"id": p["id"], "category": p["category"], "effort": p["effort"], "prompt_ids": ids, "n_prompt_tokens": len(ids), "max_new": p["max_new"]})
text, n = doc_prompt(enc, a.doc_tokens)
ids = render(enc, [{"role": "user", "content": text}], None, "off")
out.append({"id": "long_4k", "category": "long", "effort": "off", "prompt_ids": ids, "n_prompt_tokens": len(ids), "max_new": 128})
ids, pads, png = picture_prompt(enc, Path(a.hf))
out.append({"id": "pic_1", "category": "picture", "effort": "off", "prompt_ids": ids, "n_prompt_tokens": len(ids), "max_new": 128, "image": "engine/tests/qwen4/data/" + png,
"image_pads": pads})
Path(a.out).write_text(json.dumps(out), encoding="utf-8")
for o in out:
print(f"{o['id']:<14}{o['category']:<9}{o['effort']:<7}{o['n_prompt_tokens']:>6} tokens")
print(f"{len(out)} prompts -> {a.out}")
return 0
def png_write(path: Path, rgb) -> None:
h, w, _ = rgb.shape
raw = b"".join(b"\x00" + rgb[y].tobytes() for y in range(h))
def chunk(t, d):
c = struct.pack(">I", len(d)) + t + d
return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
path.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b""))
def cmd_make_image(a) -> int:
import numpy as np
n = 448
y, x = np.mgrid[0:n, 0:n]
img = np.zeros((n, n, 3), np.uint8)
img[..., 0] = (40 + 120 * y / n).astype(np.uint8) # sky-like vertical gradient
img[..., 1] = (90 + 100 * y / n).astype(np.uint8)
img[..., 2] = (200 - 80 * y / n).astype(np.uint8)
img[300:, :] = (60, 140, 60) # ground
img[200:300, 120:260] = (180, 40, 40) # red house body
for i in range(60): # roof triangle
hw = 6 + i * 64 // 60
img[140 + i, 190 - hw:190 + hw] = (90, 50, 30)
img[240:300, 170:210] = (240, 220, 120) # door
r2 = (x - 360) ** 2 + (y - 90) ** 2
img[r2 < 40 ** 2] = (250, 220, 40) # sun
img[(x - 330) ** 2 + (y - 340) ** 2 < 25 ** 2] = (30, 30, 160) # blue ball on the grass
png_write(Path(a.path), img)
print("wrote", a.path)
return 0
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sp = ap.add_subparsers(dest="cmd", required=True)
t = sp.add_parser("tokenize")
t.add_argument("--hf", required=True)
t.add_argument("--out", required=True)
t.add_argument("--doc-tokens", type=int, default=4096)
s = sp.add_parser("selfcheck")
s.add_argument("--hf", required=True)
m = sp.add_parser("make-image")
m.add_argument("path")
a = ap.parse_args()
return {"tokenize": cmd_tokenize, "selfcheck": cmd_selfcheck, "make-image": cmd_make_image}[a.cmd](a)
if __name__ == "__main__":
sys.exit(main())
File diff suppressed because it is too large. Load diff
+16 -3
View File
@@ -118,9 +118,22 @@ def extra_args(cfg: dict, base_args: list, exe: str | None = None, *, announce:
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)
loop = cfg.get(qwen4_family.LOOP_CONFIG_KEY)
flag = qwen4_family.ENGINE_FILE_FLAGS["loop"]
if loop and flag not in args and Path(str(loop)).is_file(): # (setup also writes the flags into the arguments: then they are there already, once)
args += [flag, str(loop), qwen4_family.ENGINE_LOOP_STEPS_FLAG, str(qwen4_family.LOOP_STEPS)]
if not qwen4_family.LOOP_ENGINE_READY: # Loop is coming: an old config's key and flags are ignored
if loop or any(f in args for f in qwen4_family.ENGINE_LOOP_FLAGS):
args = _without(args, qwen4_family.ENGINE_LOOP_FLAGS)
if announce:
print(f"[strata] Qwen4-35B-A3B: {qwen4_family.LOOP_COMING_NOTE}", flush=True)
loop = None
if loop and Path(str(loop)).is_file(): # (setup also writes the flags into the arguments: then they are there already, once; a flag the person wrote is kept)
build = qwen4_family.build_of_model_name(cfg.get("model_name"))
add = qwen4_family.loop_engine_args(loop, build)
pairs, i = [], 0
while i < len(add): # [flag, value] pairs, and the bare --loop-direct-t1
pairs.append(add[i:i + 1] if add[i] == qwen4_family.ENGINE_LOOP_DIRECT_FLAG else add[i:i + 2])
i += len(pairs[-1])
for pair in pairs:
if pair[0] not in args:
args += pair
if announce:
print(f"[strata] Qwen4-35B-A3B: {qwen4_family.LOOP_WORDS}", flush=True)
return args
+108 -6
View File
@@ -1604,6 +1604,17 @@ class StrataEngine:
# extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before.
if sampling.get("strata_checkpoint") is False:
keys += " ckpt=0"
# Looped Qwen3.8-Flash-Next per-request overrides (opt-in; absent = engine start-up defaults).
# Unknown GEN keys are ignored by older engines.
lp = sampling.get("loop_passes")
if isinstance(lp, int) and not isinstance(lp, bool) and lp >= 1:
keys += f" loop_passes={lp}"
lco = sampling.get("loop_cd_omega")
if isinstance(lco, (int, float)) and not isinstance(lco, bool) and math.isfinite(float(lco)):
keys += f" loop_cd_omega={float(lco)!r}"
lct = sampling.get("loop_cd_thinking")
if isinstance(lct, bool):
keys += f" loop_cd_thinking={1 if lct else 0}"
# Hy4-Flash (serve/hy4_kind.py): its pictures are files the engine reads and encodes itself, one `image=<path>` key each, in prompt order (spaces and % in a path as %20 and %25)
for p in sampling.get("strata_hy4_images") or []:
keys += " image=" + hy4_kind.encode_path(p)
@@ -3827,6 +3838,49 @@ def effort_end_args(cfg: dict, exe: str, tok) -> list[str] | None:
return ["--tail-role-token", str(role[0])]
def loop_think_id_args(cfg: dict, exe: str | None, tok) -> list[str]:
"""Opt-in looped-adapter thinking-tag wiring for ``--loop-cd-thinking`` and per-request ``loop_cd_thinking``.
When ``--loop-adapter`` (or ``"loop_cd_thinking": true``) is configured and ``--loop-cd-think-ids`` is not already
present, encode ``<think>`` and ``</think>`` with the loaded tokenizer and pass ``--loop-cd-think-ids START END``
when the engine binary supports it. Also passes ``--loop-cd-thinking`` when ``"loop_cd_thinking": true`` is set
in the run config.
"""
raw_args = [str(x) for x in (cfg.get("args") or [])] + [str(x) for x in (cfg.get("user_args") or [])]
cfg_cd_think = cfg.get("loop_cd_thinking")
if cfg_cd_think is not None and not isinstance(cfg_cd_think, bool):
raise ValueError(f'"loop_cd_thinking" must be true or false, not {cfg_cd_think!r}')
if "--loop-adapter" not in raw_args and "--loop-cd-thinking" not in raw_args and cfg_cd_think is not True:
return []
known_ids = False
known_flag = False
if exe:
try:
with open(engine_binary(exe, cfg), "rb") as f:
blob = f.read()
known_ids = b"--loop-cd-think-ids" in blob
known_flag = b"--loop-cd-thinking" in blob
except OSError:
pass
out: list[str] = []
if cfg_cd_think is True and "--loop-cd-thinking" not in raw_args:
if known_flag:
out.append("--loop-cd-thinking")
else:
print("[strata] loop_cd_thinking: this engine binary does not support --loop-cd-thinking; ignoring config key",
flush=True)
if "--loop-cd-think-ids" not in raw_args and known_ids and tok is not None:
try:
ts = tok.encode("<think>", parse_special=True)
te = tok.encode("</think>", parse_special=True)
except Exception: # noqa: BLE001
ts, te = (), ()
if (len(ts) == 1 and len(te) == 1 and isinstance(ts[0], int) and isinstance(te[0], int)
and ts[0] >= 0 and te[0] >= 0 and ts[0] != te[0]):
out.extend(["--loop-cd-think-ids", str(ts[0]), str(te[0])])
return out
def apply_ready_timeout(cfg: dict) -> None:
"""The config's "engine_ready_s": how long a start may take before READY (default ENGINE_READY_S, 900). A model of 300+ GB read
from a slow disk needs more. ValueError for anything but a number > 0."""
@@ -4503,6 +4557,10 @@ class Service:
# #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system
# turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation
self.effort_end = False
# Opt-in (--loop-direct-t1 / "loop_direct_t1": true): when a looped adapter (--loop-passes N >= 2) is loaded,
# automatically route non-thinking requests (enable_thinking=false) to stock single-pass (loop_passes=1)
# unless the request explicitly sets loop_passes.
self.loop_direct_t1 = False
self.conv_log = ConvCacheLog() # #596: the parked conversations, from the engine's log
self.config_path = None # #564: the run config the web page's Settings view edits
self.config_lock = threading.Lock()
@@ -6302,10 +6360,29 @@ class Service:
if ka is not None:
ka.release()
def validate_loop_request(self, req: dict) -> None:
"""Check per-request ``loop_passes`` against the loaded engine's ``INFO loop_passes`` before sending a request."""
if not isinstance(req, dict):
return
lp = req.get("loop_passes")
if lp is None:
return
info = getattr(self.engine, "info", None) or {}
loaded = int(info.get("loop_passes") or 0)
if loaded >= 2:
if lp not in (1, loaded):
raise ValueError(
f"loop_passes: expected 1 (stock single-pass) or {loaded} (loaded --loop-passes), got {lp}")
elif not isinstance(self.engine, MockEngine) or "loop_passes" in info:
if lp != 1:
raise ValueError(
f"loop_passes: engine was started without --loop-adapter (only 1 is valid, got {lp})")
def _run(self, ids, thinking, tools, max_new, sampling, cancel, force=None,
declared_only=False, deferred=False) -> Iterator[tuple[str, object]]:
"""Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).
`force` (forced_call): the opening of the call the reply must make - see prepare()."""
req_explicit_loop_passes = isinstance(sampling, dict) and sampling.get("loop_passes") is not None
# the model card's sampling for this thinking state, then the config's block, then the Chat settings shared with
# apps; the request's own fields win over all of them
# #3354: when MTP drafting is active (has_mtp) and the request does not explicitly ask for sampling, a family whose engine drafts only
@@ -6324,6 +6401,10 @@ class Service:
if defaults: # the request's own fields win (explicit 0 stays greedy)
req_values = {k: v for k, v in (sampling or {}).items() if v is not None}
sampling = {**defaults, **req_values}
if self.loop_direct_t1 and not thinking and not req_explicit_loop_passes:
loaded_passes = int(((getattr(self.engine, "info", None) or {}).get("loop_passes")) or 0)
if loaded_passes >= 2:
sampling = {**(sampling or {}), "loop_passes": 1}
# #123: read after the merge, so a budget shared through POST /settings is seen like the other keys
# #6734: Inkling-2-Mini writes hidden thinking whatever the request asks for (even with its effort at "none"), so its budget
# (the request's or the answer room's) applies to every request: the parser reports the hidden block (`reasoning_now`)
@@ -8759,6 +8840,7 @@ def make_handler(svc: Service):
svc.reasoning_budget(req) # a bad value is a 400 before anything is sent
stop_strings(req) # ... and so is a bad stop / stop_sequences
check_request_sampling(req) # ... and a sampling field of the wrong type
svc.validate_loop_request(req) # ... and an unsupported loop_passes value
cancel = threading.Event()
self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long)
ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req, cancel=cancel)
@@ -9004,6 +9086,10 @@ def make_handler(svc: Service):
except ValueError as e: # its message starts with the field's name: the param
raise ResponsesError(str(e), str(e).partition(":")[0]) from None
svc.load()
try:
svc.validate_loop_request(req)
except ValueError as e:
raise ResponsesError(str(e), str(e).partition(":")[0]) from None
# #924 (opt-in): a Codex compaction request is rendered with its conversation's tools, so its prompt
# starts as the cached one did; the parser and the response keep the request's own tools
shown = responses_api.prompt_tools(req, tools) if svc.codex_compaction_cache else tools
@@ -9061,6 +9147,7 @@ def make_handler(svc: Service):
svc.reasoning_budget(req) # a bad value is a 400 before anything is sent
stop_strings(req) # ... and so is a bad stop / stop_sequences
check_request_sampling(req) # ... and a sampling field of the wrong type
svc.validate_loop_request(req) # ... and an unsupported loop_passes value
cancel = threading.Event()
self._watch_client(cancel) # #430 #431 (#1999: before prepare, which can take long)
try:
@@ -9325,9 +9412,10 @@ def start_engine_or_fallback(cfg: dict, exe: str, effort_end: list[str] | None,
normal layer-split config under "split_fallback": if that engine refuses or fails to come up, say so in one plain line and start the
normal one instead, so a start never fails because of the option. Any other config starts exactly as before."""
fb = cfg.get("split_fallback")
extra = [*(effort_end or []), *loop_think_id_args(cfg, exe, tok)]
try:
return StrataEngine(exe, engine_args(cfg, exe) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy,
retry_args=mtp_retry_args(cfg, exe, effort_end), retry_vram_args=nodraft_retry_args(cfg, exe, effort_end),
return StrataEngine(exe, engine_args(cfg, exe) + extra, cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy,
retry_args=mtp_retry_args(cfg, exe, extra or None), retry_vram_args=nodraft_retry_args(cfg, exe, extra or None),
inkling=inkling_kind.is_inkling(cfg))
except Exception as e:
if not isinstance(fb, dict) or not fb.get("exe"):
@@ -9355,8 +9443,9 @@ def start_engine_or_fallback(cfg: dict, exe: str, effort_end: list[str] | None,
env2 = child_env(cfg2, offline=offline)
configure_batch_telemetry_env(env2, cfg2, batch_telemetry)
effort2 = effort_end_args(cfg2, exe2, tok)
engine = StrataEngine(exe2, engine_args(cfg2, exe2) + (effort2 or []), cwd=cfg2.get("cwd"), log=cfg2.get("log"), env=env2, lazy=lazy,
retry_args=mtp_retry_args(cfg2, exe2, effort2), retry_vram_args=nodraft_retry_args(cfg2, exe2, effort2),
extra2 = [*(effort2 or []), *loop_think_id_args(cfg2, exe2, tok)]
engine = StrataEngine(exe2, engine_args(cfg2, exe2) + extra2, cwd=cfg2.get("cwd"), log=cfg2.get("log"), env=env2, lazy=lazy,
retry_args=mtp_retry_args(cfg2, exe2, extra2 or None), retry_vram_args=nodraft_retry_args(cfg2, exe2, extra2 or None),
inkling=inkling_kind.is_inkling(cfg2))
engine.info["split_fallback"] = True
return engine
@@ -9798,6 +9887,10 @@ def _main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> i
help="split serving (opt-in): one engine on card PREFILL reads the prompt, a second on card DECODE makes "
"the answer, the session handed over in RAM (also \"split_serve\" in the config: "
"{\"prefill_gpu\": 0, \"decode_gpu\": 1}; docs/SPLIT_SERVE.md)")
ap.add_argument("--loop-direct-t1", action="store_true",
help="looped adapter (opt-in): automatically run non-thinking requests (enable_thinking=false) with "
"stock single-pass (loop_passes=1) unless the request explicitly sets loop_passes "
"(also \"loop_direct_t1\": true in the config)")
launch_args = list(sys.argv[1:] if argv is None else argv)
a = ap.parse_args(launch_args)
if a.engine == "strata" and (_rt := rttime_limit_note()): # #3238: say it before the first unexplained -9
@@ -10032,6 +10125,7 @@ def _main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> i
raise SystemExit(f"[strata] config {e}")
try:
effort_end = effort_end_args(cfg, exe, tok) # #458
loop_think = loop_think_id_args(cfg, exe, tok)
except ValueError as e:
raise SystemExit(f"[strata] config {e}")
from serve import split as split_mod
@@ -10041,10 +10135,11 @@ def _main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> i
split_mod.check_cfg(cfg, split)
except split_mod.SplitConfigError as e:
raise SystemExit(f"[strata] config {e}")
extra_args = [*(effort_end or []), *loop_think]
if groups:
engine = start_replicas(cfg, groups, exe, effort_end or [], lazy, offline=a.offline)
engine = start_replicas(cfg, groups, exe, extra_args, lazy, offline=a.offline)
elif split:
engine = start_split(cfg, split, exe, effort_end or [], lazy, offline=a.offline)
engine = start_split(cfg, split, exe, extra_args, lazy, offline=a.offline)
else:
engine = start_engine_or_fallback(cfg, exe, effort_end, env, lazy, tok, offline=a.offline, batch_telemetry=a.batch_telemetry)
engine.silence_s = silence # an attribute of its own: restart() keeps it
@@ -10249,6 +10344,13 @@ def _main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> i
raise SystemExit(f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not {rs!r}")
svc.repeat_stop_tokens = rs
svc.effort_end = bool(effort_end) # #458: "effort_position": "end" with an engine that has it
cfg_direct_t1 = cfg.get("loop_direct_t1")
if cfg_direct_t1 is not None and not isinstance(cfg_direct_t1, bool):
raise SystemExit(f'[strata] config "loop_direct_t1" must be true or false, not {cfg_direct_t1!r}')
svc.loop_direct_t1 = bool(a.loop_direct_t1 or cfg_direct_t1 is True)
if svc.loop_direct_t1 and int((getattr(engine, "info", None) or {}).get("loop_passes") or 0) >= 2:
print("[strata] loop_direct_t1: non-thinking requests (enable_thinking=false) run stock single-pass "
"(loop_passes=1) unless overridden", flush=True)
if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request
svc.reasoning_budget_configured = True
try:
+21 -1
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import hmac
import json
import math
import os
import re
import socket
@@ -579,6 +580,18 @@ def sampling_defaults_from_config(cfg: dict) -> dict:
raise SystemExit(f"[strata] config sampling.experimental_speed_projection={value!r}: expected true or "
"false (the default for requests that leave it out, when the engine has the vector)")
out[key] = value
elif key == "loop_passes":
if not number or not math.isfinite(float(value)) or value != int(value) or int(value) < 1:
raise SystemExit(f"[strata] config sampling.loop_passes={value!r}: expected an integer >= 1")
out[key] = int(value)
elif key == "loop_cd_omega":
if not number or not math.isfinite(float(value)):
raise SystemExit(f"[strata] config sampling.loop_cd_omega={value!r}: expected a finite number")
out[key] = float(value)
elif key == "loop_cd_thinking":
if not isinstance(value, bool):
raise SystemExit(f"[strata] config sampling.loop_cd_thinking={value!r}: expected true or false")
out[key] = value
else:
print(f"[strata] config sampling.{key}={value!r}: unknown key, ignored", flush=True)
return out
@@ -602,7 +615,7 @@ def check_request_sampling(req) -> None:
req["penalty_last_n"] = rl # 0 and -1 (off / the whole context) keep the engine's default window
for key, integer in (("temperature", False), ("top_p", False), ("min_p", False), ("presence_penalty", False),
("frequency_penalty", False), ("repetition_penalty", False), ("top_k", True),
("penalty_last_n", True), ("seed", True)):
("penalty_last_n", True), ("seed", True), ("loop_passes", True), ("loop_cd_omega", False)):
value = (req or {}).get(key)
if value is None:
continue
@@ -621,6 +634,13 @@ def check_request_sampling(req) -> None:
req[key] = value = num
if isinstance(value, bool) or not isinstance(value, int if integer else (int, float)):
raise ValueError(f"{key}: {'an integer' if integer else 'a number'}")
if not integer and not math.isfinite(float(value)):
raise ValueError(f"{key}: a finite number")
if key == "loop_passes" and value < 1:
raise ValueError("loop_passes: an integer >= 1")
lct = (req or {}).get("loop_cd_thinking")
if lct is not None and not isinstance(lct, bool):
raise ValueError("loop_cd_thinking: true or false")
# the API's model name per model family (the GGUF architecture, "arch" in the config) when the config names none
+329
View File
@@ -0,0 +1,329 @@
"""Unit and HTTP integration tests for looped-adapter LoopCD <think> gating and per-request loop_passes controls.
python -m unittest serve.test_loop_controls -v
"""
import http.client
import json
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from serve.frontend import ChatTemplate
from serve.server import (
ByteTokenizer,
MockEngine,
Service,
StrataEngine,
check_request_sampling,
loop_think_id_args,
sampling_defaults_from_config,
serve,
)
from strata_control import user_args
ROOT = Path(__file__).resolve().parent.parent
class RecordingMockEngine(MockEngine):
def __init__(self, tok, text="Hello from mock.", *, loaded_loop_passes: int = 2):
super().__init__(tok, text, max_context=4096)
self.info = {"loop_passes": loaded_loop_passes}
self.seen_sampling: list[dict] = []
def generate(self, prompt_ids, max_new, sampling=None, cancel=None, embeddings=None):
self.seen_sampling.append(dict(sampling or {}))
return super().generate(prompt_ids, max_new, sampling=sampling, cancel=cancel, embeddings=embeddings)
class LoopSamplingKeysAndValidation(unittest.TestCase):
def test_sampling_keys_serialization_and_family_stripping(self):
s = {"loop_passes": 1, "loop_cd_omega": 0.5, "loop_cd_thinking": True}
toks = StrataEngine.sampling_keys(s).split()
self.assertIn("loop_passes=1", toks)
self.assertIn("loop_cd_omega=0.5", toks)
self.assertIn("loop_cd_thinking=1", toks)
toks_off = StrataEngine.sampling_keys({"loop_passes": 2, "loop_cd_omega": 0.0, "loop_cd_thinking": False}).split()
self.assertIn("loop_passes=2", toks_off)
self.assertIn("loop_cd_omega=0.0", toks_off)
self.assertIn("loop_cd_thinking=0", toks_off)
# Absent fields emit nothing (backwards-compatible).
self.assertEqual(StrataEngine.sampling_keys({}), "")
# Non-Flash-Next engines strip Flash-Next-only loop keys.
for kw in ({"hy4": True}, {"inkling": True}):
stripped = StrataEngine.sampling_keys(s, **kw)
self.assertNotIn("loop_passes", stripped)
self.assertNotIn("loop_cd_omega", stripped)
self.assertNotIn("loop_cd_thinking", stripped)
def test_check_request_sampling_valid_and_invalid(self):
req = {"loop_passes": "2", "loop_cd_omega": "0.75", "loop_cd_thinking": True}
check_request_sampling(req)
self.assertEqual(req["loop_passes"], 2)
self.assertEqual(req["loop_cd_omega"], 0.75)
self.assertIs(req["loop_cd_thinking"], True)
for bad, field in (
({"loop_passes": 0}, "loop_passes"),
({"loop_passes": -1}, "loop_passes"),
({"loop_passes": 1.5}, "loop_passes"),
({"loop_passes": True}, "loop_passes"),
({"loop_passes": "abc"}, "loop_passes"),
({"loop_cd_omega": float("nan")}, "loop_cd_omega"),
({"loop_cd_omega": float("inf")}, "loop_cd_omega"),
({"loop_cd_omega": True}, "loop_cd_omega"),
({"loop_cd_omega": "nope"}, "loop_cd_omega"),
({"loop_cd_thinking": 1}, "loop_cd_thinking"),
({"loop_cd_thinking": "true"}, "loop_cd_thinking"),
):
with self.subTest(bad=bad):
with self.assertRaises(ValueError) as ctx:
check_request_sampling(dict(bad))
self.assertTrue(str(ctx.exception).startswith(field + ":"), str(ctx.exception))
def test_sampling_defaults_from_config(self):
cleaned = sampling_defaults_from_config(
{"sampling": {"loop_passes": 1, "loop_cd_omega": 0.25, "loop_cd_thinking": True}}
)
self.assertEqual(cleaned, {"loop_passes": 1, "loop_cd_omega": 0.25, "loop_cd_thinking": True})
for bad in (
{"loop_passes": 0},
{"loop_passes": True},
{"loop_passes": 1.5},
{"loop_cd_omega": float("inf")},
{"loop_cd_omega": False},
{"loop_cd_thinking": "yes"},
):
with self.subTest(bad=bad):
with self.assertRaises(SystemExit):
sampling_defaults_from_config({"sampling": bad})
def test_loop_think_id_args(self):
class FakeTok:
def encode(self, text, parse_special=False):
if parse_special and text == "<think>":
return [248068]
if parse_special and text == "</think>":
return [248069]
return [1, 2]
with tempfile.TemporaryDirectory() as d:
new_exe = Path(d) / "strata-new"
old_exe = Path(d) / "strata-old"
new_exe.write_bytes(b"ELF --loop-adapter --loop-cd-thinking --loop-cd-think-ids")
old_exe.write_bytes(b"ELF --loop-adapter --loop-cd-omega")
# No loop adapter configured -> empty args.
self.assertEqual(loop_think_id_args({"args": ["--serve"]}, str(new_exe), FakeTok()), [])
# With --loop-adapter -> injects tokenizer's <think>/<\/think> IDs automatically.
self.assertEqual(
loop_think_id_args({"args": ["--loop-adapter", "a.safetensors"]}, str(new_exe), FakeTok()),
["--loop-cd-think-ids", "248068", "248069"],
)
# Config "loop_cd_thinking": true adds both flags when missing from args.
self.assertEqual(
loop_think_id_args(
{"args": ["--loop-adapter", "a.safetensors"], "loop_cd_thinking": True},
str(new_exe),
FakeTok(),
),
["--loop-cd-thinking", "--loop-cd-think-ids", "248068", "248069"],
)
# Explicit --loop-cd-think-ids in args or user_args is preserved without duplicates.
self.assertEqual(
loop_think_id_args(
{"args": ["--loop-adapter", "a.safetensors"], "user_args": ["--loop-cd-think-ids", "10", "11"]},
str(new_exe),
FakeTok(),
),
[],
)
# Older binary without flags skips cleanly.
with mock.patch("builtins.print"):
self.assertEqual(
loop_think_id_args(
{"args": ["--loop-adapter", "a.safetensors"], "loop_cd_thinking": True},
str(old_exe),
FakeTok(),
),
[],
)
# Tokenizer without single special tokens skips --loop-cd-think-ids cleanly.
self.assertEqual(
loop_think_id_args({"args": ["--loop-adapter", "a.safetensors"]}, str(new_exe), ByteTokenizer()),
[],
)
# Non-bool loop_cd_thinking in config raises ValueError.
with self.assertRaises(ValueError):
loop_think_id_args({"loop_cd_thinking": "yes"}, str(new_exe), FakeTok())
def test_user_args_retains_loop_cd_thinking_flags(self):
self.assertIn("--loop-cd-thinking", user_args.USER_KEPT_FLAGS)
self.assertIn("--loop-cd-think-ids", user_args.USER_KEPT_FLAGS)
self.assertEqual(
user_args.set_flag([], "--loop-cd-think-ids", "248068 248069"),
["--loop-cd-think-ids", "248068", "248069"],
)
class LoopHttpIntegration(unittest.TestCase):
def setUp(self):
self.tok = ByteTokenizer()
self.engine = RecordingMockEngine(self.tok, "Hello.", loaded_loop_passes=2)
self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
self.httpd = serve(self.svc, port=0)
self.port = self.httpd.server_address[1]
def tearDown(self):
self.httpd.shutdown()
self.httpd.server_close()
def post(self, path, body):
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=20)
try:
c.request("POST", path, body=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
r = c.getresponse()
return r.status, json.loads(r.read() or b"{}")
finally:
c.close()
def test_per_request_loop_overrides_on_all_three_routes(self):
for path, body in (
(
"/v1/chat/completions",
{
"messages": [{"role": "user", "content": "hi"}],
"max_tokens": 8,
"loop_passes": 1,
"loop_cd_omega": 0.5,
"loop_cd_thinking": True,
},
),
(
"/v1/responses",
{
"model": "m",
"input": "hi",
"store": False,
"max_output_tokens": 8,
"loop_passes": 2,
"loop_cd_omega": 0.25,
"loop_cd_thinking": False,
},
),
(
"/v1/messages",
{
"messages": [{"role": "user", "content": "hi"}],
"max_tokens": 8,
"loop_passes": 1,
"loop_cd_omega": 0.0,
"loop_cd_thinking": True,
},
),
):
with self.subTest(path=path):
code, out = self.post(path, body)
self.assertEqual(code, 200, out)
seen = self.engine.seen_sampling[-1]
self.assertEqual(seen["loop_passes"], body["loop_passes"])
self.assertEqual(seen["loop_cd_omega"], body["loop_cd_omega"])
self.assertIs(seen["loop_cd_thinking"], body["loop_cd_thinking"])
def test_invalid_loop_passes_returns_400_on_all_routes(self):
for path, body in (
("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, "loop_passes": 3}),
("/v1/responses", {"model": "m", "input": "hi", "store": False, "max_output_tokens": 8, "loop_passes": 3}),
("/v1/messages", {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, "loop_passes": 3}),
):
with self.subTest(path=path):
with mock.patch("builtins.print"):
code, out = self.post(path, body)
self.assertEqual(code, 400, out)
self.assertIn("loop_passes", json.dumps(out))
def test_unloaded_adapter_rejects_loop_passes_gt_1_and_allows_1(self):
self.engine.info = {"loop_passes": 0}
code, out = self.post(
"/v1/chat/completions",
{"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, "loop_passes": 1},
)
self.assertEqual(code, 200, out)
with mock.patch("builtins.print"):
code2, out2 = self.post(
"/v1/chat/completions",
{"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, "loop_passes": 2},
)
self.assertEqual(code2, 400, out2)
self.assertIn("loop_passes", json.dumps(out2))
def test_loop_direct_t1_auto_routing_and_override(self):
# Default (loop_direct_t1=False): non-thinking request does not inject loop_passes=1.
code, _ = self.post(
"/v1/chat/completions",
{
"messages": [{"role": "user", "content": "hi"}],
"max_tokens": 8,
"chat_template_kwargs": {"enable_thinking": False},
},
)
self.assertEqual(code, 200)
self.assertNotIn("loop_passes", self.engine.seen_sampling[-1])
# Enabled (loop_direct_t1=True): non-thinking routes to loop_passes=1 on all three APIs.
self.svc.loop_direct_t1 = True
for path, body in (
(
"/v1/chat/completions",
{
"messages": [{"role": "user", "content": "hi"}],
"max_tokens": 8,
"chat_template_kwargs": {"enable_thinking": False},
},
),
(
"/v1/responses",
{"model": "m", "input": "hi", "store": False, "max_output_tokens": 8, "reasoning": {"effort": "none"}},
),
(
"/v1/messages",
{"messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, "thinking": {"type": "disabled"}},
),
):
with self.subTest(auto_t1=path):
code, out = self.post(path, body)
self.assertEqual(code, 200, out)
self.assertEqual(self.engine.seen_sampling[-1].get("loop_passes"), 1)
# Thinking request keeps loaded looped depth (does not force loop_passes=1).
code, _ = self.post(
"/v1/chat/completions",
{
"messages": [{"role": "user", "content": "hi"}],
"max_tokens": 8,
"chat_template_kwargs": {"enable_thinking": True},
},
)
self.assertEqual(code, 200)
self.assertNotIn("loop_passes", self.engine.seen_sampling[-1])
# Explicit loop_passes=2 on a non-thinking request overrides loop_direct_t1.
code, _ = self.post(
"/v1/chat/completions",
{
"messages": [{"role": "user", "content": "hi"}],
"max_tokens": 8,
"chat_template_kwargs": {"enable_thinking": False},
"loop_passes": 2,
},
)
self.assertEqual(code, 200)
self.assertEqual(self.engine.seen_sampling[-1].get("loop_passes"), 2)
if __name__ == "__main__":
unittest.main()
+25 -5
View File
@@ -61,7 +61,7 @@ class Sidecars(unittest.TestCase):
def test_nothing_is_added_without_the_keys_and_the_arguments_are_the_generic_ones(self):
with with_info({"arch": "qwen4exp_q4_lite", "images": "1"}):
args = server.engine_args(self.cfg(), EXE, announce=False)
for flag in ("--mtp", "--loop", "--loop-steps"):
for flag in ("--mtp", *F.ENGINE_LOOP_FLAGS):
self.assertNotIn(flag, args)
self.assertEqual(args[:2], ["--native", "C:/m/Qwen4-35B-A3B-Compact.strata"])
self.assertIn("--vision", args)
@@ -95,20 +95,23 @@ class Sidecars(unittest.TestCase):
self.assertNotIn(F.ENGINE_FILE_FLAGS["mtp"], args)
self.assertTrue(any("does not take the MTP sidecar" in str(c) for c in pr.call_args_list))
@mock.patch.object(F, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_loop_is_added_only_with_its_key_and_the_file(self):
with with_info({"arch": "x", "images": "1"}):
on = server.engine_args(self.cfg(**{F.LOOP_CONFIG_KEY: str(self.loop)}), EXE, announce=False)
gone = server.engine_args(self.cfg(**{F.LOOP_CONFIG_KEY: str(self.td / "missing.safetensors")}), EXE, announce=False)
i = on.index(F.ENGINE_FILE_FLAGS["loop"])
self.assertEqual(on[i:i + 4], [F.ENGINE_FILE_FLAGS["loop"], str(self.loop), F.ENGINE_LOOP_STEPS_FLAG, str(F.LOOP_STEPS)])
self.assertEqual(on[i:i + 7], ["--loop-adapter", str(self.loop), "--loop-passes", "2", "--loop-coda", "compact", "--loop-direct-t1"]) # the Compact build: the compact coda
self.assertNotIn(F.ENGINE_FILE_FLAGS["loop"], gone)
@mock.patch.object(F, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_loop_flags_already_in_the_arguments_are_not_doubled(self):
cfg = self.cfg(args=[*CFG["args"], "--loop", str(self.loop), "--loop-steps", "2"], **{F.LOOP_CONFIG_KEY: str(self.loop)})
cfg = self.cfg(args=[*CFG["args"], "--loop-adapter", str(self.loop), "--loop-passes", "2", "--loop-coda", "universal", "--loop-direct-t1"], **{F.LOOP_CONFIG_KEY: str(self.loop)})
with with_info({"arch": "x", "images": "1"}):
args = server.engine_args(cfg, EXE, announce=False)
self.assertEqual(args.count(F.ENGINE_FILE_FLAGS["loop"]), 1)
self.assertEqual(args.count(F.ENGINE_LOOP_STEPS_FLAG), 1)
for flag in F.ENGINE_LOOP_FLAGS:
self.assertEqual(args.count(flag), 1, flag)
self.assertEqual(args[args.index("--loop-coda") + 1], "universal") # a flag the person wrote is kept, not replaced and not doubled
def test_the_config_keys_never_reach_the_generic_path(self):
cfg = self.cfg(**{F.MTP_CONFIG_KEY: str(self.mtp), F.LOOP_CONFIG_KEY: str(self.loop)})
@@ -172,5 +175,22 @@ class Others(unittest.TestCase):
self.assertEqual(args[:4], ["--gguf", "x.gguf", "--vision", "v.gguf"])
class LoopComing(unittest.TestCase):
"""A config from an earlier setup with the Loop key or flags starts without them while LOOP_ENGINE_READY is False, with one log line."""
def test_the_key_and_the_flags_are_ignored(self):
with tempfile.TemporaryDirectory() as d:
loop = Path(d) / F.LOOP_FILE
loop.write_bytes(b"x")
cfg = dict(CFG, **{F.LOOP_CONFIG_KEY: str(loop)})
cfg["args"] = [*cfg["args"], "--loop-adapter", str(loop), "--loop-passes", "2", "--loop-coda", "universal", "--loop-direct-t1"]
args = K.extra_args(cfg, cfg["args"], None, announce=False)
for flag in F.ENGINE_LOOP_FLAGS:
self.assertNotIn(flag, args)
with mock.patch("builtins.print") as pr:
K.extra_args(cfg, cfg["args"], None, announce=True)
self.assertEqual(sum(F.LOOP_COMING_NOTE in str(c) for c in pr.call_args_list), 1)
if __name__ == "__main__":
unittest.main()
+6 -3
View File
@@ -11560,7 +11560,7 @@ def install_qwen4_gguf(a, family, fam, gpu, hip, amd, cuda_tk, port, adopted, *,
say("All set.")
say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: {qwen4_family.FAMILY})")
say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages")
say(f" Loop: {'on' if loop_path is not None else 'off'}. {qwen4_family.LOOP_WORDS} Change it with --loop on|off")
say(f" Loop: {'on' if loop_path is not None else 'off'}. {qwen4_family.LOOP_WORDS}" + ("" if qwen4_family.LOOP_ENGINE_READY else " (Coming soon.)") + " Change it with --loop on|off")
say(f" Effort: {qwen4_family.EFFORT_WORDS[effort]} by default (how much it thinks; a request can ask the other way); change it with --effort off|low|high|xhigh")
say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away")
if a.no_start:
@@ -11576,6 +11576,9 @@ def qwen4_effort(a) -> str:
def qwen4_loop_wanted(a) -> bool:
"""Loop (2 steps: the model runs each word twice): `--loop on|off`, off unless asked (qwen4_family.DEFAULT_LOOP). Its file is fetched only when it is on."""
word = getattr(a, "loop", None)
if word == "on" and not qwen4_family.LOOP_ENGINE_READY:
warn(qwen4_family.LOOP_COMING_NOTE) # coming: --loop on behaves as off (no key, no flags, no download)
return False
return word == "on" if word in ("on", "off") else bool(qwen4_family.DEFAULT_LOOP)
@@ -11776,7 +11779,7 @@ def install_qwen4(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted):
say("All set.")
say(f" API (OpenAI): http://127.0.0.1:{port}/v1 (any API key; model name: {qwen4_family.FAMILY})")
say(f" API (Anthropic): http://127.0.0.1:{port}/v1/messages")
say(f" Loop: {'on' if loop_path is not None else 'off'}. {qwen4_family.LOOP_WORDS} Change it with --loop on|off")
say(f" Loop: {'on' if loop_path is not None else 'off'}. {qwen4_family.LOOP_WORDS}" + ("" if qwen4_family.LOOP_ENGINE_READY else " (Coming soon.)") + " Change it with --loop on|off")
say(f" Effort: {qwen4_family.EFFORT_WORDS[effort]} by default (how much it thinks; a request can ask the other way); change it with --effort off|low|high|xhigh")
say(f" Next time: just run {'START-HERE.bat' if WIN else './setup.sh'} (or {script.name}) - it starts right away")
if a.no_start:
@@ -13405,7 +13408,7 @@ def main() -> int:
ap.add_argument("--thinking", choices=list(ling32_family.THINKING), metavar="on|off",
help="Ling-3.2-Air and Qwen4-35B-A3B only: whether it thinks before it answers (default: off; a request can ask the other way). For Qwen4-35B-A3B on = --effort high, off = --effort off")
ap.add_argument("--loop", choices=("on", "off"), metavar="on|off",
help="Qwen4-35B-A3B only: " + qwen4_family.LOOP_HELP + " Off unless you ask; its 0.15 GB file is downloaded only when it is on")
help="Qwen4-35B-A3B only: " + qwen4_family.LOOP_HELP.replace("%", "%%") + " Coming soon: the engine support is not in this release yet, so on stays off for now (then: its 0.15 GB file is downloaded only when it is on)")
ap.add_argument("--effort", choices=list(qwen4_family.EFFORTS), metavar="off|low|high|xhigh",
help="Qwen4-35B-A3B only: how much it thinks before it answers (default: " + qwen4_family.DEFAULT_EFFORT + ", the model's own; a request can ask the other way)")
ap.add_argument("--ple", type=str.lower, choices=[k.lower() for k in qwen4_family.PLE_KINDS], metavar="q4|q8",
+3 -3
View File
@@ -310,7 +310,7 @@ def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path,
if mtp_rt is not None: # the sidecar's rt folder is a config key like the other builds' (serve adds `--mtp <rt> --spec 4` at the start)
cfg[qwen4_family.MTP_CONFIG_KEY] = str(mtp_rt)
cfg[qwen4_family.MTP_MODE_KEY] = qwen4_family.DEFAULT_MTP_MODE
loop_path = qwen4_family.find_file(qwen4_family.LOOP_FILE, trunk, places) if loop == "on" else None
loop_path = qwen4_family.find_file(qwen4_family.LOOP_FILE, trunk, places) if qwen4_family.loop_word(loop) == "on" else None
if loop_path is not None:
cfg[qwen4_family.LOOP_CONFIG_KEY] = str(loop_path)
if backend:
@@ -340,8 +340,8 @@ def plan(*, family: str, model: str, model_dir: Path, data_dir: Path, src: Path,
if problems:
return None, problems
vision_path = qwen4_family.find_file(qwen4_family.VISION_FILE, native, places)
loop_path = qwen4_family.find_file(qwen4_family.LOOP_FILE, native, places) if loop == "on" else None # Loop is off unless asked: its file is only looked for when it is on
if loop == "on" and loop_path is None and notes is not None:
loop_path = qwen4_family.find_file(qwen4_family.LOOP_FILE, native, places) if qwen4_family.loop_word(loop) == "on" else None # Loop is off unless asked: its file is only looked for when it is on
if qwen4_family.loop_word(loop) == "on" and loop_path is None and notes is not None:
notes.append(f"No {qwen4_family.LOOP_FILE} beside the model: it starts without Loop. `strata launch --loop on` downloads it for a model Strata installed.")
args = qwen4_family.engine_args(native, ple=ple_path, vision=vision_path, ctx=context) # the sidecar and the Loop file are config keys (serve makes their flags at the start)
cfg = {"exe": f"component:{qwen4_family.COMPONENT}", "args": args, "cwd": str(src), "tokenizer": str(tokenizer),
+6 -3
View File
@@ -167,8 +167,8 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser]
help="Qwen4-35B-A3B only: how hard it thinks before it answers. high is the default; low and xhigh think less and more, all show the thinking as reasoning_content; off answers at once. "
"--thinking on means high, --thinking off means off. A request can still ask for another level (reasoning_effort)")
g.add_argument("--loop", type=_choice("a Loop setting", S.LOOP_MODES), metavar="on|off",
help="Qwen4-35B-A3B only, Strata's own builds: Loop (2 steps) thinks each word twice. Slower, a bit more accurate. It has no effect while --effort is off. "
"Off unless you ask; on downloads the Loop file (0.15 GB)")
help="Qwen4-35B-A3B only, Strata's own builds: 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. "
"Coming soon: the engine support is not in this release yet, so on stays off for now (then: off unless you ask; on downloads the Loop file, 0.15 GB)")
g.add_argument("--ple", type=_choice("a PLE table", S.PLE_MODES), metavar="q4|q8",
help="Qwen4-35B-A3B only: the PLE n-gram table the model reads beside its weights. q4 (11.5 GB) is the default; q8 (21.8 GB) is more exact and is chosen by itself "
"when the RAM holds it. The build (Compact, Balanced, Ultra) is the model name: --model Balanced")
@@ -386,7 +386,10 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet
if getattr(a, "effort", None): # Qwen4-35B-A3B: the thinking effort (strata_control/qwen4_family.py EFFORTS)
s.effort = a.effort
if getattr(a, "loop", None):
s.loop = a.loop
from strata_control import qwen4_family as _q4
s.loop = _q4.loop_word(a.loop) if a.loop == "on" else a.loop
if a.loop == "on" and s.loop != "on": # Loop is coming: on behaves as off, with one plain line
notices.append(S.Notice("warn", _q4.LOOP_COMING_NOTE, ""))
if getattr(a, "ple", None): # Qwen4-35B-A3B (strata_control/qwen4_family.py): the PLE table, q4 or q8
s.ple = a.ple
if getattr(a, "tier", None):
+2 -2
View File
@@ -244,10 +244,10 @@ def assess(catalog, family: str | None, model: str | None, *, vision: str = "off
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)))
if loop == "on" and not (folder / fam_mod.LOOP_FILE).is_file():
if loop == "on" and fam_mod.LOOP_ENGINE_READY and not (folder / fam_mod.LOOP_FILE).is_file():
st.parts.append(Part("loop", "the Loop file", round(fam_mod.size_of(fam_mod.LOOP_FILE) / 1e9, 2)))
return st
weight_names = (fam_mod.files_of(model, False, mtp=mtp != "off", ple=str(ple).upper() if ple else None, loop=loop == "on") if family == "qwen4-35b-a3b"
weight_names = (fam_mod.files_of(model, False, mtp=mtp != "off", ple=str(ple).upper() if ple else None, loop=loop == "on" and fam_mod.LOOP_ENGINE_READY) if family == "qwen4-35b-a3b"
else fam_mod.files_of(model, False))
got_weights = 0
missing_weights = 0
+3 -3
View File
@@ -919,11 +919,11 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str]
cfg[qwen4_family.MTP_CONFIG_KEY] = str(found)
if s.mtp in ("on", "auto") and cfg.get(qwen4_family.MTP_CONFIG_KEY):
cfg[qwen4_family.MTP_MODE_KEY] = "on" if s.mtp == "on" else "auto"
if s.loop == "off": # the Loop adapter (off by default): the key holds the file's path only when it is on; serve makes the engine flags from it
if s.loop == "off" or not qwen4_family.LOOP_ENGINE_READY: # (coming: an old config's key and flags go too) the Loop adapter (off by default): the key holds the file's path only when it is on; serve makes the engine flags from it
cfg.pop(qwen4_family.LOOP_CONFIG_KEY, None)
if isinstance(cfg.get("args"), list): # (setup also writes `--loop FILE --loop-steps N` into the arguments: off takes them out)
if isinstance(cfg.get("args"), list): # (setup also writes `--loop-adapter FILE --loop-passes N --loop-coda C --loop-direct-t1` into the arguments: off takes them all out)
cargs2 = [str(a) for a in cfg["args"]]
for lflag in (qwen4_family.ENGINE_FILE_FLAGS["loop"], qwen4_family.ENGINE_LOOP_STEPS_FLAG):
for lflag in qwen4_family.ENGINE_LOOP_FLAGS:
while lflag in cargs2:
at = cargs2.index(lflag)
del cargs2[at:at + (2 if at + 1 < len(cargs2) and not cargs2[at + 1].startswith("--") else 1)]
+9 -4
View File
@@ -189,7 +189,7 @@ class LaunchSettings:
expert_skip: str | None = None # Ling-3.2-Air expert skip: None = as installed (off), "off", "medium" (--skip-tau 0.05: faster, slightly less exact; every Ling engine except the Mac's)
turbo_ssd: bool = False # Ling-3.2-Air tier C: skip cold experts once memory covers enough of the routing weight: faster, may change answers (off unless asked)
effort: str | None = None # Qwen4-35B-A3B: off | low | high | xhigh (None = the model's default, off; `--thinking on|off` is read as high | off)
loop: str | None = None # Qwen4-35B-A3B Loop adapter (2 steps: thinks each word twice, slower, a bit more accurate): on | off (None = off)
loop: str | None = None # Qwen4-35B-A3B Loop adapter (2 steps: thinks each word twice, slower, a little closer to the original model): on | off (None = off)
ple: str | None = None # Qwen4-35B-A3B: q4 | q8 (None = the fit rule: Q4, Q8_0 when the RAM holds it; strata_control/qwen4_fit.py)
mtp: str | None = None # None = as installed (draft layer on); "off" starts without it (less graphics memory and RAM, slower); "on" overrides an installed "off"
tune: str = "skip" # quick | thorough | skip
@@ -519,11 +519,11 @@ def check_qwen4(s: LaunchSettings, *, vram_gb: float | None, ram_gb: float | Non
if s.model == "UD-Q4_K_XL": # the fourth build (Unsloth's GGUF): never recommended, its own memory estimate (qwen4_fit.GGUF_*), no PLE file of its own
return _check_qwen4_gguf(s, vram_gb=vram_gb, ram_gb=ram_gb, disk_free_gb=disk_free_gb, unified=unified, vendor=vendor, cards=cards)
try:
from strata_control import qwen4_fit
from strata_control import qwen4_family, qwen4_fit
build = s.model if s.model in qwen4_fit.BUILD_BYTES else None
ple = str(s.ple).upper() if s.ple else None
adv = qwen4_fit.advise(vram_gb, float(ram_gb or 0.0), unified=bool(unified), disk_free_gb=disk_free_gb, ctx=s.context, build=build,
ple=ple if ple in qwen4_fit.PLE_BYTES else None, vision=s.vision not in ("off", "no"), mtp=s.mtp != "off", loop=s.loop == "on")
ple=ple if ple in qwen4_fit.PLE_BYTES else None, vision=s.vision not in ("off", "no"), mtp=s.mtp != "off", loop=s.loop == "on" and qwen4_family.LOOP_ENGINE_READY)
except Exception: # noqa: BLE001 - a plan that cannot be worked out stays silent rather than wrong
return out
v = str(vendor or "").lower()
@@ -551,6 +551,8 @@ def check_qwen4(s: LaunchSettings, *, vram_gb: float | None, ram_gb: float | Non
from strata_control import qwen4_family
if s.custom_id or s.model_path and qwen4_family.build_of_file(s.model_path) is None:
out.append(Notice("warn", "--loop is for Strata's own Qwen4-35B-A3B builds only and is not used with other files.", ""))
elif not qwen4_family.LOOP_ENGINE_READY:
out.append(Notice("warn", qwen4_family.LOOP_COMING_NOTE, ""))
else:
out.append(Notice("warn", qwen4_family.LOOP_HELP, "Take --loop on away (or --loop off) for the normal speed."))
return out
@@ -591,7 +593,10 @@ def _check_qwen4_gguf(s: LaunchSettings, *, vram_gb, ram_gb, disk_free_gb=None,
if s.ple:
out.append(Notice("warn", f"--ple is not used with {qwen4_family.GGUF_TITLE}: its PLE table is in the second file.", ""))
if s.loop == "on":
out.append(Notice("warn", qwen4_family.LOOP_HELP, "Take --loop on away (or --loop off) for the normal speed."))
if qwen4_family.LOOP_ENGINE_READY:
out.append(Notice("warn", qwen4_family.LOOP_HELP, "Take --loop on away (or --loop off) for the normal speed."))
else:
out.append(Notice("warn", qwen4_family.LOOP_COMING_NOTE, ""))
return out
+1
View File
@@ -25,6 +25,7 @@ PATH_FLAGS = {
"--expert-profile": "file",
"--mtp": "directory",
"--control-vector-scaled": "file_with_scale",
"--loop-adapter": "file",
}
MONITOR_TEXTUAL_VERSION = "8.2.8"
+35 -10
View File
@@ -41,15 +41,39 @@ PLE_FILES = {"Q4": "Qwen4-35B-A3B-PLE-Q4.gguf", "Q8": "Qwen4-35B-A3B-PLE-Q8_0.gg
MTP_FILE = "Qwen4-35B-A3B-MTP.strata"
VISION_FILE = "Qwen4-35B-A3B-Vision.strata"
LOOP_FILE = "Qwen4-35B-A3B-Loop.safetensors"
#: Loop (2 steps): the model's recurrent-depth adapter (147 MB). When it is on, the engine runs a 2-step recurrent-depth pass (thinks each word twice: slower, a bit more accurate). OFF by
#: Loop (2 steps): the model's recurrent-depth adapter (147 MB). When it is on, the engine runs a 2-step recurrent-depth pass (thinks each word twice: slower, a little closer to the original model). OFF by
#: default; optional and small: the file is fetched and handed to the engine ONLY when Loop is on. Shown only for Qwen4 with Strata's own quant. CLI: `--loop on|off`, run config key `qwen4_loop`.
DEFAULT_LOOP = False
LOOP_STEPS = 2
LOOP_CONFIG_KEY = "qwen4_loop" # the run config's path of the Loop file when Loop is on (absent = off)
LOOP_WORDS = "Loop (2 steps): thinks each word twice. Slower, a bit more accurate."
LOOP_WORDS = "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."
#: the Loop file's format is strata_dual_coda_loop_v1 with bypass_effort_off = true: when Effort is Off the engine bypasses the loop, so the option has no effect there (Q4-LOOP sends the flags)
LOOP_BYPASS_EFFORT_OFF = True
LOOP_HELP = LOOP_WORDS + " It has no effect while Effort is Off."
#: THE Loop switch. False = Loop is shown as "coming" and disabled everywhere (setup, `strata launch`, the catalog row, serve, the app): `--loop on` warns once and behaves as off (no qwen4_loop key,
#: no --loop-adapter / --loop-passes / --loop-coda / --loop-direct-t1 arguments, no Loop file download). The flags are Q4-LOOP's (ENGINE_FILE_FLAGS["loop"], ENGINE_LOOP_*_FLAG below); flip this
#: to True when Q4-LOOP is merged (the app mirrors this word in app/host/server/qwen4.mjs and src/lib/qwen4.ts; the host test pins them to each other).
LOOP_ENGINE_READY = False
LOOP_COMING_NOTE = "Loop (2 steps) is coming: its engine support is not in this release yet, so it stays off."
LOOP_COMING_LABEL = "Loop (2 steps) - coming soon"
def loop_coda(build) -> str:
"""The `--loop-coda` of a build: "compact" ONLY for the Compact .strata build; "universal" for Balanced, Ultra and the GGUF build (UD-Q4_K_XL), and for anything unknown (the default)."""
return "compact" if str(build or "") == "Compact" else "universal"
def loop_engine_args(path, build=None) -> list[str]:
"""The engine's arguments with Loop ON (Q4-LOOP's real flags): `--loop-adapter <Loop file> --loop-passes 2 --loop-coda universal|compact`, and `--loop-direct-t1` (the server then runs requests with
thinking disabled at T=1 by itself; the Loop file has bypass_effort_off = true). Loop OFF passes nothing at all. The engine clamps the lookup window itself."""
if not path:
return []
return [ENGINE_FILE_FLAGS["loop"], str(path), ENGINE_LOOP_STEPS_FLAG, str(LOOP_STEPS), ENGINE_LOOP_CODA_FLAG, loop_coda(build), ENGINE_LOOP_DIRECT_FLAG]
def loop_word(word) -> str:
"""The Loop choice that counts: "on" only when asked for AND the engine supports it (LOOP_ENGINE_READY); anything else is "off"."""
return "on" if str(word or "").lower() == "on" and LOOP_ENGINE_READY else "off"
#: Q4-INTAKE vendors these (the tiktoken tokenizer and the chat template of the HF repo); the names are provisional until it reports
TOKENIZER_FILE = "tokenizer.json"
CHAT_TEMPLATE_FILE = "chat_template.jinja"
@@ -97,10 +121,13 @@ MTP_CONFIG_KEY = "qwen4_mtp" # the run config's path of the sidecar (se
DEFAULT_VISION = True # pictures are in the default download set (the Vision shard)
BACKENDS = ("cuda", "hip", "metal") # NVIDIA, AMD discrete (Windows and Linux HIP) and Apple. Intel (B70 / Arc) and Strix Halo are the owner's own work, not offered here
#: How each companion file is handed to the engine: {role: flag}. PROVISIONAL, one table (CORE-API.md decides): the model is the engine's `--native` file like the other .strata families, the
#: PLE table is `--ple-gguf` (the flag the Flash-Next engine already has), the sidecar `--mtp`, the picture shard `--vision`, the loop file `--loop`.
ENGINE_FILE_FLAGS = {"model": "--native", "ple": "--ple-gguf", "mtp": "--mtp", "vision": "--vision", "loop": "--loop"}
#: the engine's switch for the number of Loop steps, next to the file (PROVISIONAL like the table above)
ENGINE_LOOP_STEPS_FLAG = "--loop-steps"
#: PLE table is `--ple-gguf` (the flag the Flash-Next engine already has), the sidecar `--mtp`, the picture shard `--vision`. Loop's flags are Q4-LOOP's real ones (f-0226-q4-loop):
#: `--loop-adapter FILE --loop-passes 2 --loop-coda universal|compact` and, with Loop on, the server's `--loop-direct-t1`.
ENGINE_FILE_FLAGS = {"model": "--native", "ple": "--ple-gguf", "mtp": "--mtp", "vision": "--vision", "loop": "--loop-adapter"}
ENGINE_LOOP_STEPS_FLAG = "--loop-passes" # the number of passes (2; 3 also works, costs more: keep 2)
ENGINE_LOOP_CODA_FLAG = "--loop-coda" # compact | universal (loop_coda(build))
ENGINE_LOOP_DIRECT_FLAG = "--loop-direct-t1" # a bare flag, only with Loop on
ENGINE_LOOP_FLAGS = (ENGINE_FILE_FLAGS["loop"], ENGINE_LOOP_STEPS_FLAG, ENGINE_LOOP_CODA_FLAG, ENGINE_LOOP_DIRECT_FLAG) # every Loop flag: stripped together when Loop is off
ENGINE_FLAGS_VERIFIED = False # flips to True when the flags above are the ones CORE-API.md names
LICENSE_NOTE = "Qwen's base model terms (the model card of Qwen/Qwen4-35B-A3B, Hugging Face revision 849378c8db0d4537b7c6731738147378729d8920)"
HF_REVISION = "849378c8db0d4537b7c6731738147378729d8920"
@@ -190,8 +217,7 @@ def gguf_engine_args(trunk, ple_shard, *, pack=None, profile=None, mtp_rt=None,
if profile:
out += ["--expert-profile", str(profile)]
out += GGUF_RUN_ARGS
if loop:
out += [ENGINE_FILE_FLAGS["loop"], str(loop), ENGINE_LOOP_STEPS_FLAG, str(LOOP_STEPS)]
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)
@@ -279,8 +305,7 @@ def engine_args(model: str | os.PathLike, *, ple: str | os.PathLike | None = Non
out = [flags["model"], str(model)]
if ple:
out += [flags["ple"], str(ple)]
if loop:
out += [flags["loop"], str(loop), ENGINE_LOOP_STEPS_FLAG, str(LOOP_STEPS)]
out += loop_engine_args(loop, build_of_file(model)) # Compact gets the compact coda, every other build universal
if vision:
out += [flags["vision"], str(vision)]
if mtp:
+3 -2
View File
@@ -27,12 +27,13 @@ WRITTEN_KEY = "args_written"
#: option groups the engine takes more than one of, or that make sense only together: kept whole
#: (the control vector options of the experimental speed projection and the person's own vectors, #3216)
USER_KEPT_FLAGS = frozenset({"--control-vector", "--control-vector-scaled", "--control-vector-layer-range", "--cvec-mode",
"--cvec-dir"})
"--cvec-dir", "--loop-adapter", "--loop-passes", "--loop-coda", "--loop-cd-omega",
"--loop-cd-thinking", "--loop-cd-think-ids"})
#: options that take more than one value, and how many (``--control-vector-layer-range 4 44``): written as separate argv
#: entries, never as one ``4,44``, and removed with all of their values (#3504)
MULTI_VALUE_FLAGS = {"--control-vector-layer-range": 2}
MULTI_VALUE_FLAGS = {"--control-vector-layer-range": 2, "--loop-cd-think-ids": 2}
def value_tokens(flag: str, value: Any) -> list[str]:
+12 -1
View File
@@ -196,7 +196,18 @@ class EngineFlags(unittest.TestCase):
def test_engine_args_come_from_the_one_table(self):
args = F.engine_args("/m/Q.strata", ple="/m/P.gguf", vision="/m/V.strata", ctx=65536)
self.assertEqual(args, [F.ENGINE_FILE_FLAGS["model"], "/m/Q.strata", F.ENGINE_FILE_FLAGS["ple"], "/m/P.gguf", F.ENGINE_FILE_FLAGS["vision"], "/m/V.strata", "--ctx", "65536"])
self.assertEqual(F.engine_args("/m/Q.strata", loop="/m/L.safetensors")[2:], [F.ENGINE_FILE_FLAGS["loop"], "/m/L.safetensors", F.ENGINE_LOOP_STEPS_FLAG, str(F.LOOP_STEPS)])
self.assertEqual(F.engine_args("/m/Q.strata", loop="/m/L.safetensors")[2:], ["--loop-adapter", "/m/L.safetensors", "--loop-passes", "2", "--loop-coda", "universal", "--loop-direct-t1"])
self.assertEqual(F.engine_args("/m/Qwen4-35B-A3B-Compact.strata", loop="/m/L.safetensors")[2:][4:6], ["--loop-coda", "compact"])
self.assertEqual(F.engine_args("/m/Q.strata"), [F.ENGINE_FILE_FLAGS["model"], "/m/Q.strata"]) # Loop off: nothing
def test_the_loop_coda_rule(self):
self.assertEqual([F.loop_coda(b) for b in ("Compact", "Balanced", "Ultra", "UD-Q4_K_XL", None)], ["compact", "universal", "universal", "universal", "universal"])
self.assertEqual(F.loop_engine_args(None), [])
self.assertEqual(F.loop_engine_args("/m/L", "Ultra"), ["--loop-adapter", "/m/L", "--loop-passes", "2", "--loop-coda", "universal", "--loop-direct-t1"])
self.assertEqual(F.ENGINE_LOOP_FLAGS, ("--loop-adapter", "--loop-passes", "--loop-coda", "--loop-direct-t1"))
g = F.gguf_engine_args("/t/trunk", "/t/s2", loop="/m/L")
self.assertEqual(g[g.index("--loop-coda") + 1], "universal")
self.assertIn("--loop-direct-t1", g)
def test_the_sidecar_flags_follow_the_mode(self):
self.assertEqual(F.mtp_engine_args("/m/M.strata", "off"), [])
+45 -2
View File
@@ -161,15 +161,16 @@ class Sidecars(unittest.TestCase):
self.assertNotIn(F.MTP_MODE_KEY, off)
self.assertNotIn(F.MTP_CONFIG_KEY, self.d()) # nothing said: no sidecar is looked for
@mock.patch.object(F, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_loop_is_off_unless_asked(self):
self.assertNotIn(F.LOOP_CONFIG_KEY, self.d())
self.assertEqual(self.d(loop="on")[F.LOOP_CONFIG_KEY], str(self.td / F.LOOP_FILE))
saved = {**self.base, F.LOOP_CONFIG_KEY: str(self.td / F.LOOP_FILE)}
self.assertNotIn(F.LOOP_CONFIG_KEY, R.derive_config(saved, S.LaunchSettings(family=FAM, loop="off"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log"))
self.assertNotIn("--loop", self.d(loop="on")["args"]) # a key, not an argument: serve makes the flags
with_args = {**self.base, "args": [*self.base["args"], "--loop", str(self.td / F.LOOP_FILE), "--loop-steps", "2"], F.LOOP_CONFIG_KEY: str(self.td / F.LOOP_FILE)}
with_args = {**self.base, "args": [*self.base["args"], "--loop-adapter", str(self.td / F.LOOP_FILE), "--loop-passes", "2", "--loop-coda", "universal", "--loop-direct-t1"], F.LOOP_CONFIG_KEY: str(self.td / F.LOOP_FILE)}
off = R.derive_config(with_args, S.LaunchSettings(family=FAM, loop="off"), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log") # setup writes the flags into the arguments too: off takes them out
for flag in ("--loop", "--loop-steps"):
for flag in F.ENGINE_LOOP_FLAGS:
self.assertNotIn(flag, off["args"])
self.assertIn("--ctx", off["args"])
@@ -213,6 +214,7 @@ class Adopt(unittest.TestCase):
self.assertEqual(cfg[F.MTP_CONFIG_KEY], str(self.folder / F.MTP_FILE))
self.assertNotIn(F.LOOP_CONFIG_KEY, cfg) # Loop is off unless asked
@mock.patch.object(F, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_ple_q8_and_loop_on_are_taken_from_the_folder(self):
cfg, _ = self.plan(ple="q8", loop="on")
self.assertEqual(value(cfg["args"], F.ENGINE_FILE_FLAGS["ple"]), str(self.folder / F.PLE_FILES["Q8"]))
@@ -303,6 +305,7 @@ class Notices(unittest.TestCase):
out = S.check_qwen4(S.LaunchSettings(family=FAM, model="Compact"), vram_gb=16, ram_gb=64, vendor="intel", cards=[{"vendor": "intel", "vram_gb": 16}])
self.assertTrue(any("no Intel engine" in n.text for n in out))
@mock.patch.object(F, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_loop_says_what_it_costs_and_not_for_custom_files(self):
on = S.check_qwen4(S.LaunchSettings(family=FAM, model="Compact", loop="on"), vram_gb=24, ram_gb=64, vendor="nvidia", cards=[{"vendor": "nvidia", "arch": 89, "vram_gb": 24}])
self.assertTrue(any(n.text == F.LOOP_HELP for n in on)) # "... It has no effect while Effort is Off."
@@ -316,6 +319,7 @@ class GgufBuild(unittest.TestCase):
"""The fourth build, Unsloth's UD-Q4_K_XL GGUF: the same engine, two shards (shard 2 holds the PLE table), its own sidecar and picture reader files, never recommended."""
G = F.GGUF_FILES
@mock.patch.object(F, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_the_notices_name_the_build_and_ignore_ple(self):
cards = [{"vendor": "nvidia", "arch": 89, "vram_gb": 24}]
out = S.check_qwen4(S.LaunchSettings(family=FAM, model="UD-Q4_K_XL", ple="q8", loop="on"), vram_gb=24, ram_gb=64, vendor="nvidia", cards=cards)
@@ -355,6 +359,7 @@ class GgufBuild(unittest.TestCase):
self.assertIsNone(cfg2)
self.assertIn(F.GGUF_TRUNK_VIEW, problems2[0])
@mock.patch.object(F, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_the_plan_counts_the_shards_the_sidecar_and_the_reader(self):
with tempfile.TemporaryDirectory() as td:
cat = mock.Mock()
@@ -441,6 +446,7 @@ class ControlHooks(unittest.TestCase):
self.assertEqual(modelstate.drafting_for_family("dflash2", FAM), None)
self.assertEqual(modelstate.drafting_for_family("off", FAM), "off")
@mock.patch.object(F, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_the_plan_counts_loop_only_when_it_is_on(self):
with tempfile.TemporaryDirectory() as td:
cat = mock.Mock()
@@ -481,5 +487,42 @@ class Unchanged(unittest.TestCase):
self.assertEqual(S.max_parallel("ling-3.2-air"), 1)
class LoopComing(unittest.TestCase):
"""Loop (2 steps) is shown as coming until qwen4_family.LOOP_ENGINE_READY is True: `--loop on` behaves as off, with one plain line."""
def test_the_switch_is_off_in_this_release(self):
self.assertFalse(F.LOOP_ENGINE_READY)
self.assertEqual(F.loop_word("on"), "off")
with mock.patch.object(F, "LOOP_ENGINE_READY", True):
self.assertEqual(F.loop_word("on"), "on")
self.assertEqual(F.loop_word("off"), "off")
self.assertIn("coming", F.LOOP_COMING_NOTE)
self.assertIn("coming soon", F.LOOP_COMING_LABEL.lower())
def test_launch_loop_on_becomes_off_with_one_line(self):
ap = argparse.ArgumentParser()
C.add_parsers(ap.add_subparsers(dest="cmd"))
a = ap.parse_args(["launch", "--family", FAM, "--loop", "on"])
s, notes = C.settings_from_args(a)
self.assertEqual(s.loop, "off")
self.assertEqual(sum(F.LOOP_COMING_NOTE in str(n) for n in notes), 1, notes)
with mock.patch.object(F, "LOOP_ENGINE_READY", True):
s, notes = C.settings_from_args(a)
self.assertEqual(s.loop, "on")
self.assertFalse(any(F.LOOP_COMING_NOTE in str(n) for n in notes))
def test_an_old_configs_loop_key_and_flags_are_stripped_and_nothing_is_downloaded(self):
saved = {"exe": "component:strata-q4-lite", "arch": F.ARCH, "model_name": "qwen4-35b-a3b-compact", F.LOOP_CONFIG_KEY: "C:/m/Loop.safetensors",
"args": ["--native", "C:/m/Q.strata", "--loop-adapter", "C:/m/Loop.safetensors", "--loop-passes", "2", "--loop-coda", "universal", "--loop-direct-t1"]}
for word in (None, "on"):
cfg = R.derive_config(saved, S.LaunchSettings(family=FAM, loop=word), bool_flags=tune_knobs.BOOL_FLAGS, log="x.log")
self.assertNotIn(F.LOOP_CONFIG_KEY, cfg)
for flag in F.ENGINE_LOOP_FLAGS:
self.assertNotIn(flag, cfg["args"])
out = S.check_qwen4(S.LaunchSettings(family=FAM, model="Compact", loop="on"), vram_gb=24, ram_gb=64, vendor="nvidia", cards=[{"vendor": "nvidia", "arch": 89, "vram_gb": 24}])
self.assertTrue(any(n.text == F.LOOP_COMING_NOTE for n in out))
self.assertFalse(any(n.text == F.LOOP_HELP for n in out))
if __name__ == "__main__":
unittest.main()
+181
View File
@@ -0,0 +1,181 @@
# qwen4_strata_reader.py - .strata v1.1 reader with numpy decoders (S1.5, S2_K..S6_K, S2_E8P, S8_K) and FWHT-128, from the Q4-REFPY reference (engine/tests/q4lite/ref/q4_strata.py).
# The manifest is read with zstandard when it is installed, else from the JSON file named by Q4S_MANIFEST.
"""Minimal .strata v1.1 reader + codec decoders for the Qwen4 reference (numpy only for decode, torch for glue).
Container (see engine/src/artifact/strata_reader.cpp + strata_layout.hpp):
header frame 16 KiB: magic 'STRATA\\0 01 01', <IHH flags profile nsec at 8, section table at 0x20 (64 B entries:
<QQ32sIIQ file_offset byte_length sha256 section_id flags reserved). S0 manifest is zstd (at the END of the file),
S1 trunk tensors (manifest offsets relative to S1.file_offset), S2 pre-knowing, S3 expert directory (32 B entries),
S4 expert bodies (S4.file_offset + body_offset), S5 selfcheck.
Codec decoders follow the Ling hand-off golden (ling32_squant_codecs_v11.py): superblock of 256 weights =
fp16 D (2 B), 4 x u8 sub-scales u (eff = D*u/255 per 64 weights), payload.
S2_E8P uses the file's own sq.e8p_tables (U8 [256,8]).
"""
from __future__ import annotations
import json
import mmap
import struct
from typing import Dict, List, Tuple
import numpy as np
try:
import zstandard
except ImportError:
zstandard = None
QK_S = 256
CODE_IDS = {"S1.25": 0, "S1.5": 1, "S2_K": 2, "S3_K": 3, "S4_K": 4, "S5_K": 5, "S6_K": 6, "S2_E8P": 7, "S8_K": 8}
ID_TO_NAME = {v: k for k, v in CODE_IDS.items()}
SB_BYTES = {"S1.25": 48, "S1.5": 58, "S2_K": 70, "S2_E8P": 70, "S3_K": 102, "S4_K": 134, "S5_K": 166, "S6_K": 198,
"S8_K": 262}
_T5 = np.zeros((256, 5), dtype=np.int8)
for _v in range(243):
_x = _v
for _j in range(5):
_T5[_v, _j] = (_x % 3) - 1
_x //= 3
def decode_sk(raw, code: str, e8p_table: np.ndarray | None = None) -> np.ndarray:
"""raw: bytes-like / uint8 array of n_sb superblocks -> float32 1-D array of n_sb*256 weights."""
sb = SB_BYTES[code]
b = np.frombuffer(raw, dtype=np.uint8) if not isinstance(raw, np.ndarray) else raw.reshape(-1)
b = b.reshape(-1, sb)
n = b.shape[0]
D = np.ascontiguousarray(b[:, :2]).view(np.float16).reshape(n).astype(np.float32)
u = b[:, 2:6].astype(np.float32)
eff = (D[:, None] * (u / 255.0))[:, :, None] # [n,4,1]
pl = b[:, 6:]
if code == "S2_E8P":
pairs = pl.reshape(n, 4, 8, 2)
idx = pairs[..., 0].astype(np.int64)
sgn = pairs[..., 1].astype(np.int32)
mag = e8p_table.astype(np.float32)[idx] # [n,4,8,8]
sh = np.arange(8, dtype=np.int32)
neg = ((sgn[..., None] >> sh) & 1).astype(np.float32)
signed = mag * (1.0 - 2.0 * neg)
return (signed.reshape(n, 4, 64) * eff).reshape(n * QK_S)
if code == "S1.5":
tr = _T5[pl.astype(np.int64)].reshape(n, 260)[:, :256].reshape(n, 4, 64).astype(np.float32)
return (tr * eff).reshape(n * QK_S)
if code == "S8_K":
q = pl.view(np.int8).astype(np.float32).reshape(n, 4, 64)
return (q * eff).reshape(n * QK_S)
bits = int(code[1])
half = ((1 << bits) - 1) / 2.0
if bits == 2:
q = np.stack([(pl >> (2 * j)) & 3 for j in range(4)], axis=2).reshape(n, QK_S)
elif bits == 3:
p_lo, p_hi = pl[:, :64], pl[:, 64:96]
lo = np.stack([(p_lo >> (2 * j)) & 3 for j in range(4)], axis=2).reshape(n, QK_S)
hi = np.stack([(p_hi >> j) & 1 for j in range(8)], axis=2).reshape(n, QK_S)
q = lo | (hi << 2)
elif bits == 4:
q = np.stack([pl & 15, (pl >> 4) & 15], axis=2).reshape(n, QK_S)
elif bits == 5:
p_lo, p_hi = pl[:, :128], pl[:, 128:160]
lo = np.stack([p_lo & 15, (p_lo >> 4) & 15], axis=2).reshape(n, QK_S)
hi = np.stack([(p_hi >> j) & 1 for j in range(8)], axis=2).reshape(n, QK_S)
q = lo | (hi << 4)
elif bits == 6:
p_lo, p_hi = pl[:, :128], pl[:, 128:192]
lo = np.stack([p_lo & 15, (p_lo >> 4) & 15], axis=2).reshape(n, QK_S)
hi = np.stack([(p_hi >> (2 * j)) & 3 for j in range(4)], axis=2).reshape(n, QK_S)
q = lo | (hi << 4)
else:
raise ValueError(code)
qf = q.astype(np.float32).reshape(n, 4, 64) - half
return (qf * eff).reshape(n * QK_S)
def fwht128_cols(x: np.ndarray) -> np.ndarray:
"""Normalised Walsh-Hadamard (Sylvester order) on every consecutive 128 block of the last axis."""
shp = x.shape
a = np.ascontiguousarray(x, dtype=np.float32).reshape(-1, 128).copy()
h = 1
while h < 128:
a = a.reshape(-1, 128 // (2 * h), 2, h)
u = a[:, :, 0, :].copy()
v = a[:, :, 1, :].copy()
a[:, :, 0, :] = u + v
a[:, :, 1, :] = u - v
a = a.reshape(-1, 128)
h *= 2
a *= np.float32(1.0 / np.sqrt(128.0))
return a.reshape(shp)
class Strata:
def __init__(self, path: str):
self.path = path
self.f = open(path, "rb")
self.mm = mmap.mmap(self.f.fileno(), 0, access=mmap.ACCESS_READ)
hdr = self.mm[:4096]
assert hdr[:8] == b"STRATA\x00\x01", hdr[:8]
self.flags, self.profile, self.nsec = struct.unpack_from("<IHH", hdr, 8)
probe = struct.unpack_from("<Q", hdr, 0x10)[0]
off = 0x20 if probe < 4096 else 0x10
self.sec: List[Tuple[int, int]] = []
for i in range(self.nsec):
fo, bl = struct.unpack_from("<QQ", hdr, off + i * 64)
sid, fl = struct.unpack_from("<II", hdr, off + i * 64 + 48)
assert sid == i
self.sec.append((fo, bl))
fo, bl = self.sec[0]
import os
mp = os.environ.get("Q4S_MANIFEST")
self.manifest = json.load(open(mp)) if mp else json.loads(zstandard.ZstdDecompressor().decompressobj().decompress(self.mm[fo:fo + bl]))
self.tensors: Dict[str, dict] = {t["name"]: t for t in self.manifest["trunk_tensors"]}
d = self.mm[self.sec[3][0]:self.sec[3][0] + self.sec[3][1]]
n = len(d) // 32
ents = []
for i in range(n):
eid, gu, dn, cl, fl, o, bb, dno, a0, a1 = struct.unpack_from("<HBBHHQIIII", d, i * 32)
ents.append((eid, gu, dn, cl, fl, o, bb, dno, a0, a1))
self.dir = ents
self.e8p = None
if "sq.e8p_tables" in self.tensors:
self.e8p = self.raw("sq.e8p_tables").reshape(256, 8)
def raw(self, name: str) -> np.ndarray:
t = self.tensors[name]
o = self.sec[1][0] + t["offset"]
return np.frombuffer(self.mm, dtype=np.uint8, count=t["bytes"], offset=o)
def get(self, name: str) -> np.ndarray:
"""Decode a trunk tensor to float32 with its manifest shape."""
t = self.tensors[name]
fmt = t["format"]
shp = tuple(t["shape"])
r = self.raw(name)
if fmt == "F32":
return r.view(np.float32).reshape(shp).copy()
if fmt == "BF16":
a = r.view(np.uint16).astype(np.uint32) << 16
return a.view(np.float32).reshape(shp).copy()
if fmt == "F16":
return r.view(np.float16).astype(np.float32).reshape(shp)
if fmt in SB_BYTES:
return decode_sk(r, fmt, self.e8p).reshape(shp)
raise ValueError(fmt)
def get_rows(self, name: str, rows) -> np.ndarray:
"""Decode selected rows of a 2-D S_K tensor (rows are multiples of K/256 superblocks)."""
t = self.tensors[name]
fmt = t["format"]
R, K = t["shape"]
sb = SB_BYTES[fmt]
nsb = K // QK_S
base = self.sec[1][0] + t["offset"]
out = np.empty((len(rows), K), dtype=np.float32)
for i, r in enumerate(rows):
raw = np.frombuffer(self.mm, dtype=np.uint8, count=nsb * sb, offset=base + int(r) * nsb * sb)
out[i] = decode_sk(raw, fmt, self.e8p)
return out
def expert_raw(self, layer: int, e: int):
ent = self.dir[layer * 256 + e]
o = self.sec[4][0] + ent[5]
return ent, np.frombuffer(self.mm, dtype=np.uint8, count=ent[6], offset=o)
+144
View File
@@ -0,0 +1,144 @@
"""strata_to_gguf.py - Qwen4-35B-A3B .strata (Compact / Balanced / Ultra) -> the dense half of a qwen4exp GGUF for the Metal window.
The dense tensors are decoded, un-rotated (the file stores W @ H128 on the K axis), put in the layer layout the Unsloth qwen4exp file has
(GDN value heads in tiled order, norm weights as 1 + w, fused-name tensors as separate ones) and written as BF16 / F32. The routed experts
stay in the .strata (read by the window through the path in the key qwen4exp.strata_experts); tiny placeholder tensors keep the window's
tensor lookups happy. usage: strata_to_gguf.py <pydir with q4s.py> <gguf-py dir> <strata> <template gguf (Unsloth trunk view)> <out gguf> [layers]
"""
import os, sys, time
import numpy as np
sys.path.insert(0, sys.argv[1])
sys.path.insert(0, sys.argv[2])
import qwen4_strata_reader as q4s
import gguf
gguf.GGUFWriter.ggml_pad = staticmethod(lambda x, n: ((int(x) + n - 1) // n) * n) # numpy uint32 nbytes wrapped the offsets past 4 GiB
S = q4s.Strata(sys.argv[3])
TPL = gguf.GGUFReader(sys.argv[4])
OUT = sys.argv[5]
NL = int(sys.argv[6]) if len(sys.argv) > 6 else 40
LM = "model.language_model."
JP = np.array([2 * (p % 16) + p // 16 for p in range(32)]) # GGUF (tiled) value head p holds HF head JP[p]
def bf16(a):
u = np.ascontiguousarray(a, dtype=np.float32).view(np.uint32)
r = ((u >> 16) & 1) + 0x7FFF
return ((u + r) >> 16).astype(np.uint16)
def unrot(w):
return q4s.fwht128_cols(w)
w = gguf.GGUFWriter(OUT, arch="qwen4exp")
w.data_alignment = int(TPL.alignment)
for key, f in TPL.fields.items():
if key.startswith("GGUF.") or key == "general.architecture" or key.startswith("split."):
continue
vtype = gguf.GGUFValueType(f.types[0])
subtype = gguf.GGUFValueType(f.types[1]) if len(f.types) > 1 else None
w.add_key_value(key, f.contents(), vtype, subtype)
w.add_key_value("qwen4exp.strata_experts", os.path.abspath(sys.argv[3]), gguf.GGUFValueType.STRING)
w.add_key_value("qwen4exp.strata_tier", S.manifest.get("tier", ""), gguf.GGUFValueType.STRING)
keep = [] # arrays must outlive write_tensors_to_file
n_t = 0
def put_bf16(name, a):
global n_t
a = np.asarray(a, dtype=np.float32)
b = bf16(a)
b8 = np.ascontiguousarray(b).view(np.uint8).reshape(a.shape[:-1] + (a.shape[-1] * 2,))
keep.append(b8)
w.add_tensor(name, b8, raw_dtype=gguf.GGMLQuantizationType.BF16)
n_t += 1
def put_f32(name, a):
global n_t
a = np.ascontiguousarray(a, dtype=np.float32)
keep.append(a)
w.add_tensor(name, a)
n_t += 1
def put_placeholder(name):
global n_t
z = np.zeros((1, 1, 144), dtype=np.uint8)
keep.append(z)
w.add_tensor(name, z, raw_dtype=gguf.GGMLQuantizationType.Q4_K)
n_t += 1
def dense(name):
return unrot(S.get(LM + name))
t0 = time.time()
for L in range(NL):
p = "layers.%d." % L
b = "blk.%d." % L
for hf, gg in (("attn_hyper_connection", "hc_attn"), ("mlp_hyper_connection", "hc_ffn")):
put_f32(b + gg + "_norm.weight", 1.0 + S.get(LM + p + hf + ".hc_norm.weight"))
put_bf16(b + gg + "_down.weight", dense(p + hf + ".input_mix_weight_down.weight"))
put_bf16(b + gg + "_up.weight", dense(p + hf + ".input_mix_weight_up.weight"))
put_bf16(b + gg + "_inject.weight", dense(p + hf + ".block_inject_weight.weight"))
put_f32(b + "ffn_gate_inp.weight", S.get(LM + p + "mlp.gate.weight"))
put_f32(b + "ffn_gate_inp_shexp.weight", S.get(LM + p + "mlp.shared_expert_gate.weight").reshape(-1))
put_bf16(b + "ffn_gate_shexp.weight", dense(p + "mlp.shared_expert.gate_proj.weight"))
put_bf16(b + "ffn_up_shexp.weight", dense(p + "mlp.shared_expert.up_proj.weight"))
put_bf16(b + "ffn_down_shexp.weight", dense(p + "mlp.shared_expert.down_proj.weight"))
if (L + 1) % 4 != 0: # GDN
q = p + "linear_attn."
qkv = dense(q + "in_proj_qkv.weight")
qkv = np.concatenate([qkv[:4096], qkv[4096:].reshape(32, 128, -1)[JP].reshape(4096, -1)], axis=0)
put_bf16(b + "attn_qkv.weight", qkv)
put_bf16(b + "attn_gate.weight", dense(q + "in_proj_z.weight").reshape(32, 128, -1)[JP].reshape(4096, -1))
put_bf16(b + "ssm_out.weight", dense(q + "out_proj.weight").reshape(2048, 32, 128)[:, JP, :].reshape(2048, 4096))
put_bf16(b + "ssm_alpha.weight", S.get(LM + q + "in_proj_a.weight")[JP])
put_bf16(b + "ssm_beta.weight", S.get(LM + q + "in_proj_b.weight")[JP])
put_f32(b + "ssm_a", (-np.exp(S.get(LM + q + "A_log")))[JP])
put_f32(b + "ssm_dt.bias", S.get(LM + q + "dt_bias")[JP])
cv = S.get(LM + q + "conv1d.weight").reshape(8192, 4)
cv = np.concatenate([cv[:4096], cv[4096:].reshape(32, 128, 4)[JP].reshape(4096, 4)], axis=0)
put_f32(b + "ssm_conv1d.weight", cv)
put_f32(b + "ssm_norm.weight", S.get(LM + q + "norm.weight"))
else:
a = p + "self_attn."
put_bf16(b + "attn_q.weight", dense(a + "q_proj.weight"))
put_bf16(b + "attn_k.weight", dense(a + "k_proj.weight"))
put_bf16(b + "attn_v.weight", dense(a + "v_proj.weight"))
put_bf16(b + "attn_output.weight", dense(a + "o_proj.weight"))
put_f32(b + "attn_q_norm.weight", 1.0 + S.get(LM + a + "q_norm.weight"))
put_f32(b + "attn_k_norm.weight", 1.0 + S.get(LM + a + "k_norm.weight"))
ix = dense(a + "indexer.index_qk_proj.weight")
put_bf16(b + "indexer.q_proj.weight", ix[:512])
put_bf16(b + "indexer.k_proj.weight", ix[512:])
put_f32(b + "indexer.q_norm.weight", 1.0 + S.get(LM + a + "indexer.q_layernorm.weight"))
put_f32(b + "indexer.k_norm.weight", 1.0 + S.get(LM + a + "indexer.k_layernorm.weight"))
if L == 1:
pp = LM + p + "ple."
put_bf16(b + "ple_key.weight", unrot(S.get(pp + "key_proj.weight")))
put_bf16(b + "ple_value.weight", unrot(S.get(pp + "value_proj.weight")))
put_f32(b + "ple_conv1d.weight", S.get(pp + "conv1d.weight").reshape(8192, 4))
for n in ("norm_key", "norm_query", "norm_conv"):
put_f32(b + "ple_" + n + ".weight", 1.0 + S.get(pp + n + ".weight"))
for g in ("gate", "up", "down"):
put_placeholder(b + "ffn_%s_exps.weight" % g)
print("layer %d done, %.0f s" % (L, time.time() - t0), flush=True)
m = LM + "hyper_connection_mixer."
put_f32("output_hc_norm.weight", 1.0 + S.get(m + "hc_norm.weight"))
put_bf16("output_hc_down.weight", unrot(S.get(m + "input_mix_weight_down.weight")))
put_bf16("output_hc_up.weight", unrot(S.get(m + "input_mix_weight_up.weight")))
put_bf16("token_embd.weight", unrot(S.get(LM + "embed_tokens.weight")))
print("embed done %.0f s" % (time.time() - t0), flush=True)
put_bf16("output.weight", unrot(S.get("lm_head.weight")))
print("head done %.0f s" % (time.time() - t0), flush=True)
w.write_header_to_file()
w.write_kv_data_to_file()
w.write_tensors_to_file()
w.close()
print("wrote %s: %d tensors, %.0f s" % (OUT, n_t, time.time() - t0))
+3 -2
View File
@@ -881,7 +881,7 @@ class Strata:
"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
"recommended_ple": adv["recommended"]["ple"], "vram_need_gib": adv["vram_need_gib"], "ram_need_gib": adv["ram_need_gib"], "loop_available": True,
"recommended_ple": adv["recommended"]["ple"], "vram_need_gib": adv["vram_need_gib"], "ram_need_gib": adv["ram_need_gib"], "loop_available": bool(qwen4_family.LOOP_ENGINE_READY),
"notes": self._qwen4_notes(cards, backend, pick)}
@staticmethod
@@ -2785,7 +2785,7 @@ def tool_defs(models: dict, families: dict, contexts: list) -> list:
"ple": {"type": "string", "enum": ["q4", "q8"],
"description": "Qwen4-35B-A3B only: the PLE table to download and use (q4 = 11.5 GB, the default; q8 = 21.8 GB, when the RAM holds it); omitted = what this computer holds"},
"loop": {"type": "string", "enum": ["on", "off"],
"description": "Qwen4-35B-A3B only: Loop (2 steps) thinks each word twice; slower, a bit more accurate; off by default (its small file is downloaded only when on)"},
"description": "Qwen4-35B-A3B only: Loop (2 steps) thinks each word twice; slower (about 40% fewer words per second while writing), a little closer to the original model; off by default (its small file is downloaded only when on)"},
"effort": {"type": "string", "enum": ["off", "low", "high", "xhigh"],
"description": "Qwen4-35B-A3B only: how much it thinks before it answers (default: off)"},
"custom_label": {"type": "string", "maxLength": 80,
@@ -3177,6 +3177,7 @@ class Tools:
md = {**md, "download_gb": round(sum(ling32_family.size_of(n) / 1e9 for n in ling32_family.files_of(vision=vision != "no") if n not in have_files), 1)}
elif md.get("qwen4"): # Qwen4-35B-A3B: the files in <models>/qwen4-35b-a3b (build, PLE table, Loop, Vision, MTP); the disk need is what is not there yet
from strata_control import qwen4_family
loop = "off" if loop == "on" and not qwen4_family.LOOP_ENGINE_READY else loop # Loop is coming: on counts as off (no download, no flag)
qwen4_fit_loop_gb = qwen4_family.size_of(qwen4_family.LOOP_FILE) / 1e9
if gguf_dir:
md = {**md, "download_gb": 0.0}
+43 -3
View File
@@ -191,8 +191,13 @@ class Choices(unittest.TestCase):
self.assertNotIn(f["mtp"], args) # the sidecar is a config key (Control reads --mtp <folder> as Flash-Next's draft layer)
with_loop = setup.qwen4_engine_args("/m/a.strata", "/m/ple.gguf", "/m/loop.safetensors", None, 8192)
self.assertEqual(with_loop[with_loop.index(f["loop"]) + 1], "/m/loop.safetensors")
self.assertEqual(with_loop[with_loop.index("--loop-steps") + 1], "2")
self.assertEqual(with_loop[with_loop.index("--loop-passes") + 1], "2")
self.assertEqual(with_loop[with_loop.index("--loop-coda") + 1], "universal") # "/m/a.strata" is not the Compact build
self.assertIn("--loop-direct-t1", with_loop)
compact = setup.qwen4_engine_args("/m/Qwen4-35B-A3B-Compact.strata", "/m/ple.gguf", "/m/loop.safetensors", None, 8192)
self.assertEqual(compact[compact.index("--loop-coda") + 1], "compact") # compact ONLY for the Compact build
@mock.patch.object(qwen4_family, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_the_words_of_the_person(self):
self.assertEqual(setup.qwen4_effort(ns()), qwen4_family.DEFAULT_EFFORT) # the model's own default (high)
self.assertEqual(setup.qwen4_effort(ns(effort="xhigh")), "xhigh")
@@ -320,13 +325,15 @@ class Install(unittest.TestCase):
self.assertTrue(any("Effort:" in s and "Low" in s for s in says), says)
self.assertFalse([s for s in says if s.strip().startswith("Thinking:")])
@mock.patch.object(qwen4_family, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_loop_is_fetched_only_when_on(self):
rc, w, says, fetched, _ = self.run_install(loop="on")
cfg = w["cfg"]
self.assertIn(qwen4_family.LOOP_FILE, fetched)
self.assertTrue(cfg[qwen4_family.LOOP_CONFIG_KEY].endswith("Loop.safetensors"))
self.assertEqual(cfg["args"][cfg["args"].index(qwen4_family.ENGINE_FILE_FLAGS["loop"]) + 1], cfg[qwen4_family.LOOP_CONFIG_KEY])
self.assertEqual(cfg["args"][cfg["args"].index("--loop-steps") + 1], "2")
self.assertEqual(cfg["args"][cfg["args"].index("--loop-passes") + 1], "2")
self.assertIn("--loop-direct-t1", cfg["args"])
def test_pictures_and_mtp_can_be_left_out(self):
_, w, _, fetched, _ = self.run_install(vision="no", mtp="off")
@@ -539,6 +546,7 @@ class GgufBuild(unittest.TestCase):
self.assertNotIn(qwen4_family.MTP_CONFIG_KEY, w["cfg"])
self.assertTrue(any(s.startswith("warn") and "MTP is off" in s for s in says), says)
@mock.patch.object(qwen4_family, "LOOP_ENGINE_READY", True) # the engine supports Loop: the behaviour of the switch on
def test_pictures_mtp_ple_and_loop_options(self):
_, w, _, ran, downloaded, _ = self.run_install(vision="no", mtp="off")
self.assertEqual(len(downloaded), 2)
@@ -549,7 +557,9 @@ class GgufBuild(unittest.TestCase):
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):
_, w, _, _, _, _ = self.run_install(loop="on", source=True)
self.assertIn("--loop-steps", w["cfg"]["args"])
self.assertIn("--loop-passes", w["cfg"]["args"])
self.assertEqual(w["cfg"]["args"][w["cfg"]["args"].index("--loop-coda") + 1], "universal") # the GGUF build: universal
self.assertIn("--loop-direct-t1", w["cfg"]["args"])
def test_a_pinned_size_is_checked_and_a_wrong_one_is_refused(self):
pins = {**qwen4_family.GGUF_FILES, "shard1": (qwen4_family.GGUF_FILES["shard1"][0], len(BLOB) + 1, None)}
@@ -660,5 +670,35 @@ class ConfigAndCatalog(unittest.TestCase):
self.assertIn(f, flags)
class LoopComing(unittest.TestCase):
"""`--loop on` while LOOP_ENGINE_READY is False: one warning, behaves as off (no key, no flags, no download)."""
def test_loop_on_warns_once_and_is_off(self):
said = []
with mock.patch.object(setup, "warn", side_effect=lambda t="", *x: said.append(t)):
self.assertFalse(setup.qwen4_loop_wanted(ns(loop="on")))
self.assertFalse(setup.qwen4_loop_wanted(ns(loop="off")))
self.assertFalse(setup.qwen4_loop_wanted(ns()))
self.assertEqual(said, [qwen4_family.LOOP_COMING_NOTE])
def test_the_install_writes_no_loop_and_fetches_no_loop_file(self):
rc, w, says, fetched, _ = Install.run_install(Install(), loop="on")
cfg = w["cfg"]
self.assertNotIn(qwen4_family.LOOP_FILE, fetched)
self.assertNotIn(qwen4_family.LOOP_CONFIG_KEY, cfg)
self.assertNotIn(qwen4_family.ENGINE_FILE_FLAGS["loop"], cfg["args"])
for flag in qwen4_family.ENGINE_LOOP_FLAGS:
self.assertNotIn(flag, cfg["args"])
self.assertTrue(any(qwen4_family.LOOP_COMING_NOTE in s for s in says), says)
def test_the_catalog_row_says_loop_is_not_available(self):
s = M.Strata(HERE.parent)
row = s.qwen4_fit_row("Compact", 64.0, [{"vendor": "nvidia", "vram_gb": 24.0, "arch": "86", "usable": True}], loop=True)
self.assertFalse(row["loop_available"])
with mock.patch.object(qwen4_family, "LOOP_ENGINE_READY", True):
row = s.qwen4_fit_row("Compact", 64.0, [{"vendor": "nvidia", "vram_gb": 24.0, "arch": "86", "usable": True}], loop=True)
self.assertTrue(row["loop_available"])
if __name__ == "__main__":
unittest.main()