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..22ecc19 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/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 new file mode 100644 index 0000000..80827f4 --- /dev/null +++ b/packaging/app/src/features/finetune/sweep.test.ts @@ -0,0 +1,151 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +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 = { + 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 with the rest", () => { + let s = begin(planSweep(base, [2, 3, 4], [1e-4], []))!; + s = advance(s, "e2-lr1e-4", { kind: "cancelled" }); + assert.equal(s.results[0].note, "Skipped"); + assert.equal(isFinished(s), false); + 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); + 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", () => { + 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..9607fc0 --- /dev/null +++ b/packaging/app/src/features/finetune/sweep.ts @@ -0,0 +1,168 @@ +// 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"; + /** 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. The queue is emptied as soon as the run in flight + * has ended, so nothing more starts after it. */ + stopped: 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, + }; +} + +/** 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` + : `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; +/** 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 } + | { 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", 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.stopped ? [] : s.queue.slice(1), + results: [...s.results, result], + }; +} + +/** 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.stopped ? [] : 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..0a8c584 100644 --- a/packaging/app/src/features/finetune/useJob.ts +++ b/packaging/app/src/features/finetune/useJob.ts @@ -1,7 +1,9 @@ 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"; /** 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,89 @@ 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. 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. 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) return; + const inFlight = isRunning(state); + setSweep(sweepLogic.requestStop(current, inFlight)); + if (inFlight) cancel(); + }, [cancel, setSweep, state]); + 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, };