Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions packaging/app/src/features/finetune/FinetuneView.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="flex flex-col gap-4">
<div>
Expand All @@ -13,7 +17,7 @@ export function FinetuneView({ job }: { job: Job }) {
</div>
<JobPanel job={job} />
{/* Hidden while a job's result is on screen, so the result is what you see. */}
{(!job.state.info || running) && <RunForm disabled={running} onStart={job.start} />}
{(!job.state.info && job.sweep === null) || running ? <RunForm disabled={running} onStart={job.start} onSweep={job.startSweep} /> : null}
</div>
);
}
63 changes: 60 additions & 3 deletions packaging/app/src/features/finetune/JobPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -40,7 +45,8 @@ export function JobPanel({ job }: { job: Job }) {
<div className="min-w-0">
<h2 className="truncate text-sm font-medium">{info.run}</h2>
<p className="truncate text-xs text-fog">
{census ? "Gradient census" : "Training run"} · {info.repo_id}
{census ? "Gradient census" : sweep ? sweepHeadline(sweep) : "Training run"} ·{" "}
{info.repo_id}
</p>
</div>
<div className="flex shrink-0 items-center gap-2">
Expand All @@ -52,7 +58,27 @@ export function JobPanel({ job }: { job: Job }) {
{BACKEND_NAME[state.backend.name]}
</span>
)}
{running && (
{running && sweepActive && (
<>
<button
type="button"
disabled={state.stopping}
onClick={job.skipRun}
className="cursor-pointer rounded-md border border-fog-line px-2.5 py-1 text-xs font-medium hover:bg-fog-line disabled:cursor-default disabled:opacity-60"
>
Skip run
</button>
<button
type="button"
disabled={state.stopping}
onClick={job.stopSweep}
className="cursor-pointer rounded-md border border-fog-line px-2.5 py-1 text-xs font-medium hover:bg-fog-line disabled:cursor-default disabled:opacity-60"
>
{state.stopping && sweep?.stopped ? "Stopping…" : "Stop sweep"}
</button>
</>
)}
{running && !sweepActive && (
<button
type="button"
disabled={state.stopping}
Expand Down Expand Up @@ -172,7 +198,38 @@ export function JobPanel({ job }: { job: Job }) {
</p>
)}
{outcome?.kind === "cancelled" && <p role="status" className="mt-3 text-xs text-fog">Stopped. No adapter was written.</p>}
{outcome && (
{sweep && sweep.results.length > 0 && (
<div className="mt-4">
<h3 className="text-xs font-medium">{isFinished(sweep) ? "Sweep finished" : "Sweep so far"}</h3>
<table className="mt-1 w-full text-left text-xs">
<thead className="text-fog">
<tr>
<th className="py-1 pr-3 font-normal">Run</th>
<th className="py-1 pr-3 font-normal">Result</th>
<th className="py-1 text-right font-normal">Final loss</th>
</tr>
</thead>
<tbody>
{sweep.results.map((r) => (
<tr key={r.name} className="border-t border-fog-line">
<td className="py-1 pr-3 font-medium">{r.name}</td>
<td className={`py-1 pr-3 ${r.status === "failed" || r.status === "refused" ? "text-red-600" : "text-fog"}`}>
{r.status === "done" ? "Done" : r.status === "cancelled" ? r.note : `${r.status === "refused" ? "Not started" : "Failed"}: ${r.note}`}
</td>
<td className="py-1 text-right tabular-nums">{r.finalLoss === null ? "" : r.finalLoss.toFixed(3)}</td>
</tr>
))}
</tbody>
</table>
{isFinished(sweep) && lowestLoss(sweep.results) && (
<p className="mt-2 text-xs text-fog">
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.
</p>
)}
</div>
)}

{outcome && !sweepActive && (
<button
type="button"
onClick={job.dismiss}
Expand Down
152 changes: 135 additions & 17 deletions packaging/app/src/features/finetune/RunForm.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { useEffect, useState } from "react";
import { ipc } from "@/lib/ipc";
import { errorMessage, type JobKind, type JobRequest, type ProjectSummary } from "@/lib/types";
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. */
type Mode = "census" | "run" | "sweep";

const DTYPES = [
{ id: "q4_k_m", label: "Q4_K_M (smallest, the usual choice)" },
Expand All @@ -22,14 +27,24 @@ const num = (text: string) => (text.trim() === "" ? NaN : Number(text));
export function RunForm({
disabled,
onStart,
onSweep,
}: {
/** A job is running, so a second cannot start. */
disabled: boolean;
onStart: (request: JobRequest, datasetRows: number | null) => Promise<void>;
onSweep: (plan: SweepPlan, datasetRows: number | null) => Promise<void>;
}) {
const [projects, setProjects] = useState<ProjectSummary[]>([]);
const [repoId, setRepoId] = useState("");
const [kind, setKind] = useState<JobKind>("census");
const [kind, setKind] = useState<Mode>("census");
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.
// 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<string | null>(null);
const [name, setName] = useState("");
const [lr, setLr] = useState("1e-4");
const [epochs, setEpochs] = useState("2");
Expand All @@ -51,19 +66,76 @@ export function RunForm({
.catch((e) => setError(errorMessage(e)));
}, []);

useEffect(() => {
if (!repoId) return;
let current = true;
ipc
.projectDetail(repoId)
.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";
const census = kind === "census";
const sweeping = kind === "sweep";

const epochList = parseEpochs(sweepEpochs);
const rateList = parseRates(sweepRates);
const base: JobRequest = {
repo_id: repoId,
kind: "run",
name: "",
learning_rate: 1e-4,
epochs: 1,
lora_rank: num(rank),
Comment thread
setoelkahfi marked this conversation as resolved.
Resolved
lora_alpha: num(alpha),
max_seq_len: num(maxSeq),
dtype,
};
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
: 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}.`
: null;

async function submit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setBusy(true);
try {
if (sweeping) {
if (plan && !sweepProblem) await onSweep(plan, project?.dataset_rows ?? null);
return;
}
await onStart(
{
repo_id: repoId,
kind,
kind: census ? "census" : "run",
name: census ? "" : name.trim(),
learning_rate: num(lr),
epochs: num(epochs),
Expand All @@ -83,16 +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
? Number.isFinite(num(lr)) && Number.isFinite(num(epochs))
: true;
const ready =
!disabled &&
why === null &&
numbers &&
Number.isFinite(num(rank)) &&
Number.isFinite(num(alpha)) &&
Number.isFinite(num(maxSeq));
// 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 (
<form onSubmit={submit} className="flex flex-col gap-3 rounded-lg border border-fog-line px-4 py-3">
Expand Down Expand Up @@ -122,15 +189,64 @@ export function RunForm({
</span>
</label>
<label className="flex cursor-pointer items-start gap-2 text-sm">
<input type="radio" name="kind" checked={!census} onChange={() => setKind("run")} className="mt-1" />
<input type="radio" name="kind" checked={kind === "run"} onChange={() => setKind("run")} className="mt-1" />
<span>
Training run
<span className="block text-xs text-fog">Train a LoRA adapter, merge it into the base model and export a GGUF.</span>
</span>
</label>
<label className="flex cursor-pointer items-start gap-2 text-sm">
<input type="radio" name="kind" checked={sweeping} onChange={() => setKind("sweep")} className="mt-1" />
<span>
Sweep
<span className="block text-xs text-fog">
Train once for each epoch count and learning rate you list, one after another, then compare them under Projects.
</span>
</span>
</label>
</fieldset>

{!census && (
{sweeping && (
<div className="grid grid-cols-2 gap-3">
<label className={label}>
Epochs
<input className={field} value={sweepEpochs} onChange={(e) => setSweepEpochs(e.target.value)} disabled={disabled} spellCheck={false} />
</label>
<label className={label}>
Learning rates
<input className={field} value={sweepRates} onChange={(e) => setSweepRates(e.target.value)} disabled={disabled} spellCheck={false} />
</label>
<label className={label}>
Export as
<select className={field} value={dtype} onChange={(e) => setDtype(e.target.value as JobRequest["dtype"])} disabled={disabled}>
{DTYPES.map((d) => (
<option key={d.id} value={d.id}>
{d.label}
</option>
))}
</select>
</label>
<div className="col-span-2 text-xs text-fog" aria-live="polite">
{sweepProblem ? (
<p className="text-amber-600">{sweepProblem}</p>
) : plan ? (
<>
<p>
{plan.runs.length} {plan.runs.length === 1 ? "run" : "runs"}: {plan.runs.map((r) => r.name).join(", ")}
</p>
{plan.skipped.length > 0 && <p>Already in the project, so left alone: {plan.skipped.join(", ")}</p>}
<p>
Each run uses LoRA rank {rank.trim()}, alpha {alpha.trim()} and max sequence {maxSeq.trim()}. Change them under LoRA
settings.
</p>
<p>Each run trains, merges and exports a GGUF of its own, so a sweep takes as long as all of them together.</p>
</>
) : null}
</div>
</div>
)}

{kind === "run" && (
<div className="grid grid-cols-2 gap-3">
<label className={label}>
Run name
Expand All @@ -156,7 +272,7 @@ export function RunForm({
</label>
</div>
)}
<details className="text-xs text-fog">
<details className="text-xs text-fog" open={loraIssue !== null || undefined}>
<summary className="cursor-pointer">LoRA settings</summary>
<div className="mt-2 grid grid-cols-3 gap-3">
<label className={label}>
Expand All @@ -173,6 +289,8 @@ export function RunForm({
</label>
</div>
</details>
{loraIssue && <p className="text-xs text-amber-600">{loraIssue}</p>}
{runIssue && <p className="text-xs text-amber-600">{runIssue}</p>}

{error && (
<p role="alert" className="text-xs text-red-600">
Expand All @@ -186,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" : "Start training"}
{busy ? "Starting…" : census ? "Run census" : sweeping ? (plan ? `Start ${plan.runs.length}-run sweep` : "Start sweep") : "Start training"}
</button>
</div>
</form>
Expand Down
37 changes: 37 additions & 0 deletions packaging/app/src/features/finetune/settings.test.ts
Original file line number Diff line number Diff line change
@@ -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/);
});
Loading
Loading