okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
19.1 KiB234 linesraw
1import { tr } from '../lib/i18n';
2import { FloatingMenu } from '../components/FloatingMenu';
3import { LifecycleNotice } from '../components/LifecycleNotice';
4/** One configuration draft shared by simple choices, parameters and JSON. */
5import { useEffect, useMemo, useRef, useState } from 'react';
6import { DemoTest, PerformancePreview } from '../components/EngineExperience';
7import { AutoTune } from '../components/AutoTune';
8import { contextTokens, estimate, execution, RECOMMENDED_CONTEXT_TOKENS } from '../lib/experience';
9import type { Workload } from '../lib/experience';
10import { ActionError, Btn, Dialog, ErrorNotice, Icon, Select } from '../components/ui';
11import { Screen, SectionHead } from '../components/layout';
12import { configDocument, configPatch, draftParams, readConfig, type ConfigDocument } from '../lib/config';
13import { useStore, setConfigDraft, saveEngine, restartEngine, validateEngine, pushToast, lifecycleAvailable, useLifecycle } from '../lib/store';
14import type { BeginnerConfig, EngineConfig, ExpertParam } from '../lib/types';
15type Issue = {
16    level: 'warn' | 'error';
17    key?: string;
18    message: string;
19};
20export function TuningScreen() {
21    const engine = useStore(s => s.engine);
22    const hardware = useStore(s => s.hardware);
23    const [workload, setWorkload] = useState<Workload>('document');
24    const [testOpen, setTestOpen] = useState(false);
25    const [tuneOpen, setTuneOpen] = useState(false);
26    const [unsupported, setUnsupported] = useState(false);
27    const [updating, setUpdating] = useState(false);
28    const library = useStore(s => s.library);
29    const rawDraft = useStore(s => s.configDraft);
30    const connected = useStore(s => s.connection === 'live');
31    const [mode, setMode] = useState<'beginner' | 'expert'>('beginner');
32    const [view, setView] = useState<'parameters' | 'raw'>('parameters');
33    const [query, setQuery] = useState('');
34    const [group, setGroup] = useState('all');
35    const [changedOnly, setChangedOnly] = useState(false);
36    const [descriptions, setDescriptions] = useState(false);
37    const [moreOpen, setMoreOpen] = useState(false);
38    const lifecycle = useLifecycle();
39    const [issues, setIssues] = useState<Issue[]>([]);
40    const [preview, setPreview] = useState<EngineConfig['predicted'] | null>(null);
41    const [pending, setPending] = useState(false);
42    const [checked, setChecked] = useState(false);
43    const [applyOpen, setApplyOpen] = useState(false);
44    const [discardOpen, setDiscardOpen] = useState(false);
45    const importRef = useRef<HTMLInputElement>(null);
46    const moreRef = useRef<HTMLButtonElement>(null);
47    function closeMore() { setMoreOpen(false); moreRef.current?.focus(); }
48    const saved = useMemo(() => engine ? configDocument(engine) : null, [engine]);
49    const text = rawDraft ?? (saved ? JSON.stringify(saved, null, 2) : '');
50    const parsed = useMemo(() => {
51        try {
52            return { doc: readConfig(text), error: null };
53        }
54        catch (e) {
55            return { doc: null, error: e instanceof Error ? e.message : String(e) };
56        }
57    }, [text]);
58    const doc = parsed.doc;
59    const params = useMemo(() => engine && doc ? draftParams(engine, doc) : [], [engine, doc]);
60    const changed = useMemo(() => params.filter(p => p.value !== saved?.expert[p.id]), [params, saved]);
61    const dirty = rawDraft !== null && (!doc || JSON.stringify(doc) !== JSON.stringify(saved));
62    const groups = [...new Set(params.map(p => p.group))];
63    const rows = params.filter(p => p.id !== 'server.host' && (unsupported || !!p.applies && !p.applies.startsWith('Preserved'))).filter(p => (group === 'all' || p.group === group) && (!changedOnly || p.value !== saved?.expert[p.id]) && `${p.id} ${p.label} ${p.effect} ${p.group}`.toLowerCase().includes(query.toLowerCase()));
64    const current = library?.variants.find(v => v.id === library?.loaded);
65    useEffect(() => {
66        setChecked(false);
67        setUpdating(true);
68        if (!doc || !engine || !connected) {
69            setPreview(null);
70            setUpdating(false);
71            return;
72        }
73        let active = true;
74        const timer = setTimeout(() => {
75            void validateEngine(configPatch(doc)).then(result => {
76                if (!active)
77                    return;
78                setUpdating(false);
79                setIssues(result.issues);
80                setPreview(result.predicted ?? null);
81            }).catch(e => { if (active) {
82                setUpdating(false);
83                setIssues([{ level: 'error', message: e.message }]);
84            } });
85        }, 180);
86        return () => { active = false; clearTimeout(timer); };
87    }, [text, connected, engine?.variantId]);
88    function update(next: ConfigDocument) { setConfigDraft(JSON.stringify(next, null, 2)); }
89    function changeParam(id: string, value: ExpertParam['value']) {
90        if (!doc)
91            return;
92        const next = { ...doc, beginner: { ...doc.beginner }, expert: { ...doc.expert, [id]: value } };
93        if (id === 'perf.batch')
94            Object.assign(next, { batchAutomatic: false });
95        if (id === 'ctx.length')
96            next.beginner.contextLength = String(value).toLowerCase() as BeginnerConfig['contextLength'];
97        update(next);
98    }
99    async function check() {
100        if (!doc) {
101            setChecked(true);
102            return false;
103        }
104        const result = await validateEngine(configPatch(doc));
105        setIssues(result.issues);
106        setPreview(result.predicted ?? null);
107        setChecked(true);
108        return result.ok;
109    }
110    async function save(apply = false) {
111        if (!doc || pending)
112            return;
113        setPending(true);
114        try {
115            if (!await check())
116                return;
117            if (apply && !lifecycleAvailable())
118                return;
119            await saveEngine(configPatch(doc), true, apply);
120            setConfigDraft(null);
121            setApplyOpen(false);
122            if (apply)
123                await restartEngine();
124            else
125                pushToast('success', 'Settings saved', 'Used the next time this model loads. Sampling defaults affect the next request.');
126        }
127        catch (e) {
128            setIssues([{ level: 'error', message: e instanceof Error ? e.message : String(e) }]);
129        }
130        finally {
131            setPending(false);
132        }
133    }
134    function download() {
135        if (!doc)
136            return;
137        const url = URL.createObjectURL(new Blob([JSON.stringify(doc, null, 2)], { type: 'application/json' }));
138        const a = document.createElement('a');
139        a.href = url;
140        a.download = 'strata-engine.json';
141        a.click();
142        URL.revokeObjectURL(url);
143    }
144    function resetDraft() {
145        if (!engine || !doc)
146            return;
147        update({ ...doc, batchAutomatic: true, beginner: { priority: 'balanced', contextLength: 'recommended', readImages: false, gpuIdle: 'never' }, expert: Object.fromEntries(engine.expert.map(p => [p.id, p.recommended])) });
148    }
149    async function importFile(file: File | undefined) {
150        if (!file)
151            return;
152        try {
153            update(readConfig(await file.text()));
154            setMode('expert');
155            setView('raw');
156        }
157        catch (e) {
158            setIssues([{ level: 'error', message: `Import failed: ${e instanceof Error ? e.message : String(e)}` }]);
159        }
160    }
161    if (!engine || !saved)
162        return <Screen plainHeader title={tr("Engine")}><div className="setup__note">{tr(connected ? 'Loading settings…' : 'Connect the engine to edit its settings.')}</div></Screen>;
163    const predicted = preview ?? engine.predicted;
164    const cfg = execution(doc?.expert, contextTokens(doc?.beginner.contextLength ?? engine.beginner.contextLength));
165    const savedCfg = execution(saved.expert, contextTokens(saved.beginner.contextLength));
166    const contextMax = Math.max(4, Math.floor((current?.contextMax ?? 32768) / 1024));
167    const recommendedContext = RECOMMENDED_CONTEXT_TOKENS / 1024;
168    const recommendedPosition = contextMax === 4 ? 0 : Math.min(100, (recommendedContext - 4) / (contextMax - 4) * 100);
169    const experience = estimate(current, hardware, cfg, workload, library?.mode === 'simulated');
170    const savedExperience = estimate(current, hardware, savedCfg, workload, library?.mode === 'simulated');
171    const showPreview = <PerformancePreview experience={experience} saved={savedExperience} workload={workload} onWorkload={setWorkload} updating={updating}/>;
172    const errors = parsed.error ? [{ level: 'error', message: parsed.error } as Issue] : issues;
173    const visibleIssues = errors.filter(i => !i.message.startsWith('Estimated working memory (') && !i.message.includes('is fast memory. Actual fit and offload behavior'));
174    const invalid = !!parsed.error || errors.some(i => i.level === 'error');
175    return <Screen plainHeader title={tr("Engine")} actions={<><button className="st-btn st-btn--secondary" aria-pressed={mode === 'expert'} onClick={() => setMode(mode === 'expert' ? 'beginner' : 'expert')}>{tr(mode === 'expert' ? 'Easy mode' : 'Expert mode')}</button><Btn disabled={!doc} onClick={resetDraft}>{tr("Reset to recommended")}</Btn><Btn disabled={!doc} onClick={() => setTestOpen(true)}>{tr("Run speed test")}</Btn></>}>
176    <div className="stack stack--lg tuning" data-mode={mode}>
177      <ActionError />
178      {tr(mode === 'beginner' && doc ? <div className="instrument-layout">
179        <section className="instrument-controls simple-engine"><div className="auto-tune-card"><Icon name="gauge" size={28}/><h2 className="h3">{tr("Make the most of this computer")}</h2><p className="small muted">{tr("Find a starting point for your hardware, then review before saving.")}</p><Btn variant="primary" disabled={!hardware || !current} onClick={() => setTuneOpen(true)}>{tr("Auto-tune for my PC")}</Btn>
180          <label className="input-field"><span>{tr("Conversation context \u00B7 ")}{tr(cfg.context / 1024)}{tr("K")}</span>
181            <div className="context-slider"><input type="range" className="st-slider" aria-label={tr("Conversation context")} aria-valuetext={`${cfg.context / 1024}K tokens`} aria-describedby="context-recommendation context-help" min={4} max={contextMax} step={1} value={cfg.context / 1024} onChange={e => changeParam('ctx.length', `${e.target.value}K`)}/><span className="context-recommendation-mark" aria-hidden="true" style={{ left: `calc(${recommendedPosition}% + ${8 - recommendedPosition * .16}px)` }}/></div>
182            <div className="context-guidance"><div className="context-scale" aria-hidden="true"><span>{tr("4K")}</span><span>{tr(contextMax)}{tr("K")}</span></div><p className="context-recommendation" id="context-recommendation"><span aria-hidden="true"/>{tr("Recommended: ")}{tr(recommendedContext)}{tr("K")}</p><p className="xs muted" id="context-help">{tr("More conversation history uses more memory.")}</p></div>
183          </label></div>
184          <section><h2 className="h4">{tr("Resources")}</h2><div className="workload-cards">{tr([{ id: 'shared', title: 'Leave room for other apps', detail: 'Keep this computer responsive' }, { id: 'full', title: 'Full speed', detail: 'Give the engine more CPU threads' }].map(h => <button key={h.id} aria-pressed={(doc.headroom ?? 'shared') === h.id} onClick={() => update({ ...doc, headroom: h.id, expert: { ...doc.expert, 'perf.threads': Math.max(1, (hardware?.cpu.cores ?? 4) - (h.id === 'shared' ? 2 : 0)) } })}><strong>{tr(h.title)}</strong><span>{tr(h.detail)}</span></button>))}</div></section>
185        </section>{tr(showPreview)}
186      </div> : <div className="stack expert-engine">
187        <div className="engine-subtabs" role="tablist" aria-label={tr("Expert editor")}>{tr((['parameters', 'raw'] as const).map(v => <button role="tab" aria-selected={view === v} key={v} onClick={() => setView(v)}>{tr(v === 'raw' ? 'Raw config' : 'Parameters')}</button>))}</div>
188        {tr(view === 'raw' ? <section className="stack">
189          <SectionHead title={tr("Configuration draft")} right={<div className="row"><Btn size="sm" onClick={() => setDiscardOpen(true)}>{tr("Reload saved")}</Btn><Btn size="sm" onClick={download} disabled={!doc}>{tr("Export")}</Btn><Btn size="sm" onClick={() => importRef.current?.click()}>{tr("Import")}</Btn></div>}/>
190          {tr(parsed.error ? <ErrorNotice message={parsed.error} next={tr("Correct the JSON before saving or applying.")}/> : null)}<textarea className="st-input config-editor" aria-label={tr("Configuration draft")} aria-invalid={!!parsed.error} aria-describedby={visibleIssues.length ? 'config-errors' : undefined} spellCheck={false} value={text} onChange={e => setConfigDraft(e.target.value)}/>
191        </section> : <>
192          <div className="row small muted"><a href="#/serving">{tr("Server access is managed in Serving")}</a><label className="check-label"><input type="checkbox" checked={unsupported} onChange={e => setUnsupported(e.target.checked)}/>{tr("Show unsupported")}</label></div><div className="parameter-toolbar">
193            <input className="st-input" type="search" aria-label={tr("Search parameters")} placeholder={tr("Search name or technical key…")} value={query} onChange={e => setQuery(e.target.value)}/>
194            <Select value={group} ariaLabel={tr("Parameter group")} options={[{ value: 'all', label: 'All groups' }, ...groups.map(g => ({ value: g, label: g }))]} onChange={setGroup}/>
195            <label className="check-label"><input type="checkbox" checked={changedOnly} onChange={e => setChangedOnly(e.target.checked)}/>{tr("Changed only (")}{tr(changed.length)})</label><label className="check-label"><input type="checkbox" checked={descriptions} onChange={e => setDescriptions(e.target.checked)}/>{tr("Show descriptions")}</label>
196          </div>
197          {tr(groups.filter(g => rows.some(p => p.group === g)).map(g => <section className="parameter-group" key={g}>
198            <h2 className="h4">{tr(g)}</h2>
199            {tr(rows.filter(p => p.group === g).map(p => <div className="parameter-row" key={p.id}>
200              <div><label className="strong" htmlFor={`param-${p.id}`}>{tr(p.label)}</label><code className="parameter-key">{p.id}</code>{tr(descriptions ? <div className="small muted">{tr(p.effect)}</div> : null)}<div className="parameter-support xs muted" data-unsupported={!p.applies || p.applies.startsWith('Preserved') || undefined}>{tr(!p.applies || p.applies.startsWith('Preserved') ? 'Not used by this engine' : p.applies)}{tr(" \u00B7 recommended ")}{tr(String(p.recommended))}</div></div>
201              <div><div className="parameter-control"><ExpertInput param={p} disabled={!p.applies || p.applies.startsWith('Preserved')} onChange={value => changeParam(p.id, value)}/><Btn variant="ghost" size="sm" disabled={p.value === saved.expert[p.id]} onClick={() => changeParam(p.id, saved.expert[p.id] ?? p.recommended)}>{tr("Revert")}</Btn></div>{tr(errors.filter(i => i.message.startsWith(p.id + ':')).map(i => <p className="small inline-error" role="alert" key={i.message}>{tr(i.message)}</p>))}</div>
202            </div>))}
203          </section>))}
204          {tr(!rows.length ? <div className="empty-inline">{tr("No parameters match. ")}<Btn variant="ghost" onClick={() => { setQuery(''); setGroup('all'); setChangedOnly(false); }}>{tr("Clear filters")}</Btn></div> : null)}
205        </>)}
206      </div>)}
207      <input type="file" accept=".json,application/json" ref={importRef} hidden onChange={e => { void importFile(e.target.files?.[0]); e.target.value = ''; }}/>
208      {tr(mode === 'expert' && descriptions && predicted.notes.length ? <p className="xs muted">{tr(predicted.notes.join(' '))}</p> : null)}
209      {tr(visibleIssues.length ? <div className="validation-list" id="config-errors" role="status">{tr(visibleIssues.map((issue, i) => <div key={i} data-tone={issue.level}><Icon name={issue.level === 'error' ? 'error' : 'info'} size={16}/><span>{tr(issue.message)}</span></div>))}</div> : checked ? <p className="small" role="status">{tr("Configuration checked. No validation errors.")}</p> : null)}
210      {tr(dirty ? <div className="config-savebar"><span className="small">{tr(changed.length || 'Configuration')} {tr(changed.length === 1 ? 'change' : 'changes')}</span><span className="spacer"/>{tr(library?.loaded && library.mode !== 'simulated' ? <Btn size="sm" disabled={invalid || pending || !connected || !lifecycle.allowed} onClick={() => setApplyOpen(true)}>{tr("Apply now\u2026")}</Btn> : null)}<Btn size="sm" variant="ghost" disabled={pending} onClick={() => setDiscardOpen(true)}>{tr("Discard")}</Btn><Btn size="sm" variant="primary" disabled={invalid || pending || !connected} onClick={() => void save()}>{tr(pending ? 'Saving…' : 'Save')}</Btn></div> : null)}
211
212    </div>
213    {tr(moreOpen ? <FloatingMenu anchor={moreRef.current} title={tr("More actions")} onClose={closeMore}>
214      <button role="menuitem" className="menu__item" disabled={pending || !doc} onClick={() => { closeMore(); resetDraft(); }}>{tr("Recommended defaults")}</button>
215      <button role="menuitem" className="menu__item" disabled={!connected || pending} onClick={() => { closeMore(); void check().catch(e => setIssues([{ level: 'error', message: e.message }])); }}>{tr("Validate draft")}</button>
216      <button role="menuitem" className="menu__item" disabled={!doc || invalid} onClick={() => { closeMore(); setTestOpen(true); }}>{tr("Preview test \u00B7 Example")}</button>
217    </FloatingMenu> : null)}
218    <DemoTest open={testOpen} onClose={() => setTestOpen(false)} experience={experience}/>
219    <AutoTune open={tuneOpen} onClose={() => setTuneOpen(false)} onDone={() => { resetDraft(); setTuneOpen(false); }}/>
220    <Dialog open={discardOpen} compact title={tr("Discard configuration changes?")} onClose={() => setDiscardOpen(false)} actions={<><Btn onClick={() => setDiscardOpen(false)}>{tr("Keep editing")}</Btn><Btn variant="danger" onClick={() => { setConfigDraft(null); setIssues([]); setDiscardOpen(false); }}>{tr("Discard changes")}</Btn></>}><p>{tr("Discard all unsaved engine changes and return to the saved configuration.")}</p></Dialog>
221    <Dialog open={applyOpen} title={tr("Apply settings now?")} onClose={() => setApplyOpen(false)} actions={<><Btn onClick={() => setApplyOpen(false)}>{tr("Keep editing")}</Btn><Btn variant="primary" disabled={pending || invalid || !lifecycle.allowed} onClick={() => void save(true)}>{tr("Save and restart")}</Btn></>}><p>{tr("Save the draft and restart ")}{tr(current?.label ?? 'the loaded model')}.</p><LifecycleNotice /></Dialog>
222  </Screen>;
223}
224function ExpertInput({ param, onChange, disabled = false }: {
225    param: ExpertParam;
226    disabled?: boolean;
227    onChange: (value: ExpertParam['value']) => void;
228}) {
229    if (param.type === 'select' && param.options)
230        return <Select disabled={disabled} value={String(param.value)} ariaLabel={tr(param.label)} options={param.options.map(value => ({ value, label: value }))} onChange={onChange}/>;
231    if (param.type === 'toggle')
232        return <button disabled={disabled} className="st-toggle" type="button" role="switch" aria-checked={!!param.value} aria-label={tr(param.label)} onClick={() => onChange(!param.value)}/>;
233    return <input disabled={disabled} id={`param-${param.id}`} className="st-input" aria-label={tr(param.label)} inputMode={param.type === 'number' ? 'decimal' : undefined} value={String(param.value)} onChange={e => { const v = e.target.value; onChange(param.type === 'number' && v.trim() !== '' && Number.isFinite(Number(v)) ? Number(v) : v); }}/>;
234}