diff --git a/app/host/server/native-resources.mjs b/app/host/server/native-resources.mjs index ecce17e77a..59d25d465d 100644 --- a/app/host/server/native-resources.mjs +++ b/app/host/server/native-resources.mjs @@ -1,4 +1,4 @@ -import {USER_KEY,flagValue} from './native-user-args.mjs'; +import {USER_KEY,flagValue,capture} from './native-user-args.mjs'; import {parseEngineVersion} from './engine-version.mjs'; /** The engine's own default reserve, and the one setup writes for pictures read on the GPU: neither is a choice of the person. */ @@ -93,6 +93,8 @@ export function resourceSettings(config,hardware,profile,model={},values={}){ const dropEnv=name=>{if(config.env&&name in config.env){env={...(env??config.env)};delete env[name];}}; if(baseline.ramHeadroom)dropEnv('STRATA_RESIDENT_HEADROOM_GIB'); if(baseline.ramKeep)dropEnv('STRATA_RAM_KEEP_GIB'); + /* setup's two budgets (setupRamBudget): a STRATA_RAM_KEEP_GIB or STRATA_RESIDENT_HEADROOM_GIB of the person's (what is left in the env now is theirs) says how much RAM to leave, so "work" swaps in no number of its own. */ + const setupBudget=setupRamBudget(config,args,profile,baseline.setupBudget,Boolean((env??config.env)?.STRATA_RAM_KEEP_GIB||(env??config.env)?.STRATA_RESIDENT_HEADROOM_GIB||args.includes('--ram-keep-gib'))); const ram=Number(hardware?.ram_gb)||0,arena=Number(model?.arenaGb)||0;let ramKeep=false,ramBudget=false,ramHeadroom=false; // The person's own RAM choice wins: a RAM mode or --ram-keep-gib in their args, and STRATA_RAM_KEEP_GIB or STRATA_RESIDENT_HEADROOM_GIB of theirs in the env (the engine reads those first). const mineEnv=Boolean((env??config.env)?.STRATA_RAM_KEEP_GIB); @@ -105,7 +107,22 @@ export function resourceSettings(config,hardware,profile,model={},values={}){ if(!(env??config.env)?.STRATA_RESIDENT_HEADROOM_GIB){env={...(env??config.env??{}),STRATA_RESIDENT_HEADROOM_GIB:String(Math.ceil(ram*.2))};ramHeadroom=true;} } } - return {args,vram_reserve_mib:reserve,...(asked!==null?{}:{ui_reserve_applied:reserve}),...(env?{env}:{}),ui_resource_baseline:{...baseline,ramBudget,ramHeadroom,ramKeep}}; + const kept={...baseline,ramBudget,ramHeadroom,ramKeep};delete kept.setupBudget;if(setupBudget!==null)kept.setupBudget=setupBudget; + return {args,vram_reserve_mib:reserve,...(asked!==null?{}:{ui_reserve_applied:reserve}),...(env?{env}:{}),ui_resource_baseline:kept}; +} + +/** The RAM budget setup wrote (--resident-budget-gib in "args"), when setup also wrote the number "Leave 20% for my work" runs with ("ui_budget_work_gib", setup.py + * resident_budget_gib(work=True): the one place of the rule, so the app holds no copy of it). setup's budget is the RAM less 17 GB; the work number is the earlier rule, + * the RAM less 24 GB (40 on 64 GB: 16.6 GiB really free under a 64 GiB limit, against 9.3 GiB at 47). "work" swaps it into `args` (in place) and returns the + * setup number it replaced, kept in the baseline (`setupBudget`); "performance" puts that number back, but only while the budget is still the one the app swapped in. + * A budget the person set (user_args, or a change of "args" since the file was written, as capture() reads them) is theirs in both profiles; a config with no work number + * (a 0.2.16 install, a budget the person asked setup for, a layer split, unified memory where both rules are 24) is left as it is. Returns the setup number the baseline must keep, or null. */ +function setupRamBudget(config,args,profile,previous,ownRam=false){ + const work=Number(config.ui_budget_work_gib),at=args.indexOf('--resident-budget-gib'),have=at>=0?Number(args[at+1]):NaN; + if(!(work>0)||!Number.isFinite(have)||flagValue(capture(config),'--resident-budget-gib')!==null)return null; + if(profile==='work'){if(have===work)return Number(previous)>0?Number(previous):null;if(ownRam)return null;args[at+1]=String(work);return have;} // already swapped in (an earlier load): keep what it replaced + if(have===work&&Number(previous)>0)args[at+1]=String(Number(previous)); // back to setup's own + return null; } /** The RAM, in GiB, "Leave 20% for my work" asks the engine to keep free: a fifth of the PC's RAM rounded up, never under 5 or over 8 diff --git a/app/host/tests/resource-rammode.test.mjs b/app/host/tests/resource-rammode.test.mjs new file mode 100644 index 0000000000..a2d888251f --- /dev/null +++ b/app/host/tests/resource-rammode.test.mjs @@ -0,0 +1,119 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { resourceSettings } from '../server/native-resources.mjs'; + +/* 0.2.17 RAMMODE (owner 11-19): setup writes the RAM budget of the new rule (the RAM less 17 GB, 47 on 64 GB) in "args" and, beside it, the number of the old rule (the RAM less + 24 GB, 40) as "ui_budget_work_gib". "Leave 20% for my work" swaps the second in and records the first in the baseline; "Full performance" runs with setup's own, and puts it back + after a work load. The app holds no copy of the rule. */ + +const pc64 = { cpu: { cores: 12 }, ram_gb: 63, gpus: [{ index: 0, name: 'NVIDIA GeForce RTX 5070', vram_gb: 11.9 }] }; +const udQ4 = { arenaGb: 77, engineVersion: '0.1.57' }; +const flag = (args, name) => args[args.indexOf(name) + 1]; +const budgetOf = r => flag(r.args, '--resident-budget-gib'); +const written = args => ({ args, args_written: [...args] }); +const base = ['--native', 'x.gguf', '--max-context', '8192', '--pool-workers', '12']; +/** A 0.2.17 config: setup's 47 and the work number 40. */ +const fresh = (extra = {}) => ({ gpu: 0, ...written([...base, '--resident-budget-gib', '47']), ui_budget_work_gib: 40, ...extra }); +/** A 0.2.16 config: setup's old 40, no second number. */ +const old0216 = (extra = {}) => ({ gpu: 0, ...written([...base, '--resident-budget-gib', '40']), ...extra }); +const asSaved = (config, r, profile) => ({ ...config, args: r.args, args_written: [...r.args], env: r.env, ui_resource_profile: profile, ui_resource_baseline: r.ui_resource_baseline }); + +test('a config from setup 0.2.17: work gets the old number, full performance setup\'s own', () => { + const work = resourceSettings(fresh(), pc64, 'work', udQ4); + assert.equal(budgetOf(work), '40'); + assert.equal(work.ui_resource_baseline.setupBudget, 47, 'what it replaced is kept to put back'); + assert.equal(work.env, undefined, 'a RAM mode is in the args: the app adds no env of its own (as before)'); + const perf = resourceSettings(fresh(), pc64, 'performance', udQ4); + assert.equal(budgetOf(perf), '47'); + assert.equal(perf.ui_resource_baseline.setupBudget, undefined); +}); + +test('every RAM size setup writes both numbers for (32, 48, 64 GB): work takes the second, performance the first', () => { + for (const [ram, newer, older] of [[32, 15, 8], [48, 31, 24], [64, 47, 40]]) { + const pc = { ...pc64, ram_gb: ram - 0.3 }; + const config = { gpu: 0, ...written([...base, '--resident-budget-gib', String(newer)]), ui_budget_work_gib: older }; + assert.equal(budgetOf(resourceSettings(config, pc, 'work', udQ4)), String(older), `${ram} GB work`); + assert.equal(budgetOf(resourceSettings(config, pc, 'performance', udQ4)), String(newer), `${ram} GB performance`); + } +}); + +test('work then performance puts setup\'s number back, work again swaps again, and a second work load changes nothing', () => { + const cfg = fresh(); + const work = resourceSettings(cfg, pc64, 'work', udQ4); + const savedWork = asSaved(cfg, work, 'work'); + const again = resourceSettings(savedWork, pc64, 'work', udQ4); + assert.equal(budgetOf(again), '40'); + assert.equal(again.ui_resource_baseline.setupBudget, 47, 'the number it replaced is not lost on a second work load'); + const back = resourceSettings(savedWork, pc64, 'performance', udQ4); + assert.equal(budgetOf(back), '47'); + assert.equal(back.ui_resource_baseline.setupBudget, undefined); + const backAndForth = resourceSettings(asSaved(cfg, back, 'performance'), pc64, 'work', udQ4); + assert.equal(budgetOf(backAndForth), '40'); + assert.equal(backAndForth.args.filter(a => a === '--resident-budget-gib').length, 1); +}); + +test('an existing 0.2.16 config (setup\'s 40, no second number) is left as it is in both modes (the update moves it, setup.migrate_ram_budget)', () => { + for (const profile of ['work', 'performance']) { + const r = resourceSettings(old0216(), pc64, profile, udQ4); + assert.equal(budgetOf(r), '40', profile); + assert.equal(r.ui_resource_baseline.setupBudget, undefined, profile); + assert.equal(r.env, undefined, profile); + } + // after the move: 47 in args, 40 beside it: work keeps 40, performance has 47 + const moved = { ...old0216(), ...written([...base, '--resident-budget-gib', '47']), ui_budget_work_gib: 40 }; + assert.equal(budgetOf(resourceSettings(moved, pc64, 'work', udQ4)), '40'); + assert.equal(budgetOf(resourceSettings(moved, pc64, 'performance', udQ4)), '47'); +}); + +test('the person\'s own budget wins in both modes: user_args, a hand edit of args, an edit after the app wrote its number', () => { + const inUser = fresh({ user_args: ['--resident-budget-gib', '36'], args: [...base, '--resident-budget-gib', '36'] }); + const edited = { gpu: 0, args: [...base, '--resident-budget-gib', '33'], args_written: [...base, '--resident-budget-gib', '47'], ui_budget_work_gib: 40 }; + const sameAsWork = { gpu: 0, args: [...base, '--resident-budget-gib', '40'], args_written: [...base, '--resident-budget-gib', '47'], ui_budget_work_gib: 40 }; // typed by hand + for (const [label, cfg, expect] of [['user_args', inUser, '36'], ['edited args', edited, '33'], ['typed 40 over setup\'s 47', sameAsWork, '40']]) { + for (const profile of ['work', 'performance']) { + const r = resourceSettings(cfg, pc64, profile, udQ4); + assert.equal(budgetOf(r), expect, `${label}, ${profile}`); + assert.equal(r.ui_resource_baseline.setupBudget, undefined, `${label}, ${profile}: nothing to put back`); + } + } + // the app swapped 40 in, then the person set 30: performance does not put 47 over it + const work = resourceSettings(fresh(), pc64, 'work', udQ4); + const later = { ...asSaved(fresh(), work, 'work'), args: [...work.args.slice(0, work.args.indexOf('--resident-budget-gib') + 1), '30'] }; + assert.equal(budgetOf(resourceSettings(later, pc64, 'performance', udQ4)), '30'); + assert.equal(budgetOf(resourceSettings(later, pc64, 'work', udQ4)), '30'); +}); + +test('a --ram-keep-gib or a RAM mode of the person\'s, and STRATA_RAM_KEEP_GIB / STRATA_RESIDENT_HEADROOM_GIB of theirs in the env: no number swapped in, nothing added', () => { + for (const env of [{ STRATA_RAM_KEEP_GIB: '12' }, { STRATA_RESIDENT_HEADROOM_GIB: '20' }]) { + const work = resourceSettings(fresh({ env }), pc64, 'work', udQ4); + assert.equal(budgetOf(work), '47', JSON.stringify(env) + ': their RAM setting says how much to leave; setup\'s number stays'); + assert.deepEqual(work.env ?? env, env); + assert.equal(budgetOf(resourceSettings(fresh({ env }), pc64, 'performance', udQ4)), '47'); + } + const keepFlag = fresh({ user_args: ['--ram-keep-gib', '10'], args: [...base, '--resident-budget-gib', '47', '--ram-keep-gib', '10'] }); + assert.equal(budgetOf(resourceSettings(keepFlag, pc64, 'work', udQ4)), '47', 'a --ram-keep-gib of the person\'s says how much to leave: setup\'s number stays'); + assert.equal(flag(resourceSettings(keepFlag, pc64, 'work', udQ4).args, '--ram-keep-gib'), '10'); + // the env setting the app itself wrote (the 0.2.9 headroom) is not the person's + const appEnv = fresh({ env: { STRATA_RESIDENT_HEADROOM_GIB: '13' }, ui_resource_baseline: { workers: 12, reserve: 0, ramHeadroom: true } }); + assert.equal(budgetOf(resourceSettings(appEnv, pc64, 'work', udQ4)), '40'); +}); + +test('no second number (a budget the person asked setup for, a unified-memory PC, a layer split, every expert in RAM): the budget is left alone in both modes', () => { + const none = { gpu: 0, ...written([...base, '--resident-budget-gib', '52']) }; + for (const profile of ['work', 'performance']) { + assert.equal(budgetOf(resourceSettings(none, pc64, profile, udQ4)), '52', profile); + const noBudget = resourceSettings({ gpu: 0, ...written(base), ui_budget_work_gib: 40 }, pc64, profile, udQ4); + assert.equal(noBudget.args.includes('--resident-budget-gib'), false, `${profile}: a stale second number adds no budget`); + } + const uma = { cpu: { cores: 8 }, ram_gb: 63, gpus: [{ index: 0, name: 'AMD Radeon 8060S', vram_gb: 112, uma: true }] }; + const halo = { gpu: 0, ...written([...base, '--resident-budget-gib', '40']) }; // unified memory: 24 in both rules, setup writes no second number + for (const profile of ['work', 'performance']) assert.equal(budgetOf(resourceSettings(halo, uma, profile, udQ4)), '40', `unified memory, ${profile}`); +}); + +test('the other rules are unchanged: an older engine and no RAM mode still gets the 0.2.9 rule, a new engine the keep setting', () => { + const plain = { gpu: 0, args: [...base] }; + const oldEngine = resourceSettings(plain, pc64, 'work', { arenaGb: 50.3, engineVersion: '0.1.55' }); + assert.equal(flag(oldEngine.args, '--resident-budget-gib'), '40'); + assert.equal(oldEngine.ui_resource_baseline.setupBudget, undefined); + assert.equal(resourceSettings(plain, pc64, 'work', { arenaGb: 50.3, engineVersion: '0.1.57' }).env.STRATA_RAM_KEEP_GIB, '8'); +}); diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 261ec27621..8ee22bdcf3 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -120,7 +120,8 @@ The license is the Swift Open License 1.0. Install it with `strata launch --fami ### Unsloth's UD-Q4_K_XL A 4-bit quantization of the same model (111 GB, 72 GiB of experts). Install it with `--family unsloth --model UD-Q4_K_XL` -(RAM budget: your RAM less 17 GB, the rest read from the SSD). What it does and the manual workflow are in +(RAM budget: your RAM less 17 GB, 47 on 64 GB, the rest read from the SSD; the app's "Leave 20% for my work" keeps the earlier RAM less 24 GB, 40 on 64 GB: 16.6 GiB free +of 64 against 9.3 GiB, decode 57.7 against 84.2 tok/s). What it does and the manual workflow are in [UNSLOTH_Q4.md](UNSLOTH_Q4.md). --- @@ -798,7 +799,7 @@ in a RAM copy, as much as the RAM available at the start allows after a headroom fell to 0.9 GiB during the copy. `STRATA_RESIDENT_HEADROOM_GIB`, when set, decides the headroom instead of both (testers). - With W = 0 nothing about the fallback changes: the full system is used, the arena whenever it fits, with no margin, and the copy leaves the safety headroom. The explicit modes (`--resident-budget-gib N`, `--resident-experts`) leave `max(W, their own 4 GiB)`. -- The app's "Leave 20% for my work" passes W = clamp(ceil(0.2 x RAM in GB), 5, 8) as `STRATA_RAM_KEEP_GIB` in the run config's env (not as the flag, so an older engine chosen in the Engine tab, which ignores an env variable, still starts); `strata serve` and full performance pass nothing. +- The app's "Leave 20% for my work" passes W = clamp(ceil(0.2 x RAM in GB), 5, 8) as `STRATA_RAM_KEEP_GIB` in the run config's env (not as the flag, so an older engine chosen in the Engine tab, which ignores an env variable, still starts); `strata serve` and full performance pass nothing. A setup-written `--resident-budget-gib` in the run config is a RAM mode of its own: with it the app adds no `STRATA_RAM_KEEP_GIB`, and for UD-Q4_K_XL and UD-IQ4_XS "Leave 20% for my work" swaps in the earlier rule's number (`"ui_budget_work_gib"`, the RAM less 24 GB; the Terminal and full performance keep the RAM less 17 GB). - `STRATA_ARENA_FALLBACK_RESIDENT=0` keeps the plain file source for the fallback (testers). - The RAM copy is page-locked. `STRATA_RESIDENT_PIN=0` keeps it in ordinary pageable memory, as with `--resident-budget-gib`. Under a tight memory limit the system can then swap part of it out: with a 51.75 GiB limit on an R9700 PC (explicit 45.24 GiB budget, one run) diff --git a/docs/UNSLOTH_Q4.md b/docs/UNSLOTH_Q4.md index 6c71241545..29bd47f17f 100644 --- a/docs/UNSLOTH_Q4.md +++ b/docs/UNSLOTH_Q4.md @@ -29,7 +29,16 @@ strata launch --family unsloth --model UD-Q4_K_XL `--model UD-Q4_K_XL --yes` installs it anyway. - **The RAM budget** is the PC's RAM less 17 GB (`--resident-budget-gib 47` on 64 GB; 0.2.16 and earlier: less 24 GB, 40), at most all 71 GiB of experts. From a 64K context up, where the KV cache moves to RAM, its size comes out of the budget. `--resident-budget-gib N` at - setup sets another one; a bigger one is kept, with a note on what it risks. + setup sets another one; a bigger one is kept, with a note on what it risks. The reading is rounded up to the size the PC is sold with where it + is within 3% under it (a "64 GB" Windows PC reads 63.1 GiB, Linux 62.5 to 63.7: both give 47; a PC with 60 GB gives 43). +- **Which mode gets which number (0.2.17).** `--resident-budget-gib` in the run config is the RAM less 17 GB (47 on 64 GB): the Terminal (`strata launch`, + `strata serve`, Docker) and the app's "Full performance" run with it. The app's "Leave 20% for my work" runs with the number of the earlier rule, the RAM + less 24 GB (40 on 64 GB; 24 on 48 GB, 8 on 32 GB), which setup writes beside it as `"ui_budget_work_gib"`; the app swaps it in for that mode and puts the first one back + for "Full performance". The key is left out where the two numbers are the same (a unified-memory GPU keeps 24 in both; 96 GB and up keep every expert in RAM) and when + you asked setup for a budget (`--resident-budget-gib N`, or one in the config's `user_args`, or an edit of `args`): yours is used in both modes, as is a `--ram-keep-gib`, + `STRATA_RAM_KEEP_GIB` or `STRATA_RESIDENT_HEADROOM_GIB` of yours. A run config of 0.2.16 (setup's 40, no second number) is moved once, at the first + command of the new Control after the update: 40 becomes 47 and `"ui_budget_work_gib": 40` is added, so "Leave 20% for my work" keeps 40 + (32 GB: 8 -> 15 and 8; 48 GB: 24 -> 31 and 24). A number you set, a unified-memory PC and a layer split are not touched; the earlier file is kept as `.bak`. - **Download.** The four shards below from the pinned revision `38bb39e`, resumable. Setup checks each one's size and SHA-256 against the table below once and remembers it in the file's finish mark. A file with the wrong hash is deleted, so the next run downloads it again. @@ -162,10 +171,13 @@ Under a real 64 GiB memory limit (a cgroup the engine reads; UD-Q4_K_XL, an RTX | RAM less 17 | 47 | 37.0 GB | 2,873 ms | 84.2 tok/s | 54.7 GiB | 9.3 GiB | | RAM less 12 | 52 | 0.9 GB | 2,138 ms | 83.4 to 88.6 tok/s | 57.4 GiB | 6.6 GiB | +So "Full performance" and the Terminal read 9.3 GiB free of 64 with N 47, and "Leave 20% for my work" 16.6 GiB with N 40 (decode 84.2 and 57.7 tok/s). + A program that took 8 GiB after the engine had started: N 47 and 40 ran on, N 52 was killed by the kernel (the engine reads the free RAM at its start and lowers an N that does not fit then, not later). On Windows the engine takes the smaller of available RAM and available commit; for `--resident-budget-gib` its headroom is 4 GiB and the margin 256 MiB, so a PC -with A GiB available at the start runs N at most A - 4.25 (setup writes no `STRATA_RESIDENT_HEADROOM_GIB`). +with A GiB available at the start runs N at most A - 4.25 (setup writes no `STRATA_RESIDENT_HEADROOM_GIB`): on a 64 GB Windows PC (reads 63.1) with 55 GiB +available N 47 holds (room 50.75), with 50 GiB available it is 45.75, and N 40 ("Leave 20% for my work") holds from 44.25 GiB available. Setup does not count the experts of the card's own cache: the rule is the same for every card, and N above the experts outside the cache is not used (47.9 GiB on that card, about 63 GiB on a 12 GB card). diff --git a/terminal/setup.py b/terminal/setup.py index 83f318d17c..c1de05beb2 100644 --- a/terminal/setup.py +++ b/terminal/setup.py @@ -2315,6 +2315,7 @@ def split_budget(cfg: dict, yes: bool = False, explicit: bool = False) -> bool: "start it on one GPU: START-HERE.bat --gpu N (Linux: ./setup.sh --gpu N)") i = a.index("--resident-budget-gib") del a[i:i + 2] + cfg.pop(WORK_BUDGET_KEY, None) # no budget in args: nothing for "Leave 20% for my work" to swap ok(f"{model} on several GPUs: no RAM budget (the engine has none with a layer split) - all its experts are " "loaded into RAM from the model files at start, and the files pass through the OS file cache (#498)") return True @@ -3748,15 +3749,138 @@ def ready_fetch(model: str, models_dir: Path) -> None: verify_sha256(dst, size, sha) -def resident_budget_gib(model, ram, kv_ram_gb=0.0, uma=False) -> int: +def resident_budget_gib(model, ram, kv_ram_gb=0.0, uma=False, work=False) -> int: """UD-Q4_K_XL: the GiB of experts the engine keeps in RAM (--resident-budget-gib): the RAM (GiB, ram_gb()) less 17 (UNSLOTH_BUDGET_LEFT_GB) for the OS, the engine and the file cache the other experts are read through, less a KV cache streamed to RAM; at most all of them, at least 8. 64 GB: 47 (0.2.16: 40; docs/UNSLOTH_Q4.md). A unified-memory - GPU (`uma`) keeps the 24 it had: there the GPU's expert cache is RAM too, and 17 was measured on discrete cards only.""" - gib = round(ram) - (UNSLOTH_RAM_LEFT_GB if uma else UNSLOTH_BUDGET_LEFT_GB) - math.ceil(kv_ram_gb) + GPU (`uma`) keeps the 24 it had: there the GPU's expert cache is RAM too, and 17 was measured on discrete cards only. + `work`: the number the app's "Leave 20% for my work" runs with, the old rule (RAM less 24, 40 on 64 GB: 16.6 GiB really + free under a 64 GiB limit, against 9.3 GiB at 47, RESULTS-0217-RAMMODE). setup writes it beside the budget (WORK_BUDGET_KEY, + work_budget_key) and the app swaps it in; the app holds no copy of the rule.""" + return _budget_gib(model, nominal_ram_gb(ram), kv_ram_gb, UNSLOTH_RAM_LEFT_GB if (uma or work) else UNSLOTH_BUDGET_LEFT_GB) + + +def _budget_gib(model, ram, kv_ram_gb, left) -> int: + gib = round(ram) - left - math.ceil(kv_ram_gb) return max(8, min(gib, int(MODELS[model]["arena_gb"] / 1.073741824))) +NOMINAL_RAM_GB = (16, 24, 32, 48, 64, 96, 128, 192, 256) # the sizes a PC is sold with (above 256: a multiple of 8) +NOMINAL_RAM_MARGIN = 0.03 # a reading this close under one of them is that size + + +def nominal_ram_gb(ram) -> float: + """0.2.17 (owner 11-19): the RAM reading rounded UP to the size the PC is sold with, where it reads within 3% under it. A "64 GB" Windows PC reads + 63.1 GiB (ullTotalPhys; Linux MemTotal 62.5 to 63.7), which gave 46 where the same PC on Linux gave 47. A PC that really has less (60 GB) is not counted + as 64: 3% under 64 is 62.1. Only the RAM budget rule uses it (resident_budget_gib); every other test keeps the reading.""" + ram = float(ram) + size = next((s for s in NOMINAL_RAM_GB if ram <= s), None) + if size is None: + size = math.ceil(ram / 8) * 8 + return float(size) if size * (1 - NOMINAL_RAM_MARGIN) <= ram <= size else ram + + +WORK_BUDGET_KEY = "ui_budget_work_gib" # run config: the RAM budget (GiB) the app's "Leave 20% for my work" runs with, when it differs from the --resident-budget-gib in args + + +def work_budget_key(cfg: dict, work, asked=None) -> None: + """0.2.17: write (or leave out) WORK_BUDGET_KEY. `work` is resident_budget_gib(..., work=True) for a budget setup chose by its rule. The key is + left out when the person asked for the budget (`asked`: --resident-budget-gib N, theirs in every mode), when the args hold no budget (a layer + split, every expert in RAM, a mode of its own) and when the two numbers are the same (a unified-memory GPU: 24 in both).""" + cfg.pop(WORK_BUDGET_KEY, None) + args = cfg.get("args") + have = flag_value(args, "--resident-budget-gib") if isinstance(args, list) else None + if work is None or asked is not None or have is None: + return + try: + if float(have) == float(work): + return + except ValueError: + return + cfg[WORK_BUDGET_KEY] = int(work) + + +def _unified_memory_pc() -> bool: + """True when a graphics chip of this PC shares the RAM (Strix Halo and the like): its budget keeps the 24.""" + try: + return any(bool(g.get("uma")) for g in [*(gpus() or []), *(amd_gpus() or [])]) + except Exception: # noqa: BLE001 - an unreadable probe: the cautious answer, nothing moves + return True + + +def migrate_ram_budget(cfg: dict, ram=None, uma=None): + """0.2.17 (owner 11-19): a 0.2.16 run config (setup's budget under the old rule, the RAM less 24: 40 on 64 GB) without a setup run. Returns the config + with that budget moved to the new rule (47) and WORK_BUDGET_KEY set to the number "Leave 20% for my work" keeps (40), or None when nothing moves. + Moves only a number setup wrote: it is the one the old rule gives for this PC's RAM (the reading as 0.2.16 took it, or rounded to the PC's size), and + it is the same in "args_written" (an edited args differs), not in "user_args", no RAM setting of the person's is in the env (STRATA_RAM_KEEP_GIB, + STRATA_RESIDENT_HEADROOM_GIB, unless the app wrote it: ui_resource_baseline), no mode of the person's is in args (--ram-keep-gib) and no layer split + or unified-memory GPU is involved (24 in both rules). Idempotent: a config with WORK_BUDGET_KEY, or already on the new number, gives None. + A hand edit that typed exactly the old number into args looks the same as setup's own (a number in user_args does not).""" + args, written = cfg.get("args"), cfg.get(user_args.WRITTEN_KEY) + flag = "--resident-budget-gib" + have = flag_value(args, flag) if isinstance(args, list) else None + if WORK_BUDGET_KEY in cfg or have is None or not isinstance(written, list) or flag_value(written, flag) != have: + return None + if flag_value(user_args.flat(user_args.groups(cfg.get(user_args.USER_KEY))), flag) is not None or "--ram-keep-gib" in args: + return None + base = cfg.get("ui_resource_baseline") if isinstance(cfg.get("ui_resource_baseline"), dict) else {} + if base.get("ramBudget"): + return None # the 0.2.9 app wrote this one (80% of the RAM), not setup + env = cfg.get("env") if isinstance(cfg.get("env"), dict) else {} + for name, own in (("STRATA_RAM_KEEP_GIB", base.get("ramKeep")), ("STRATA_RESIDENT_HEADROOM_GIB", base.get("ramHeadroom"))): + if env.get(name) and not own: + return None + if isinstance(cfg.get("gpu"), list) and len(cfg["gpu"]) > 1: + return None # a layer split (#642 keeps the budget there): 24, as RAM64 left it + try: + have_n = float(have) + model = budget_model(cfg) + reading = ram_gb() if ram is None else float(ram) + ctx = int(flag_value(args, "--max-context") or 0) if "--kv-resident" in args else 0 + kv_ram = kv_streaming_ram_gb(ctx, flag_value(args, "--kv") or "int8") if ctx else 0.0 + if reading <= 0 or (_unified_memory_pc() if uma is None else uma): + return None + wrote = {_budget_gib(model, r, kv_ram, UNSLOTH_RAM_LEFT_GB) for r in (reading, nominal_ram_gb(reading))} # what 0.2.16 wrote on this PC (or now would) + new = resident_budget_gib(model, reading, kv_ram) + work = resident_budget_gib(model, reading, kv_ram, work=True) + except (ValueError, TypeError, KeyError): + return None + if have_n not in wrote or new == have_n: + return None + out = json.loads(json.dumps(cfg)) + out["args"][out["args"].index(flag) + 1] = str(new) + if work != new: + out[WORK_BUDGET_KEY] = int(work) + user_args.stamp(out) # args_written follows: the move is setup's own change, not the person's + return out + + +MOVE_MARK = "ram-budget-0217.done" # in a folder of run configs: the move below has looked at it (once, at the first command of the new Control) + + +def migrate_run_configs(folder) -> list: + """The run configs (strata-*.json) of `folder` moved by migrate_ram_budget, each written whole through a temporary file, the earlier one kept as + .bak. Returns the names moved. A file that cannot be read or written is skipped. strata_cli/ram_budget_move.py calls it once per folder.""" + moved = [] + for path in sorted(model_config_files(Path(folder))): + try: + old = json.loads(path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + continue + new = migrate_ram_budget(old) if isinstance(old, dict) else None + if new is None: + continue + try: + shutil.copyfile(path, path.with_name(path.name + ".bak")) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(new, indent=1), encoding="utf-8") + atomic.replace(tmp, path) + moved.append(path.name) + except OSError: + continue + return moved + + # MODEL-UPDATE Phase 2: Unsloth's files keep every expert in RAM (a pinned arena, as ISTA's files do) where the experts # and this much more fit the PC's RAM; the RAM budget (--resident-budget-gib: the hottest experts in RAM, the rest read # from the GGUF in place) only below that. The rule and the 16 GiB are sergqwer's fork (sergqwer/strata-nvfp4, @@ -7174,7 +7298,7 @@ def write_config(path: Path, cfg: dict): # "args_written" (strata_control/user_args.py) is setup's own; "user_args" is not in SETUP_KEYS on purpose: carry_over keeps it, # then applies the person's options over the generated ones SETUP_KEYS = frozenset({"exe", "args", "cwd", "tokenizer", "model_name", "log", "lib_dirs", "port", "backend", "env", - "gpu", "gpus_asked", "gpus_by", "layer_split", "host", "api_key", "draft_vocab", "vision", "args_written"}) + "gpu", "gpus_asked", "gpus_by", "layer_split", "host", "api_key", "draft_vocab", "vision", "args_written", "ui_budget_work_gib"}) SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_ROCBLAS_TUNING", "STRATA_RESIDENT_PIN", "STRATA_NO_ARENA_THP", "STRATA_MMQ_KQ", "STRATA_HC_Q8", "STRATA_ROUTE_TAIL_SKIP"}) | frozenset(GFX1103_SWITCHES) | frozenset(GFX1150_SWITCHES) # the "env" entries setup writes (the gfx1103 switches are setup's too: a re-run refreshes them, they do not linger) # 0.1.44 added these three, written for Unsloth's files only (unsloth_default_env). In any other model's config they are the @@ -7287,6 +7411,8 @@ def carry_user_args(old: dict, cfg: dict, explicit: list[str] | None = None) -> return [] cfg["args"] = user_args.merge(nargs, mine) user_args.stamp(cfg, mine) + if flag_value(mine, "--resident-budget-gib") is not None: + cfg.pop(WORK_BUDGET_KEY, None) # a RAM budget of the person's: theirs in every mode, no second number for the app to swap in return ["args " + f for f in dict.fromkeys(g[0] for g in user_args.groups(mine) if g[0].startswith("--"))] diff --git a/terminal/strata.py b/terminal/strata.py index 97eaec6336..94287aa363 100644 --- a/terminal/strata.py +++ b/terminal/strata.py @@ -51,6 +51,11 @@ if __name__ == "__main__": launcher_heal.heal(extra=[launcher_heal.installed_bin()]) except Exception: # noqa: BLE001 - never a reason for the command to fail pass + try: # the RAM budget setup wrote under the 0.2.16 rule moves to the 0.2.17 rule, once (strata_cli/ram_budget_move.py) + from strata_cli import ram_budget_move + ram_budget_move.run() + except Exception: # noqa: BLE001 - never a reason for the command to fail + pass code = _preflight(sys.argv[1:]) if code: raise SystemExit(code) diff --git a/terminal/strata_cli/ram_budget_move.py b/terminal/strata_cli/ram_budget_move.py new file mode 100644 index 0000000000..a8fa0aefca --- /dev/null +++ b/terminal/strata_cli/ram_budget_move.py @@ -0,0 +1,72 @@ +"""Move the RAM budget setup wrote under the 0.2.16 rule (the RAM less 24 GB, 40 on 64 GB) to the 0.2.17 rule (the RAM less 17 GB, 47), once, without a setup run. + +`strata update` installs a newer Control beside the install and never rewrites a run config, and the app's Load runs setup again only when the context, KV type or +pictures change, so an installed 0.2.16 model kept its 40 for ever (RESULTS-0217-RAM64). Owner 11-19: it moves. The first command a new Control runs (strata.py +calls this before anything heavy, the app host's first `strata models list --installed` among them) looks at every folder of run configs once and leaves a mark +there (`ram-budget-0217.done`). The rule and every check of what is setup's and what is the person's are setup.migrate_ram_budget (one place); this module only +finds the folders, imports setup.py when a config has a budget and no "ui_budget_work_gib" yet, and writes the mark. A config with nothing to move is not +written (byte-identical). Every failure is swallowed: a command must never fail because of this. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path + +BUDGET = "--resident-budget-gib" +WORK_KEY = "ui_budget_work_gib" +MARK = "ram-budget-0217.done" + + +def _folders() -> list[Path]: + from strata_control import models + return [p for p, _src in models.all_installs()] + + +def _needs_setup(folder: Path) -> bool: + """True when a config of the folder has a RAM budget and no second number: the only ones the move can change (stdlib only, no setup.py import).""" + for path in folder.glob("strata-*.json"): + if path.name.endswith(".shared-settings.json"): + continue + try: + cfg = json.loads(path.read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + continue + if isinstance(cfg, dict) and isinstance(cfg.get("args"), list) and BUDGET in cfg["args"] and WORK_KEY not in cfg: + return True + return False + + +def _load_setup(): + path = Path(__file__).resolve().parents[1] / "setup.py" + spec = importlib.util.spec_from_file_location("strata_setup_ram_budget", path) + module = importlib.util.module_from_spec(spec) + real = sys.stdout + sys.stdout = sys.stderr + try: + spec.loader.exec_module(module) + finally: + sys.stdout = real + return module + + +def run(folders=None, setup_module=None, say=None) -> dict: + """{folder: [config names moved]} for the folders looked at now (a folder with its mark is not looked at again).""" + say = say or (lambda text: sys.stderr.write(text + "\n")) + done: dict = {} + for folder in (_folders() if folders is None else [Path(f) for f in folders]): + try: + if not folder.is_dir() or (folder / MARK).exists(): + continue + moved = [] + if _needs_setup(folder): + moved = (setup_module or _load_setup()).migrate_run_configs(folder) + (folder / MARK).write_text("looked at by 0.2.17: the RAM budget setup wrote under the old rule is moved to the new one once (strata_cli/ram_budget_move.py)\n", encoding="utf-8") + done[str(folder)] = moved + if moved: + say("strata: the RAM budget of " + ", ".join(moved) + " moved to the 0.2.17 rule (the RAM less 17 GB); the earlier file is kept as .bak") + except Exception: # noqa: BLE001 - never a reason for the command to fail + continue + return done diff --git a/terminal/strata_control/setup_config.py b/terminal/strata_control/setup_config.py index ad165cb6ac..3e8f2ba730 100644 --- a/terminal/strata_control/setup_config.py +++ b/terminal/strata_control/setup_config.py @@ -227,6 +227,7 @@ def config_for(inp: SetupInputs, lib) -> SetupConfig: resident = False # an engine from before --resident-experts would refuse it ok(f"low-RAM mode: engine {meta.get('version')} has no resident variant yet; the experts are read through " "the OS file cache (run setup again after the next engine update)") + work_budget, work_asked = None, None # the app's "Leave 20% for my work" number (the old rule), written beside the budget (setup.work_budget_key) if low_ram and ready: # NVFP4 (68 GB of experts) on a PC whose RAM does not hold them: the RAM-budget mode, as Unsloth's files - the # most-used experts outside VRAM pinned within RAM less 17 GB (24 on a unified-memory GPU), the rest read from experts.bin. Mapped @@ -234,6 +235,7 @@ def config_for(inp: SetupInputs, lib) -> SetupConfig: # fell to 0.6 GB on the RTX 5070 PC (2026-10-13), where the budget mode kept 22 GB free rb = resident_budget_gib(model, ram, uma=gpu_uma) args += ["--resident-budget-gib", str(rb)] + work_budget = resident_budget_gib(model, ram, uma=gpu_uma, work=True) ok(f"low-RAM mode: {rb} GiB of {model}'s experts kept in RAM (the most used), the rest read from the pack's " "experts.bin on the SSD as needed") elif low_ram: # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped @@ -327,6 +329,8 @@ def config_for(inp: SetupInputs, lib) -> SetupConfig: warn("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off") if budget is not None and not q4_split: # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N args += ["--resident-budget-gib", f"{budget:g}"] # GiB kept in RAM (#498: a layer split had no budget) + work_budget = resident_budget_gib(model, ram, kv_ram_gb if "--kv-resident" in args else 0.0, gpu_uma, work=True) + work_asked = a.resident_budget_gib if gpu.get("uma") and "--expert-cache" in args: # #1715: the cache and the budget draw on the same RAM: a number that leaves the OS its room, not `auto` slots = uma_expert_cache(model, ram, budget, kv_ram_gb if "--kv-resident" in args else 0.0) @@ -428,6 +432,7 @@ def config_for(inp: SetupInputs, lib) -> SetupConfig: "lib_dirs": lib_dirs, "port": port} if cuda_tk == 12: # the experimental CUDA 12 engine (engine-cuda12/) cfg["cuda"] = 12 + lib.work_budget_key(cfg, work_budget, work_asked) # "ui_budget_work_gib": the number "Leave 20% for my work" swaps in for args' budget (none: the app leaves the budget alone) if (uenv := unsloth_default_env(family, model, hip, in_budget, str(gpu.get("arch") or ""))): cfg["env"] = uenv if hip: diff --git a/terminal/tests/snapshot/golden/nv_12gb_streaming/ud_iq4_xs_v31.json b/terminal/tests/snapshot/golden/nv_12gb_streaming/ud_iq4_xs_v31.json index 909918ce7e..c0be546235 100644 --- a/terminal/tests/snapshot/golden/nv_12gb_streaming/ud_iq4_xs_v31.json +++ b/terminal/tests/snapshot/golden/nv_12gb_streaming/ud_iq4_xs_v31.json @@ -60,6 +60,7 @@ "log": "/strata-unsloth-ud-iq4_xs-v31.log", "lib_dirs": [], "port": 8080, + "ui_budget_work_gib": 39, "env": { "STRATA_ROUTE_TAIL_SKIP": "0" }, diff --git a/terminal/tests/snapshot/golden/nv_12gb_streaming/ud_q4_k_xl.json b/terminal/tests/snapshot/golden/nv_12gb_streaming/ud_q4_k_xl.json index d429aa32b2..c4dac8c078 100644 --- a/terminal/tests/snapshot/golden/nv_12gb_streaming/ud_q4_k_xl.json +++ b/terminal/tests/snapshot/golden/nv_12gb_streaming/ud_q4_k_xl.json @@ -60,6 +60,7 @@ "log": "/strata-unsloth-ud-q4_k_xl.log", "lib_dirs": [], "port": 8080, + "ui_budget_work_gib": 39, "env": { "STRATA_ROUTE_TAIL_SKIP": "0" }, diff --git a/terminal/tools/test_setup_golden.json b/terminal/tools/test_setup_golden.json index 420369a2b2..491a2e8a93 100644 --- a/terminal/tools/test_setup_golden.json +++ b/terminal/tools/test_setup_golden.json @@ -548,6 +548,7 @@ "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", + "ui_budget_work_gib": 8, "vision": { "exe": "/engine/", "gpu": true, @@ -819,7 +820,7 @@ "--kv", "int8", "--resident-budget-gib", - "30", + "31", "--vision" ], "cwd": "", @@ -840,6 +841,7 @@ "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", + "ui_budget_work_gib": 24, "vision": { "exe": "/engine/", "gpu": false, @@ -1104,6 +1106,7 @@ "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "port": 8080, "tokenizer": "/data/packs/unsloth-ud-q4_k_xl/tokenizer", + "ui_budget_work_gib": 38, "vision": { "exe": "/engine/", "gpu": true, diff --git a/terminal/tools/test_setup_nvfp4.py b/terminal/tools/test_setup_nvfp4.py index 665761cedf..98a2a68049 100644 --- a/terminal/tools/test_setup_nvfp4.py +++ b/terminal/tools/test_setup_nvfp4.py @@ -278,6 +278,7 @@ class MockedInstall(unittest.TestCase): a = cfg["args"] self.assertFalse({"--mmap-experts", "--resident-experts"} & set(a)) self.assertEqual(a[a.index("--resident-budget-gib") + 1], "47") + self.assertEqual(cfg["ui_budget_work_gib"], 40) # 0.2.17: what "Leave 20% for my work" keeps (the RAM less 24) def test_amd_is_refused_with_a_recommendation(self): import test_setup_golden as G diff --git a/terminal/tools/test_setup_rammode.py b/terminal/tools/test_setup_rammode.py new file mode 100644 index 0000000000..441791c0aa --- /dev/null +++ b/terminal/tools/test_setup_rammode.py @@ -0,0 +1,318 @@ +"""0.2.17 RAMMODE (owner 11-19): setup writes two RAM budgets for UD-Q4_K_XL / UD-IQ4_XS. `--resident-budget-gib` in "args" is the new rule (the RAM less 17 GB: 47 on +64 GB), used by "Full performance" and by the Terminal; "ui_budget_work_gib" is the old rule (the RAM less 24 GB: 40 on 64 GB) that the app's "Leave 20% for my work" +swaps in (app/host/server/native-resources.mjs, tests/resource-rammode.test.mjs). The rule lives in one place, setup.resident_budget_gib(work=...). The person's own +budget wins in every mode: the key is left out when setup was asked for a budget, when the config keeps one of the person's, and where both rules give the same number. +Every outside effect is mocked (tools/test_setup_golden.py's install()). + + python -m unittest tools.test_setup_rammode +""" +from __future__ import annotations + +import json +import sys +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +from test_setup_golden import PROFILES, install # noqa: E402 +from test_setup_unsloth import Base # noqa: E402 + +M = "UD-Q4_K_XL" +KEY = "ui_budget_work_gib" +NAME = "strata-unsloth-ud-q4_k_xl.json" + + +def value(args, flag): + return args[args.index(flag) + 1] if flag in args[:-1] else None + + +class Rule(unittest.TestCase): + def test_the_two_numbers_for_every_ram_size(self): + # ram_gb() reads a little under the label. new = the RAM less 17 (Terminal, Full performance), work = the RAM less 24 (Leave 20% for my work) + for label, new, work in ((32, 15, 8), (48, 31, 24), (64, 47, 40), (96, 71, 71), (128, 71, 71)): + ram = label - 0.3 + self.assertEqual(setup.resident_budget_gib(M, ram), new, label) + self.assertEqual(setup.resident_budget_gib(M, ram, work=True), work, label) + self.assertEqual(setup.resident_budget_gib(M, ram, uma=True), work, label) # a unified-memory GPU: 24 in both + self.assertEqual(setup.resident_budget_gib(M, ram, uma=True, work=True), work, label) + self.assertEqual(setup.resident_budget_gib(M, 63.7, 1.7), 45) # a streamed KV cache comes out of both + self.assertEqual(setup.resident_budget_gib(M, 63.7, 1.7, work=True), 38) + self.assertEqual(setup.UNSLOTH_RAM_LEFT_GB, 24) + self.assertEqual(setup.UNSLOTH_BUDGET_LEFT_GB, 17) + # the other set that has a budget: UD-IQ4_XS (its cap is 55 GiB) + self.assertEqual((setup.resident_budget_gib("UD-IQ4_XS", 63.7), setup.resident_budget_gib("UD-IQ4_XS", 63.7, work=True)), (47, 40)) + + def test_the_key_helper(self): + def cfg(*extra): + return {"args": ["--max-context", "8192", *extra], KEY: 99} + c = cfg("--resident-budget-gib", "47") + setup.work_budget_key(c, 40) + self.assertEqual(c[KEY], 40) + for label, c, work, asked in (("the person asked for a budget", cfg("--resident-budget-gib", "52"), 40, 52.0), + ("both rules give the same number", cfg("--resident-budget-gib", "40"), 40, None), + ("no budget in the args", cfg(), 40, None), + ("no number", cfg("--resident-budget-gib", "47"), None, None), + ("another mode", cfg("--mmap-experts"), 40, None)): + setup.work_budget_key(c, work, asked) + self.assertNotIn(KEY, c, label) + self.assertIn(KEY, setup.SETUP_KEYS) # setup's own: a re-run refreshes it and takes it out again, never carries an old one over + + +class Nominal(unittest.TestCase): + """The reading is rounded UP to the size the PC is sold with, within 3% under it (Windows reads 63.1 on a 64 GB PC, and gave 46 where Linux gave 47).""" + + def test_rounds_up_to_the_size(self): + for reading, size in ((63.1, 64), (63.11, 64), (63.7, 64), (62.5, 64), (62.1, 64), (64.0, 64), (31.6, 32), (47.6, 48), (47.0, 48), (95.7, 96), (127.8, 128), + (15.7, 16), (23.5, 24), (191.0, 192), (254.0, 256), (300.0, 304), (303.0, 304)): + self.assertEqual(setup.nominal_ram_gb(reading), size, reading) + + def test_a_pc_with_less_stays_as_it_reads(self): + for reading in (60.0, 62.0, 61.0, 44.0, 30.0, 40.0, 80.0, 0.0, 20.0, 280.0): + self.assertEqual(setup.nominal_ram_gb(reading), reading, reading) + + def test_the_budget_rule_uses_it(self): + for reading, new, work in ((63.1, 47, 40), (63.7, 47, 40), (62.5, 47, 40), (31.6, 15, 8), (47.6, 31, 24), (60.0, 43, 36)): + self.assertEqual(setup.resident_budget_gib(M, reading), new, reading) + self.assertEqual(setup.resident_budget_gib(M, reading, work=True), work, reading) + self.assertEqual(setup.resident_budget_gib(M, 63.1, uma=True), 40) # a unified-memory PC: the same reading, 24 left + + +def old_config(budget, **extra): + """A run config as 0.2.16 setup wrote it (no second number), with its copy of what it wrote.""" + args = ["--native", "/models/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", "--max-context", "8192", "--kv", "int8", "--resident-budget-gib", str(budget)] + return {"exe": "component:strata-engine", "args": args, "args_written": list(args), "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "gpu": 0, **extra} + + +class Move(unittest.TestCase): + """0.2.17 (owner 11-19): an installed 0.2.16 config moves to the new rule without a setup run; what the person set stays.""" + + def move(self, cfg, ram=63.7, uma=False): + return setup.migrate_ram_budget(cfg, ram=ram, uma=uma) + + def test_a_0216_config_moves_and_work_mode_keeps_the_old_number(self): + for ram, old, new in ((31.7, 8, 15), (47.7, 24, 31), (63.7, 40, 47), (62.6, 40, 47)): + cfg = old_config(old) + before = json.dumps(cfg) + moved = self.move(cfg, ram) + self.assertEqual(value(moved["args"], "--resident-budget-gib"), str(new), ram) + self.assertEqual(moved[KEY], old, ram) # "Leave 20% for my work" keeps the old amount + self.assertEqual(moved["args_written"], moved["args"], ram) # setup's own change, not the person's + self.assertEqual(json.dumps(cfg), before, "the input is not changed") + self.assertEqual({k: v for k, v in moved.items() if k not in ("args", "args_written", KEY)}, {k: v for k, v in cfg.items() if k not in ("args", "args_written")}) + + def test_the_owner_pc_on_windows(self): + moved = self.move(old_config(39), ram=63.11) # 0.2.16 read 63.11 and wrote 39 + self.assertEqual((value(moved["args"], "--resident-budget-gib"), moved[KEY]), ("47", 40)) + + def test_a_second_run_changes_nothing(self): + moved = self.move(old_config(40)) + self.assertIsNone(self.move(moved)) + self.assertIsNone(self.move(old_config(47))) # already the new number + self.assertIsNone(self.move({**old_config(40), KEY: 40})) # the second number is there + + def test_every_expert_in_ram_and_no_budget(self): + cfg = old_config(40) + for flag in ("--resident-budget-gib", "40"): + cfg["args"].remove(flag) + cfg["args_written"] = list(cfg["args"]) + self.assertIsNone(self.move(cfg)) + self.assertIsNone(self.move(old_config(71), ram=95.7)) # 96 GB: 71 in both rules + + def test_what_the_person_set_is_never_touched(self): + mine = old_config(40) + mine["user_args"] = ["--resident-budget-gib", "40"] + edited = old_config(40) + edited["args"][-1] = "36" # a hand edit of args: differs from what setup wrote + edited_same = old_config(40) + edited_same["args_written"][-1] = "36" # (a budget the person edited back to setup's number is theirs too) + keep = old_config(40, env={"STRATA_RAM_KEEP_GIB": "12"}) + headroom = old_config(40, env={"STRATA_RESIDENT_HEADROOM_GIB": "20"}) + flag = old_config(40) + flag["args"] += ["--ram-keep-gib", "12"] + flag["args_written"] += ["--ram-keep-gib", "12"] + no_copy = old_config(40) + del no_copy["args_written"] # an older config: setup's number cannot be told from the person's + not_the_rule = old_config(36) # not what the old rule gives for this PC + for label, cfg in (("user_args", mine), ("args edited", edited), ("written differs", edited_same), ("STRATA_RAM_KEEP_GIB", keep), + ("STRATA_RESIDENT_HEADROOM_GIB", headroom), ("--ram-keep-gib", flag), ("no args_written", no_copy), ("a number of its own", not_the_rule)): + self.assertIsNone(self.move(cfg), label) + + def test_an_env_setting_the_app_wrote_is_not_the_persons(self): + cfg = old_config(40, env={"STRATA_RAM_KEEP_GIB": "8"}, ui_resource_baseline={"workers": 6, "ramKeep": True}) + self.assertEqual(value(self.move(cfg)["args"], "--resident-budget-gib"), "47") + app_budget = old_config(40, ui_resource_baseline={"workers": 6, "ramBudget": True}) # the 0.2.9 app's 80% rule wrote it + self.assertIsNone(self.move(app_budget)) + + def test_unified_memory_and_the_layer_split_stay_at_24(self): + self.assertIsNone(self.move(old_config(40), uma=True)) + self.assertIsNone(self.move({**old_config(40), "gpu": [0, 1], "layer_split": "auto"})) + + def test_a_streamed_kv_cache_comes_out_of_both(self): + cfg = old_config(38) + cfg["args"][cfg["args"].index("--max-context") + 1] = "131072" + cfg["args"] += ["--kv-resident", "32768"] + cfg["args_written"] = list(cfg["args"]) + moved = self.move(cfg) + self.assertEqual((value(moved["args"], "--resident-budget-gib"), moved[KEY]), ("45", 38)) + + def test_iq4_xs(self): + cfg = old_config(40) + cfg["args"][1] = "/models/Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf" + cfg["args_written"] = list(cfg["args"]) + self.assertEqual(setup.budget_model(cfg), "UD-IQ4_XS") + moved = self.move(cfg) + self.assertEqual((value(moved["args"], "--resident-budget-gib"), moved[KEY]), ("47", 40)) + + +class MoveFiles(unittest.TestCase): + """strata_cli/ram_budget_move.py: once per folder, byte-identical where nothing moves, the earlier file kept.""" + + def setUp(self): + import tempfile + self.tmp = tempfile.TemporaryDirectory() + self.dir = Path(self.tmp.name) + self.patches = [mock.patch.object(setup, "ram_gb", lambda: 63.7), mock.patch.object(setup, "_unified_memory_pc", lambda: False)] + for p in self.patches: + p.start() + from strata_cli import ram_budget_move + self.mod = ram_budget_move + + def tearDown(self): + for p in self.patches: + p.stop() + self.tmp.cleanup() + + def write(self, name, cfg): + (self.dir / name).write_text(json.dumps(cfg, indent=1), encoding="utf-8") + + def test_moves_once_and_leaves_the_rest_alone(self): + self.write("strata-unsloth-ud-q4_k_xl.json", old_config(40)) + mine = {**old_config(40), "user_args": ["--resident-budget-gib", "40"]} + self.write("strata-mine.json", mine) + self.write("strata-iq3_s.json", {"exe": "x", "args": ["--max-context", "8192"], "args_written": ["--max-context", "8192"]}) + self.write("strata-unsloth-ud-q4_k_xl.shared-settings.json", {"temperature": 0.7}) + before = {p.name: p.read_bytes() for p in self.dir.glob("*.json")} + done = self.mod.run([self.dir], setup_module=setup, say=lambda t: None) + self.assertEqual(done, {str(self.dir): ["strata-unsloth-ud-q4_k_xl.json"]}) + moved = json.loads((self.dir / "strata-unsloth-ud-q4_k_xl.json").read_text()) + self.assertEqual((value(moved["args"], "--resident-budget-gib"), moved[KEY]), ("47", 40)) + self.assertEqual((self.dir / "strata-unsloth-ud-q4_k_xl.json.bak").read_bytes(), before["strata-unsloth-ud-q4_k_xl.json"]) + for name in ("strata-mine.json", "strata-iq3_s.json", "strata-unsloth-ud-q4_k_xl.shared-settings.json"): + self.assertEqual((self.dir / name).read_bytes(), before[name], name) # byte-identical + self.assertTrue((self.dir / self.mod.MARK).is_file()) + after = (self.dir / "strata-unsloth-ud-q4_k_xl.json").read_bytes() + self.assertEqual(self.mod.run([self.dir], setup_module=setup, say=lambda t: None), {}) # a second run looks at nothing + self.assertEqual((self.dir / "strata-unsloth-ud-q4_k_xl.json").read_bytes(), after) + + def test_even_without_the_mark_a_moved_config_is_not_moved_again(self): + self.write("strata-unsloth-ud-q4_k_xl.json", old_config(40)) + self.mod.run([self.dir], setup_module=setup, say=lambda t: None) + (self.dir / self.mod.MARK).unlink() + after = (self.dir / "strata-unsloth-ud-q4_k_xl.json").read_bytes() + self.assertEqual(self.mod.run([self.dir], setup_module=setup, say=lambda t: None), {str(self.dir): []}) + self.assertEqual((self.dir / "strata-unsloth-ud-q4_k_xl.json").read_bytes(), after) + + def test_a_folder_that_is_not_there_is_skipped(self): + self.assertEqual(self.mod.run([self.dir / "nothing"], setup_module=setup), {}) + + +class Written(unittest.TestCase): + """The run config setup writes (setup.main() on a mocked PC).""" + found = PROFILES["64GB-1x32GB"][1] + + def run_setup(self, ram, *extra, configs=(), model=M): + return install(ram, self.found, ["--family", "unsloth", "--model", model, "--no-start", "--context", "8192", *extra], configs=configs) + + def test_each_ram_size(self): + for label, new, work in ((32, 15, 8), (48, 31, 24), (64, 47, 40)): + code, out, cfg, _ = self.run_setup(label - 0.3) + self.assertEqual(code, 0, out[-2000:]) + self.assertEqual(value(cfg["args"], "--resident-budget-gib"), str(new), label) + self.assertEqual(cfg[KEY], work, label) + for label in (96, 128): # every expert in RAM: no budget to swap + code, out, cfg, _ = self.run_setup(label - 0.3) + self.assertEqual(code, 0, out[-2000:]) + self.assertNotIn("--resident-budget-gib", cfg["args"], label) + self.assertNotIn(KEY, cfg, label) + + def test_the_budget_mode_at_the_cap_has_one_number(self): + with mock.patch.object(setup, "unsloth_budget", lambda *a, **k: True): # the budget mode on a 96 GB PC: 71 either way + code, out, cfg, _ = self.run_setup(95.7) + self.assertEqual(value(cfg["args"], "--resident-budget-gib"), "71") + self.assertNotIn(KEY, cfg) + + def test_a_streamed_kv_cache_comes_out_of_both(self): + code, out, cfg, _ = install(63.7, self.found, ["--family", "unsloth", "--model", M, "--no-start", "--context", "131072"]) + self.assertEqual(code, 0, out[-2000:]) + self.assertIn("--kv-resident", cfg["args"]) + self.assertEqual((value(cfg["args"], "--resident-budget-gib"), cfg[KEY]), ("45", 38)) + + def test_a_budget_the_person_asked_for_has_no_second_number(self): + for asked in ("52", "40", "30"): + code, out, cfg, _ = self.run_setup(63.7, "--resident-budget-gib", asked) + self.assertEqual(code, 0, out[-2000:]) + self.assertEqual(value(cfg["args"], "--resident-budget-gib"), asked) + self.assertNotIn(KEY, cfg, asked) + + def test_a_setup_run_again_over_a_0216_config(self): + code, out, first, _ = self.run_setup(63.7) + old = [*first["args"]] + old[old.index("--resident-budget-gib") + 1] = "40" # what 0.2.16 wrote: setup's 40, its copy, no second number + old_cfg = {k: v for k, v in first.items() if k != KEY} + code, out, cfg, _ = self.run_setup(63.7, configs=[(NAME, {**old_cfg, "args": old, "args_written": old})]) + self.assertEqual(code, 0, out[-2000:]) + self.assertEqual((value(cfg["args"], "--resident-budget-gib"), cfg[KEY]), ("47", 40)) + code, out, again, _ = self.run_setup(63.7, configs=[(NAME, cfg)]) # and once more: the same + self.assertEqual((value(again["args"], "--resident-budget-gib"), again[KEY]), ("47", 40)) + + def test_a_setup_run_again_over_a_config_the_app_put_in_work_mode(self): + code, out, first, _ = self.run_setup(63.7) + swapped = [*first["args"]] + swapped[swapped.index("--resident-budget-gib") + 1] = "40" # the app wrote its work budget and recorded it as written + code, out, cfg, _ = self.run_setup(63.7, configs=[(NAME, {**first, "args": swapped, "args_written": swapped, "ui_resource_profile": "work", + "ui_resource_baseline": {"workers": 6, "reserve": 0, "setupBudget": 47}})]) + self.assertEqual(code, 0, out[-2000:]) + self.assertEqual((value(cfg["args"], "--resident-budget-gib"), cfg[KEY]), ("47", 40)) + self.assertNotIn("user_args", cfg) # the app's swap is not taken for the person's + + def test_a_budget_the_person_set_stays_and_leaves_no_second_number(self): + code, out, first, _ = self.run_setup(63.7) + written = [*first["args"]] + written[written.index("--resident-budget-gib") + 1] = "40" + mine = [*written] + mine[mine.index("--resident-budget-gib") + 1] = "36" + for label, old in (("in user_args", {**first, "args": mine, "args_written": written, "user_args": ["--resident-budget-gib", "36"], KEY: 40}), + ("a hand edit of args", {**first, "args": mine, "args_written": written, KEY: 40})): + code, out, cfg, _ = self.run_setup(63.7, configs=[(NAME, old)]) + self.assertEqual(code, 0, out[-2000:]) + self.assertEqual(value(cfg["args"], "--resident-budget-gib"), "36", label) + self.assertNotIn(KEY, cfg, label) + + def test_a_layer_split_has_no_budget_and_no_second_number(self): + cfg = {"args": ["--pack", "p", "--resident-budget-gib", "47", "--kv", "int8"], KEY: 40, "gpu": [0, 1]} + with mock.patch.object(setup, "resident_split", lambda: False), mock.patch.object(setup, "ram_gb", lambda: 165.0): + self.assertTrue(setup.split_budget(cfg, yes=True, explicit=True)) + self.assertNotIn("--resident-budget-gib", cfg["args"]) + self.assertNotIn(KEY, cfg) + + +class UnifiedMemory(Base): + """A unified-memory GPU keeps 24 for the budget in every mode: there is no second number.""" + HALO = [{"index": 0, "name": "AMD Radeon 8060S", "vram_gb": 114.0, "arch": "gfx1151", "driver": "amdgpu", + "uma": True, "dedicated_gb": 2.0, "shared_gb": 112.0}] + + def test_one_number(self): + with mock.patch.object(setup, "get_prebuilt_hip", lambda *a, **k: self.t / "engine"), mock.patch.object(setup, "WIN", False), \ + mock.patch.object(setup, "build_engine_hip", lambda *a, **k: self.t / "engine"): + code, out, cfg = self.main(["--context", "8192", "--backend", "hip"], version="0.1.41", amd=self.HALO, ram=63.7, m="UD-IQ4_XS") + self.assertEqual(code, 0, out) + self.assertEqual(value(cfg["args"], "--resident-budget-gib"), "40") + self.assertNotIn(KEY, cfg) + + +if __name__ == "__main__": + unittest.main()