From d383e9e66f00c307455d6e22eac5db7b9eedc56c Mon Sep 17 00:00:00 2001 From: Seto Elkahfi <1797197+setoelkahfi@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:17:42 +0100 Subject: [PATCH 1/3] app: sweep epochs and learning rates in one go A sweep is the same training run over several epoch counts and learning rates, one after another. Pick Sweep on the Fine-tune tab, list the epochs and rates, and the form shows the runs it will make, named the usual way (e2-lr1e-4). Runs the project already has are left alone and listed, a grid with nothing new to run is refused, and more than 24 runs is refused, since each can take an hour. While it runs, the header says which run it is on, and Skip run cancels the current one and carries on, while Stop sweep cancels it and starts no more. A run that fails or that the backend refuses to start is recorded with the reason and the sweep carries on. A table of every run, with its result and final loss, stays on screen when it ends, and points at the lowest loss with a note that a low training loss is not proof of a better model. A stopped sweep says how far it got, not "run 4 of 4". The queue lives in the webview, so a reload during a sweep keeps the run in progress (it reattaches) but not the runs after it. The planning and queue logic is plain functions with 12 tests. Checked in the running app on a 12-row project with Qwen3-1.7B: the full 4-run grid ran in order to a summary of final losses. Skip cancelled run 1 mid-training and run 2 started, run 2 finished, and Stop cancelled run 3 so run 4 never started. A first attempt hit a full disk during run 1's merge, and the sweep recorded that failure with its reason and went on to run 2. Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: siGit Code v1.7.10 Co-Authored-By: OndeCode v1.1.2 --- .../src/features/finetune/FinetuneView.tsx | 8 +- .../app/src/features/finetune/JobPanel.tsx | 63 ++++++- .../app/src/features/finetune/RunForm.tsx | 117 +++++++++++-- .../app/src/features/finetune/sweep.test.ts | 111 +++++++++++++ packaging/app/src/features/finetune/sweep.ts | 156 ++++++++++++++++++ packaging/app/src/features/finetune/useJob.ts | 83 +++++++++- 6 files changed, 522 insertions(+), 16 deletions(-) create mode 100644 packaging/app/src/features/finetune/sweep.test.ts create mode 100644 packaging/app/src/features/finetune/sweep.ts diff --git a/packaging/app/src/features/finetune/FinetuneView.tsx b/packaging/app/src/features/finetune/FinetuneView.tsx index b5fd579..2b7ab6c 100644 --- a/packaging/app/src/features/finetune/FinetuneView.tsx +++ b/packaging/app/src/features/finetune/FinetuneView.tsx @@ -1,10 +1,14 @@ import { isRunning } from "./job"; +import { isFinished } from "./sweep"; import { JobPanel } from "./JobPanel"; import { RunForm } from "./RunForm"; import type { Job } from "./useJob"; export function FinetuneView({ job }: { job: Job }) { - const running = isRunning(job.state); + // Between two runs of a sweep the outcome of the last is still on screen for + // an instant. The form stays hidden for the whole sweep. + const sweepActive = job.sweep !== null && !isFinished(job.sweep); + const running = isRunning(job.state) || sweepActive; return (
@@ -13,7 +17,7 @@ export function FinetuneView({ job }: { job: Job }) {
{/* Hidden while a job's result is on screen, so the result is what you see. */} - {(!job.state.info || running) && } + {(!job.state.info && job.sweep === null) || running ? : null}
); } diff --git a/packaging/app/src/features/finetune/JobPanel.tsx b/packaging/app/src/features/finetune/JobPanel.tsx index 106e446..ee58102 100644 --- a/packaging/app/src/features/finetune/JobPanel.tsx +++ b/packaging/app/src/features/finetune/JobPanel.tsx @@ -2,6 +2,7 @@ import { LossChart } from "@/features/projects/LossChart"; import { formatBytes } from "@/features/projects/format"; import { censusVerdict } from "./census"; import { formatDuration, isRunning, rowsLeftOut, secondsLeft, stepsDone } from "./job"; +import { headline as sweepHeadline, isFinished, lowestLoss } from "./sweep"; import type { Job } from "./useJob"; const BACKEND_NAME = { mlx: "MLX", cpu: "CPU", metal: "Metal" } as const; @@ -25,6 +26,10 @@ export function JobPanel({ job }: { job: Job }) { if (!info) return null; const running = isRunning(state); + const sweep = job.sweep; + // Between two runs of a sweep the last one's outcome is on screen for an + // instant. Dismissing then would throw the sweep away, so there is no button. + const sweepActive = sweep !== null && !isFinished(sweep); const census = info.kind === "census"; const total = position ? position.totalEpochs * position.totalSteps : 0; const elapsed = job.trainingStartedAt ? Date.now() - job.trainingStartedAt : 0; @@ -40,7 +45,8 @@ export function JobPanel({ job }: { job: Job }) {

{info.run}

- {census ? "Gradient census" : "Training run"} · {info.repo_id} + {census ? "Gradient census" : sweep ? sweepHeadline(sweep) : "Training run"} ·{" "} + {info.repo_id}

@@ -52,7 +58,27 @@ export function JobPanel({ job }: { job: Job }) { {BACKEND_NAME[state.backend.name]} )} - {running && ( + {running && sweepActive && ( + <> + + + + )} + {running && !sweepActive && (
diff --git a/packaging/app/src/features/finetune/sweep.test.ts b/packaging/app/src/features/finetune/sweep.test.ts new file mode 100644 index 0000000..c990dd9 --- /dev/null +++ b/packaging/app/src/features/finetune/sweep.test.ts @@ -0,0 +1,111 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { advance, begin, headline, isFinished, lowestLoss, parseEpochs, parseRates, planSweep, position, refuse } from "./sweep.ts"; +import type { JobRequest } from "../../lib/types.ts"; + +const base: JobRequest = { + repo_id: "acme/tiny", + kind: "run", + name: "", + learning_rate: 1e-4, + epochs: 2, + lora_rank: 8, + lora_alpha: 16, + max_seq_len: 512, + dtype: "q4_k_m", +}; + +test("lists accept commas, spaces and semicolons, drop duplicates and keep order", () => { + assert.deepEqual(parseEpochs("2, 3 3;4"), { ok: true, values: [2, 3, 4] }); + assert.deepEqual(parseRates("5e-5 1e-4"), { ok: true, values: [5e-5, 1e-4] }); +}); + +test("bad values are named in the error", () => { + assert.match((parseEpochs("2, 2.5") as { error: string }).error, /"2\.5" is not valid/); + assert.match((parseEpochs("0") as { error: string }).error, /"0"/); + assert.match((parseEpochs("101") as { error: string }).error, /"101"/); + assert.match((parseRates("1e-4, fast") as { error: string }).error, /"fast"/); + assert.match((parseRates("0") as { error: string }).error, /"0"/); + assert.match((parseRates("2") as { error: string }).error, /"2"/); + assert.equal(parseEpochs(" ").ok, false); +}); + +test("the grid goes through each learning rate in turn and names runs the usual way", () => { + const plan = planSweep(base, [2, 3], [5e-5, 1e-4], []); + assert.deepEqual(plan.runs.map((r) => r.name), ["e2-lr5e-5", "e3-lr5e-5", "e2-lr1e-4", "e3-lr1e-4"]); + const r = plan.runs[1].request; + assert.deepEqual([r.kind, r.epochs, r.learning_rate, r.name, r.lora_rank], ["run", 3, 5e-5, "e3-lr5e-5", 8]); +}); + +test("runs that already exist are skipped and reported, not repeated", () => { + const plan = planSweep(base, [2, 3], [1e-4], ["e2-lr1e-4", "census-1"]); + assert.deepEqual(plan.runs.map((r) => r.name), ["e3-lr1e-4"]); + assert.deepEqual(plan.skipped, ["e2-lr1e-4"]); +}); + +test("a grid that collapses to a single name does not repeat it", () => { + assert.equal(planSweep(base, [2, 2], [1e-4], []).runs.length, 1); +}); + +test("a sweep with nothing to run does not start", () => { + assert.equal(begin(planSweep(base, [2], [1e-4], ["e2-lr1e-4"])), null); +}); + +test("each finished run is recorded and the next one comes up", () => { + let s = begin(planSweep(base, [2, 3], [1e-4], []))!; + assert.equal(position(s), 1); + s = advance(s, "e2-lr1e-4", { kind: "done", finalLoss: 0.5 }); + assert.equal(position(s), 2); + assert.equal(s.queue.length, 1); + assert.equal(isFinished(s), false); + s = advance(s, "e3-lr1e-4", { kind: "done", finalLoss: 0.3 }); + assert.equal(isFinished(s), true); + assert.deepEqual(s.results.map((r) => [r.name, r.status, r.finalLoss]), [ + ["e2-lr1e-4", "done", 0.5], + ["e3-lr1e-4", "done", 0.3], + ]); +}); + +test("a failed run is recorded with its reason and the sweep carries on", () => { + let s = begin(planSweep(base, [2, 3], [1e-4], []))!; + s = advance(s, "e2-lr1e-4", { kind: "failed", message: "out of memory" }); + assert.equal(isFinished(s), false); + assert.deepEqual(s.results[0], { name: "e2-lr1e-4", status: "failed", finalLoss: null, note: "out of memory" }); +}); + +test("skipping a run carries on, and stopping ends the sweep", () => { + let s = begin(planSweep(base, [2, 3, 4], [1e-4], []))!; + s = advance({ ...s, skipCurrent: true }, "e2-lr1e-4", { kind: "cancelled" }); + assert.equal(s.results[0].note, "Skipped"); + assert.equal(isFinished(s), false); + s = advance({ ...s, stopped: true }, "e3-lr1e-4", { kind: "cancelled" }); + assert.equal(s.results[1].note, "Sweep stopped"); + assert.equal(isFinished(s), true, "a run is still left in the queue, but stopped wins"); +}); + +test("a request the backend refuses is recorded and does not stall the queue", () => { + let s = begin(planSweep(base, [2, 3], [1e-4], []))!; + s = refuse(s, "e2-lr1e-4", "The base model is not downloaded"); + assert.equal(s.results[0].status, "refused"); + assert.equal(s.queue.length, 1); +}); + +test("the lowest final loss is pointed out, and only among runs that have one", () => { + const s = begin(planSweep(base, [2, 3], [1e-4], []))!; + const after = advance(advance(s, "a", { kind: "done", finalLoss: 0.5 }), "b", { kind: "done", finalLoss: 0.3 }); + assert.equal(lowestLoss(after.results), "b"); + assert.equal(lowestLoss([]), null); + assert.equal(lowestLoss([{ name: "x", status: "failed", finalLoss: null, note: "e" }]), null); +}); + +test("the header says where a sweep is, and a stopped one does not claim runs it never reached", () => { + let s = begin(planSweep(base, [2, 3, 4], [1e-4], []))!; + assert.equal(headline(s), "Sweep, run 1 of 3"); + s = advance(s, "e2-lr1e-4", { kind: "done", finalLoss: 1 }); + assert.equal(headline(s), "Sweep, run 2 of 3"); + s = advance({ ...s, stopped: true }, "e3-lr1e-4", { kind: "cancelled" }); + assert.equal(headline(s), "Sweep stopped after 2 of 3 runs"); + let all = begin(planSweep(base, [2], [1e-4], []))!; + all = advance(all, "e2-lr1e-4", { kind: "done", finalLoss: 1 }); + assert.equal(headline(all), "Sweep of 1 run"); +}); diff --git a/packaging/app/src/features/finetune/sweep.ts b/packaging/app/src/features/finetune/sweep.ts new file mode 100644 index 0000000..3164ac2 --- /dev/null +++ b/packaging/app/src/features/finetune/sweep.ts @@ -0,0 +1,156 @@ +// Planning and running a sweep: the same training run over several epoch counts +// and learning rates. Pure functions, so they can be tested without a window. +import type { JobRequest, RunStatus } from "../../lib/types.ts"; +import { defaultRunName } from "./job.ts"; + +/** More than this is almost certainly a typo, and each run can take an hour. */ +export const MAX_SWEEP_RUNS = 24; + +export type ListResult = { ok: true; values: number[] } | { ok: false; error: string }; + +/** "2, 3" or "5e-5 1e-4" into numbers. Duplicates are dropped, order is kept. */ +export function parseList(text: string, label: string, valid: (n: number) => boolean, rule: string): ListResult { + const parts = text + .split(/[\s,;]+/) + .map((p) => p.trim()) + .filter((p) => p !== ""); + if (parts.length === 0) return { ok: false, error: `${label}: enter at least one value.` }; + const values: number[] = []; + for (const part of parts) { + const n = Number(part); + if (!Number.isFinite(n) || !valid(n)) return { ok: false, error: `${label}: "${part}" is not valid. ${rule}` }; + if (!values.includes(n)) values.push(n); + } + return { ok: true, values }; +} + +export const parseEpochs = (text: string) => + parseList(text, "Epochs", (n) => Number.isInteger(n) && n >= 1 && n <= 100, "Use whole numbers from 1 to 100."); +export const parseRates = (text: string) => + parseList(text, "Learning rates", (n) => n > 0 && n <= 1, "Use numbers above 0 and at most 1, like 1e-4."); + +export interface Planned { + request: JobRequest; + name: string; +} + +export interface SweepPlan { + /** Runs to do, in order: every epoch count at each learning rate in turn. */ + runs: Planned[]; + /** Names that already exist in the project. They are left alone. */ + skipped: string[]; +} + +/** The grid of runs for a base request, minus the ones that already exist. */ +export function planSweep( + base: JobRequest, + epochs: number[], + rates: number[], + existing: string[], +): SweepPlan { + const taken = new Set(existing); + const runs: Planned[] = []; + const skipped: string[] = []; + for (const learning_rate of rates) { + for (const ep of epochs) { + const name = defaultRunName(ep, learning_rate); + if (taken.has(name)) { + skipped.push(name); + continue; + } + taken.add(name); + runs.push({ name, request: { ...base, kind: "run", name, epochs: ep, learning_rate } }); + } + } + return { runs, skipped }; +} + +export interface SweepResult { + name: string; + status: RunStatus | "refused" | "skipped"; + /** Mean loss of the last epoch, when the run got that far. */ + finalLoss: number | null; + /** Why it did not finish, when it did not. */ + note: string | null; +} + +export interface SweepState { + total: number; + /** Requests still to start, in order. */ + queue: JobRequest[]; + /** What each finished or refused run came to. */ + results: SweepResult[]; + /** The user asked to stop: nothing more starts after the current run. */ + stopped: boolean; + /** The user asked to skip the current run and carry on. */ + skipCurrent: boolean; +} + +export function begin(plan: SweepPlan): SweepState | null { + if (plan.runs.length === 0) return null; + return { + total: plan.runs.length, + queue: plan.runs.map((r) => r.request), + results: [], + stopped: false, + skipCurrent: false, + }; +} + +/** What the header says: where a sweep in progress is, or how far a finished one + * got. A stopped sweep did not reach its last runs, so it must not claim to. */ +export function headline(s: SweepState): string { + if (!isFinished(s)) return `Sweep, run ${position(s)} of ${s.total}`; + return s.results.length < s.total + ? `Sweep stopped after ${s.results.length} of ${s.total} runs` + : `Sweep of ${s.total} ${s.total === 1 ? "run" : "runs"}`; +} + +/** 1-based number of the run in progress. */ +export const position = (s: SweepState): number => s.results.length + 1; +export const isFinished = (s: SweepState): boolean => s.queue.length === 0 || s.stopped; + +export type Outcome = + | { kind: "done"; finalLoss: number | null } + | { kind: "failed"; message: string } + | { kind: "cancelled" }; + +/** Record how the current run ended and move to the next one. Returns the new + * state; the caller starts `state.queue[0]` unless the sweep is finished. */ +export function advance(s: SweepState, name: string, outcome: Outcome): SweepState { + const result: SweepResult = + outcome.kind === "done" + ? { name, status: "done", finalLoss: outcome.finalLoss, note: null } + : outcome.kind === "failed" + ? { name, status: "failed", finalLoss: null, note: outcome.message } + : { name, status: "cancelled", finalLoss: null, note: s.stopped ? "Sweep stopped" : "Skipped" }; + // Cancelling a run is either "skip this one" or "stop everything". Anything + // else that ends a run, including a failure, carries on with the rest. + const stopped = s.stopped; + return { + ...s, + queue: s.queue.slice(1), + results: [...s.results, result], + skipCurrent: false, + stopped, + }; +} + +/** A request the backend refused to start: record it and move on. */ +export function refuse(s: SweepState, name: string, message: string): SweepState { + return { + ...s, + queue: s.queue.slice(1), + results: [...s.results, { name, status: "refused", finalLoss: null, note: message }], + }; +} + +/** The name of the run with the lowest final loss. A lower loss on the training + * set is not a better model, so this is only a pointer, never a verdict. */ +export function lowestLoss(results: SweepResult[]): string | null { + let best: SweepResult | null = null; + for (const r of results) { + if (r.finalLoss !== null && (best === null || r.finalLoss < (best.finalLoss as number))) best = r; + } + return best?.name ?? null; +} diff --git a/packaging/app/src/features/finetune/useJob.ts b/packaging/app/src/features/finetune/useJob.ts index 9e20c9e..db0db69 100644 --- a/packaging/app/src/features/finetune/useJob.ts +++ b/packaging/app/src/features/finetune/useJob.ts @@ -2,6 +2,8 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { ipc } from "@/lib/ipc"; import type { JobRequest, RunEvent, StepRecord } from "@/lib/types"; import { apply, defaultRunName, elapsedFromSteps, idle, positionFromSteps, type JobState } from "./job"; +import * as sweepLogic from "./sweep"; +import type { SweepPlan, SweepState } from "./sweep"; /** The running job as the screen sees it. It lives in `App`, so it survives * switching tabs, and it reattaches to a job that kept running while the @@ -16,6 +18,16 @@ export function useJob() { const datasetRows = useRef(null); const [, redraw] = useState(0); const timer = useRef(undefined); + // The queue of a sweep. It lives in a ref so the event handlers always see the + // current one, and is copied to state for the screen to draw. It is not kept + // across a reload: the run in progress reattaches, but the ones after it do not. + const sweepRef = useRef(null); + const [sweep, setSweepState] = useState(null); + const handledOutcome = useRef(null); + const setSweep = useCallback((next: SweepState | null) => { + sweepRef.current = next; + setSweepState(next); + }, []); const scheduleRedraw = useCallback(() => { if (timer.current !== undefined) return; @@ -113,19 +125,88 @@ export function useJob() { void ipc.cancelJob(); }, []); + /** Start the next queued run of the sweep, recording any the backend refuses. */ + const launchNext = useCallback(async () => { + for (;;) { + const current = sweepRef.current; + if (!current || sweepLogic.isFinished(current)) return; + const request = current.queue[0]; + try { + await start(request, datasetRows.current); + return; + } catch (e) { + const message = e && typeof e === "object" && "message" in e ? String((e as { message: unknown }).message) : String(e); + setSweep(sweepLogic.refuse(current, request.name, message)); + } + } + }, [start, setSweep]); + + /** Run every planned run in turn. `rows` is the dataset size, for the warning + * about rows the trainer leaves out. */ + const startSweep = useCallback( + async (plan: SweepPlan, rows: number | null) => { + const first = sweepLogic.begin(plan); + if (!first) return; + datasetRows.current = rows; + handledOutcome.current = null; + setSweep(first); + await launchNext(); + }, + [launchNext, setSweep], + ); + + // When a run of a sweep ends, record how it went and start the next. + useEffect(() => { + const outcome = state.outcome; + const current = sweepRef.current; + if (!outcome || !current || handledOutcome.current === outcome) return; + handledOutcome.current = outcome; + const name = state.info?.run ?? ""; + const next = sweepLogic.advance( + current, + name, + outcome.kind === "done" + ? { kind: "done", finalLoss: outcome.record.epoch_loss.at(-1) ?? null } + : outcome.kind === "failed" + ? { kind: "failed", message: outcome.message } + : { kind: "cancelled" }, + ); + setSweep(next); + if (!sweepLogic.isFinished(next)) void launchNext(); + }, [state.outcome, state.info, launchNext, setSweep]); + + /** Cancel the current run and carry on with the rest of the sweep. */ + const skipRun = useCallback(() => { + const current = sweepRef.current; + if (current) setSweep({ ...current, skipCurrent: true }); + cancel(); + }, [cancel, setSweep]); + + /** Cancel the current run and start no more. */ + const stopSweep = useCallback(() => { + const current = sweepRef.current; + if (current) setSweep({ ...current, stopped: true }); + cancel(); + }, [cancel, setSweep]); + const dismiss = useCallback(() => { steps.current = []; trainingStartedAt.current = null; datasetRows.current = null; + setSweep(null); setState(idle); - }, []); + }, [setSweep]); return { state, steps: steps.current, trainingStartedAt: trainingStartedAt.current, datasetRows: datasetRows.current, + sweep, start, + startSweep, + skipRun, + stopSweep, cancel, dismiss, }; From 21cde34a072b0cfbcbdb5ed3bb5007f9c6a0c05d Mon Sep 17 00:00:00 2001 From: Seto Elkahfi <1797197+setoelkahfi@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:25:34 +0100 Subject: [PATCH 2/3] app: fix sweep stop state, explain why Start is disabled A stopped sweep now reads "Stopping after run N of M" until the run in flight ends, then empties the queue. Before, the header and the Stop and Cancel buttons said the sweep was over while a run was still going. Stopping between runs ends the sweep at once. The unused skipCurrent field is gone. The run form now says why Start is disabled: a bad LoRA rank, alpha or max sequence, learning rate or epoch count. The LoRA disclosure opens when one of those is wrong, and the sweep preview shows the LoRA values every run will use. If a project's existing runs are unknown or failed to load, a sweep can't start and the form says so. A census is still allowed. The button reads "Start sweep" until the plan is known. Checked in a browser against a stubbed Tauri bridge. pnpm build and pnpm test (38 tests) pass. Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: siGit Code v1.7.10 Co-Authored-By: OndeCode v1.1.2 --- .../app/src/features/finetune/RunForm.tsx | 53 +++++++++++++------ .../src/features/finetune/settings.test.ts | 37 +++++++++++++ .../app/src/features/finetune/settings.ts | 24 +++++++++ .../app/src/features/finetune/sweep.test.ts | 50 +++++++++++++++-- packaging/app/src/features/finetune/sweep.ts | 36 ++++++++----- packaging/app/src/features/finetune/useJob.ts | 23 ++++---- 6 files changed, 179 insertions(+), 44 deletions(-) create mode 100644 packaging/app/src/features/finetune/settings.test.ts create mode 100644 packaging/app/src/features/finetune/settings.ts diff --git a/packaging/app/src/features/finetune/RunForm.tsx b/packaging/app/src/features/finetune/RunForm.tsx index 56f52d7..4a1b323 100644 --- a/packaging/app/src/features/finetune/RunForm.tsx +++ b/packaging/app/src/features/finetune/RunForm.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { ipc } from "@/lib/ipc"; import { errorMessage, type JobRequest, type ProjectSummary } from "@/lib/types"; +import { loraProblem, runProblem } from "./settings"; import { MAX_SWEEP_RUNS, parseEpochs, parseRates, planSweep, type SweepPlan } from "./sweep"; /** What the form can start. A sweep is several training runs. */ @@ -39,7 +40,11 @@ export function RunForm({ const [sweepEpochs, setSweepEpochs] = useState("2, 3"); const [sweepRates, setSweepRates] = useState("5e-5, 1e-4"); // Names of the runs the project already has, so a sweep does not repeat them. - const [existing, setExisting] = useState([]); + // Tagged with its project: another project's names must never be used, and + // until a project's names have loaded (or failed to) they are unknown, which + // is not the same as "none". + const [existingFor, setExistingFor] = useState<{ repoId: string; names: string[] } | null>(null); + const [existingError, setExistingError] = useState(null); const [name, setName] = useState(""); const [lr, setLr] = useState("1e-4"); const [epochs, setEpochs] = useState("2"); @@ -66,12 +71,21 @@ export function RunForm({ let current = true; ipc .projectDetail(repoId) - .then((d) => current && setExisting(d.runs.map((r) => r.name))) - .catch(() => current && setExisting([])); + .then((d) => { + if (!current) return; + setExistingFor({ repoId, names: d.runs.map((r) => r.name) }); + setExistingError(null); + }) + .catch((e) => { + if (!current) return; + setExistingFor(null); + setExistingError(errorMessage(e)); + }); return () => { current = false; }; }, [repoId, disabled]); + const existing = existingFor?.repoId === repoId ? existingFor.names : null; const project = projects.find((p) => p.repo_id === repoId); const why = project ? blocked(project) : "there are no projects yet"; @@ -91,14 +105,19 @@ export function RunForm({ max_seq_len: num(maxSeq), dtype, }; - const plan = epochList.ok && rateList.ok ? planSweep(base, epochList.values, rateList.values, existing) : null; + const plan = + epochList.ok && rateList.ok && existing !== null ? planSweep(base, epochList.values, rateList.values, existing) : null; const sweepProblem = !sweeping ? null : !epochList.ok ? epochList.error : !rateList.ok ? rateList.error - : plan && plan.runs.length === 0 + : existing === null + ? existingError + ? `Could not read this project's runs (${existingError}), so the runs that already exist are not known.` + : "Reading the project's runs…" + : plan && plan.runs.length === 0 ? "Every run in this grid already exists." : plan && plan.runs.length > MAX_SWEEP_RUNS ? `That is ${plan.runs.length} runs. The most one sweep can hold is ${MAX_SWEEP_RUNS}.` @@ -136,15 +155,11 @@ export function RunForm({ const field = "w-full rounded-md border border-fog-line bg-transparent px-3 py-1.5 text-sm outline-none focus:border-ink disabled:opacity-50"; const label = "flex flex-col gap-1 text-xs text-fog"; - const numbers = census || sweeping ? true : Number.isFinite(num(lr)) && Number.isFinite(num(epochs)); - const ready = - !disabled && - why === null && - numbers && - Number.isFinite(num(rank)) && - Number.isFinite(num(alpha)) && - Number.isFinite(num(maxSeq)) && - !sweepProblem; + // Every reason Start can be disabled is shown, because several of the fields + // are out of sight: the LoRA settings sit in a disclosure that starts closed. + const loraIssue = loraProblem(rank, alpha, maxSeq); + const runIssue = kind === "run" ? runProblem(lr, epochs) : null; + const ready = !disabled && why === null && !loraIssue && !runIssue && !sweepProblem; return (
@@ -220,6 +235,10 @@ export function RunForm({ {plan.runs.length} {plan.runs.length === 1 ? "run" : "runs"}: {plan.runs.map((r) => r.name).join(", ")}

{plan.skipped.length > 0 &&

Already in the project, so left alone: {plan.skipped.join(", ")}

} +

+ Each run uses LoRA rank {rank.trim()}, alpha {alpha.trim()} and max sequence {maxSeq.trim()}. Change them under LoRA + settings. +

Each run trains, merges and exports a GGUF of its own, so a sweep takes as long as all of them together.

) : null} @@ -253,7 +272,7 @@ export function RunForm({ )} -
+
LoRA settings
+ {loraIssue &&

{loraIssue}

} + {runIssue &&

{runIssue}

} {error && (

@@ -283,7 +304,7 @@ export function RunForm({ disabled={!ready || busy} className="cursor-pointer rounded-md bg-ink px-3 py-1.5 text-xs font-medium text-paper disabled:cursor-default disabled:opacity-50" > - {busy ? "Starting…" : census ? "Run census" : sweeping ? `Start ${plan?.runs.length ?? 0}-run sweep` : "Start training"} + {busy ? "Starting…" : census ? "Run census" : sweeping ? (plan ? `Start ${plan.runs.length}-run sweep` : "Start sweep") : "Start training"}

diff --git a/packaging/app/src/features/finetune/settings.test.ts b/packaging/app/src/features/finetune/settings.test.ts new file mode 100644 index 0000000..0a499d2 --- /dev/null +++ b/packaging/app/src/features/finetune/settings.test.ts @@ -0,0 +1,37 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { loraProblem, runProblem } from "./settings.ts"; + +test("the usual LoRA settings are fine", () => { + assert.equal(loraProblem("8", "16", "512"), null); + assert.equal(loraProblem("256", "0.5", "8192"), null); + assert.equal(loraProblem(" 8 ", "16", "16"), null); +}); + +test("each LoRA setting names itself when it is out of range or not a number", () => { + assert.match(loraProblem("0", "16", "512")!, /rank/); + assert.match(loraProblem("257", "16", "512")!, /rank/); + assert.match(loraProblem("8.5", "16", "512")!, /rank/, "the backend takes a whole number"); + assert.match(loraProblem("", "16", "512")!, /rank/); + assert.match(loraProblem("8", "0", "512")!, /alpha/); + assert.match(loraProblem("8", "-1", "512")!, /alpha/); + assert.match(loraProblem("8", "abc", "512")!, /alpha/); + assert.match(loraProblem("8", "16", "15")!, /Max sequence/); + assert.match(loraProblem("8", "16", "8193")!, /Max sequence/); + assert.match(loraProblem("8", "16", "512.5")!, /Max sequence/); +}); + +test("the first bad LoRA setting is the one reported", () => { + assert.match(loraProblem("0", "0", "0")!, /rank/); +}); + +test("a training run's learning rate and epochs are checked the way the backend checks them", () => { + assert.equal(runProblem("1e-4", "2"), null); + assert.equal(runProblem("1", "100"), null); + assert.match(runProblem("0", "2")!, /Learning rate/); + assert.match(runProblem("1.5", "2")!, /Learning rate/); + assert.match(runProblem("fast", "2")!, /Learning rate/); + assert.match(runProblem("1e-4", "0")!, /Epochs/); + assert.match(runProblem("1e-4", "101")!, /Epochs/); + assert.match(runProblem("1e-4", "2.5")!, /Epochs/); +}); diff --git a/packaging/app/src/features/finetune/settings.ts b/packaging/app/src/features/finetune/settings.ts new file mode 100644 index 0000000..bc86751 --- /dev/null +++ b/packaging/app/src/features/finetune/settings.ts @@ -0,0 +1,24 @@ +// Why a setting blocks Start, in words. The limits mirror `build_spec` in the +// backend (`desktop/jobs.rs`), so the form says what the backend would say, and +// says it before the click instead of leaving Start quietly disabled. + +const toNumber = (text: string): number => (text.trim() === "" ? NaN : Number(text)); +const isWhole = (n: number, lo: number, hi: number): boolean => Number.isInteger(n) && n >= lo && n <= hi; + +/** The LoRA settings live in a disclosure that is closed by default, so a bad + * value there is invisible. `null` means all three are fine. */ +export function loraProblem(rank: string, alpha: string, maxSeq: string): string | null { + if (!isWhole(toNumber(rank), 1, 256)) return "LoRA rank must be a whole number from 1 to 256."; + const a = toNumber(alpha); + if (!(Number.isFinite(a) && a > 0)) return "LoRA alpha must be a number above 0."; + if (!isWhole(toNumber(maxSeq), 16, 8192)) return "Max sequence must be a whole number from 16 to 8192."; + return null; +} + +/** The learning rate and epochs of a single training run. `null` means both are fine. */ +export function runProblem(learningRate: string, epochs: string): string | null { + const lr = toNumber(learningRate); + if (!(Number.isFinite(lr) && lr > 0 && lr <= 1)) return "Learning rate must be above 0 and at most 1, like 1e-4."; + if (!isWhole(toNumber(epochs), 1, 100)) return "Epochs must be a whole number from 1 to 100."; + return null; +} diff --git a/packaging/app/src/features/finetune/sweep.test.ts b/packaging/app/src/features/finetune/sweep.test.ts index c990dd9..80827f4 100644 --- a/packaging/app/src/features/finetune/sweep.test.ts +++ b/packaging/app/src/features/finetune/sweep.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { advance, begin, headline, isFinished, lowestLoss, parseEpochs, parseRates, planSweep, position, refuse } from "./sweep.ts"; +import { advance, begin, headline, isFinished, isStopping, lowestLoss, parseEpochs, parseRates, planSweep, position, refuse, requestStop } from "./sweep.ts"; import type { JobRequest } from "../../lib/types.ts"; const base: JobRequest = { @@ -73,14 +73,54 @@ test("a failed run is recorded with its reason and the sweep carries on", () => assert.deepEqual(s.results[0], { name: "e2-lr1e-4", status: "failed", finalLoss: null, note: "out of memory" }); }); -test("skipping a run carries on, and stopping ends the sweep", () => { +test("skipping a run carries on with the rest", () => { let s = begin(planSweep(base, [2, 3, 4], [1e-4], []))!; - s = advance({ ...s, skipCurrent: true }, "e2-lr1e-4", { kind: "cancelled" }); + s = advance(s, "e2-lr1e-4", { kind: "cancelled" }); assert.equal(s.results[0].note, "Skipped"); assert.equal(isFinished(s), false); - s = advance({ ...s, stopped: true }, "e3-lr1e-4", { kind: "cancelled" }); + assert.equal(s.queue.length, 2); +}); + +test("a stop waits for the run in flight: the sweep is stopping, not finished", () => { + let s = begin(planSweep(base, [2, 3, 4], [1e-4], []))!; + s = advance(s, "e2-lr1e-4", { kind: "done", finalLoss: 1 }); + s = requestStop(s, true); + assert.equal(isStopping(s), true); + assert.equal(isFinished(s), false, "the run in flight has not ended yet"); + assert.equal(headline(s), "Stopping after run 2 of 3"); + assert.equal(s.results.length, 1, "the run in flight is not counted as done"); + + s = advance(s, "e3-lr1e-4", { kind: "cancelled" }); assert.equal(s.results[1].note, "Sweep stopped"); - assert.equal(isFinished(s), true, "a run is still left in the queue, but stopped wins"); + assert.equal(isFinished(s), true); + assert.equal(isStopping(s), false); + assert.equal(s.queue.length, 0, "the run still queued will never start"); + assert.equal(headline(s), "Sweep stopped after 2 of 3 runs"); +}); + +test("a stop pressed while a merge cannot be interrupted still ends the sweep once that run finishes", () => { + let s = begin(planSweep(base, [2, 3, 4], [1e-4], []))!; + s = requestStop(s, true); + s = advance(s, "e2-lr1e-4", { kind: "done", finalLoss: 0.4 }); + assert.equal(s.results[0].status, "done", "it finished, so it is recorded as done"); + assert.equal(isFinished(s), true, "and nothing after it starts"); + assert.equal(headline(s), "Sweep stopped after 1 of 3 runs"); +}); + +test("a stop between two runs, with nothing in flight, ends the sweep at once", () => { + let s = begin(planSweep(base, [2, 3, 4], [1e-4], []))!; + s = advance(s, "e2-lr1e-4", { kind: "done", finalLoss: 1 }); + s = requestStop(s, false); + assert.equal(isFinished(s), true, "otherwise it would wait forever for a run that is not coming"); + assert.equal(isStopping(s), false); + assert.equal(headline(s), "Sweep stopped after 1 of 3 runs"); +}); + +test("a request refused while stopping does not leave the queue behind", () => { + let s = begin(planSweep(base, [2, 3], [1e-4], []))!; + s = requestStop(s, true); + s = refuse(s, "e2-lr1e-4", "no base model"); + assert.equal(isFinished(s), true); }); test("a request the backend refuses is recorded and does not stall the queue", () => { diff --git a/packaging/app/src/features/finetune/sweep.ts b/packaging/app/src/features/finetune/sweep.ts index 3164ac2..84d2d48 100644 --- a/packaging/app/src/features/finetune/sweep.ts +++ b/packaging/app/src/features/finetune/sweep.ts @@ -80,10 +80,9 @@ export interface SweepState { queue: JobRequest[]; /** What each finished or refused run came to. */ results: SweepResult[]; - /** The user asked to stop: nothing more starts after the current run. */ + /** The user asked to stop. The queue is emptied as soon as the run in flight + * has ended, so nothing more starts after it. */ stopped: boolean; - /** The user asked to skip the current run and carry on. */ - skipCurrent: boolean; } export function begin(plan: SweepPlan): SweepState | null { @@ -93,13 +92,13 @@ export function begin(plan: SweepPlan): SweepState | null { queue: plan.runs.map((r) => r.request), results: [], stopped: false, - skipCurrent: false, }; } /** What the header says: where a sweep in progress is, or how far a finished one * got. A stopped sweep did not reach its last runs, so it must not claim to. */ export function headline(s: SweepState): string { + if (isStopping(s)) return `Stopping after run ${position(s)} of ${s.total}`; if (!isFinished(s)) return `Sweep, run ${position(s)} of ${s.total}`; return s.results.length < s.total ? `Sweep stopped after ${s.results.length} of ${s.total} runs` @@ -108,7 +107,21 @@ export function headline(s: SweepState): string { /** 1-based number of the run in progress. */ export const position = (s: SweepState): number => s.results.length + 1; -export const isFinished = (s: SweepState): boolean => s.queue.length === 0 || s.stopped; +/** Nothing is left to start. A stopped sweep is not finished until the run that + * was in flight has ended, so the screen does not claim it is over (or swap the + * Stop button for Cancel) while that run is still winding down. */ +export const isFinished = (s: SweepState): boolean => s.queue.length === 0; + +/** Stop was asked for and the run in flight has not ended yet. */ +export const isStopping = (s: SweepState): boolean => s.stopped && !isFinished(s); + +/** The user pressed Stop. With a run in flight, it is allowed to end first + * (training stops after its step, a merge or export finishes). With none, which + * is the instant between two runs, there is nothing to wait for, so the sweep + * ends now. */ +export function requestStop(s: SweepState, runInFlight: boolean): SweepState { + return { ...s, stopped: true, queue: runInFlight ? s.queue : [] }; +} export type Outcome = | { kind: "done"; finalLoss: number | null } @@ -124,15 +137,14 @@ export function advance(s: SweepState, name: string, outcome: Outcome): SweepSta : outcome.kind === "failed" ? { name, status: "failed", finalLoss: null, note: outcome.message } : { name, status: "cancelled", finalLoss: null, note: s.stopped ? "Sweep stopped" : "Skipped" }; - // Cancelling a run is either "skip this one" or "stop everything". Anything - // else that ends a run, including a failure, carries on with the rest. - const stopped = s.stopped; + // Cancelling a run is either "skip this one" or "stop everything", and the + // note above follows `stopped`. Anything else that ends a run, including a + // failure, carries on with the rest. A stop empties the queue, whatever the + // run ended with: it may have finished before the cancel landed. return { ...s, - queue: s.queue.slice(1), + queue: s.stopped ? [] : s.queue.slice(1), results: [...s.results, result], - skipCurrent: false, - stopped, }; } @@ -140,7 +152,7 @@ export function advance(s: SweepState, name: string, outcome: Outcome): SweepSta export function refuse(s: SweepState, name: string, message: string): SweepState { return { ...s, - queue: s.queue.slice(1), + queue: s.stopped ? [] : s.queue.slice(1), results: [...s.results, { name, status: "refused", finalLoss: null, note: message }], }; } diff --git a/packaging/app/src/features/finetune/useJob.ts b/packaging/app/src/features/finetune/useJob.ts index db0db69..0a8c584 100644 --- a/packaging/app/src/features/finetune/useJob.ts +++ b/packaging/app/src/features/finetune/useJob.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { ipc } from "@/lib/ipc"; import type { JobRequest, RunEvent, StepRecord } from "@/lib/types"; -import { apply, defaultRunName, elapsedFromSteps, idle, positionFromSteps, type JobState } from "./job"; +import { apply, defaultRunName, elapsedFromSteps, idle, isRunning, positionFromSteps, type JobState } from "./job"; import * as sweepLogic from "./sweep"; import type { SweepPlan, SweepState } from "./sweep"; @@ -175,19 +175,20 @@ export function useJob() { if (!sweepLogic.isFinished(next)) void launchNext(); }, [state.outcome, state.info, launchNext, setSweep]); - /** Cancel the current run and carry on with the rest of the sweep. */ - const skipRun = useCallback(() => { - const current = sweepRef.current; - if (current) setSweep({ ...current, skipCurrent: true }); - cancel(); - }, [cancel, setSweep]); + /** Cancel the current run and carry on with the rest of the sweep. A cancelled + * run of a sweep that is not stopping counts as skipped. */ + const skipRun = useCallback(() => cancel(), [cancel]); - /** Cancel the current run and start no more. */ + /** Cancel the current run and start no more. The sweep reads as stopping until + * that run has ended. With no run in flight (the instant between two runs) + * there is nothing to wait for and it ends at once. */ const stopSweep = useCallback(() => { const current = sweepRef.current; - if (current) setSweep({ ...current, stopped: true }); - cancel(); - }, [cancel, setSweep]); + if (!current) return; + const inFlight = isRunning(state); + setSweep(sweepLogic.requestStop(current, inFlight)); + if (inFlight) cancel(); + }, [cancel, setSweep, state]); const dismiss = useCallback(() => { steps.current = []; From cfd5abbf73c3ba5bdf6e31c00fad51ab9c2d123d Mon Sep 17 00:00:00 2001 From: Seto Elkahfi <1797197+setoelkahfi@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:33:34 +0100 Subject: [PATCH 3/3] app: show the lowest loss value in the sweep summary, drop an unused status The sweep summary said "Lowest training loss" and then printed a run name. It now prints the name with its final loss. The "skipped" result status was never produced, since a skipped run is recorded as cancelled, so it is removed. Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: siGit Code v1.7.10 Co-Authored-By: OndeCode v1.1.2 --- packaging/app/src/features/finetune/JobPanel.tsx | 2 +- packaging/app/src/features/finetune/sweep.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packaging/app/src/features/finetune/JobPanel.tsx b/packaging/app/src/features/finetune/JobPanel.tsx index ee58102..22ecc19 100644 --- a/packaging/app/src/features/finetune/JobPanel.tsx +++ b/packaging/app/src/features/finetune/JobPanel.tsx @@ -223,7 +223,7 @@ export function JobPanel({ job }: { job: Job }) { {isFinished(sweep) && lowestLoss(sweep.results) && (

- Lowest training loss: {lowestLoss(sweep.results)}. A low loss on the training set does not mean a better model, so check the replies before you pick one. + Lowest final training loss: {lowestLoss(sweep.results)} ({sweep.results.find((r) => r.name === lowestLoss(sweep.results))?.finalLoss?.toFixed(3)}). A low loss on the training set does not mean a better model, so check the replies before you pick one.

)} diff --git a/packaging/app/src/features/finetune/sweep.ts b/packaging/app/src/features/finetune/sweep.ts index 84d2d48..9607fc0 100644 --- a/packaging/app/src/features/finetune/sweep.ts +++ b/packaging/app/src/features/finetune/sweep.ts @@ -67,7 +67,7 @@ export function planSweep( export interface SweepResult { name: string; - status: RunStatus | "refused" | "skipped"; + status: RunStatus | "refused"; /** Mean loss of the last epoch, when the run got that far. */ finalLoss: number | null; /** Why it did not finish, when it did not. */