Merge f-022-ownfiles: own GGUF files load again, plain download/prepare steps, chosen models folder
This commit is contained in:
commit
c7938c2d3e
33 files changed
+1385
-151
No files matched your search
@@ -182,13 +182,16 @@ export function chooserUnavailable(picked) {
|
||||
return { message: picked.reason, code: 'folder-chooser-unavailable', details: picked.detail };
|
||||
}
|
||||
|
||||
/** A typed path stands in for the dialog: it must be an absolute directory that exists. */
|
||||
export async function typedFolder(value, { isAbsolute }) {
|
||||
const text = typeof value === 'string' ? value.trim() : '';
|
||||
/** A typed path stands in for the dialog: it must be an absolute directory that exists. `fileType` (a RegExp on the name) also lets a
|
||||
* file of that kind through (the model page takes a folder or one .gguf file). Quotes around the path (Windows "Copy as path") go. */
|
||||
export async function typedFolder(value, { isAbsolute, fileType = null }) {
|
||||
let text = typeof value === 'string' ? value.trim() : '';
|
||||
if (text.length > 1 && /^(["'])[\s\S]*\1$/.test(text)) text = text.slice(1, -1).trim();
|
||||
if (!text || text.includes('\0')) return null;
|
||||
if (!isAbsolute(text)) throw new Error('Enter the full path of the folder.');
|
||||
if (!isAbsolute(text)) throw new Error(fileType ? 'Enter the full path of the folder or the file.' : 'Enter the full path of the folder.');
|
||||
let info;
|
||||
try { info = await stat(text); } catch { throw new Error('That folder does not exist.'); }
|
||||
if (!info.isDirectory()) throw new Error('Choose a folder, not a file.');
|
||||
try { info = await stat(text); } catch { throw new Error(fileType ? 'That folder or file does not exist.' : 'That folder does not exist.'); }
|
||||
if (info.isFile() && fileType?.test(text)) return text;
|
||||
if (!info.isDirectory()) throw new Error(fileType ? 'Choose a folder, or a .gguf file.' : 'Choose a folder, not a file.');
|
||||
return cleanChosenPath(text);
|
||||
}
|
||||
@@ -980,7 +980,7 @@ async function api(req, res, path, method, url) {
|
||||
return json(res,200,{path:file});}
|
||||
if(path==='/api/native/local/preview'&&method==='POST'){
|
||||
/* "Use a local GGUF": pick (or type) the folder, and Control says what is in it. Nothing is copied or changed. */
|
||||
const typed=await typedFolder((await readBody(req)).path,{isAbsolute});
|
||||
const typed=await typedFolder((await readBody(req)).path,{isAbsolute,fileType:/\.gguf$/i});
|
||||
const picked=typed?{path:typed}:await chooseFolder('Choose the folder that holds your GGUF files');
|
||||
if(picked.unavailable){const u=chooserUnavailable(picked);return error(res,501,u.message,{code:u.code});};
|
||||
if(picked.cancelled)return json(res,200,{cancelled:true});
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Where the person's models go: what a picked folder means (0.2.2).
|
||||
*
|
||||
* - A drive on its own (D:\ or /) is never filled with model files: it becomes D:\Strata (the data folder) and D:\Strata\Models (the
|
||||
* model library), which the person is told.
|
||||
* - The data folder is the person's own choice, so it is written into the settings file Strata Control reads (`data_dir`). Control's
|
||||
* installer accepts a data folder that is that setting, whatever the folder is called; for a folder it has not been told about it wants a
|
||||
* name starting with "Strata" (a rule against an AI tool filling an arbitrary folder, tools/strata_mcp.py check_data_dir).
|
||||
* - The link that makes `<data>/models` and `<data>/Models` one folder is only needed where the file system tells them apart; where it cannot be
|
||||
* made (exFAT, FAT, a network share) the models simply go in `<data>/models`.
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, parse, resolve } from 'node:path';
|
||||
|
||||
export const isDriveRoot = path => { const p = resolve(path); return p === parse(p).root; };
|
||||
|
||||
/** The data folder for a picked folder: a drive root gets a `Strata` folder of its own. `{ path, note }`. */
|
||||
export function dataFolderFromPick(picked) {
|
||||
const path = resolve(picked);
|
||||
if (!isDriveRoot(path)) return { path, note: null };
|
||||
const target = join(path, 'Strata');
|
||||
return { path: target, note: `${path} is a whole drive, so the models go in ${target}.` };
|
||||
}
|
||||
|
||||
/** The model library folder for a picked folder: a drive root gets `Strata/Models`. `{ path, note }`. */
|
||||
export function libraryFolderFromPick(picked) {
|
||||
const path = resolve(picked);
|
||||
if (!isDriveRoot(path)) return { path, note: null };
|
||||
const target = join(path, 'Strata', 'Models');
|
||||
return { path: target, note: `${path} is a whole drive, so the models go in ${target}.` };
|
||||
}
|
||||
|
||||
/** Make a folder the person asked for; a refusal of the disk is said in words. */
|
||||
export function makeFolder(path) {
|
||||
try { mkdirSync(path, { recursive: true }); }
|
||||
catch (error) { throw new Error(`Strata could not create ${path} (${error.code === 'EACCES' || error.code === 'EPERM' ? 'access was denied' : error.code === 'ENOSPC' ? 'the drive is full' : error.message}). Choose another folder.`); }
|
||||
return path;
|
||||
}
|
||||
|
||||
/** `models` beside `Models`: a link where the two are different names. A disk that cannot hold the link gets a plain `models` folder instead. */
|
||||
export function alignModels(data, library, { link = symlinkSync } = {}) {
|
||||
const models = join(data, 'models');
|
||||
if (existsSync(models)) return { data, linked: false };
|
||||
try { link(process.platform === 'win32' ? library : 'Models', models, process.platform === 'win32' ? 'junction' : 'dir'); return { data, linked: true }; }
|
||||
catch { /* exFAT, FAT, NFS, a share: no links there */ }
|
||||
try { mkdirSync(models, { recursive: true }); } catch { /* the install says what it cannot write */ }
|
||||
return { data, linked: false };
|
||||
}
|
||||
|
||||
/** Write the person's data folder into the Control settings file (merged, atomically); returns whether it changed. Never throws: the folder
|
||||
* still works for the app, only the Terminal and the installer's own check lose the shared setting. */
|
||||
export function rememberDataFolder(file, folder) {
|
||||
if (!file || !folder) return false;
|
||||
try {
|
||||
let current = {};
|
||||
try { const parsed = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, '')); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) current = parsed; } catch { /* a new file */ }
|
||||
if (current.data_dir === folder) return false;
|
||||
mkdirSync(dirname(file), { recursive: true });
|
||||
const temp = `${file}.${process.pid}.tmp`;
|
||||
writeFileSync(temp, JSON.stringify({ ...current, data_dir: folder }, null, 1) + '\n', { mode: 0o600 });
|
||||
renameSync(temp, file);
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import os from 'node:os';
|
||||
import { runtimeVision } from './native-vision.mjs';
|
||||
import { componentsDirectory, installerEnvironment, controlEnvironment } from './control-runtime.mjs';
|
||||
import { createEngineStep } from './engine-step.mjs';
|
||||
import { dataFolderFromPick, isDriveRoot, makeFolder, rememberDataFolder } from './model-folder.mjs';
|
||||
import { createAutoTune, writeTuneConfig } from './native-autotune.mjs';
|
||||
import { plainError, PHASE_TEXT } from './update-messages.mjs';
|
||||
import { checkRunConfig, describeIssues } from './run-config-check.mjs';
|
||||
@@ -72,6 +73,8 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
if(JSON.stringify(next)!==JSON.stringify(config)){try{writeModelConfig(path,next);}catch{/* read-only folder: the load reports it */}}}}
|
||||
function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;/* A model the person pointed at their own GGUF folder (not <data>/models/<tag>): remembered, so a later load runs setup with that folder again instead of downloading the files (#3199). */const ownGgufDir=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))!=='models'&&existsSync(nativeFile)?dirname(nativeFile):undefined;return {...entry,ownGgufDir,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,visionPrepared:!!cfg.vision,/* The picture files are prepared when the run config has a vision section: the Models screen then loads straight away instead of running setup again (it used to read 'off' for every model, which sent every load of a picture-capable model through "Apply settings and load", and setup writes the arguments, the draft layer and the reader back each time). */images:cfg.vision?'yes':'off',draftLayer:cfg.mtp!==false,/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};}
|
||||
function installRoot(){const found=[preferences.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());}
|
||||
/* The settings file Strata Control and the installer read (control-runtime.mjs sets STRATA_SETTINGS_FILE to it): the app's data folder is written there. */
|
||||
function controlSettingsFile(){return process.env.STRATA_SETTINGS_FILE||join(dirname(componentsDirectory()),'app-settings.json');}
|
||||
function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;}
|
||||
function python(){return resolvePython({repo:preferences.repo});}
|
||||
function send(method,params,timeout=30000){return new Promise((resolve,reject)=>{const id=++seq;const alarm=setTimeout(()=>{pending.delete(id);reject(new Error('The native engine did not respond in time. Check engine logs.'));},timeout);pending.set(id,{resolve,reject,alarm});child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');});}
|
||||
@@ -121,7 +124,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
refreshing=(async()=>{try{const [catalog,status]=packaged?await (async()=>{const s=await tool('strata_status',{hardware:true});const c=await tool('strata_models').catch(error=>({families:[],contexts:[],recommendation:{family:null,model:null},context_note:'',error:error.message}));return [c,s];})():await Promise.all([tool('strata_models'),tool('strata_status',{hardware:true})]);let visionReader=false;if(packaged){try{const e=await control.engine();const root=e?.engine?.root??(e?.engine?.exe?dirname(e.engine.exe):'');visionReader=!!root&&['strata-vision','strata-vision.exe'].some(n=>existsSync(join(root,n)));}catch{visionReader=false;}}const markImages=c=>c&&Array.isArray(c.families)?{...c,families:c.families.map(f=>({...f,imagesCapable:!!f.images,images:!!f.images&&visionReader,sizes:(f.sizes??[]).map(s=>({...s,imagesCapable:!!s.images,images:!!s.images&&visionReader}))}))}:c;snapshot={available:true,repo:packaged?status.installDir:repo(),version:packaged?(control.version??null):await execute('git',['describe','--tags','--always'],repo()).then(s=>s.trim()).catch(()=>null),summary:status.summary,catalog:markEngine(packaged?markImages(catalog):catalog,status.engine),engineInfo:{version:status.engine?.version??null,source:status.engine?.source??null},visionReader:packaged?visionReader:true,installed:installedInfo(status.installed),hardware:status.hardware,error:null,install:status.install,external:status.running??null,...(packaged?{packaged:true,installDir:status.installDir,engine:status.engine,installerError:status.installerError}:{})};lastRead=Date.now();if(status.install?.running&&![...jobs.values()].some(j=>j.state==='running'))begin('install',j=>watchInstall(j,status.install));}catch(error){snapshot={...snapshot,available:false,error:error.message};lastRead=Date.now();}emit();return state();})().finally(()=>{refreshing=null;});const run=refreshing;if(!force&&snapshot.available){run.catch(()=>{});return state();}return run;
|
||||
}
|
||||
function configure({repository}){if(packaged){if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));if(!statSync(next).isDirectory())throw new Error('Choose the folder that holds your Strata model configurations.');preferences={...preferences,installDir:next};packagedInstall=null;disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}if(instances.size||[...jobs.values()].some(j=>j.state==='running'))throw new Error('Unload models and finish operations before changing the installation.');const next=realpathSync(String(repository));const old=preferences;preferences={...preferences,repo:next};try{repo();}catch(e){preferences=old;throw e;}disconnect();writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});lastRead=0;return refresh(true);}
|
||||
function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');const path=realpathSync(input.trim());if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');accessSync(path,constants.R_OK|constants.W_OK);preferences={...preferences,downloadDirectory:path};writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}
|
||||
function setDownloadDirectory(input){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before changing the folder.');if(typeof input!=='string'||!input.trim()||/[\r\n\0]/.test(input))throw new Error('Choose a model folder.');let path;try{path=realpathSync(input.trim());}catch{throw new Error('That folder does not exist. Check the path, or that the drive is connected.');}if(!statSync(path).isDirectory())throw new Error('Choose a folder, not a file.');/* A whole drive (D:\) is not filled with models: D:\Strata is made and used. */if(isDriveRoot(path)){const own=dataFolderFromPick(path).path;makeFolder(own);path=realpathSync(own);}try{accessSync(path,constants.R_OK|constants.W_OK);}catch{throw new Error('Strata cannot write in that folder. Choose a folder you can save files in.');}preferences={...preferences,downloadDirectory:path};/* the same choice for the installer and the Terminal: the Control settings file */if(packaged)rememberDataFolder(controlSettingsFile(),path);writeFileSync(settingsPath,JSON.stringify(preferences,null,2),{mode:0o600});emit();return state();}
|
||||
function recordFile(model){if(!safeId(model))throw new Error('Choose an installed model.');const entry=snapshot.installed?.models?.find(i=>i.model===model);if(!entry)throw new Error('This model is not installed. Download and prepare it first.');const path=realpathSync(entry.configPath??join(repo(),entry.config));if(dirname(path)!==repo()||!/^strata-[a-z0-9_-]+\.json$/i.test(basename(path)))throw new Error('The model configuration is outside the Strata installation.');return {entry,path};}
|
||||
function record(model){const {entry,path}=recordFile(model);return {entry,path,config:readJson(path)};}
|
||||
/* The text file a power user edits by hand: where it is and what is wrong in it (run-config-check.mjs). */
|
||||
@@ -133,7 +136,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp
|
||||
function save(model,{values,mcp}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish the current operation before saving native settings.');const {path,config}=record(model);if(busy(requests().filter(r=>instances.get(r.instanceId)?.model===model)))throw new Error('Finish this model’s requests before saving its settings.');const patch=validateNativeSettings(values??{}),next={...config};for(const field of nativeFields())if(field.supported===false&&patch[field.id]!=null&&JSON.stringify(patch[field.id])!==JSON.stringify(config[field.id]))throw new Error(`${field.label} needs a newer native Strata installation. Update it in Settings → About.`);for(const [key,value] of Object.entries(patch)){if(key==='env')next.env=restoreNativeEnv(value,config.env??{});else if(value===null)delete next[key];else next[key]=value;}if('vram_reserve_mib' in patch){const base=captureUserArgs(next);const mine=setUserFlag(base,'--vram-reserve-mib',patch.vram_reserve_mib);if(mine.length)next[USER_KEY]=mine;else delete next[USER_KEY];next.args=mine.length&&patch.vram_reserve_mib!==null?mergeUserArgs(next.args??[],mine):setUserFlag(next.args??[],'--vram-reserve-mib',null);delete next.ui_reserve_applied;if(Array.isArray(next.args_written))next.args_written=[...next.args];}if(mcp!==undefined){next.mcp_servers=validateMcpServers(mcp,config.mcp_servers??config.mcpServers??{});delete next.mcpServers;}copyFileSync(path,path+'.bak');chmodSync(path+'.bak',0o600);const temp=path+'.ui-tmp';writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{mode:0o600});renameSync(temp,path);return settings(model);}
|
||||
function previousEngine(){if(packaged)return !!snapshot.engine?.previous;try{const data=snapshot.installed?.data_dir??snapshot.installed?.data_folder;return [join(preferences.repo,'engine/.previous'),data&&join(data,'engine/.previous')].filter(Boolean).some(existsSync)&&readFileSync(join(preferences.repo,'setup.py'),'utf8').includes('--rollback-engine');}catch{return false;}}
|
||||
async function plan(args){await refresh();if(!snapshot.available)throw new Error(snapshot.error);return tool('strata_install',installArgs(args,false));}
|
||||
function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port','gguf_dir'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);/* A model adopted from the person's own GGUF folder reports that folder's parent as its data folder: it is theirs, not Strata's, so a second preparation never uses it for the packs. */if(args.gguf_dir===undefined&&existing?.ownGgufDir)args={...args,gguf_dir:existing.ownGgufDir};const data=nativeDataDirectory(args.data_dir??(args.gguf_dir?undefined:existing?.dataFolder)??preferences.downloadDirectory??modelsDirectory?.());return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),/* One card is "gpu", never "gpus" (the installer wants two or more there: "Gpus='0' is not valid", #3203). */...(/^\d{1,2}$/.test(String(args.gpus??''))?{gpu:Number(args.gpus),gpus:undefined}:{}),/* Picture reading is only downloaded when it was asked for (Read pictures); the default stays the smaller download. */...(packaged&&args.vision===undefined?{vision:'no'}:{}),confirm};}
|
||||
function installArgs(args,confirm){const allowed=['family','model','context','vision','kv','gpu','gpus','backend','low_ram','port','gguf_dir'];const size=snapshot.catalog?.families?.find(f=>f.family===args.family)?.sizes.find(s=>s.model===args.model);const existing=snapshot.installed?.models?.find(m=>m.model===size?.id);/* A model adopted from the person's own GGUF folder reports that folder's parent as its data folder: it is theirs, not Strata's, so a second preparation never uses it for the packs. */if(args.gguf_dir===undefined&&existing?.ownGgufDir)args={...args,gguf_dir:existing.ownGgufDir};const data=nativeDataDirectory(args.data_dir??(args.gguf_dir?undefined:existing?.dataFolder)??preferences.downloadDirectory??modelsDirectory?.());if(data&&packaged&&!args.data_dir)rememberDataFolder(controlSettingsFile(),data);return {...(data?{data_dir:data}:{}),...Object.fromEntries(allowed.filter(k=>args[k]!==undefined).map(k=>[k,args[k]])),/* One card is "gpu", never "gpus" (the installer wants two or more there: "Gpus='0' is not valid", #3203). */...(/^\d{1,2}$/.test(String(args.gpus??''))?{gpu:Number(args.gpus),gpus:undefined}:{}),/* Picture reading is only downloaded when it was asked for (Read pictures); the default stays the smaller download. */...(packaged&&args.vision===undefined?{vision:'no'}:{}),confirm};}
|
||||
|
||||
function begin(kind,run,metadata={}){if([...jobs.values()].some(j=>j.state==='running'))throw new Error('Finish or cancel the current engine operation first.');const job={id:randomUUID(),kind,state:'running',startedAt:new Date().toISOString(),summary:'Starting…',result:null,error:null,...metadata};for(const [id,old] of jobs)if(jobs.size>=12&&old.state!=='running')jobs.delete(id);jobs.set(job.id,job);emit();void run(job).then(result=>{if(job.state==='running'){Object.assign(job,{state:'done',summary:result?.summary??'Complete',result,finishedAt:new Date().toISOString()});}}).catch(error=>{if(job.state==='running')Object.assign(job,{state:'error',error:error.message,summary:error.message,...(error.details?{details:error.details}:{}),finishedAt:new Date().toISOString()});}).finally(()=>{if(job.kind.startsWith('update')||job.kind==='rollback')disconnect();lastRead=0;emit();void refresh(true);});return state().jobs.find(j=>j.id===job.id);}
|
||||
async function watchInstall(job,current){job.summary=current.step??'Resuming preparation status…';job.result={install:current};while(job.state==='running'){await new Promise(r=>setTimeout(r,1500));const result=await tool('strata_install');job.summary=result.summary;job.result=result;emit();if(!result.install?.running){if(result.install?.exit_code!==0)throw new Error(result.install?.error??'Preparation did not finish. Retry to reuse completed files.');return {summary:'Model preparation complete. Load it from Models.'};}}}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { migrateSetup } from './setup.mjs';
|
||||
/** Tiny persisted state for the host: one JSON file under STRATA_HOME. */
|
||||
import { accessSync, constants, mkdirSync, readFileSync, writeFileSync, existsSync, realpathSync, readdirSync, statSync, statfsSync, symlinkSync } from 'node:fs';
|
||||
import { alignModels, isDriveRoot, libraryFolderFromPick, makeFolder } from './model-folder.mjs';
|
||||
import { dirname, isAbsolute, join, parse, relative, resolve } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { defaultModelDirectory } from './model-directory-default.mjs';
|
||||
@@ -75,12 +76,9 @@ export function nativeDataDirectory(input) {
|
||||
if(!input||process.env.STRATA_MODELS_DIR||!existsSync(DEFAULT_MODELS_DIRECTORY))return input;
|
||||
const root=realpathSync(DEFAULT_MODELS_DIRECTORY);
|
||||
if(resolve(input)!==resolve(DEFAULT_MODELS_DIRECTORY)&&realpathSync(input)!==root)return input;
|
||||
const data=dirname(root),nativeModels=join(data,'models');
|
||||
// On Windows/macOS case-insensitive volumes, Models already resolves as models.
|
||||
// On Linux, a relative alias keeps the native layout inside the requested folder.
|
||||
if(!existsSync(nativeModels))symlinkSync(process.platform==='win32'?root:'Models',nativeModels,process.platform==='win32'?'junction':'dir');
|
||||
const a=statSync(nativeModels),b=statSync(root);
|
||||
if(realpathSync(nativeModels)!==root&&!(a.ino&&a.ino===b.ino&&a.dev===b.dev))throw new Error('The default model folder conflicts with another library. Choose a different folder.');
|
||||
const data=dirname(root);
|
||||
// `models` and `Models` are one folder on Windows and macOS; where they are not (Linux) a link makes them one, and where no link can be made (exFAT, a share) models go in `models`.
|
||||
alignModels(data,root);
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -95,6 +93,8 @@ export function validateModelsDirectory(input) {
|
||||
if (!statSync(directory).isDirectory()) throw new Error();
|
||||
accessSync(directory, constants.R_OK | constants.W_OK | constants.X_OK);
|
||||
} catch { throw new Error('This folder is unavailable or not writable. Check the path and folder permissions.'); }
|
||||
// A whole drive (D:\) is not filled with models: D:\Strata\Models is made and used.
|
||||
if (isDriveRoot(directory)) directory = realpathSync(makeFolder(libraryFolderFromPick(directory).path));
|
||||
const data = realpathSync(DATA_DIR);
|
||||
const contains = (parent, child) => { const r = relative(parent, child); return !r || !r.startsWith('..') && !isAbsolute(r); };
|
||||
if (directory === parse(directory).root || contains(directory, data) || contains(data, directory)) throw new Error('Choose a separate folder for models, outside Strata’s app data.');
|
||||
|
||||
@@ -8,18 +8,20 @@ import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog'
|
||||
import { sizeGb } from '../lib/format';
|
||||
import { NativeProgress } from './NativeModels';
|
||||
|
||||
interface Preview { path: string; preview: { file_count: number; total_bytes: number; file_set_status: string; issues: string[]; messages?: string[]; projectors?: { name: string; status: string; pinned: boolean; plain: string }[]; reads_pictures?: boolean; candidate_selection: { family: string; model: string } | null } }
|
||||
interface Preview { path: string; preview: { model_dir?: string; plain_issues?: string[]; already_set_up?: { data_dir?: string | null; pack?: string | null } | null; file_count: number; total_bytes: number; file_set_status: string; issues: string[]; messages?: string[]; projectors?: { name: string; status: string; pinned: boolean; plain: string }[]; reads_pictures?: boolean; candidate_selection: { family: string; model: string } | null } }
|
||||
|
||||
/** The words for why a folder of GGUF files cannot be used: a sentence and what to do, the checker's own codes under Details. */
|
||||
function problem(issues: string[]): { message: string; next: string } {
|
||||
const has = (re: RegExp) => issues.some(i => re.test(i));
|
||||
if (has(/incomplete_or_invalid_shard_set|multiple_model_groups/))
|
||||
return { message: 'Some parts of this model are missing, or the folder holds more than one model.', next: 'Put every part of one model in one folder, then check again.' };
|
||||
if (has(/multiple_model_groups/))
|
||||
return { message: 'This folder holds more than one model.', next: 'Type the full path of the .gguf file of the one you want, or choose the folder of that model.' };
|
||||
if (has(/incomplete_or_invalid_shard_set/))
|
||||
return { message: 'Some parts of this model are missing.', next: 'Put every part of one model (all the -0000N-of-0000M files) in one folder, then check again.' };
|
||||
if (has(/unsupported_architecture|unsupported_or_missing_architecture/))
|
||||
return { message: 'This model type isn’t supported by the Strata engine.', next: 'Add it as a Custom model API instead: start it with llama-server, then open Settings > Models > Add model provider > Custom model API.' };
|
||||
if (has(/unrecognized_or_unsupported_model_variant|expert_quantization|tokenizer/))
|
||||
return { message: 'Strata can’t run these files yet.', next: 'Strata runs the Qwen3.8-Flash-Next models. Download one from Models, or choose a folder with its files.' };
|
||||
return { message: 'These files could not be checked.', next: 'Check that the folder holds complete GGUF files, then try again.' };
|
||||
return { message: 'These files could not be checked.', next: 'Check that the folder holds complete GGUF files, then try again. The file named under Details says what is wrong with it.' };
|
||||
}
|
||||
|
||||
/** "Use a local GGUF": choose the folder of a model you already have, Strata checks it, and prepares and loads it without copying
|
||||
@@ -47,13 +49,16 @@ export function NativeLocalModel({ onBack }: { onBack: () => void }) {
|
||||
catch (e) { setError(e instanceof Error ? e.message : String(e)); }
|
||||
finally { setPending(false); }
|
||||
}
|
||||
/* Files that sit in a Strata data folder (<data>/models/<tag>) with their prepared model data beside them: that folder is used as the data
|
||||
* folder, so the prepared data is not made a second time. A folder the installer would not accept as a data folder is not passed. */
|
||||
const ownDataFolder = (() => { const d = checked?.preview.already_set_up?.pack ? checked.preview.already_set_up.data_dir : null; return d && /strata/i.test(d.split(/[\\/]/).filter(Boolean).pop() ?? '') ? d : null; })();
|
||||
async function prepare() {
|
||||
if (!usable || !selection || !checked)
|
||||
return;
|
||||
setPending(true);
|
||||
setError('');
|
||||
try {
|
||||
const result = await nativeAction<NativeJob>('operations', { kind: 'install', args: { family: selection.family, model: selection.model, gguf_dir: checked.path, context: native?.catalog?.recommendation?.context ?? 32768, vision: checked.preview.projectors?.some(p => p.status === 'ok' && p.pinned) && native?.visionReader ? 'yes' : 'no', kv: 'int8', loadAfter: true } });
|
||||
const result = await nativeAction<NativeJob>('operations', { kind: 'install', args: { family: selection.family, model: selection.model, gguf_dir: checked.preview.model_dir ?? checked.path, ...(ownDataFolder ? { data_dir: ownDataFolder } : {}), context: native?.catalog?.recommendation?.context ?? 32768, vision: checked.preview.projectors?.some(p => p.status === 'ok' && p.pinned) && native?.visionReader ? 'yes' : 'no', kv: 'int8', loadAfter: true } });
|
||||
setJobId(result.id);
|
||||
}
|
||||
catch (e) { setError(e instanceof Error ? e.message : String(e)); }
|
||||
@@ -64,8 +69,8 @@ export function NativeLocalModel({ onBack }: { onBack: () => void }) {
|
||||
<div className="native-model-layout">
|
||||
<div className="stack stack--lg">
|
||||
<section className="st-card native-choice"><h2 className="h3">{tr("Use a local GGUF…")}</h2>
|
||||
<p className="small muted">{tr("Already have a supported model on this computer? Choose the folder that holds its files. Strata checks them, prepares the model and loads it. Nothing is copied or downloaded.")}</p>
|
||||
<label className="input-field"><span>{tr("Folder with the GGUF files")}</span><input className="st-input" value={typed} placeholder={tr("Full path to the folder")} spellCheck={false} onChange={e => setTyped(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && typed.trim()) void check(typed); }}/></label>
|
||||
<p className="small muted">{tr("Already have a supported model on this computer? Choose the folder that holds its files, or one of its .gguf files. Strata checks them, prepares the model and loads it. Nothing is copied or downloaded.")}</p>
|
||||
<label className="input-field"><span>{tr("Folder with the GGUF files, or one .gguf file")}</span><input className="st-input" value={typed} placeholder={tr("Full path to the folder or the file")} spellCheck={false} onChange={e => setTyped(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && typed.trim()) void check(typed); }}/></label>
|
||||
<div className="native-settings-actions"><Btn icon="folder" disabled={pending || !!active} onClick={() => void check('')}>{tr("Choose folder")}</Btn><Btn disabled={pending || !typed.trim() || !!active} onClick={() => void check(typed)}>{tr(pending && !jobId ? 'Checking…' : 'Check files')}</Btn></div>
|
||||
</section>
|
||||
{tr(checked ? <section className="st-card native-choice">{tr(usable ? <>
|
||||
@@ -77,6 +82,8 @@ export function NativeLocalModel({ onBack }: { onBack: () => void }) {
|
||||
</> : <>
|
||||
<h2 className="h3">{tr(found!.message)}</h2>
|
||||
<p className="small muted">{tr(found!.next)}</p>
|
||||
{tr(checked.preview.plain_issues?.map(m => <p className="small muted" key={m}>{tr(m)}</p>))}
|
||||
{tr(checked.preview.messages?.map(m => <p className="small muted" key={m}>{tr(m)}</p>))}
|
||||
{tr(checked.preview.issues.length ? <details><summary className="small">{tr("Details")}</summary><pre className="small muted error-detail-text">{checked.preview.issues.join(String.fromCharCode(10))}</pre></details> : null)}
|
||||
</>)}</section> : null)}
|
||||
{tr(active ? <NativeProgress job={active}/> : job?.state === 'error' ? <ErrorNotice message={job.error ?? job.summary} detail={job.details}/> : job?.state === 'done' ? <p className="small" role="status"><Icon name="check" size={15}/> {tr(job.summary)}</p> : null)}
|
||||
|
||||
@@ -231,4 +231,4 @@ catch (e) {
|
||||
}
|
||||
finally {
|
||||
setStopping(false);
|
||||
} } return <section className="st-card native-progress" aria-live="polite"><div className="section-toolbar"><h2 className="h4">{tr(job.kind === 'install' ? (label ? tr('Preparing {0}', [label]) : 'Preparing your model') : job.kind === 'load' ? 'Loading model' : job.kind === 'autotune' || job.kind === 'recheck' ? 'Tuning your model' : 'Engine operation')}</h2>{tr(job.kind === 'install' || job.kind === 'load' || job.kind === 'autotune' || job.kind === 'recheck' ? <div className="onboard-progress-actions">{tr(eta ? <span className="small muted">{eta}</span> : null)}<Btn size="sm" disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}</Btn></div> : null)}</div><p className="small">{tr(job.kind === 'install' ? (download && /^5\//.test(job.result?.install?.step ?? '') ? stageText(installStage(job.result?.install)) : installStepLabel(job.result?.install?.step)) : job.summary)}</p>{tr(download ? <><progress max={100} value={download.percent ?? 0}/><p className="xs muted">{tr(download.file === 'model files' ? 'Model files' : download.file === 'picture reader' ? 'Picture reader' : download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}</p></> : null)}<DownloadParts parts={job.result?.install?.parts}/>{tr(detailsText ? <details><summary className="small">{tr("Details")}</summary><pre className="small muted error-detail-text">{detailsText}</pre></details> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}</section>; }
|
||||
} } return <section className="st-card native-progress" aria-live="polite"><div className="section-toolbar"><h2 className="h4">{tr(job.kind === 'install' ? (label ? tr('Preparing {0}', [label]) : 'Preparing your model') : job.kind === 'load' ? 'Loading model' : job.kind === 'autotune' || job.kind === 'recheck' ? 'Tuning your model' : 'Engine operation')}</h2>{tr(job.kind === 'install' || job.kind === 'load' || job.kind === 'autotune' || job.kind === 'recheck' ? <div className="onboard-progress-actions">{tr(eta ? <span className="small muted">{eta}</span> : null)}<Btn size="sm" disabled={stopping} onClick={() => void stop()}>{tr(stopping ? 'Stopping…' : 'Stop')}</Btn></div> : null)}</div><p className="small">{tr(job.kind === 'install' ? (job.result?.install?.label ?? (download && /^5\//.test(job.result?.install?.step ?? '') ? stageText(installStage(job.result?.install)) : installStepLabel(job.result?.install?.step))) : job.summary)}</p>{tr(download ? <><progress max={100} value={download.percent ?? 0}/><p className="xs muted">{tr(download.file === 'model files' ? 'Model files' : download.file === 'picture reader' ? 'Picture reader' : download.file === 'checking files' ? 'Checking files' : download.file === 'MTP draft layer' ? 'Draft layer' : download.file)} · {tr(download.percent ?? 0)}%{tr(Number.isFinite(download.done_gb) && Number.isFinite(download.total_gb) ? ` · ${download.done_gb!.toFixed(1)} / ${download.total_gb!.toFixed(1)} GB` : '')}</p></> : null)}<DownloadParts parts={job.result?.install?.parts}/>{tr(detailsText ? <details><summary className="small">{tr("Details")}</summary><pre className="small muted error-detail-text">{detailsText}</pre></details> : null)}{tr(error ? <ErrorNotice message={error}/> : null)}</section>; }
|
||||
@@ -77,6 +77,23 @@ test('a typed path must be an absolute existing directory', async () => {
|
||||
} finally { await rm(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('the model page takes a folder or one .gguf file, with or without quotes around the path', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'strata-gguf-typed-'));
|
||||
try {
|
||||
await writeFile(join(dir, 'model-00001-of-00002.gguf'), 'x');
|
||||
await writeFile(join(dir, 'notes.txt'), 'x');
|
||||
const only = { isAbsolute, fileType: /\.gguf$/i };
|
||||
assert.equal(await typedFolder(dir, only), dir);
|
||||
assert.equal(await typedFolder(join(dir, 'model-00001-of-00002.gguf'), only), join(dir, 'model-00001-of-00002.gguf'));
|
||||
assert.equal(await typedFolder(`"${join(dir, 'model-00001-of-00002.gguf')}"`, only), join(dir, 'model-00001-of-00002.gguf'));
|
||||
assert.equal(await typedFolder(` "${dir}" `, only), dir);
|
||||
await assert.rejects(typedFolder(join(dir, 'notes.txt'), only), /folder, or a \.gguf file/);
|
||||
await assert.rejects(typedFolder(join(dir, 'missing.gguf'), only), /does not exist/);
|
||||
// the other pickers still refuse a file
|
||||
await assert.rejects(typedFolder(join(dir, 'model-00001-of-00002.gguf'), { isAbsolute }), /not a file/);
|
||||
} finally { await rm(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
async function startHost() {
|
||||
const home = await mkdtemp(join(tmpdir(), 'strata-folder-home-'));
|
||||
const net = await import('node:net');
|
||||
|
||||
@@ -32,7 +32,7 @@ test('directory preferences survive restart, scope demo installs, and reject bad
|
||||
import assert from 'node:assert/strict';import {join} from 'node:path';import {existsSync} from 'node:fs';
|
||||
const store=await import('./server/store.mjs');const models=await import('./server/models.mjs');
|
||||
const original=store.MODELS_DIR,id='qwen38-q4_k_m';store.update({installed:{[id]:{simulated:true}},setup:{complete:true,step:4},serving:{apiKey:'fixture-only-key'}});
|
||||
for(const path of ['relative/path',join(store.HOME,'missing'),store.DATA_DIR,store.HOME,'/'])assert.throws(()=>store.validateModelsDirectory(path));
|
||||
for(const path of ['relative/path',join(store.HOME,'missing'),store.DATA_DIR,store.HOME])assert.throws(()=>store.validateModelsDirectory(path));
|
||||
assert.equal(store.MODELS_DIR,original);assert.equal(existsSync(join(store.HOME,'missing')),false);
|
||||
store.changeModelsDirectory(${JSON.stringify(next)});models.init({send(){}});
|
||||
assert.equal(models.isOnDisk(id),false);assert.equal(store.get().setup.complete,true);assert.equal(store.get().serving.apiKey,'fixture-only-key');
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, parse } from 'node:path';
|
||||
import { alignModels, dataFolderFromPick, isDriveRoot, libraryFolderFromPick, makeFolder, rememberDataFolder } from '../server/model-folder.mjs';
|
||||
import { nativeFixture } from './helpers/native-fixture.mjs';
|
||||
|
||||
const scratch = t => { const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-folder-'))); t.after(() => rmSync(dir, { recursive: true, force: true })); return dir; };
|
||||
|
||||
test('a whole drive is not filled with models: it becomes Strata (data) and Strata/Models (library)', () => {
|
||||
const root = parse(tmpdir()).root;
|
||||
assert.equal(isDriveRoot(root), true);
|
||||
assert.equal(isDriveRoot(tmpdir()), false);
|
||||
assert.deepEqual(dataFolderFromPick(root), { path: join(root, 'Strata'), note: `${root} is a whole drive, so the models go in ${join(root, 'Strata')}.` });
|
||||
assert.equal(libraryFolderFromPick(root).path, join(root, 'Strata', 'Models'));
|
||||
assert.deepEqual(dataFolderFromPick(tmpdir()), { path: tmpdir(), note: null });
|
||||
assert.deepEqual(libraryFolderFromPick(tmpdir()), { path: tmpdir(), note: null });
|
||||
});
|
||||
|
||||
test('a folder that cannot be made is said in words', t => {
|
||||
const dir = scratch(t);
|
||||
writeFileSync(join(dir, 'a-file'), 'x');
|
||||
assert.throws(() => makeFolder(join(dir, 'a-file', 'Strata')), /Strata could not create .*Choose another folder\./);
|
||||
assert.equal(makeFolder(join(dir, 'new', 'Strata')), join(dir, 'new', 'Strata'));
|
||||
assert.equal(existsSync(join(dir, 'new', 'Strata')), true);
|
||||
});
|
||||
|
||||
test('models and Models are one folder; a disk that cannot hold the link gets a plain models folder', t => {
|
||||
const dir = scratch(t), library = join(dir, 'Models');
|
||||
mkdirSync(library);
|
||||
const refuses = () => { throw Object.assign(new Error('EPERM: operation not permitted, symlink'), { code: 'EPERM' }); };
|
||||
const result = alignModels(dir, library, { link: refuses });
|
||||
assert.equal(result.linked, false);
|
||||
assert.equal(existsSync(join(dir, 'models')), true);
|
||||
// where the names are one folder already (Windows, macOS) nothing is made; where a link works it is used
|
||||
const other = scratch(t);
|
||||
const calls = [];
|
||||
assert.equal(alignModels(other, join(other, 'Models'), { link: (...args) => { calls.push(args); } }).linked, true);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0][1], join(other, 'models'));
|
||||
});
|
||||
|
||||
test('the data folder is written into the Control settings file, merged and only when it changes', t => {
|
||||
const dir = scratch(t), file = join(dir, 'config', 'app-settings.json');
|
||||
assert.equal(rememberDataFolder(file, 'D:\\Strata'), true);
|
||||
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { data_dir: 'D:\\Strata' });
|
||||
writeFileSync(file, JSON.stringify({ installs: ['C:\\x'], data_dir: 'C:\\old' }));
|
||||
assert.equal(rememberDataFolder(file, 'D:\\Strata'), true);
|
||||
assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { installs: ['C:\\x'], data_dir: 'D:\\Strata' });
|
||||
assert.equal(rememberDataFolder(file, 'D:\\Strata'), false);
|
||||
writeFileSync(file, '\uFEFF{"data_dir":"E:\\\\Strata","installs":[]}');
|
||||
assert.equal(rememberDataFolder(file, 'E:\\Strata'), false);
|
||||
writeFileSync(file, 'not json');
|
||||
assert.equal(rememberDataFolder(file, 'F:\\Strata'), true);
|
||||
assert.equal(rememberDataFolder('', 'F:\\Strata'), false);
|
||||
});
|
||||
|
||||
test('choosing a folder that is gone or cannot be written says so in words', async t => {
|
||||
const f = nativeFixture();
|
||||
t.after(() => f.cleanup());
|
||||
await f.control.refresh();
|
||||
assert.throws(() => f.control.setDownloadDirectory(join(f.repo, 'not-there')), /That folder does not exist\. Check the path, or that the drive is connected\./);
|
||||
assert.throws(() => f.control.setDownloadDirectory(join(f.repo, 'setup.py')), /Choose a folder, not a file\./);
|
||||
});
|
||||
|
||||
test('Windows: a drive picked as D:\\ becomes D:\\Strata, and the person is not asked for a different folder', { skip: process.platform !== 'win32' }, async t => {
|
||||
const dir = scratch(t);
|
||||
const letter = 'QRSTUVWXYZ'.split('').find(l => !existsSync(`${l}:\\`));
|
||||
assert.ok(letter, 'a free drive letter');
|
||||
execFileSync('subst', [`${letter}:`, dir]);
|
||||
t.after(() => { try { execFileSync('subst', [`${letter}:`, '/D']); } catch { /* gone */ } });
|
||||
const f = nativeFixture();
|
||||
t.after(() => f.cleanup());
|
||||
await f.control.refresh();
|
||||
f.control.setDownloadDirectory(`${letter}:\\`);
|
||||
const shown = f.control.state().downloadDirectory;
|
||||
assert.equal(shown.toLowerCase(), `${letter}:\\Strata`.toLowerCase());
|
||||
assert.equal(existsSync(join(dir, 'Strata')), true);
|
||||
assert.equal(readdirNames(dir).includes('Strata'), true);
|
||||
});
|
||||
|
||||
function readdirNames(dir) { return execFileSync('cmd', ['/c', 'dir', '/b', dir]).toString().split(/\r?\n/).filter(Boolean); }
|
||||
|
||||
test('Windows: the model library on a whole drive goes to X:\\Strata\\Models', { skip: process.platform !== 'win32' }, t => {
|
||||
const dir = scratch(t), home = scratch(t);
|
||||
const letter = 'QRSTUVWXYZ'.split('').find(l => !existsSync(`${l}:\\`));
|
||||
execFileSync('subst', [`${letter}:`, dir]);
|
||||
t.after(() => { try { execFileSync('subst', [`${letter}:`, '/D']); } catch { /* gone */ } });
|
||||
const cwd = fileURLToPath(new URL('..', import.meta.url));
|
||||
const drive = `${letter}:\\`;
|
||||
const run = spawnSync(process.execPath, ['--input-type=module', '-e', `const store=await import('./server/store.mjs');console.log(store.validateModelsDirectory(${JSON.stringify(drive)}));`],
|
||||
{ cwd, env: { ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models') }, encoding: 'utf8' });
|
||||
assert.equal(run.status, 0, run.stderr);
|
||||
assert.equal(run.stdout.trim().toLowerCase(), `${drive}Strata\\Models`.toLowerCase());
|
||||
assert.equal(existsSync(join(dir, 'Strata', 'Models')), true);
|
||||
});
|
||||
@@ -166,7 +166,7 @@ test('no recognised engine: the app still downloads, warns in the card, and load
|
||||
|
||||
test('the draft layer download of setup step 6 is a stage of its own and counts in the one figure (#3257)', () => {
|
||||
lib.setTranslationLanguage('en');
|
||||
const draft = { parts: [{ kind: 'model', name: 'Model files', state: 'done', done_gb: 60, total_gb: 60 }, { kind: 'draft', name: 'Speed-up layer', state: 'downloading', done_gb: 2, total_gb: 5 }] };
|
||||
const draft = { parts: [{ kind: 'model', name: 'Model files', state: 'done', done_gb: 60, total_gb: 60 }, { kind: 'draft', name: 'Draft layer', state: 'downloading', done_gb: 2, total_gb: 5 }] };
|
||||
assert.deepEqual(lib.installStage(draft), { kind: 'draft' });
|
||||
assert.equal(lib.stageText(lib.installStage(draft)), 'Preparing your model…');
|
||||
const p = lib.installProgress(draft);
|
||||
|
||||
@@ -215,6 +215,86 @@
|
||||
],
|
||||
"repo": "agentionai/Qwen3.8-Flash-Next-Gyro-GGUF"
|
||||
},
|
||||
"unsloth/UD-Q5_K_XL": {
|
||||
"arch": "qwen4exp",
|
||||
"tensors": 1224,
|
||||
"bytes": 158275381760,
|
||||
"expert_bytes": {
|
||||
"Q5_K": 54211379200,
|
||||
"Q6_K": 1376256000,
|
||||
"Q8_0": 42781900800
|
||||
},
|
||||
"experts_bpw": 6.515,
|
||||
"bpw": 7.156,
|
||||
"files": [
|
||||
"UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00001-of-00006.gguf",
|
||||
"UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00002-of-00006.gguf",
|
||||
"UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00003-of-00006.gguf",
|
||||
"UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00004-of-00006.gguf",
|
||||
"UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00005-of-00006.gguf",
|
||||
"UD-Q5_K_XL/Qwen3.8-Flash-Next-UD-Q5_K_XL-00006-of-00006.gguf"
|
||||
],
|
||||
"repo": "unsloth/Qwen3.8-Flash-Next-GGUF"
|
||||
},
|
||||
"unsloth/UD-Q6_K_XL": {
|
||||
"arch": "qwen4exp",
|
||||
"tensors": 1224,
|
||||
"bytes": 169154357760,
|
||||
"expert_bytes": {
|
||||
"Q6_K": 64684032000,
|
||||
"Q8_0": 44564480000
|
||||
},
|
||||
"experts_bpw": 7.235,
|
||||
"bpw": 7.648,
|
||||
"files": [
|
||||
"UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00001-of-00006.gguf",
|
||||
"UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00002-of-00006.gguf",
|
||||
"UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00003-of-00006.gguf",
|
||||
"UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00004-of-00006.gguf",
|
||||
"UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00005-of-00006.gguf",
|
||||
"UD-Q6_K_XL/Qwen3.8-Flash-Next-UD-Q6_K_XL-00006-of-00006.gguf"
|
||||
],
|
||||
"repo": "unsloth/Qwen3.8-Flash-Next-GGUF"
|
||||
},
|
||||
"unsloth/Q8_0": {
|
||||
"arch": "qwen4exp",
|
||||
"tensors": 1224,
|
||||
"bytes": 188214008320,
|
||||
"expert_bytes": {
|
||||
"Q8_0": 128345702400
|
||||
},
|
||||
"experts_bpw": 8.5,
|
||||
"bpw": 8.51,
|
||||
"files": [
|
||||
"Q8_0/Qwen3.8-Flash-Next-Q8_0-00001-of-00006.gguf",
|
||||
"Q8_0/Qwen3.8-Flash-Next-Q8_0-00002-of-00006.gguf",
|
||||
"Q8_0/Qwen3.8-Flash-Next-Q8_0-00003-of-00006.gguf",
|
||||
"Q8_0/Qwen3.8-Flash-Next-Q8_0-00004-of-00006.gguf",
|
||||
"Q8_0/Qwen3.8-Flash-Next-Q8_0-00005-of-00006.gguf",
|
||||
"Q8_0/Qwen3.8-Flash-Next-Q8_0-00006-of-00006.gguf"
|
||||
],
|
||||
"repo": "unsloth/Qwen3.8-Flash-Next-GGUF"
|
||||
},
|
||||
"swift/IQ3_S": {
|
||||
"arch": "qwen4exp",
|
||||
"tensors": 1224,
|
||||
"bytes": 83732712960,
|
||||
"expert_bytes": {
|
||||
"IQ2_S": 10747904000,
|
||||
"IQ3_S": 7208960000,
|
||||
"IQ3_XXS": 10918297600,
|
||||
"IQ4_NL": 18402508800,
|
||||
"IQ4_XS": 891289600,
|
||||
"Q2_0": 2123366400
|
||||
},
|
||||
"experts_bpw": 3.331,
|
||||
"bpw": 3.786,
|
||||
"files": [
|
||||
"Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
|
||||
"Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf"
|
||||
],
|
||||
"repo": "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF"
|
||||
},
|
||||
"_roles": {
|
||||
"blk.N.attn_gate.weight": [
|
||||
"IQ3_S",
|
||||
|
||||
@@ -134,6 +134,9 @@ variable; the model and tuning stay in `/data`. Anything else: `docker exec stra
|
||||
What is in the volume `/data`: `Strata-data/` (model files, the prepared pack), `state/` (presets, tuning, the key), `install/`
|
||||
(run settings and logs), `home/`. The engine and the Terminal are in the image, so updating the image never touches your files.
|
||||
|
||||
To keep it all on a big disk, mount a folder there instead of the named volume: `-v /mnt/big/strata:/data` (the folder must be writable by the
|
||||
container's user). Nothing large is written anywhere else in the container.
|
||||
|
||||
### Files you already have
|
||||
|
||||
Mount the folder with the model's GGUF files read-only and name it: `-v /srv/gguf/IQ3_XXS:/models:ro -e MODEL_PATH=/models
|
||||
|
||||
@@ -305,6 +305,26 @@ says so and starts the engine you had.
|
||||
GitHub at the commit `LLAMA_CPP_COMMIT` in `setup.py` names. Put that commit's tree in `third_party/llama.cpp`
|
||||
yourself (from a mirror or another PC) and setup uses it instead (#585).
|
||||
|
||||
### Keeping the models on another disk
|
||||
|
||||
The model files are the only big part (70 to 190 GB). Put them where there is room; the app and the Terminal use the same folder.
|
||||
|
||||
- **In the app:** the first screen shows the model folder with a button to change it, and Settings > Storage changes it
|
||||
later. Pick a folder you can save files in; a whole drive (`D:\`) becomes `D:\Strata`, which Strata makes and says so.
|
||||
Models you already have in the old folder stay there and keep working; nothing is moved or deleted for you.
|
||||
- **In the Terminal:** `strata launch --data-dir D:\Strata` once. The folder is remembered for the next `strata launch`
|
||||
and `strata models list`. Until you give it one, the Terminal uses the folder the app chose; the app keeps its own setting
|
||||
(Settings > Storage) and does not read the Terminal's. `--move-data` moves the models you already have into it; without it they stay where they
|
||||
are and the new folder gets the new downloads. Use your own files in place with `strata launch --model-path FOLDER` (a
|
||||
folder of shards, a folder above it, or one `.gguf` file); a folder that holds several sizes needs the one `.gguf` file.
|
||||
- **Drives that are not NTFS** (exFAT, FAT32, a network share) work: Strata writes straight into `<folder>\models` and makes no
|
||||
link there.
|
||||
- **What stays on C:** the engine (`%LOCALAPPDATA%\Strata\components`, 1 to 2 GB per version; `STRATA_COMPONENTS_DIR` moves it),
|
||||
the app itself (the installer asks), your settings, chat history, tuning results and logs (`%LOCALAPPDATA%\Strata`,
|
||||
`%APPDATA%\Strata`; a few MB). Nothing else large: downloads, the prepared model data (`packs`) and the draft layer (`mtp`) are
|
||||
written in the model folder, and so are the half-finished files of an interrupted download.
|
||||
- **Docker:** `-v /mnt/big/strata:/data` (a folder on the big disk) instead of the volume `strata-data`; everything above lives in it.
|
||||
|
||||
## Setup's questions
|
||||
|
||||
These are the questions of the installer from source (`START-HERE.bat`, `./setup.sh`). The app's first screen and
|
||||
|
||||
@@ -2526,7 +2526,7 @@ def gguf_dir_problem(folder: Path, first: Path, fam: dict, model: str) -> tuple
|
||||
return f"{folder} has no {fam['title']} {model} file", hint
|
||||
|
||||
|
||||
def verify_sha256(s: Path, size: int, sha: str) -> None:
|
||||
def verify_sha256(s: Path, size: int, sha: str, own: bool = False) -> None:
|
||||
"""A shard's size and SHA-256 against the pinned values (the Unsloth file); the result is kept in its finish mark,
|
||||
so the ~5 minutes of hashing 111 GB happen once. A wrong file is deleted, so the next run downloads it again."""
|
||||
m = s.with_name(s.name + ".done")
|
||||
@@ -2534,16 +2534,29 @@ def verify_sha256(s: Path, size: int, sha: str) -> None:
|
||||
return
|
||||
have = s.stat().st_size if s.exists() else -1
|
||||
if have != size:
|
||||
if own: # --gguf-dir: the person's own file is never deleted by setup
|
||||
fail(f"{s.name} is {have:,} bytes; the published file is {size:,}",
|
||||
"it may be cut short or another version; your file was left as it is. Copy the whole published file into the folder")
|
||||
fail(f"{s.name} is {have:,} bytes, not {size:,}", "delete it and run setup again (the download restarts)")
|
||||
say(f" checking {s.name} (SHA-256, {size / 1e9:.1f} GB) ...")
|
||||
h = hashlib.sha256()
|
||||
seen, last = 0, 0.0
|
||||
with open(s, "rb") as f:
|
||||
while True:
|
||||
b = f.read(16 << 20)
|
||||
if not b:
|
||||
break
|
||||
h.update(b)
|
||||
seen += len(b)
|
||||
if time.time() - last > 2 and size >= (1 << 30): # a figure for the app and the Terminal: hashing 60 GB takes minutes
|
||||
last = time.time()
|
||||
print(f"\r checking {s.name}: {seen / 1e9:6.2f} / {size / 1e9:.2f} GB ({100 * seen // size}%) ", end="", flush=True)
|
||||
if seen >= (1 << 30):
|
||||
print()
|
||||
if h.hexdigest() != sha:
|
||||
if own:
|
||||
fail(f"{s.name} does not match the published file (SHA-256 {h.hexdigest()}, expected {sha})",
|
||||
"it may be damaged or another version; your file was left as it is. Copy the whole published file into the folder")
|
||||
s.unlink(missing_ok=True)
|
||||
m.unlink(missing_ok=True)
|
||||
fail(f"{s.name} has the wrong SHA-256 ({h.hexdigest()}, expected {sha}): deleted",
|
||||
@@ -7074,7 +7087,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
|
||||
if a.gguf_dir:
|
||||
fail(f"{gguf} is missing", f"put {gguf.name} in {folder}, or drop --gguf-dir to download it")
|
||||
download(fam["hf"] + gguf.name, gguf)
|
||||
verify_sha256(gguf, *fam["sha256"][gguf.name])
|
||||
verify_sha256(gguf, *fam["sha256"][gguf.name], own=bool(a.gguf_dir))
|
||||
ok(f"model file: {gguf}")
|
||||
mmproj = folder / fam["mmproj"]
|
||||
if vision != "none": # the image encoder: Unsloth's mmproj, pinned, size + SHA-256 checked
|
||||
@@ -7084,7 +7097,7 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte
|
||||
if a.gguf_dir:
|
||||
fail(f"{mmproj} is missing", f"put {mmproj.name} in {folder}, or drop --gguf-dir to download it")
|
||||
download(fam["mmproj_hf"] + mmproj.name, mmproj, "vision encoder")
|
||||
verify_sha256(mmproj, *fam["sha256"][mmproj.name])
|
||||
verify_sha256(mmproj, *fam["sha256"][mmproj.name], own=bool(a.gguf_dir))
|
||||
ok(f"vision encoder: {mmproj}")
|
||||
|
||||
step(6, "preparing the model for Strata")
|
||||
@@ -8250,7 +8263,7 @@ def main() -> int:
|
||||
check_shards(shards)
|
||||
for s in ([] if ready else shards): # the Unsloth files: pinned sizes and SHA-256
|
||||
if s.name in fam.get("sha256", {}):
|
||||
verify_sha256(s, *fam["sha256"][s.name])
|
||||
verify_sha256(s, *fam["sha256"][s.name], own=bool(a.gguf_dir))
|
||||
ok("model files present")
|
||||
mmproj = Path(a.models_dir) / fam.get("mmproj", MMPROJ)
|
||||
if not mmproj.exists(): # an earlier install's copy (the same file for every family)
|
||||
|
||||
+2
-5
@@ -597,12 +597,9 @@ def _import_problem(plan: dict) -> str:
|
||||
issues = [x for x in issues if x != "unrecognized_or_unsupported_model_variant"]
|
||||
words = "; ".join(dict.fromkeys(plain_issue(x) for x in issues))
|
||||
text = f"These files cannot be used as they are: {words}."
|
||||
holds = plan.get("folder_holds") or []
|
||||
holds = next((m for m in plan.get("messages") or [] if "holds" in m), "")
|
||||
if holds:
|
||||
known = [f"{h['family']} {h['model']} ({h['file']})" for h in holds if h.get("model")]
|
||||
other = [h["file"] for h in holds if not h.get("model")]
|
||||
text += " The folder holds " + str(len(holds)) + " models" + (": " + ", ".join(known + other) if known or other else "") + \
|
||||
". Point at the .gguf file of the one you want."
|
||||
text += " " + holds
|
||||
return text
|
||||
|
||||
|
||||
|
||||
+36
-39
@@ -280,11 +280,12 @@ def launch_dir() -> Path:
|
||||
# ----------------------------------------------------------------------------------------------- the runner
|
||||
|
||||
|
||||
def download_text(dl: dict, already: bool) -> str:
|
||||
"""The step line for the model download. A model whose files were all on disk before this run says so instead of "Downloading 58.5 of 58.5 GB"."""
|
||||
def download_text(dl: dict, already: bool, label: str | None = None) -> str:
|
||||
"""The step line for a download or a check. `label` is what is being fetched, in words (strata_control/progress_words.py). A model whose
|
||||
files were all on disk before this run says so instead of "Downloading 58.5 of 58.5 GB"."""
|
||||
if already:
|
||||
return f"Model already downloaded ({dl['total_gb']:.1f} GB), checking the files"
|
||||
return f"Downloading {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB"
|
||||
return f"The model files are already on this computer ({dl['total_gb']:.1f} GB); checking them"
|
||||
return f"{label}: {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB" if label else f"Downloading {dl['done_gb']:.1f} of {dl['total_gb']:.1f} GB"
|
||||
|
||||
|
||||
class Runner:
|
||||
@@ -511,6 +512,8 @@ class Runner:
|
||||
args += ["--data-dir", str(data)]
|
||||
if self.move_data and s.data_dir: # only when the person said so: setup moves nothing otherwise
|
||||
args.append("--move-data")
|
||||
if s.data_dir: # a folder the person chose is remembered for the next start and for the app
|
||||
args.append("--set-default-data-dir")
|
||||
if s.model_path:
|
||||
p = Path(s.model_path)
|
||||
args += ["--gguf-dir", str(p if p.is_dir() else p.parent)]
|
||||
@@ -518,8 +521,9 @@ class Runner:
|
||||
args += ["--gpus", ",".join(str(g) for g in s.gpus)] if len(s.gpus) > 1 else ["--gpu", str(s.gpus[0])]
|
||||
if sys.platform == "darwin":
|
||||
# a Mac's setup (Control mode, strata_control/mac_fit.py) takes fewer options (no --kv, --gpu, speed projection)
|
||||
keep = {"--yes", "--no-start", "--family", "--model", "--context", "--vision", "--data-dir", "--gguf-dir", "--move-data"}
|
||||
flags = ("--yes", "--no-start", "--move-data")
|
||||
keep = {"--yes", "--no-start", "--family", "--model", "--context", "--vision", "--data-dir", "--gguf-dir", "--move-data",
|
||||
"--set-default-data-dir"}
|
||||
flags = ("--yes", "--no-start", "--move-data", "--set-default-data-dir")
|
||||
out, i = [], 0
|
||||
while i < len(args):
|
||||
if args[i] in keep:
|
||||
@@ -591,7 +595,7 @@ class Runner:
|
||||
|
||||
def ensure_model(self) -> Path:
|
||||
s, cat = self.s, self.catalog
|
||||
if s.model_path and not (s.family and s.model):
|
||||
if s.model_path:
|
||||
self.resolve_own_files()
|
||||
self.resolved_vision()
|
||||
if not (s.family and s.model):
|
||||
@@ -632,15 +636,17 @@ class Runner:
|
||||
if not line:
|
||||
continue
|
||||
lines.append(line)
|
||||
lines[:] = lines[-400:]
|
||||
lines[:] = lines[-1500:]
|
||||
prog = cat.mcp.install_progress(lines)
|
||||
prog = cat.mcp.combined_progress(prog, {"folder": folder, "total_gb": total})
|
||||
dl = prog.get("download")
|
||||
if dl and not s.model_path and dl.get("total_gb", 0) >= 0.05:
|
||||
if already is None:
|
||||
dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label")
|
||||
if dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"):
|
||||
if phase == "download" and already is None:
|
||||
already = float(dl["percent"]) >= 99.5
|
||||
text = download_text(dl, already)
|
||||
text = download_text(dl, bool(already) and phase == "download", label)
|
||||
self.emit("model", text, float(dl["percent"]), step=prog.get("step"))
|
||||
elif label:
|
||||
self.emit("model", label, None, step=prog.get("step"))
|
||||
elif prog.get("step"):
|
||||
self.emit("model", f"Setup step {prog['step']}", None, step=prog.get("step"))
|
||||
code = p.wait()
|
||||
@@ -702,20 +708,34 @@ class Runner:
|
||||
return path
|
||||
|
||||
def resolve_own_files(self) -> None:
|
||||
""""Use model files I already have": the fingerprint table says which catalog model the files are."""
|
||||
""""Use model files I already have": the fingerprint table says which catalog model the files are, and which folder holds them (the
|
||||
person may have named the folder above it). When the person also named the model (--model), the files are never refused here: setup
|
||||
takes the files of that model out of the folder by name, as it always did (0.1.45), and says what is wrong when it cannot."""
|
||||
from strata_control import models
|
||||
s = self.s
|
||||
given = bool(s.family and s.model)
|
||||
try:
|
||||
plan = models.plan_import(str(Path(s.model_path).expanduser().resolve()))
|
||||
plan = models.plan_import(models.absolute(s.model_path))
|
||||
except Exception as e: # noqa: BLE001
|
||||
if given:
|
||||
return
|
||||
raise LaunchError(f"These model files cannot be used: {e}.", "Pick the folder with every shard of one model, or a .gguf file of it.", 5) from None
|
||||
if given:
|
||||
hold = [h for h in plan.get("folder_holds") or [] if (h.get("family"), h.get("model")) == (s.family, s.model)]
|
||||
if len(hold) == 1 and hold[0].get("folder"):
|
||||
s.model_path = hold[0]["folder"]
|
||||
elif not plan.get("issues"):
|
||||
s.model_path = models.import_target(s.model_path, plan)
|
||||
return
|
||||
sel = plan.get("candidate_selection") or {}
|
||||
fam, model = sel.get("family"), sel.get("model")
|
||||
if not (fam and model) or plan.get("issues"):
|
||||
issues = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows"
|
||||
raise LaunchError(f"These files cannot be used as they are ({issues}).",
|
||||
more = " " + next((m for m in plan.get("messages") or [] if "holds" in m), "")
|
||||
raise LaunchError(f"These files cannot be used as they are ({issues}).{more.rstrip()}",
|
||||
"Choose the matching model in the list, or check that every shard is in the folder.", 5)
|
||||
s.family, s.model = fam, model
|
||||
s.model_path = models.import_target(s.model_path, plan)
|
||||
self.emit("model", f"These files are {fam} {model}.", None)
|
||||
|
||||
# ---- 3. config and profile
|
||||
@@ -925,30 +945,7 @@ class Runner:
|
||||
return out
|
||||
|
||||
|
||||
ISSUE_WORDS = {
|
||||
"multiple_model_groups": "the folder holds more than one model",
|
||||
"incomplete_or_invalid_shard_set": "some shards are missing",
|
||||
"unrecognized_or_unsupported_model_variant": "this is not a model size Strata knows",
|
||||
"unsupported_or_missing_architecture": "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)",
|
||||
"unsupported_or_incomplete_tokenizer_metadata": "the file has no usable tokenizer",
|
||||
"missing_or_unexpected_expert_quantization": "its quantization is not one Strata knows",
|
||||
}
|
||||
|
||||
|
||||
def plain_issue(code: str) -> str:
|
||||
"""One problem from the GGUF preview, in words (it may be `file.gguf: GGUF shard is not a nonempty regular file` and the like)."""
|
||||
if code in ISSUE_WORDS:
|
||||
return ISSUE_WORDS[code]
|
||||
low = code.lower()
|
||||
if "not a nonempty regular file" in low or "unreadable" in low:
|
||||
return "a file is empty, unreadable or not a regular file"
|
||||
if "does not begin with a gguf header" in low or "header version" in low:
|
||||
return "a file is not a GGUF model file"
|
||||
if "unsupported_architecture" in low:
|
||||
return "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)"
|
||||
if "symlink" in low:
|
||||
return "a file is a shortcut (symbolic link); point at the real file"
|
||||
return code.replace("_", " ")
|
||||
from strata_control.models import ISSUE_WORDS, plain_issue # noqa: E402,F401 (one wording for the app, the Terminal and `models import`)
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict | None:
|
||||
|
||||
@@ -495,14 +495,14 @@ class ModelScreen(Base):
|
||||
from strata_cli.launch.runner import plain_issue
|
||||
from strata_control import models
|
||||
try:
|
||||
plan = models.plan_import(str(Path(path).expanduser().resolve()))
|
||||
plan = models.plan_import(models.absolute(path))
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.say(f"These files cannot be used: {e}. Pick the folder with every shard of one model, or a .gguf file of it.", True)
|
||||
return
|
||||
sel = plan.get("candidate_selection") or {}
|
||||
if sel.get("family") and sel.get("model") and not plan.get("issues"):
|
||||
s = self.ctx.settings
|
||||
s.model_path, s.family, s.model = str(Path(path).expanduser()), sel["family"], sel["model"]
|
||||
s.model_path, s.family, s.model = models.import_target(path, plan), sel["family"], sel["model"]
|
||||
self.ctx.picked_in_list = False
|
||||
self.close_field("own")
|
||||
gb = plan.get("total_bytes", 0) / 1e9
|
||||
@@ -511,7 +511,9 @@ class ModelScreen(Base):
|
||||
self.paint()
|
||||
else:
|
||||
why = "; ".join(plain_issue(str(x)) for x in (plan.get("issues") or [])[:3]) or "they are not a model Strata knows"
|
||||
self.say(f"These files cannot be used as they are ({why}). Check that every shard is in the folder, or pick a model from the list.", True)
|
||||
holds = next((m for m in plan.get("messages") or [] if "holds" in m), "")
|
||||
self.say(f"These files cannot be used as they are ({why}). " + (holds + " " if holds else "") +
|
||||
"Check that every shard is in the folder, or pick a model from the list.", True)
|
||||
|
||||
def action_back(self) -> None:
|
||||
if self.input_open():
|
||||
|
||||
@@ -86,12 +86,27 @@ class _Reader:
|
||||
return None
|
||||
|
||||
|
||||
def inspect_metadata(path: Path) -> dict:
|
||||
"""Return only bounded compatibility signals from one regular GGUF v3 shard."""
|
||||
def real_model_file(path: Path) -> Path:
|
||||
"""The regular file a model path stands for. A model file the person picked can be a link (a Hugging Face cache snapshot, an
|
||||
Ollama blob, a shortcut to a bigger drive): it is followed here, once, and the target is what gets opened. Strata's own state files
|
||||
(run configs, profiles, runtime records) keep the strict no-link rule in their readers."""
|
||||
try:
|
||||
if stat.S_ISLNK(path.lstat().st_mode):
|
||||
raise ProfileError("GGUF shard is a symlink", 5)
|
||||
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
target = Path(os.path.realpath(path))
|
||||
info = target.stat()
|
||||
except OSError:
|
||||
if os.path.islink(path):
|
||||
raise ProfileError(f"{Path(path).name} is a link to a file that is not there", 5) from None
|
||||
raise ProfileError(f"{Path(path).name} is missing", 5) from None
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
raise ProfileError("GGUF shard must be a regular file", 5)
|
||||
return target
|
||||
|
||||
|
||||
def inspect_metadata(path: Path) -> dict:
|
||||
"""Return only bounded compatibility signals from one regular GGUF v3 shard (a link to one is followed)."""
|
||||
try:
|
||||
path = real_model_file(Path(path))
|
||||
descriptor = os.open(path, os.O_RDONLY)
|
||||
with os.fdopen(descriptor, "rb") as stream:
|
||||
details = os.fstat(stream.fileno())
|
||||
if not stat.S_ISREG(details.st_mode):
|
||||
@@ -102,7 +117,8 @@ def inspect_metadata(path: Path) -> dict:
|
||||
version, tensors, keys = reader.u32(), reader.u64(), reader.u64()
|
||||
if version != 3:
|
||||
raise ProfileError("Strata metadata preflight requires GGUF v3", 5)
|
||||
if not 1 <= tensors <= MAX_TENSORS or keys > MAX_METADATA_KEYS:
|
||||
# tensors == 0 is a real file: a split set made with llama.cpp's gguf-split (Unsloth's) keeps only the metadata in its first shard
|
||||
if not 0 <= tensors <= MAX_TENSORS or keys > MAX_METADATA_KEYS:
|
||||
raise ProfileError("GGUF tensor or metadata count exceeds the inspection limit", 5)
|
||||
found: dict[str, object] = {}
|
||||
for _ in range(keys):
|
||||
@@ -159,7 +175,7 @@ def inspect_metadata(path: Path) -> dict:
|
||||
extents.sort()
|
||||
if any(next_start < end for (_, end), (next_start, _) in zip(extents, extents[1:])):
|
||||
raise ProfileError("GGUF tensor byte ranges overlap", 5)
|
||||
if data_start + required_payload_bytes > details.st_size:
|
||||
if tensors and data_start + required_payload_bytes > details.st_size:
|
||||
raise ProfileError("GGUF tensor payload is shorter than its directory requires", 5)
|
||||
if tensors == 1 and details.st_size - (data_start + required_payload_bytes) >= 64:
|
||||
raise ProfileError("single-tensor GGUF shard has unexplained trailing bytes", 5)
|
||||
|
||||
+232
-54
@@ -23,7 +23,7 @@ from pathlib import Path
|
||||
|
||||
from strata_control import discovery
|
||||
from strata_control.doctor import inspect as inspect_components
|
||||
from strata_control.gguf_preflight import inspect_metadata
|
||||
from strata_control.gguf_preflight import inspect_metadata, real_model_file
|
||||
from strata_control.profiles import ProfileError
|
||||
|
||||
|
||||
@@ -34,8 +34,9 @@ MAX_CONFIGS = 128
|
||||
MAX_IMPORT_SHARDS = 128
|
||||
SHARD = re.compile(r"(.+)-(\d{5})-of-(\d{5})\.gguf\Z", re.I)
|
||||
SUPPORTED_SELECTIONS = frozenset({"qwen/Q2_0", "qwen/IQ2_XS", "qwen/IQ3_XXS", "qwen/IQ3_S",
|
||||
"swift/IQ2_XS", "swift/IQ3_XXS", "coder/IQ1_M",
|
||||
"unsloth/UD-IQ4_XS", "unsloth/UD-Q4_K_XL", "gyro/Gyro-S", "gyro/Gyro-M"})
|
||||
"swift/IQ2_XS", "swift/IQ3_XXS", "swift/IQ3_S", "coder/IQ1_M",
|
||||
"unsloth/UD-IQ4_XS", "unsloth/UD-Q4_K_XL", "unsloth/UD-Q5_K_XL", "unsloth/UD-Q6_K_XL",
|
||||
"unsloth/Q8_0", "gyro/Gyro-S", "gyro/Gyro-M"})
|
||||
|
||||
|
||||
def settings_path() -> Path:
|
||||
@@ -216,10 +217,10 @@ def inspect(model_id: str, override: str | None = None) -> dict:
|
||||
|
||||
|
||||
def _gguf_header(path: Path) -> dict:
|
||||
"""The first bytes of one model file (a link to it is followed: Hugging Face cache snapshots and Ollama blobs are links)."""
|
||||
real = real_model_file(path)
|
||||
try:
|
||||
if stat.S_ISLNK(path.lstat().st_mode):
|
||||
raise ProfileError("GGUF shard is a symlink", 5)
|
||||
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
descriptor = os.open(real, os.O_RDONLY)
|
||||
with os.fdopen(descriptor, "rb") as stream:
|
||||
details = os.fstat(stream.fileno())
|
||||
if not stat.S_ISREG(details.st_mode) or details.st_size < 8:
|
||||
@@ -293,6 +294,51 @@ def _already_set_up(shards: list[Path], candidate: dict | None) -> dict | None:
|
||||
return {"config": str(cfg) if cfg else None, **{k: (str(v) if v else None) for k, v in beside.items()}}
|
||||
|
||||
|
||||
ISSUE_WORDS = {
|
||||
"multiple_model_groups": "the folder holds more than one model",
|
||||
"incomplete_or_invalid_shard_set": "some parts of the model are missing",
|
||||
"unrecognized_or_unsupported_model_variant": "this is not a model size Strata knows",
|
||||
"unsupported_or_missing_architecture": "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)",
|
||||
"unsupported_or_incomplete_tokenizer_metadata": "the file has no usable tokenizer",
|
||||
"missing_or_unexpected_expert_quantization": "its quantization is not one Strata knows",
|
||||
}
|
||||
# the checker's own sentences about one file, in words
|
||||
_REASON_WORDS = (
|
||||
("not a nonempty regular file", "the file is empty or is not a file"),
|
||||
("unreadable", "the file cannot be read (is it open in another program, or on a drive that is gone?)"),
|
||||
("could not be read", "the file cannot be read (is it open in another program, or on a drive that is gone?)"),
|
||||
("is missing", "the file is not there"),
|
||||
("link to a file that is not there", "this is a shortcut to a file that is not there any more"),
|
||||
("does not begin with a gguf header", "this is not a GGUF model file"),
|
||||
("header version", "this GGUF is from a format Strata does not read"),
|
||||
("requires gguf v3", "this GGUF is in an old format (version 2); Strata reads version 3"),
|
||||
("metadata is truncated", "the file is cut short (a download or copy that did not finish)"),
|
||||
("payload is shorter", "the file is shorter than its own header says (a download or copy that did not finish)"),
|
||||
("exceeds the bounded inspection limit", "its header is larger than Strata reads"),
|
||||
("too large to inspect", "its header is larger than Strata reads"),
|
||||
("unsupported encoding or shape", "it stores weights in a format Strata does not read"),
|
||||
("unsupported array type", "its header uses a type Strata does not read"),
|
||||
("unsupported value type", "its header uses a type Strata does not read"),
|
||||
("byte ranges overlap", "its header is damaged"),
|
||||
("unsupported_architecture", "this model type is not supported by the Strata engine (add it as a Custom model API with llama-server instead)"),
|
||||
("symlink", "this is a shortcut (symbolic link) that cannot be followed"),
|
||||
)
|
||||
|
||||
|
||||
def plain_issue(code: str) -> str:
|
||||
"""One problem from the GGUF preview, in words, with the file's name when it is about one file
|
||||
(`file.gguf: GGUF shard is not a nonempty regular file`)."""
|
||||
code = str(code)
|
||||
if code in ISSUE_WORDS:
|
||||
return ISSUE_WORDS[code]
|
||||
name, sep, reason = code.partition(": ")
|
||||
if not (sep and name.lower().endswith(".gguf")):
|
||||
name, reason = "", code
|
||||
low = reason.lower()
|
||||
words = next((w for key, w in _REASON_WORDS if key in low), reason.replace("_", " "))
|
||||
return f"{name}: {words}" if name else words
|
||||
|
||||
|
||||
UNSUPPORTED_MODEL_TYPE = ("This model type isn't supported by the Strata engine. "
|
||||
"Add it as a Custom model API (llama-server) instead.")
|
||||
# The picture readers Strata ships a pinned copy of (setup downloads and checks one of these next to the model).
|
||||
@@ -333,31 +379,161 @@ def _assess_projector(path: Path) -> dict:
|
||||
return row
|
||||
|
||||
|
||||
MAX_LISTED = 5000 # .gguf files looked at in one folder (the checker reads headers of the chosen set only)
|
||||
MAX_TREE_DIRS = 300 # folders looked into when the picked folder holds no GGUF itself
|
||||
TREE_DEPTH = 3
|
||||
SKIP_DIRS = frozenset({"packs", "mtp", "engine", "node_modules", "windows", "program files", "program files (x86)",
|
||||
"$recycle.bin", "system volume information", "appdata"})
|
||||
|
||||
|
||||
def _list_gguf(folder: Path) -> tuple[list[Path], list[str], bool]:
|
||||
"""(model files, picture-reader file names, cut) of one folder. A link to a file counts (it is followed when read); a name that
|
||||
only ends in .gguf but is a folder does not."""
|
||||
shards: list[Path] = []
|
||||
readers: list[str] = []
|
||||
cut = False
|
||||
try:
|
||||
with os.scandir(folder) as entries:
|
||||
for entry in entries:
|
||||
low = entry.name.lower()
|
||||
if not low.endswith(".gguf"):
|
||||
continue
|
||||
try:
|
||||
is_file = entry.is_file() or entry.is_symlink()
|
||||
except OSError:
|
||||
is_file = False
|
||||
if not is_file:
|
||||
continue
|
||||
if low.startswith("mmproj"):
|
||||
readers.append(entry.name)
|
||||
continue
|
||||
if len(shards) >= MAX_LISTED:
|
||||
cut = True
|
||||
break
|
||||
shards.append(Path(entry.path))
|
||||
except OSError:
|
||||
raise ProfileError("cannot inspect GGUF directory", 5) from None
|
||||
return shards, readers, cut
|
||||
|
||||
|
||||
def _folders_with_models(root: Path) -> list[Path]:
|
||||
"""The folders under `root` (a Strata data folder, a whole Hugging Face repository, a drive's model folder) that hold model files,
|
||||
breadth first, `TREE_DEPTH` levels deep. A folder with models is not searched further."""
|
||||
found: list[Path] = []
|
||||
seen: set[str] = set()
|
||||
queue = [(root, 0)]
|
||||
while queue and len(seen) < MAX_TREE_DIRS:
|
||||
folder, depth = queue.pop(0)
|
||||
try:
|
||||
key = os.path.normcase(os.path.realpath(folder))
|
||||
except OSError:
|
||||
continue
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
try:
|
||||
with os.scandir(folder) as scan:
|
||||
entries = sorted(scan, key=lambda e: e.name.lower())
|
||||
except OSError:
|
||||
continue
|
||||
if any(e.name.lower().endswith(".gguf") and not e.name.lower().startswith("mmproj") for e in entries):
|
||||
found.append(folder)
|
||||
continue
|
||||
if depth >= TREE_DEPTH:
|
||||
continue
|
||||
for e in entries:
|
||||
try:
|
||||
if e.is_dir() and not e.name.startswith(".") and e.name.lower() not in SKIP_DIRS:
|
||||
queue.append((Path(e.path), depth + 1))
|
||||
except OSError:
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
def _split_groups(shards: list[Path]) -> dict:
|
||||
"""Model files by set: (name before -0000i-of-0000N, N) -> files. A file with no shard number is a set of its own."""
|
||||
groups: dict = {}
|
||||
for item in shards:
|
||||
match = SHARD.fullmatch(item.name)
|
||||
key = (match.group(1), int(match.group(3))) if match else (item.name, 1)
|
||||
groups.setdefault(key, []).append(item)
|
||||
return groups
|
||||
|
||||
|
||||
def _known(members: list[Path]) -> dict | None:
|
||||
try:
|
||||
return _candidate_selection(sorted(members, key=lambda item: item.name))
|
||||
except ProfileError:
|
||||
return None
|
||||
|
||||
|
||||
def _holds(groups_by_place: list) -> list[dict]:
|
||||
"""What a folder (or several) holds, set by set, for the message that asks the person to point at one."""
|
||||
rows = []
|
||||
for place, members_by_key in groups_by_place:
|
||||
for key in sorted(members_by_key):
|
||||
members = sorted(members_by_key[key], key=lambda item: item.name)
|
||||
sel = _known(members)
|
||||
rows.append({"file": members[0].name, "files": len(members), "folder": str(place),
|
||||
"family": sel["family"] if sel else None, "model": sel["model"] if sel else None})
|
||||
return rows
|
||||
|
||||
|
||||
def absolute(picked: str) -> str:
|
||||
"""The picked path as an absolute path, links left alone (a snapshot file in the Hugging Face cache keeps its model name)."""
|
||||
return os.path.abspath(os.path.expanduser(str(picked)))
|
||||
|
||||
|
||||
def import_target(picked: str, plan: dict) -> str:
|
||||
"""What to hand on as the person's model files: the file when they picked a file (a folder of several sizes needs the name), else the
|
||||
folder the model files are really in (they may have picked the folder above it)."""
|
||||
picked = absolute(picked)
|
||||
try:
|
||||
if Path(picked).is_file():
|
||||
return picked
|
||||
except OSError:
|
||||
pass
|
||||
return plan.get("model_dir") or picked
|
||||
|
||||
|
||||
def plan_import(raw_path: str) -> dict:
|
||||
"""Inspect a local candidate without copying, parsing tensors or adopting it."""
|
||||
"""Inspect a local candidate without copying, parsing tensors or adopting it.
|
||||
|
||||
The picked path can be a .gguf file (any shard of a split set), the folder with the files, or a folder above it (a Strata data
|
||||
folder, a whole Hugging Face repository): the folder with the model is looked for, and when a folder holds several models
|
||||
the one Strata knows is used if it is the only one; with two it says which and asks for the file. The result's `model_dir`
|
||||
is the folder to hand to setup (--gguf-dir). Links to files and folders are followed."""
|
||||
path = Path(raw_path).expanduser()
|
||||
if not path.is_absolute():
|
||||
raise ProfileError("model import path must be absolute")
|
||||
try:
|
||||
details = path.lstat()
|
||||
details = path.stat()
|
||||
except OSError:
|
||||
raise ProfileError("model import path does not exist", 5) from None
|
||||
if stat.S_ISLNK(details.st_mode):
|
||||
raise ProfileError("model import path must not be a symlink", 5)
|
||||
raise ProfileError("model import path does not exist (or is a link to something that is gone)", 5) from None
|
||||
notes: list[str] = []
|
||||
folder_holds: list[dict] = []
|
||||
issues: list[str] = []
|
||||
if stat.S_ISDIR(details.st_mode):
|
||||
try:
|
||||
shards = []
|
||||
ignored_auxiliary = []
|
||||
for child in path.iterdir():
|
||||
if child.name.lower().endswith(".gguf"):
|
||||
if child.name.lower().startswith("mmproj"):
|
||||
ignored_auxiliary.append(child.name)
|
||||
continue
|
||||
shards.append(child)
|
||||
if len(shards) > MAX_IMPORT_SHARDS:
|
||||
raise ProfileError("more than 128 GGUF candidates in the directory", 5)
|
||||
except OSError:
|
||||
raise ProfileError("cannot inspect GGUF directory", 5) from None
|
||||
shards, ignored_auxiliary, cut = _list_gguf(path)
|
||||
if cut:
|
||||
notes.append(f"This folder holds more than {MAX_LISTED} GGUF files; only the first {MAX_LISTED} were looked at.")
|
||||
if not shards:
|
||||
places = _folders_with_models(path)
|
||||
if not places:
|
||||
raise ProfileError("no GGUF files found at the model import path (or in the folders inside it)", 5)
|
||||
scanned = [(place, *_list_gguf(place)[:2]) for place in places]
|
||||
usable = [(place, files, readers, members) for place, files, readers in scanned
|
||||
for _key, members in sorted(_split_groups(files).items(), key=lambda kv: kv[0]) if _known(members)]
|
||||
if len(usable) == 1:
|
||||
place, shards, ignored_auxiliary, members = usable[0]
|
||||
notes.append(f"The model files are in {place}.")
|
||||
else:
|
||||
place, shards, ignored_auxiliary = scanned[0]
|
||||
if len(usable) > 1 or len(scanned) > 1:
|
||||
issues.append("multiple_model_groups")
|
||||
folder_holds = _holds([(p, _split_groups(f)) for p, f, _r in scanned])
|
||||
else:
|
||||
notes.append(f"The model files are in {place}.")
|
||||
elif stat.S_ISREG(details.st_mode) and path.name.lower().endswith(".gguf"):
|
||||
ignored_auxiliary = []
|
||||
try: # the picture reader that sits next to a chosen model file
|
||||
@@ -382,31 +558,24 @@ def plan_import(raw_path: str) -> dict:
|
||||
if not shards:
|
||||
raise ProfileError("no GGUF files found at the model import path", 5)
|
||||
shards.sort(key=lambda item: item.name)
|
||||
groups = {}
|
||||
for item in shards:
|
||||
match = SHARD.fullmatch(item.name)
|
||||
if match:
|
||||
key = (match.group(1), int(match.group(3)))
|
||||
groups.setdefault(key, set()).add(int(match.group(2)))
|
||||
groups = _split_groups(shards)
|
||||
if len(groups) != 1 and "multiple_model_groups" not in issues:
|
||||
known_sets = [key for key, members in groups.items() if _known(members)]
|
||||
if len(known_sets) == 1:
|
||||
# one set in the folder is a model Strata knows: use it and say what else is there
|
||||
keep = known_sets[0]
|
||||
others = sorted(sorted(m, key=lambda x: x.name)[0].name for k, m in groups.items() if k != keep)
|
||||
shards = sorted(groups[keep], key=lambda item: item.name)
|
||||
notes.append("The folder also holds " + ", ".join(others[:6]) + (" and more" if len(others) > 6 else "") +
|
||||
f"; Strata uses {shards[0].name} and leaves the others alone.")
|
||||
groups = {keep: shards}
|
||||
else:
|
||||
groups.setdefault((item.name, 1), set()).add(1)
|
||||
issues = []
|
||||
folder_holds = []
|
||||
if len(groups) != 1:
|
||||
issues.append("multiple_model_groups")
|
||||
# a folder with several models: say which ones Strata knows, so the person can point at one of them
|
||||
for key in sorted(groups):
|
||||
members = [item for item in shards if (SHARD.fullmatch(item.name) and (SHARD.fullmatch(item.name).group(1),
|
||||
int(SHARD.fullmatch(item.name).group(3))) == key) or (not SHARD.fullmatch(item.name) and (item.name, 1) == key)]
|
||||
try:
|
||||
known = _candidate_selection(members)
|
||||
except ProfileError:
|
||||
known = None
|
||||
folder_holds.append({"file": members[0].name if members else key[0], "files": len(members),
|
||||
"family": known["family"] if known else None, "model": known["model"] if known else None})
|
||||
if len(groups) == 1:
|
||||
(_, total), indices = next(iter(groups.items()))
|
||||
if total > MAX_IMPORT_SHARDS or indices != set(range(1, total + 1)):
|
||||
issues.append("multiple_model_groups")
|
||||
folder_holds = _holds([(shards[0].parent, groups)])
|
||||
if len(groups) == 1 and "multiple_model_groups" not in issues:
|
||||
(_, total), members = next(iter(groups.items()))
|
||||
found = {int(m.group(2)) for m in (SHARD.fullmatch(item.name) for item in members) if m} or {1}
|
||||
if total > MAX_IMPORT_SHARDS or found != set(range(1, total + 1)):
|
||||
issues.append("incomplete_or_invalid_shard_set")
|
||||
files = []
|
||||
for item in shards:
|
||||
@@ -438,9 +607,15 @@ def plan_import(raw_path: str) -> dict:
|
||||
if metadata["tokenizer_model"] != "gpt2" or not metadata["tokenizer_tokens_present"] or \
|
||||
not metadata["tokenizer_merges_present"]:
|
||||
issues.append("unsupported_or_incomplete_tokenizer_metadata")
|
||||
projectors = [_assess_projector(path.parent / n if path.is_file() else path / n)
|
||||
for n in sorted(ignored_auxiliary)[:8]]
|
||||
messages = []
|
||||
model_dir = shards[0].parent
|
||||
projectors = [_assess_projector(model_dir / n) for n in sorted(ignored_auxiliary)[:8]]
|
||||
messages = list(notes)
|
||||
if folder_holds:
|
||||
several = len({h.get("folder") for h in folder_holds}) > 1
|
||||
names = [(f"{h['family']} {h['model']}" if h.get("model") else h["file"]) + (f" in {h['folder']}" if several else f" ({h['file']})")
|
||||
for h in folder_holds[:8]]
|
||||
messages.append(f"The folder holds {len(folder_holds)} models: " + "; ".join(names) + (" and more" if len(folder_holds) > 8 else "") +
|
||||
". Choose the folder of the one you want, or type the path of its .gguf file.")
|
||||
if any(i.endswith("unsupported_architecture") or i == "unsupported_or_missing_architecture" for i in issues):
|
||||
messages.append(UNSUPPORTED_MODEL_TYPE)
|
||||
elif projectors:
|
||||
@@ -448,15 +623,18 @@ def plan_import(raw_path: str) -> dict:
|
||||
candidate = _candidate_selection(shards)
|
||||
if candidate is None and metadata is not None and not issues:
|
||||
candidate = _candidate_by_header(shards, observed_tensor_count, observed_payload, observed_experts)
|
||||
if candidate is None:
|
||||
if "multiple_model_groups" in issues:
|
||||
candidate = None # nothing is chosen for the person
|
||||
if candidate is None and not {"multiple_model_groups", "incomplete_or_invalid_shard_set"} & set(issues):
|
||||
issues.append("unrecognized_or_unsupported_model_variant")
|
||||
elif metadata is not None:
|
||||
elif candidate is not None and metadata is not None:
|
||||
expected = set(candidate["expected_expert_types"])
|
||||
if not observed_experts or observed_experts - expected:
|
||||
issues.append("missing_or_unexpected_expert_quantization")
|
||||
return {"source": str(path), "scope": "local_gguf_candidate", "files": files,
|
||||
return {"source": str(path), "model_dir": str(model_dir), "scope": "local_gguf_candidate", "files": files,
|
||||
"file_count": len(files), "total_bytes": sum(item["bytes"] for item in files),
|
||||
"metadata": metadata, "candidate_selection": candidate,
|
||||
"plain_issues": list(dict.fromkeys(plain_issue(i) for i in issues)),
|
||||
"observed_expert_types": sorted(observed_experts),
|
||||
"observed_tensor_count": observed_tensor_count,
|
||||
"ignored_auxiliary_files": sorted(ignored_auxiliary),
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""What the person is told while a model downloads and is prepared: ONE place for the words, read by the app (through
|
||||
tools/strata_mcp.py `install_progress`) and by the Terminal (`strata launch`, strata_cli/launch/runner.py).
|
||||
|
||||
Setup prints its work in seven steps and the tools it runs print their command lines (`> python tools/strata_pack.py build ...`)
|
||||
and progress lines (`name: 1.20 / 5.04 GB (24%)`). Those titles are for people who read the setup log ("writing the start script",
|
||||
"preparing the model for Strata"), and the name in a progress line is a file name or an internal label ("MTP draft layer",
|
||||
"llama.cpp source"). This turns what setup last printed into one plain sentence that says what is really happening now.
|
||||
The sentences are English; the app translates them like its other texts.
|
||||
|
||||
Nothing here reads a file or starts a process: it works on the last lines of setup's output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
STEP_RE = re.compile(r"=== Step (\d+): (.+?) ===")
|
||||
CHECKING_RE = re.compile(r"^\s*checking\b.*\bSHA-256\b", re.I)
|
||||
PROGRESS_RE = re.compile(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Words:
|
||||
phase: str # a short key for tests and for the app to pick an icon: check, helpers, engine, download, verify, pictures,
|
||||
# pack, tokenizer, draft_download, draft, settings, ...
|
||||
label: str # the sentence
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {"phase": self.phase, "label": self.label}
|
||||
|
||||
|
||||
def _after_last_step(lines: list[str]) -> list[str]:
|
||||
for i in range(len(lines) - 1, -1, -1):
|
||||
if STEP_RE.search(lines[i]):
|
||||
return lines[i + 1:]
|
||||
return lines
|
||||
|
||||
|
||||
def _last_matching(lines: list[str], *needles: str) -> str | None:
|
||||
"""The newest line that holds one of the needles (lower case compare)."""
|
||||
for line in reversed(lines):
|
||||
low = line.lower()
|
||||
if any(n in low for n in needles):
|
||||
return line
|
||||
return None
|
||||
|
||||
|
||||
def describe(step: int | None, lines: list[str], download: dict | None = None) -> Words:
|
||||
"""The sentence for setup's step `step` (1 to 7; None when unknown) given the lines it printed since the step began and the
|
||||
download figure in them (`{"file": ..., "percent": ...}` or None)."""
|
||||
recent = _after_last_step(lines)
|
||||
dl_file = str((download or {}).get("file", "")).lower()
|
||||
if step is None:
|
||||
return Words("working", "Getting your model ready")
|
||||
if step <= 2:
|
||||
return Words("check", "Checking your computer")
|
||||
if step == 3:
|
||||
return Words("helpers", "Getting the helper packages ready")
|
||||
if step == 4:
|
||||
if "engine" in dl_file:
|
||||
return Words("engine", "Downloading the engine for this PC")
|
||||
if "source" in dl_file or "llama.cpp" in dl_file:
|
||||
return Words("helpers", "Downloading the small tools used to prepare models")
|
||||
return Words("engine", "Checking the engine for this PC")
|
||||
if step == 5:
|
||||
last = recent[-1] if recent else ""
|
||||
if dl_file.startswith("checking") or CHECKING_RE.search(last):
|
||||
return Words("verify", "Checking that the model files are complete (a few minutes for a big model; nothing is downloaded)")
|
||||
if "vision" in dl_file or "picture" in dl_file or "mmproj" in dl_file:
|
||||
return Words("pictures", "Downloading the picture reader")
|
||||
if download and not dl_file.startswith("checking"):
|
||||
return Words("download", "Downloading the model files")
|
||||
if _last_matching(recent, "already downloaded", "model files present"):
|
||||
return Words("verify", "The model files are on this computer; checking them")
|
||||
return Words("download", "Getting the model files")
|
||||
if step == 6:
|
||||
marker = _last_matching(recent, "mtp_rt.py", "mtp_pack.py", "mtp_fetch.py", "mtp draft layer:", "strata_pack.py", "pack_index.py",
|
||||
"strata_tokenizer.py", "iq_pack.py", "nvfp4_local_pack.py", "converting the q2_0 experts",
|
||||
"writing the experts into one file", "of mtp tensors", "[ok] model prepared")
|
||||
low = (marker or "").lower()
|
||||
if not marker and dl_file.startswith("mtp draft"):
|
||||
low = "mtp draft layer:"
|
||||
if "[ok] mtp draft layer" in low:
|
||||
return Words("draft", "Preparing the draft layer")
|
||||
if "mtp_fetch.py" in low or "mtp draft layer:" in low or "of mtp tensors" in low:
|
||||
return Words("draft_download", "Downloading the draft layer (about 5 GB; it makes answers about twice as fast)")
|
||||
if "mtp_rt.py" in low or "mtp_pack.py" in low or "[ok] model prepared" in low:
|
||||
return Words("draft", "Preparing the draft layer")
|
||||
if "strata_pack.py" in low or "converting the q2_0 experts" in low:
|
||||
return Words("pack", "Packing the model's experts for your processor (one time, a few minutes)")
|
||||
if "pack_index.py" in low:
|
||||
return Words("pack", "Indexing the packed experts")
|
||||
if "strata_tokenizer.py" in low:
|
||||
return Words("tokenizer", "Preparing the tokenizer")
|
||||
if "writing the experts into one file" in low or ("iq_pack.py" in low and "--experts-bin" in low):
|
||||
return Words("pack", "Packing the experts into one file for low-memory mode (one time)")
|
||||
if "iq_pack.py" in low:
|
||||
return Words("pack", "Preparing the model data for the engine (one time)")
|
||||
if "nvfp4_local_pack.py" in low:
|
||||
return Words("pack", "Converting NVIDIA's FP4 checkpoint on this PC (20 to 40 minutes, one time)")
|
||||
return Words("pack", "Preparing your model for Strata (one time)")
|
||||
return Words("settings", "Saving the model's settings")
|
||||
|
||||
|
||||
def with_numbers(words: Words, download: dict | None) -> str:
|
||||
"""The sentence with the figure after it when there is one: `Downloading the model files: 12.3 of 66.4 GB`."""
|
||||
if not download:
|
||||
return words.label
|
||||
try:
|
||||
done, total = float(download["done_gb"]), float(download["total_gb"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return words.label
|
||||
if total <= 0.05:
|
||||
return words.label
|
||||
return f"{words.label}: {done:.1f} of {total:.1f} GB"
|
||||
@@ -198,7 +198,7 @@ class GuiLayout(unittest.TestCase):
|
||||
self.assertIn("more than one model", text)
|
||||
self.assertIn("holds 2 models", text)
|
||||
self.assertIn("gyro Gyro-S", text)
|
||||
self.assertIn("Point at the .gguf file of the one you want", text)
|
||||
self.assertIn("type the path of its .gguf file", text)
|
||||
self.assertNotIn("multiple_model_groups", text)
|
||||
self.assertNotIn("not a model size", text)
|
||||
|
||||
|
||||
@@ -407,11 +407,13 @@ class SetupArgs(unittest.TestCase):
|
||||
["--gpu", "1"]):
|
||||
self.assertIn(pair[0], a)
|
||||
self.assertEqual(a[a.index(pair[0]) + 1], pair[1])
|
||||
self.assertIn("--set-default-data-dir", a) # a folder the person chose is the remembered one (the app and the next start use it)
|
||||
|
||||
def test_a_mac_gets_only_the_options_its_setup_knows(self):
|
||||
with mock.patch.object(sys, "platform", "darwin"):
|
||||
a = self.runner(data_dir="/d", gpus=[0])
|
||||
self.assertEqual(a, ["--yes", "--no-start", "--family", "qwen", "--model", "IQ3_XXS", "--context", "32768", "--vision", "no", "--data-dir", "/d"])
|
||||
self.assertEqual(a, ["--yes", "--no-start", "--family", "qwen", "--model", "IQ3_XXS", "--context", "32768", "--vision", "no", "--data-dir", "/d",
|
||||
"--set-default-data-dir"])
|
||||
|
||||
|
||||
class AdoptRules(unittest.TestCase):
|
||||
|
||||
@@ -262,7 +262,7 @@ class ModelStep(Base):
|
||||
with mock.patch("strata_control.models.plan_import", return_value=plan) as pi:
|
||||
await typed(pilot, "/data/models/IQ3_XXS")
|
||||
await press(pilot, "enter")
|
||||
self.assertEqual(ctx.settings.model_path, str(Path("/data/models/IQ3_XXS")))
|
||||
self.assertEqual(ctx.settings.model_path, os.path.abspath("/data/models/IQ3_XXS"))
|
||||
self.assertEqual((ctx.settings.family, ctx.settings.model), ("qwen", "IQ3_XXS"))
|
||||
self.assertIn("These files are qwen IQ3_XXS (2 file(s), 44 GB)", text_of(app))
|
||||
await press(pilot, "enter")
|
||||
@@ -278,7 +278,7 @@ class ModelStep(Base):
|
||||
await typed(pilot, "/x")
|
||||
await press(pilot, "enter")
|
||||
t = flat(app)
|
||||
self.assertIn("some shards are missing", t)
|
||||
self.assertIn("some parts of the model are missing", t)
|
||||
self.assertIn("pick a model from the list", t)
|
||||
self.assertIsNone(ctx.settings.model_path)
|
||||
self.run_app(case)
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
"""0.2.2: "use my own model files" accepts every layout 0.1.45's `setup.py --gguf-dir` accepted (issues #3316 #3292 #3190 #3209 #3331).
|
||||
|
||||
The checker in front of setup (strata_control/models.plan_import) used to be stricter than setup itself: a split set whose first shard
|
||||
holds only the metadata (Unsloth's), a link to the file (Hugging Face cache, Ollama), a folder holding several sizes, a folder above the
|
||||
model folder (a whole repository, a 0.1.45 data folder), more than 128 files in a folder. Tiny GGUF files with the real shard names
|
||||
stand for the real ones (the shard names and the expert types are what the table checks)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from strata_control import gguf_preflight, models
|
||||
from strata_control.profiles import ProfileError
|
||||
from tools.gguf_reader import BLOCK_GEOMETRY
|
||||
|
||||
TYPE_IDS = {"Q8_0": 8, "IQ3_S": 21, "IQ4_NL": 20, "IQ4_XS": 23, "IQ3_XXS": 18, "Q2_0": 42, "IQ2_S": 22, "IQ2_XS": 17}
|
||||
|
||||
|
||||
def string(value: str) -> bytes:
|
||||
raw = value.encode()
|
||||
return struct.pack("<Q", len(raw)) + raw
|
||||
|
||||
|
||||
def gguf_bytes(experts: list[str], *, metadata: bool = True) -> bytes:
|
||||
"""A tiny qwen4exp GGUF with one routed-expert tensor per type named; `experts=[]` is the metadata-only first shard of a split set."""
|
||||
pairs = [("general.architecture", 8, string("qwen4exp")), ("tokenizer.ggml.model", 8, string("gpt2")),
|
||||
("tokenizer.ggml.tokens", 9, struct.pack("<IQ", 8, 1) + string("a")),
|
||||
("tokenizer.ggml.merges", 9, struct.pack("<IQ", 8, 1) + string("a b"))] if metadata else []
|
||||
header = b"GGUF" + struct.pack("<IQQ", 3, len(experts), len(pairs)) + \
|
||||
b"".join(string(k) + struct.pack("<I", kind) + value for k, kind, value in pairs)
|
||||
offset = 0
|
||||
for i, name in enumerate(experts):
|
||||
block, size = BLOCK_GEOMETRY[name]
|
||||
header += string(f"blk.{i}.ffn_gate_exps.weight") + struct.pack("<IQIQ", 1, block, TYPE_IDS[name], offset)
|
||||
offset += -(-size // 32) * 32
|
||||
header += b"\x00" * (-len(header) % 32)
|
||||
return header + b"\x00" * offset
|
||||
|
||||
|
||||
UNSLOTH_Q4 = ["Qwen3.8-Flash-Next-UD-Q4_K_XL-0000%d-of-00004.gguf" % i for i in (1, 2, 3, 4)]
|
||||
UNSLOTH_IQ4 = ["Qwen3.8-Flash-Next-UD-IQ4_XS-0000%d-of-00003.gguf" % i for i in (1, 2, 3)]
|
||||
Q2 = ["Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-0000%d-of-00002.gguf" % i for i in (1, 2)]
|
||||
IQ3XXS = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-0000%d-of-00002.gguf" % i for i in (1, 2)]
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory(prefix="strata-own-")
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.base = Path(self.tmp.name)
|
||||
|
||||
def put(self, folder: Path, names: list[str], experts: list[str]) -> Path:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for n in names:
|
||||
(folder / n).write_bytes(gguf_bytes(experts))
|
||||
return folder
|
||||
|
||||
def gsq(self, folder: Path, names: list[str], kind: str) -> Path:
|
||||
return self.put(folder, names, [kind])
|
||||
|
||||
def unsloth(self, folder: Path, names: list[str], kinds: list[str]) -> Path:
|
||||
"""The first shard has only the metadata (what llama.cpp's gguf-split makes), the others carry tensors."""
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
(folder / names[0]).write_bytes(gguf_bytes([]))
|
||||
for n in names[1:]:
|
||||
(folder / n).write_bytes(gguf_bytes(kinds, metadata=False))
|
||||
return folder
|
||||
|
||||
|
||||
class MetadataOnlyFirstShard(Base):
|
||||
def test_unsloth_split_set_is_recognised(self):
|
||||
folder = self.unsloth(self.base / "u", UNSLOTH_Q4, ["IQ4_NL"])
|
||||
plan = models.plan_import(str(folder))
|
||||
# the tiny files carry IQ4_NL experts, which UD-Q4_K_XL does not list: the set is found, the quantization is what is flagged
|
||||
self.assertNotIn("unsupported_or_missing_architecture", plan["issues"])
|
||||
self.assertNotIn("unsupported_or_incomplete_tokenizer_metadata", plan["issues"])
|
||||
self.assertNotIn("GGUF tensor or metadata count", " ".join(plan["issues"]))
|
||||
self.assertEqual((plan["candidate_selection"]["family"], plan["candidate_selection"]["model"]), ("unsloth", "UD-Q4_K_XL"))
|
||||
|
||||
def test_unsloth_iq4_xs_passes_with_its_real_expert_types(self):
|
||||
folder = self.unsloth(self.base / "u", UNSLOTH_IQ4, ["IQ3_S", "IQ4_NL", "IQ4_XS", "Q8_0"])
|
||||
plan = models.plan_import(str(folder))
|
||||
self.assertEqual(plan["issues"], [])
|
||||
self.assertEqual(plan["candidate_selection"]["model"], "UD-IQ4_XS")
|
||||
self.assertEqual(plan["model_dir"], str(folder))
|
||||
|
||||
def test_a_shard_with_no_tensors_and_no_metadata_is_still_refused(self):
|
||||
f = self.base / "x.gguf"
|
||||
f.write_bytes(gguf_bytes([], metadata=False))
|
||||
plan = models.plan_import(str(f))
|
||||
self.assertIn("unsupported_or_missing_architecture", plan["issues"])
|
||||
|
||||
|
||||
class Links(Base):
|
||||
def make_links(self):
|
||||
blobs = self.base / "blobs"
|
||||
snap = self.base / "snapshots" / "abc" / "Q2_0"
|
||||
blobs.mkdir()
|
||||
snap.mkdir(parents=True)
|
||||
for i, n in enumerate(Q2):
|
||||
(blobs / f"sha{i}").write_bytes(gguf_bytes(["Q2_0"]))
|
||||
try:
|
||||
os.symlink(blobs / f"sha{i}", snap / n)
|
||||
except (OSError, NotImplementedError):
|
||||
self.skipTest("this account cannot create symbolic links")
|
||||
return snap
|
||||
|
||||
def test_a_hugging_face_cache_snapshot_is_used_through_its_links(self):
|
||||
snap = self.make_links()
|
||||
plan = models.plan_import(str(snap))
|
||||
self.assertEqual(plan["issues"], [])
|
||||
self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
|
||||
self.assertEqual(plan["file_count"], 2)
|
||||
|
||||
def test_a_link_to_the_folder_is_followed(self):
|
||||
real = self.gsq(self.base / "real", Q2, "Q2_0")
|
||||
link = self.base / "link"
|
||||
try:
|
||||
os.symlink(real, link, target_is_directory=True)
|
||||
except (OSError, NotImplementedError):
|
||||
self.skipTest("this account cannot create symbolic links")
|
||||
self.assertEqual(models.plan_import(str(link))["issues"], [])
|
||||
|
||||
def test_a_link_to_a_file_that_is_gone_says_so(self):
|
||||
snap = self.base / "s"
|
||||
snap.mkdir()
|
||||
try:
|
||||
os.symlink(self.base / "gone", snap / Q2[0])
|
||||
except (OSError, NotImplementedError):
|
||||
self.skipTest("this account cannot create symbolic links")
|
||||
with self.assertRaises(ProfileError) as ctx:
|
||||
gguf_preflight.real_model_file(snap / Q2[0])
|
||||
self.assertIn("link to a file that is not there", str(ctx.exception))
|
||||
|
||||
def test_a_missing_file_is_missing_not_a_link(self):
|
||||
with self.assertRaises(ProfileError) as ctx:
|
||||
gguf_preflight.real_model_file(self.base / "nope.gguf")
|
||||
self.assertIn("is missing", str(ctx.exception))
|
||||
|
||||
def test_run_configs_keep_the_no_link_rule(self):
|
||||
cfg = self.base / "real.json"
|
||||
cfg.write_text("{}")
|
||||
link = self.base / "strata-x.json"
|
||||
try:
|
||||
os.symlink(cfg, link)
|
||||
except (OSError, NotImplementedError):
|
||||
self.skipTest("this account cannot create symbolic links")
|
||||
with self.assertRaises(ProfileError) as ctx:
|
||||
models._read(link) # noqa: SLF001
|
||||
self.assertIn("symlink", str(ctx.exception))
|
||||
|
||||
|
||||
class Folders(Base):
|
||||
def test_many_other_gguf_files_in_the_folder_do_not_refuse(self):
|
||||
folder = self.gsq(self.base / "m", Q2, "Q2_0")
|
||||
for i in range(140):
|
||||
(folder / f"other-{i:03d}.gguf").write_bytes(b"GGUF")
|
||||
plan = models.plan_import(str(folder))
|
||||
self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
|
||||
self.assertEqual(plan["file_count"], 2)
|
||||
|
||||
def test_several_sizes_in_one_folder_name_them_and_ask_for_one_file(self):
|
||||
folder = self.gsq(self.base / "many", Q2, "Q2_0")
|
||||
self.gsq(folder, IQ3XXS, "IQ3_XXS")
|
||||
plan = models.plan_import(str(folder))
|
||||
self.assertEqual(plan["issues"], ["multiple_model_groups"])
|
||||
self.assertIsNone(plan["candidate_selection"])
|
||||
self.assertEqual(sorted(h["model"] for h in plan["folder_holds"]), ["IQ3_XXS", "Q2_0"])
|
||||
self.assertTrue(any("holds 2 models" in m and "type the path of its .gguf file" in m for m in plan["messages"]))
|
||||
|
||||
def test_one_known_size_among_other_files_is_used_and_the_rest_is_named(self):
|
||||
folder = self.gsq(self.base / "mix", Q2, "Q2_0")
|
||||
(folder / "some-other-model-Q4_K_M.gguf").write_bytes(gguf_bytes(["IQ3_S"]))
|
||||
plan = models.plan_import(str(folder))
|
||||
self.assertEqual(plan["issues"], [])
|
||||
self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
|
||||
self.assertEqual(plan["file_count"], 2)
|
||||
self.assertTrue(any("some-other-model-Q4_K_M.gguf" in m and "leaves the others alone" in m for m in plan["messages"]))
|
||||
|
||||
def test_a_shard_file_picks_its_set_out_of_a_folder_of_several(self):
|
||||
folder = self.gsq(self.base / "many", Q2, "Q2_0")
|
||||
self.gsq(folder, IQ3XXS, "IQ3_XXS")
|
||||
plan = models.plan_import(str(folder / IQ3XXS[1]))
|
||||
self.assertEqual(plan["issues"], [])
|
||||
self.assertEqual(plan["candidate_selection"]["model"], "IQ3_XXS")
|
||||
self.assertEqual(plan["model_dir"], str(folder))
|
||||
|
||||
def test_a_folder_above_the_model_folder_is_searched(self):
|
||||
data = self.base / "Strata-data"
|
||||
self.gsq(data / "models" / "q2_0", Q2, "Q2_0")
|
||||
(data / "packs").mkdir()
|
||||
for start in (data, data / "models"):
|
||||
plan = models.plan_import(str(start))
|
||||
self.assertEqual(plan["issues"], [], start)
|
||||
self.assertEqual(plan["model_dir"], str(data / "models" / "q2_0"))
|
||||
self.assertTrue(any("The model files are in" in m for m in plan["messages"]))
|
||||
|
||||
def test_a_whole_repository_with_one_folder_per_size_asks_which(self):
|
||||
repo = self.base / "repo"
|
||||
self.gsq(repo / "Q2_0", Q2, "Q2_0")
|
||||
self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
|
||||
plan = models.plan_import(str(repo))
|
||||
self.assertIn("multiple_model_groups", plan["issues"])
|
||||
self.assertEqual(sorted((Path(h["folder"]).name, h["model"]) for h in plan["folder_holds"]),
|
||||
[("IQ3_XXS", "IQ3_XXS"), ("Q2_0", "Q2_0")])
|
||||
self.assertTrue(plan["file_set_status"] == "invalid_or_incomplete")
|
||||
|
||||
def test_one_known_folder_next_to_unrelated_ones_is_used(self):
|
||||
top = self.base / "all"
|
||||
self.gsq(top / "models" / "q2_0", Q2, "Q2_0")
|
||||
(top / "stuff").mkdir()
|
||||
(top / "stuff" / "notes.txt").write_text("x")
|
||||
plan = models.plan_import(str(top))
|
||||
self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
|
||||
|
||||
def test_a_folder_with_no_gguf_anywhere_says_so(self):
|
||||
(self.base / "empty" / "a" / "b").mkdir(parents=True)
|
||||
with self.assertRaises(ProfileError) as ctx:
|
||||
models.plan_import(str(self.base / "empty"))
|
||||
self.assertIn("no GGUF files found", str(ctx.exception))
|
||||
|
||||
def test_a_folder_name_with_spaces_and_a_second_drive_style_path(self):
|
||||
folder = self.gsq(self.base / "my models" / "Qwen 3.8 files", Q2, "Q2_0")
|
||||
self.assertEqual(models.plan_import(str(folder))["issues"], [])
|
||||
|
||||
def test_a_missing_second_shard_is_one_plain_issue(self):
|
||||
folder = self.put(self.base / "half", Q2[:1], ["Q2_0"])
|
||||
plan = models.plan_import(str(folder))
|
||||
self.assertEqual(plan["issues"], ["incomplete_or_invalid_shard_set"])
|
||||
|
||||
|
||||
class Launcher(Base):
|
||||
"""`strata launch --model-path` and the TUI's "use my own files" (strata_cli/launch/runner.py, screens.py)."""
|
||||
|
||||
def runner(self, **kw):
|
||||
from strata_cli.launch import settings as S
|
||||
from strata_cli.launch.catalog import Catalog
|
||||
from strata_cli.launch.runner import Runner
|
||||
from tests.terminal.launch_support import HW_12
|
||||
return Runner(S.LaunchSettings(**kw), catalog=Catalog(hardware=HW_12))
|
||||
|
||||
def test_a_folder_above_the_model_is_resolved_to_the_model_folder(self):
|
||||
data = self.base / "Strata-data"
|
||||
self.gsq(data / "models" / "q2_0", Q2, "Q2_0")
|
||||
r = self.runner(model_path=str(data))
|
||||
r.resolve_own_files()
|
||||
self.assertEqual((r.s.family, r.s.model), ("qwen", "Q2_0"))
|
||||
self.assertEqual(Path(r.s.model_path), data / "models" / "q2_0")
|
||||
argv = r.setup_args()
|
||||
self.assertEqual(Path(argv[argv.index("--gguf-dir") + 1]), data / "models" / "q2_0")
|
||||
|
||||
def test_a_named_model_in_a_folder_of_several_sizes_is_never_refused_here(self):
|
||||
folder = self.gsq(self.base / "many", Q2, "Q2_0")
|
||||
self.gsq(folder, IQ3XXS, "IQ3_XXS")
|
||||
r = self.runner(model_path=str(folder), family="qwen", model="IQ3_XXS")
|
||||
r.resolve_own_files()
|
||||
self.assertEqual(Path(r.s.model_path), folder) # setup picks the IQ3_XXS files by name, as in 0.1.45
|
||||
self.assertEqual((r.s.family, r.s.model), ("qwen", "IQ3_XXS"))
|
||||
|
||||
def test_a_named_model_is_found_in_the_folder_that_holds_it(self):
|
||||
repo = self.base / "repo"
|
||||
self.gsq(repo / "Q2_0", Q2, "Q2_0")
|
||||
self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
|
||||
r = self.runner(model_path=str(repo), family="qwen", model="IQ3_XXS")
|
||||
r.resolve_own_files()
|
||||
self.assertEqual(Path(r.s.model_path), repo / "IQ3_XXS")
|
||||
|
||||
def test_two_models_and_none_named_says_which_in_plain_words(self):
|
||||
from strata_cli.launch.runner import LaunchError
|
||||
repo = self.base / "repo"
|
||||
self.gsq(repo / "Q2_0", Q2, "Q2_0")
|
||||
self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
|
||||
r = self.runner(model_path=str(repo))
|
||||
with self.assertRaises(LaunchError) as ctx:
|
||||
r.resolve_own_files()
|
||||
text = str(ctx.exception)
|
||||
self.assertIn("more than one model", text)
|
||||
self.assertIn("holds 2 models", text)
|
||||
|
||||
def test_a_linked_model_file_keeps_its_name(self):
|
||||
snap = Links.make_links(self)
|
||||
r = self.runner(model_path=str(snap / Q2[0]))
|
||||
r.resolve_own_files()
|
||||
self.assertEqual((r.s.family, r.s.model), ("qwen", "Q2_0"))
|
||||
self.assertEqual(Path(r.s.model_path).name, Q2[0]) # not the blob's hash name
|
||||
|
||||
|
||||
class Words(unittest.TestCase):
|
||||
def test_a_file_problem_names_the_file_and_says_why(self):
|
||||
self.assertEqual(models.plain_issue("model-00002-of-00002.gguf: GGUF metadata is truncated"),
|
||||
"model-00002-of-00002.gguf: the file is cut short (a download or copy that did not finish)")
|
||||
self.assertIn("shorter than its own header", models.plain_issue("a.gguf: GGUF tensor payload is shorter than its directory requires"))
|
||||
self.assertIn("old format (version 2)", models.plain_issue("a.gguf: Strata metadata preflight requires GGUF v3"))
|
||||
self.assertEqual(models.plain_issue("incomplete_or_invalid_shard_set"), "some parts of the model are missing")
|
||||
|
||||
def test_the_plan_carries_the_words(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
f = Path(tmp) / Q2[0]
|
||||
f.write_bytes(gguf_bytes(["Q2_0"])[:60])
|
||||
plan = models.plan_import(str(f))
|
||||
self.assertTrue(plan["plain_issues"])
|
||||
self.assertTrue(any(x.startswith(Q2[0] + ":") or x.startswith(Q2[1] + ":") for x in plan["plain_issues"]), plan["plain_issues"])
|
||||
|
||||
|
||||
class Table(unittest.TestCase):
|
||||
def test_every_size_setup_installs_is_in_the_table(self):
|
||||
"""Setup can install it from --gguf-dir, so the checker in front of it must know it too (0.2.0 knew 7 of 10)."""
|
||||
import importlib.util
|
||||
spec = importlib.util.spec_from_file_location("strata_setup_for_test", models.ROOT / "setup.py")
|
||||
setup = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(setup)
|
||||
table = json.loads((models.ROOT / "data" / "gguf_fingerprints.json").read_text(encoding="utf-8"))
|
||||
missing = []
|
||||
for family, fam in setup.FAMILIES.items():
|
||||
if fam.get("ready"):
|
||||
continue
|
||||
for model, row in setup.MODELS.items():
|
||||
if family not in row.get("families", ("qwen", "swift")):
|
||||
continue
|
||||
names = {setup.model_file(fam, model, i) for i in range(1, setup.model_shards(fam, model) + 1)}
|
||||
key = f"{family}/{model}"
|
||||
have = {Path(n).name for n in (table.get(key) or {}).get("files", [])}
|
||||
if key not in models.SUPPORTED_SELECTIONS or have != names:
|
||||
missing.append(key)
|
||||
self.assertEqual(missing, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,148 @@
|
||||
"""0.2.2: the words for a model download and its preparation are plain and true (strata_control/progress_words.py), and the app's
|
||||
and the Terminal's progress read the same lines the same way (tools/strata_mcp.py install_progress / combined_progress).
|
||||
|
||||
The excerpts are from real setup logs (Gyro-S on the RTX 5070 PC, 2026-10-19) and from the steps a Q2_0 install adds."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
|
||||
import strata_mcp # noqa: E402
|
||||
from strata_control import progress_words as W # noqa: E402
|
||||
|
||||
HEAD = ["Strata - Qwen3.8-Flash-Next on a normal PC", "=== Step 1: checking your PC ===", " [ok] GPU: NVIDIA GeForce RTX 5070",
|
||||
"=== Step 2: your choices ===", " [ok] size: Gyro-S", "=== Step 3: Python packages ===", " [ok] numpy ...",
|
||||
"=== Step 4: the Strata engine ==="]
|
||||
STEP5 = ["=== Step 5: downloading Qwen3.8-Flash-Next (Gyro) Gyro-S ===",
|
||||
" The model files go in C:\\Users\\x\\Documents\\Strata\\models\\gyro-Gyro-S"]
|
||||
MODEL_PROGRESS = " Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf: 30.53 / 58.49 GB (52%) "
|
||||
CHECK = " checking Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf (SHA-256, 58.5 GB) ..."
|
||||
STEP6 = ["=== Step 6: preparing the model for Strata ==="]
|
||||
|
||||
|
||||
def prog(lines):
|
||||
p = strata_mcp.install_progress(lines)
|
||||
return p, p.get("label"), p.get("phase")
|
||||
|
||||
|
||||
class StepWords(unittest.TestCase):
|
||||
def test_checking_the_pc(self):
|
||||
self.assertEqual(prog(HEAD[:3])[1:], ("Checking your computer", "check"))
|
||||
|
||||
def test_the_engine_and_the_helper_download_have_their_own_words(self):
|
||||
self.assertEqual(prog(HEAD + [" llama.cpp source: 0.01 / 0.04 GB (21%) "])[2], "helpers")
|
||||
self.assertIn("small tools", prog(HEAD + [" llama.cpp source: 0.01 / 0.04 GB (21%) "])[1])
|
||||
self.assertEqual(prog(HEAD + [" Strata engine: 0.20 / 0.90 GB (22%) "])[1], "Downloading the engine for this PC")
|
||||
self.assertEqual(prog(HEAD)[2], "engine")
|
||||
|
||||
def test_the_model_download(self):
|
||||
_p, label, phase = prog(HEAD + STEP5 + [MODEL_PROGRESS])
|
||||
self.assertEqual((label, phase), ("Downloading the model files", "download"))
|
||||
|
||||
def test_a_figure_from_an_earlier_step_does_not_leak_into_the_next(self):
|
||||
"""Step 4's 'llama.cpp source' line must not make step 5 'Downloading ...' before any model line is printed."""
|
||||
p, label, phase = prog(HEAD + [" llama.cpp source: 0.04 / 0.04 GB (100%) "] + STEP5)
|
||||
self.assertNotIn("download", p)
|
||||
self.assertEqual(phase, "download")
|
||||
self.assertEqual(label, "Getting the model files")
|
||||
|
||||
def test_the_hash_check_is_checking_not_downloading(self):
|
||||
lines = HEAD + STEP5 + [MODEL_PROGRESS, " [ok] downloaded", CHECK]
|
||||
p, label, phase = prog(lines)
|
||||
self.assertEqual(phase, "verify")
|
||||
self.assertIn("Checking that the model files are complete", label)
|
||||
self.assertNotIn("Downloading", label)
|
||||
# with its own figure
|
||||
p, label, phase = prog(lines + [" checking Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf: 12.00 / 58.49 GB (20%) "])
|
||||
self.assertEqual(phase, "verify")
|
||||
self.assertEqual(p["download"]["percent"], 20)
|
||||
|
||||
def test_the_picture_reader(self):
|
||||
lines = HEAD + STEP5 + [" [ok] model files present", " vision encoder: 0.30 / 0.91 GB (33%) "]
|
||||
self.assertEqual(prog(lines)[1:], ("Downloading the picture reader", "pictures"))
|
||||
|
||||
def test_files_already_there(self):
|
||||
lines = HEAD + STEP5 + [" [ok] Qwen3.8-Flash-Next-Q2_0-00001-of-00002.gguf already downloaded"]
|
||||
self.assertEqual(prog(lines)[2], "verify")
|
||||
|
||||
def test_step_six_packing_the_experts(self):
|
||||
lines = HEAD + STEP5 + STEP6 + [" Converting the Q2_0 experts for the AVX-512 kernel (one time, ~40 GB written, 2-5 min) ...",
|
||||
" > python tools/strata_pack.py build --gguf x --out y --skip-hash --force"]
|
||||
self.assertEqual(prog(lines)[1:], ("Packing the model's experts for your processor (one time, a few minutes)", "pack"))
|
||||
self.assertEqual(prog(lines + [" > python tools/pack_index.py --pack y"])[1], "Indexing the packed experts")
|
||||
self.assertEqual(prog(lines + [" > python tools/strata_tokenizer.py --gguf x --out y"])[1], "Preparing the tokenizer")
|
||||
|
||||
def test_step_six_the_draft_layer_download_then_its_preparation(self):
|
||||
fetch = [" [ok] model prepared: y", " The MTP draft layer (speculative decoding, ~2x faster output) comes from the original Qwen checkpoint:",
|
||||
" only its ~5 GB of MTP tensors are downloaded.", " > python tools/mtp_fetch.py fetch --out z",
|
||||
" MTP draft layer: 1.65 / 5.21 GB (31%)"]
|
||||
p, label, phase = prog(HEAD + STEP5 + STEP6 + fetch)
|
||||
self.assertEqual(phase, "draft_download")
|
||||
self.assertIn("Downloading the draft layer", label)
|
||||
# the download is over: the numbers it printed are stale, the next tool is running
|
||||
p, label, phase = prog(HEAD + STEP5 + STEP6 + fetch + [" MTP draft layer: 5.21 / 5.21 GB (100%)", " > python tools/mtp_pack.py --src z"])
|
||||
self.assertEqual((label, phase), ("Preparing the draft layer", "draft"))
|
||||
p, label, phase = prog(HEAD + STEP5 + STEP6 + fetch + [" > python tools/mtp_rt.py --gguf g --out rt"])
|
||||
self.assertEqual(phase, "draft")
|
||||
|
||||
def test_step_six_with_everything_already_there(self):
|
||||
lines = HEAD + STEP5 + STEP6 + [" [ok] model prepared: y", " [ok] MTP draft layer: z"]
|
||||
self.assertEqual(prog(lines)[2], "draft")
|
||||
|
||||
def test_low_memory_mode_packing(self):
|
||||
lines = HEAD + STEP5 + STEP6 + [" Writing the experts into one file for the low-memory mode (one time, 80 GB) ...",
|
||||
" > python tools/iq_pack.py --gguf x --out y --experts-bin"]
|
||||
self.assertEqual(prog(lines)[1], "Packing the experts into one file for low-memory mode (one time)")
|
||||
|
||||
def test_the_last_step(self):
|
||||
lines = HEAD + STEP5 + STEP6 + ["=== Step 7: writing the start script ===", " [ok] KV streaming on"]
|
||||
self.assertEqual(prog(lines)[1:], ("Saving the model's settings", "settings"))
|
||||
|
||||
def test_the_heading_is_found_even_after_hundreds_of_tool_lines(self):
|
||||
lines = HEAD + STEP5 + STEP6 + [" > python tools/iq_pack.py --gguf x --out y"] + [f" layer {i}/40" for i in range(900)]
|
||||
self.assertEqual(prog(lines)[2], "pack")
|
||||
|
||||
def test_no_step_yet(self):
|
||||
self.assertEqual(prog(["Strata - Qwen3.8-Flash-Next"])[1:], ("Getting your model ready", "working"))
|
||||
|
||||
def test_with_numbers(self):
|
||||
w = W.describe(5, STEP5, {"file": "x.gguf", "done_gb": 12.34, "total_gb": 58.49, "percent": 21})
|
||||
self.assertEqual(W.with_numbers(w, {"done_gb": 12.34, "total_gb": 58.49}), "Downloading the model files: 12.3 of 58.5 GB")
|
||||
self.assertEqual(W.with_numbers(w, None), "Downloading the model files")
|
||||
|
||||
|
||||
class CombinedFigure(unittest.TestCase):
|
||||
def test_a_part_file_the_pieces_filled_ahead_is_not_a_finished_download(self):
|
||||
"""The parallel download writes the last pieces early, so the .part is full length while the pieces done are 50%: the log's
|
||||
figure is the truth (the bar used to jump to 99%)."""
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
folder = Path(tmp)
|
||||
part = folder / "m-00001-of-00002.gguf.part"
|
||||
part.write_bytes(b"\0" * 1000)
|
||||
files = [{"path": str(folder / "m-00001-of-00002.gguf"), "bytes": 1_000_000_000, "role": "model"}]
|
||||
prog_ = {"step": "5/7: downloading X", "download": {"file": "m-00001-of-00002.gguf", "done_gb": 0.5, "total_gb": 1.0, "percent": 50}}
|
||||
# the .part says 1000 bytes here; make it say 1 GB without writing it
|
||||
import os
|
||||
with open(part, "r+b") as f:
|
||||
f.truncate(1_000_000_000)
|
||||
out = strata_mcp.files_progress(prog_, {"total_gb": 1.0}, files)
|
||||
self.assertAlmostEqual(out["download"]["done_gb"], 0.5, places=2)
|
||||
self.assertEqual(out["download"]["percent"], 50)
|
||||
|
||||
def test_the_hash_check_has_its_own_figure(self):
|
||||
lines = HEAD + STEP5 + [CHECK, " checking Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf: 12.00 / 58.49 GB (20%) "]
|
||||
p = strata_mcp.install_progress(lines)
|
||||
out = strata_mcp.combined_progress(p, {"folder": None, "total_gb": 58.5})
|
||||
self.assertEqual(out["download"]["file"], "checking files")
|
||||
self.assertEqual(out["download"]["percent"], 20)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -14,11 +14,12 @@ from strata_cli.launch.runner import download_text
|
||||
class AlreadyDownloaded(unittest.TestCase):
|
||||
def test_a_model_on_disk_is_not_called_a_download(self):
|
||||
dl = {"done_gb": 58.5, "total_gb": 58.5, "percent": 100.0}
|
||||
self.assertEqual(download_text(dl, True), "Model already downloaded (58.5 GB), checking the files")
|
||||
self.assertEqual(download_text(dl, True), "The model files are already on this computer (58.5 GB); checking them")
|
||||
|
||||
def test_a_real_download_keeps_its_numbers(self):
|
||||
dl = {"done_gb": 12.0, "total_gb": 58.5, "percent": 20.5}
|
||||
self.assertEqual(download_text(dl, False), "Downloading 12.0 of 58.5 GB")
|
||||
self.assertEqual(download_text(dl, False, "Downloading the draft layer"), "Downloading the draft layer: 12.0 of 58.5 GB")
|
||||
|
||||
|
||||
class MonitorFindsLaunch(unittest.TestCase):
|
||||
|
||||
@@ -40,9 +40,13 @@ KNOWN = [
|
||||
("swift", "Q2_0", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0"),
|
||||
("swift", "IQ2_XS", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ2_XS"),
|
||||
("swift", "IQ3_XXS", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS"),
|
||||
("swift", "IQ3_S", "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF", "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S"),
|
||||
("coder", "IQ1_M", "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF", "IQ1_M/"),
|
||||
("unsloth", "UD-IQ4_XS", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-IQ4_XS/"),
|
||||
("unsloth", "UD-Q4_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q4_K_XL/"),
|
||||
("unsloth", "UD-Q5_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q5_K_XL/"),
|
||||
("unsloth", "UD-Q6_K_XL", "unsloth/Qwen3.8-Flash-Next-GGUF", "UD-Q6_K_XL/"),
|
||||
("unsloth", "Q8_0", "unsloth/Qwen3.8-Flash-Next-GGUF", "Q8_0/"),
|
||||
]
|
||||
|
||||
|
||||
|
||||
+31
-6
@@ -1319,7 +1319,7 @@ class Strata:
|
||||
res = self.state("install-result")
|
||||
running = proc_alive(j.get("pid"), j.get("ident"))
|
||||
log_path = Path(j.get("log", ""))
|
||||
tail = read_tail(log_path, 400) if log_path.name else []
|
||||
tail = read_tail(log_path, 1500) if log_path.name else [] # a step's heading must stay inside it: the pack tools print hundreds of lines
|
||||
prog = install_progress(tail)
|
||||
prog = combined_progress(prog, j)
|
||||
out = {"running": running, "started": j.get("started"), "model": j.get("model"), "family": j.get("family"),
|
||||
@@ -1406,8 +1406,12 @@ def files_progress(prog: dict, job: dict, files: list) -> dict:
|
||||
except OSError:
|
||||
state, have = "waiting", 0
|
||||
total = f.get("bytes") or (have if state == "done" else 0)
|
||||
if state == "downloading" and not total and cur_gb and p.name in str(log.get("file", "")): # the log line names this file
|
||||
total = int(cur_gb * 1e9)
|
||||
if state == "downloading" and cur_gb and p.name in str(log.get("file", "")): # the log line names this file
|
||||
# The .part file is as long as the furthest byte written, which the parallel pieces push to the full size well before the
|
||||
# download is done: the pieces setup counts are the truth.
|
||||
have = min(have, int(float(log.get("done_gb") or 0) * 1e9)) if have else have
|
||||
if not total:
|
||||
total = int(cur_gb * 1e9)
|
||||
rows.append({"role": f.get("role", "model"), "state": state, "have": have, "total": max(total, have)})
|
||||
plan_total = float(job.get("total_gb") or 0) * 1e9
|
||||
parts = []
|
||||
@@ -1443,12 +1447,12 @@ def draft_progress(prog: dict, job: dict, dl: dict) -> dict:
|
||||
if job.get("files"):
|
||||
base = files_progress({}, job, job["files"])
|
||||
parts = [dict(p, state="done", done_gb=p["total_gb"]) for p in base.get("parts", []) if p.get("state") == "done"]
|
||||
parts.append({"kind": "draft", "name": "Speed-up layer", "state": "done" if int(dl.get("percent") or 0) >= 100 else "downloading",
|
||||
parts.append({"kind": "draft", "name": "Draft layer", "state": "done" if int(dl.get("percent") or 0) >= 100 else "downloading",
|
||||
"done_gb": round(done_gb, 3), "total_gb": round(total_gb, 3)})
|
||||
total = sum(p["total_gb"] for p in parts)
|
||||
done = min(sum(p["done_gb"] for p in parts), total)
|
||||
prog["parts"] = parts
|
||||
prog["download"] = {"file": "Speed-up layer", "done_gb": round(done, 3), "total_gb": round(total, 3),
|
||||
prog["download"] = {"file": "Draft layer", "done_gb": round(done, 3), "total_gb": round(total, 3),
|
||||
"remaining_gb": round(max(0.0, total - done), 3),
|
||||
"percent": min(99, int(100 * done / total)) if total else 0}
|
||||
return prog
|
||||
@@ -1463,6 +1467,13 @@ def combined_progress(prog: dict, job: dict) -> dict:
|
||||
dl = prog.get("download") or {}
|
||||
if step.startswith("6/") and str(dl.get("file", "")).startswith("MTP draft layer"):
|
||||
return draft_progress(prog, job, dl)
|
||||
if step.startswith("5/") and str(dl.get("file", "")).startswith("checking "):
|
||||
# setup is hashing files that are all on disk: the figure is the check's own (not a download at "99%")
|
||||
if job.get("files"):
|
||||
prog = files_progress(prog, job, job["files"])
|
||||
prog["download"] = {"file": "checking files", "done_gb": dl["done_gb"], "total_gb": dl["total_gb"],
|
||||
"remaining_gb": round(max(0.0, dl["total_gb"] - dl["done_gb"]), 3), "percent": int(dl["percent"])}
|
||||
return prog
|
||||
if job.get("files") and step.startswith("5/"): # the install knows its files: count each of them
|
||||
return files_progress(prog, job, job["files"])
|
||||
if not folder or not total or not step.startswith("5/"):
|
||||
@@ -1494,7 +1505,7 @@ def install_progress(lines: list[str]) -> dict:
|
||||
for i, line in enumerate(lines):
|
||||
m = re.search(r"=== Step (\d+): (.+?) ===", line)
|
||||
if m:
|
||||
step, title, err = int(m.group(1)), m.group(2), None
|
||||
step, title, err, dl = int(m.group(1)), m.group(2), None, None # a download figure belongs to its own step
|
||||
m = re.match(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)", line)
|
||||
if m:
|
||||
dl = {"file": m.group(1), "done_gb": float(m.group(2)), "total_gb": float(m.group(3)),
|
||||
@@ -1508,6 +1519,9 @@ def install_progress(lines: list[str]) -> dict:
|
||||
out["download"] = dl
|
||||
if err:
|
||||
out["error"] = err
|
||||
words = progress_words_for(step, lines, dl)
|
||||
if words:
|
||||
out["label"], out["phase"] = words
|
||||
return out
|
||||
|
||||
|
||||
@@ -1524,6 +1538,17 @@ def physical_cores() -> int | None:
|
||||
return os.cpu_count()
|
||||
|
||||
|
||||
def progress_words_for(step, lines, download):
|
||||
"""(the plain sentence, its phase) for what setup is doing now (strata_control/progress_words.py, the words the Terminal uses too);
|
||||
None when this Strata folder does not carry the module."""
|
||||
try:
|
||||
from strata_control import progress_words
|
||||
except ImportError:
|
||||
return None
|
||||
w = progress_words.describe(step, lines, download)
|
||||
return w.label, w.phase
|
||||
|
||||
|
||||
def own_ram_gb() -> float:
|
||||
if WIN:
|
||||
class MS(ctypes.Structure):
|
||||
|
||||
@@ -113,7 +113,7 @@ def install(ram, found, argv, answers=None, extra=(), avx512=False, configs=()):
|
||||
mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None),
|
||||
mock.patch.object(setup, "download", fake_download),
|
||||
mock.patch.object(setup, "check_shards", lambda shards: None),
|
||||
mock.patch.object(setup, "verify_sha256", lambda *a: None),
|
||||
mock.patch.object(setup, "verify_sha256", lambda *a, **k: None),
|
||||
mock.patch.object(setup, "run", lambda *a, **k: None),
|
||||
mock.patch.object(setup, "mtp_corrupt", lambda *a, **k: False),
|
||||
mock.patch.object(setup, "refresh_draft_vocab", lambda *a, **k: None),
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
"""setup.py and the person's own model files (--gguf-dir): setup checks them, it never deletes them (0.2.2).
|
||||
|
||||
python -m unittest tools.test_setup_ownfiles
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tools"))
|
||||
import setup # noqa: E402
|
||||
|
||||
|
||||
def run(fn, *args, **kw):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
try:
|
||||
fn(*args, **kw)
|
||||
code = 0
|
||||
except SystemExit as e:
|
||||
code = e.code
|
||||
return code, out.getvalue()
|
||||
|
||||
|
||||
class OwnFileChecks(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.file = Path(self.tmp.name) / "model-00001-of-00002.gguf"
|
||||
self.file.write_bytes(b"abcdefgh" * 100)
|
||||
self.sha = hashlib.sha256(self.file.read_bytes()).hexdigest()
|
||||
|
||||
def test_a_downloaded_file_of_the_wrong_size_asks_to_delete_it(self):
|
||||
code, text = run(setup.verify_sha256, self.file, 801, self.sha)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("delete it and run setup again", text)
|
||||
|
||||
def test_an_own_file_of_the_wrong_size_is_left_and_the_text_says_so(self):
|
||||
code, text = run(setup.verify_sha256, self.file, 801, self.sha, own=True)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("your file was left as it is", text)
|
||||
self.assertTrue(self.file.exists())
|
||||
|
||||
def test_an_own_file_with_another_hash_is_not_deleted(self):
|
||||
code, text = run(setup.verify_sha256, self.file, 800, "0" * 64, own=True)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("does not match the published file", text)
|
||||
self.assertTrue(self.file.exists())
|
||||
|
||||
def test_a_downloaded_file_with_another_hash_is_deleted_as_before(self):
|
||||
code, _text = run(setup.verify_sha256, self.file, 800, "0" * 64)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertFalse(self.file.exists())
|
||||
|
||||
def test_a_matching_own_file_passes(self):
|
||||
code, _text = run(setup.verify_sha256, self.file, 800, self.sha, own=True)
|
||||
self.assertEqual(code, 0)
|
||||
|
||||
|
||||
class CheckingShowsItsProgress(unittest.TestCase):
|
||||
def test_a_big_file_is_hashed_with_a_progress_line_of_its_own(self):
|
||||
"""Hashing a 60 GB shard takes minutes: the app and the Terminal show it as 'checking', with a figure (not a download stuck at 99%)."""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
f = Path(tmp) / "big-00001-of-00002.gguf"
|
||||
size = (1 << 30) + 4096
|
||||
with open(f, "wb") as g:
|
||||
g.truncate(size)
|
||||
sha = hashlib.sha256()
|
||||
with open(f, "rb") as g:
|
||||
for block in iter(lambda: g.read(16 << 20), b""):
|
||||
sha.update(block)
|
||||
import time
|
||||
original = time.time
|
||||
ticks = iter(range(0, 10_000, 3))
|
||||
setup.time.time = lambda: float(next(ticks)) # every read looks 3 s later: the progress line prints
|
||||
try:
|
||||
code, text = run(setup.verify_sha256, f, size, sha.hexdigest())
|
||||
finally:
|
||||
setup.time.time = original
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("checking big-00001-of-00002.gguf (SHA-256", text)
|
||||
self.assertRegex(text, r"checking big-00001-of-00002\.gguf: +\d+\.\d\d / 1\.07 GB \(\d+%\)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -106,7 +106,7 @@ class InstallOwnPath(unittest.TestCase):
|
||||
self.calls.append(("config", path.name))
|
||||
|
||||
patches = [mock.patch.object(setup, "download", lambda url, dst, what=None: self.calls.append(("get", url, dst))),
|
||||
mock.patch.object(setup, "verify_sha256", lambda s, size, sha: self.calls.append(("sha", s.name))),
|
||||
mock.patch.object(setup, "verify_sha256", lambda s, size, sha, own=False: self.calls.append(("sha", s.name))),
|
||||
mock.patch.object(setup, "free_gb", lambda p: 500.0),
|
||||
mock.patch.object(setup, "pip_install", lambda *a, **k: None),
|
||||
mock.patch.object(setup, "engine_step", engine_step),
|
||||
|
||||
@@ -346,6 +346,17 @@ class Validation(FakeRoot):
|
||||
for d in ok:
|
||||
self.assertEqual(M.norm(self.tools.check_data_dir(str(d))), M.norm(d))
|
||||
|
||||
def test_the_persons_own_data_folder_is_accepted_whatever_it_is_called(self):
|
||||
"""The app writes the folder the person chose into the settings file (apps/host model-folder.mjs); an AI tool naming a new
|
||||
folder still needs a Strata... name."""
|
||||
chosen = self.root.parent / "my-big-disk"
|
||||
chosen.mkdir()
|
||||
self.assertRejected("strata_install", {"data_dir": str(chosen)}, "named Strata")
|
||||
settings = self.tools.s.settings_path()
|
||||
settings.parent.mkdir(parents=True, exist_ok=True)
|
||||
settings.write_text(json.dumps({"data_dir": str(chosen)}))
|
||||
self.assertEqual(M.norm(self.tools.check_data_dir(str(chosen))), M.norm(chosen))
|
||||
|
||||
def test_other_tools_arguments(self):
|
||||
self.assertRejected("strata_start", {"model": "../../etc/passwd"}, "not valid")
|
||||
self.assertRejected("strata_start", {"model": "q2_0"}, "no model is installed")
|
||||
@@ -944,7 +955,7 @@ class DraftLayerAndCancel(unittest.TestCase):
|
||||
shard.write_bytes(b"x" * 20_000_000)
|
||||
job = {"files": [{"path": str(shard), "bytes": None, "role": "model"}], "total_gb": 60}
|
||||
prog = M.combined_progress(M.install_progress(lines), job)
|
||||
self.assertEqual(prog["download"]["file"], "Speed-up layer")
|
||||
self.assertEqual(prog["download"]["file"], "Draft layer")
|
||||
self.assertEqual([p["kind"] for p in prog["parts"]], ["model", "draft"])
|
||||
self.assertEqual(prog["parts"][0]["state"], "done")
|
||||
self.assertAlmostEqual(prog["parts"][1]["done_gb"], 2.0)
|
||||
|
||||
Reference in new issue
Block a user