okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-s5 dab63e9c3 (tuning presets on Models, effective values, outcome codes, apply_saved_tuning) into f-split-int0c165b48b

main
9.1 KiB158 linesraw
1import test from 'node:test';
2import assert from 'node:assert/strict';
3import { readFileSync, writeFileSync, existsSync } from 'node:fs';
4import { join } from 'node:path';
5import { nativeFixture, finishJob } from './helpers/native-fixture.mjs';
6import { resultSentence } from '../server/native-autotune.mjs';
7
8const arg = (args, name) => { const i = args.indexOf(name); return i < 0 ? undefined : args[i + 1]; };
9
10/** A pretend `strata` command: records what it was asked, writes status-file steps, then prints its JSON. */
11function handler(log, { result, hold = false, delayMs = 60 } = {}) {
12  return (child, args) => {
13    log.push(args.slice(args.findIndex(a => String(a).endsWith('strata.py')) + 1));
14    const cmd = log.at(-1);
15    const out = json => { child.stdout.emit('data', Buffer.from(JSON.stringify(json))); child.exitCode = 0; child.emit('exit', 0); child.emit('close', 0); };
16    if (cmd[0] === 'presets' && cmd[1] === 'status') return out({ ok: true, active: null, suggested_name: 'IQ2_XS 32K – Full speed', presets: [], state: null, reasons: [] });
17    if (cmd[0] === 'presets' && cmd[1] === 'list') return out({ ok: true, presets: [{ id: 'a'.repeat(32), name: 'x' }] });
18    if (cmd[0] === 'presets' && cmd[1] === 'effective') return out({ ok: true, applied: true, preset: { id: 'a'.repeat(32), name: 'IQ2_XS 32K – Work' }, args: ['--kv-resident', '65536'], changed: [{ flag: '--kv-resident', was: '32768', now: '65536' }] });
19    if (cmd[0] === 'presets') return out({ ok: true, done: cmd[1] });
20    if (cmd[0] === 'tune') {
21      const status = arg(cmd, '--status-file');
22      writeFileSync(status, JSON.stringify({ state: 'running', stage: 'rounds', text: 'Finding the fastest settings for your PC… about 9 min left', minutes_left: 9, runs_done: 3, runs_planned: 9, elapsed_s: 400, message: 'Trying: host core' }));
23      if (hold) return;                       // stays running until killed
24      setTimeout(() => out({ ok: true, result }), delayMs);
25    }
26  };
27}
28
29const improved = { outcome: 'improved', gain_pct: 11.6, seconds: 900, preset: { id: 'b'.repeat(32), name: 'IQ2_XS 32K – Full speed' }, answers: { class: 'exact', fields: [] }, settings: { args: { '--host-core': 'last' }, env: {}, per_request: {} } };
30
31test('the result sentence is plain words with the gain and the saved name', () => {
32  assert.equal(resultSentence(improved), "+12% faster answers, saved as 'IQ2_XS 32K – Full speed'");
33  assert.match(resultSentence({ outcome: 'default_confirmed', preset: { name: 'X' } }), /already the fastest/);
34  assert.equal(resultSentence({ outcome: 'inconclusive', message: 'The PC was too noisy.' }), 'The PC was too noisy.');
35});
36
37test('a tune is started on the config a load would use, unloads nothing it did not have, follows progress and reports the saved name', async () => {
38  const log = [];
39  const f = nativeFixture({ tuneHandler: handler(log, { result: improved, delayMs: 2500 }) });
40  try {
41    await f.control.refresh(true);
42    const job = f.control.operation('autotune', { model: 'iq2_xs', mode: 'quick', use: 'chat', resourceProfile: 'work' });
43    let seen = null;
44    for (let n = 0; n < 200 && !seen; n++) { await new Promise(r => setTimeout(r, 30)); const j = f.control.state().jobs.find(x => x.id === job.id); if (j.progress) seen = j.progress; }
45    assert.ok(seen, 'progress from the status file reaches the job');
46    assert.equal(seen.minutesLeft, 9);
47    const done = await finishJob(f.control, job.id);
48    assert.equal(done.state, 'done', done.error);
49    assert.equal(done.result.summary, "+12% faster answers, saved as 'IQ2_XS 32K – Full speed'");
50    const cmd = log.find(c => c[0] === 'tune');
51    assert.equal(cmd[1], 'auto');
52    assert.equal(arg(cmd, '--mode'), 'quick');
53    assert.equal(arg(cmd, '--goal'), 'room');                 // "Leave 20% for my work"
54    assert.equal(arg(cmd, '--leave-ram'), '20');
55    assert.ok(!cmd.includes('--allow-small-differences'));
56    const cfg = JSON.parse(readFileSync(cmd[2], 'utf8'));      // the config the tuner measures is the one a load would start
57    assert.equal(cfg.ui_resource_profile, 'work');
58    assert.ok(Array.isArray(cfg.args) && cfg.args.includes('--max-context'));
59    assert.equal(cfg.api_key, undefined);
60    assert.ok(!existsSync(arg(cmd, '--status-file')), 'the status file is removed afterwards');
61  } finally { await f.cleanup(); }
62});
63
64test('full performance asks for speed with no memory left over, and the tick for small differences is only passed when ticked', async () => {
65  const log = [];
66  const f = nativeFixture({ tuneHandler: handler(log, { result: improved }) });
67  try {
68    await f.control.refresh(true);
69    const done = await finishJob(f.control, f.control.operation('autotune', { model: 'iq3_s', mode: 'thorough', resourceProfile: 'performance', allowSmallDifferences: true }).id);
70    assert.equal(done.state, 'done', done.error);
71    const cmd = log.find(c => c[0] === 'tune');
72    assert.equal(arg(cmd, '--goal'), 'speed');
73    assert.equal(cmd.includes('--leave-ram'), false);
74    assert.equal(arg(cmd, '--mode'), 'thorough');
75    assert.ok(cmd.includes('--allow-small-differences'));
76  } finally { await f.cleanup(); }
77});
78
79test('Stop ends the tune and keeps your settings; only one operation at a time', async () => {
80  const log = [];
81  const f = nativeFixture({ tuneHandler: handler(log, { hold: true }) });
82  try {
83    await f.control.refresh(true);
84    const job = f.control.operation('autotune', { model: 'iq2_xs' });
85    await new Promise(r => setTimeout(r, 80));
86    assert.throws(() => f.control.operation('autotune', { model: 'iq3_s' }), /current engine operation/);
87    await f.control.cancel(job.id);
88    const j = f.control.state().jobs.find(x => x.id === job.id);
89    assert.equal(j.state, 'cancelled');
90    assert.equal(j.result, null);
91  } finally { await f.cleanup(); }
92});
93
94test('a tune is refused while a model is generating, and loaded models are unloaded first', async () => {
95  const log = [];
96  const f = nativeFixture({ tuneHandler: handler(log, { result: improved }) });
97  try {
98    await f.control.refresh(true);
99    const loaded = await finishJob(f.control, f.control.operation('load', { model: 'iq2_xs' }).id);
100    assert.equal(loaded.state, 'done', loaded.error);
101    f.requests.push({ instanceId: loaded.result.instanceId, state: 'generating' });
102    const refused = await finishJob(f.control, f.control.operation('autotune', { model: 'iq2_xs' }).id);
103    assert.equal(refused.state, 'error');
104    assert.match(refused.error, /Finish requests/);
105    f.requests.length = 0;
106    const done = await finishJob(f.control, f.control.operation('autotune', { model: 'iq2_xs' }).id);
107    assert.equal(done.state, 'done', done.error);
108    assert.equal(f.control.state().instances.length, 0, 'the model was unloaded so the tuner has the graphics card');
109  } finally { await f.cleanup(); }
110});
111
112test('saved tunings: status for the choices, list, and actions go to Strata Control by id', async () => {
113  const log = [];
114  const f = nativeFixture({ tuneHandler: handler(log, {}) });
115  try {
116    await f.control.refresh(true);
117    const st = await f.control.tuneStatus({ model: 'iq2_xs', resourceProfile: 'performance' });
118    assert.equal(st.suggested_name, 'IQ2_XS 32K – Full speed');
119    const listed = await f.control.tunePresets.list();
120    assert.equal(listed.presets.length, 1);
121    await f.control.tunePresets.action('rename', 'a'.repeat(32), { name: 'My fast one' });
122    assert.deepEqual(log.at(-1).slice(0, 4), ['presets', 'rename', 'a'.repeat(32), 'My fast one']);
123    await assert.rejects(f.control.tunePresets.action('apply', '../x'), /Choose a saved tuning/);
124    await assert.rejects(f.control.tunePresets.action('format', 'a'.repeat(32)), /supported action/);
125  } finally { await f.cleanup(); }
126});
127
128test('a model that is not prepared cannot be tuned', async () => {
129  const f = nativeFixture({ tuneHandler: handler([], {}) });
130  try {
131    await f.control.refresh(true);
132    f.installed.models[0].ready = false;
133    await f.control.refresh(true);
134    const job = await finishJob(f.control, f.control.operation('autotune', { model: 'iq2_xs' }).id);
135    assert.equal(job.state, 'error');
136    assert.match(job.error, /Prepare the model/);
137  } finally { await f.cleanup(); }
138});
139
140test('Expert mode can read the tuned values and the tuning can be switched off for these choices', async () => {
141  const log = [];
142  const f = nativeFixture({ tuneHandler: handler(log, {}) });
143  try {
144    await f.control.refresh(true);
145    const eff = await f.control.tuneEffective({ model: 'iq2_xs', resourceProfile: 'work' });
146    assert.equal(eff.applied, true);
147    assert.deepEqual(eff.changed, [{ flag: '--kv-resident', was: '32768', now: '65536' }]);
148    const cmd = log.find(c => c[1] === 'effective');
149    const cfg = JSON.parse(readFileSync(cmd[2], 'utf8'));
150    assert.equal(cfg.ui_resource_profile, 'work');                 // the choices a load would make, so the right tuning is found
151    await f.control.tuneOff({ model: 'iq2_xs', resourceProfile: 'work' });
152    assert.deepEqual(log.at(-1).slice(0, 2), ['presets', 'off']);
153  } finally { await f.cleanup(); }
154});
155
156test('a busy PC is a plain result, not an error', () => {
157  assert.match(resultSentence({ outcome: 'inconclusive', code: 'busy_pc', message: 'x' }), /PC was busy/);
158});