From a90f7ad7179b280866d185a0dcd19ca54dd27bc2 Mon Sep 17 00:00:00 2001 From: Seto Elkahfi <1797197+setoelkahfi@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:39:34 +0100 Subject: [PATCH 1/3] app: run gradient censuses and training runs with live charts The Fine-tune tab. Pick a project, then either run a gradient census (one epoch at a learning rate of 0, which trains nothing and shows whether the backward pass is sane) or a training run that ends in a GGUF. While a job runs the tab shows the stage (train, merge, export), the backend (a CPU fallback is called out with the reason), a progress bar, the time left, live loss and gradient-norm charts, skipped steps, and a Cancel button. A census ends with a verdict: norms of 10 to 100 are healthy, 1e6 or more means a broken backward pass, and skipped steps are a warning. Rows the trainer left out because they are longer than the max sequence length are reported, since the trainer only logs that. The job lives in App, so it survives switching tabs, the sidebar shows a dot while it runs, and a webview that reloads picks the job back up. One job runs at a time. The Mac is kept awake for the length of a run with an activity assertion, which pmset lists while it is held. Cancel stops after the current step and leaves no adapter. Fixes a bug in the pipeline's progress events: RunProgress::Failed held a bare string inside an internally tagged enum, which serde cannot serialize, so every failure message would have been lost on its way to the app. It now carries { message }, and a test serializes every variant. The release scripts now bundle mlx.metallib next to the app binary and fail the build if it is missing. Without it MLX falls back to the CPU quietly. find-mlx-metallib.sh takes a profile and honours CARGO_TARGET_DIR. tauri dev now builds dependencies with optimizations. A debug trainer took about seven minutes to fine-tune and export a 1.7B model on 12 rows, and the optimized one takes 47 seconds. The first build is slower, about 12 minutes. Checked in the running app: a census (MLX, 4 steps, verdict "healthy"), a full run to a 1.19 GB GGUF whose run.json, adapter and charts match, and Cancel mid-run (status cancelled, no adapter). Not checked: the bundled metallib in a signed release build, a CPU fallback run, or a reload in the middle of a job. Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: siGit Code v1.7.10 Co-Authored-By: OndeCode v1.1.2 --- packaging/app/package.json | 3 +- packaging/app/scripts/build-appstore.sh | 7 +- packaging/app/scripts/build-direct.sh | 7 +- packaging/app/scripts/release-lib.sh | 27 +- packaging/app/src-tauri/Cargo.toml | 10 +- packaging/app/src-tauri/src/commands/jobs.rs | 40 ++ packaging/app/src-tauri/src/commands/mod.rs | 1 + packaging/app/src-tauri/src/desktop/jobs.rs | 485 ++++++++++++++++++ packaging/app/src-tauri/src/desktop/mod.rs | 2 + packaging/app/src-tauri/src/desktop/power.rs | 86 ++++ .../app/src-tauri/src/desktop/projects.rs | 4 + packaging/app/src-tauri/src/lib.rs | 4 + packaging/app/src/App.tsx | 8 +- packaging/app/src/components/AppSidebar.tsx | 10 + packaging/app/src/components/nav-items.ts | 1 + .../src/features/finetune/FinetuneView.tsx | 19 + .../app/src/features/finetune/JobPanel.tsx | 185 +++++++ .../app/src/features/finetune/RunForm.tsx | 194 +++++++ .../app/src/features/finetune/census.test.ts | 49 ++ packaging/app/src/features/finetune/census.ts | 58 +++ .../app/src/features/finetune/job.test.ts | 74 +++ packaging/app/src/features/finetune/job.ts | 115 +++++ packaging/app/src/features/finetune/useJob.ts | 103 ++++ packaging/app/src/lib/ipc.ts | 16 + packaging/app/src/lib/types.ts | 41 ++ packaging/app/tsconfig.json | 8 +- packaging/macos/find-mlx-metallib.sh | 19 +- src/gguf.rs | 2 +- src/pipeline.rs | 80 ++- 29 files changed, 1635 insertions(+), 23 deletions(-) create mode 100644 packaging/app/src-tauri/src/commands/jobs.rs create mode 100644 packaging/app/src-tauri/src/desktop/jobs.rs create mode 100644 packaging/app/src-tauri/src/desktop/power.rs create mode 100644 packaging/app/src/features/finetune/FinetuneView.tsx create mode 100644 packaging/app/src/features/finetune/JobPanel.tsx create mode 100644 packaging/app/src/features/finetune/RunForm.tsx create mode 100644 packaging/app/src/features/finetune/census.test.ts create mode 100644 packaging/app/src/features/finetune/census.ts create mode 100644 packaging/app/src/features/finetune/job.test.ts create mode 100644 packaging/app/src/features/finetune/job.ts create mode 100644 packaging/app/src/features/finetune/useJob.ts diff --git a/packaging/app/package.json b/packaging/app/package.json index 0b91b9e..86b8a20 100644 --- a/packaging/app/package.json +++ b/packaging/app/package.json @@ -11,7 +11,8 @@ "tauri": "tauri", "appstore": "bash scripts/build-appstore.sh", "direct": "bash scripts/build-direct.sh", - "check:config": "node scripts/check-tauri-config.mjs" + "check:config": "node scripts/check-tauri-config.mjs", + "test": "node --test" }, "dependencies": { "@tauri-apps/api": "^2.12.5", diff --git a/packaging/app/scripts/build-appstore.sh b/packaging/app/scripts/build-appstore.sh index 7d9c3cc..26b7c27 100755 --- a/packaging/app/scripts/build-appstore.sh +++ b/packaging/app/scripts/build-appstore.sh @@ -35,15 +35,20 @@ do_build() { echo "🏷 bundleVersion → ${BUNDLE_VERSION}" echo "📜 profile → ${MAS_PROVISIONING_PROFILE_PATH}" + prebuild_mlx + METALLIB="$(mlx_metallib)" + echo "🧩 mlx.metallib → ${METALLIB}" + # --config values merge in order; the file is never modified. (cd "$APP_DIR" && pnpm tauri build \ --bundles app \ --target universal-apple-darwin \ --config "$CONFIG" \ - --config "$(config_json "$BUNDLE_VERSION" "$MAS_PROVISIONING_PROFILE_PATH")") + --config "$(config_json "$BUNDLE_VERSION" "$MAS_PROVISIONING_PROFILE_PATH" "$METALLIB")") [[ -d "$APP_PATH" ]] || fail "Build succeeded but the .app is not at: ${APP_PATH}" verify_codesign_matches_profile "$APP_PATH" + require_metallib "$APP_PATH" require_entitlements "$APP_PATH" \ com.apple.security.app-sandbox \ com.apple.security.network.client \ diff --git a/packaging/app/scripts/build-direct.sh b/packaging/app/scripts/build-direct.sh index 91b9c51..b4e5849 100755 --- a/packaging/app/scripts/build-direct.sh +++ b/packaging/app/scripts/build-direct.sh @@ -42,14 +42,19 @@ do_build() { echo "🏷 bundleVersion → ${BUNDLE_VERSION}" echo "📜 profile → ${DEVID_PROVISIONING_PROFILE_PATH}" + prebuild_mlx + METALLIB="$(mlx_metallib)" + echo "🧩 mlx.metallib → ${METALLIB}" + (cd "$APP_DIR" && pnpm tauri build \ --bundles app,dmg \ --target universal-apple-darwin \ --config "$CONFIG" \ - --config "$(config_json "$BUNDLE_VERSION" "$DEVID_PROVISIONING_PROFILE_PATH")") + --config "$(config_json "$BUNDLE_VERSION" "$DEVID_PROVISIONING_PROFILE_PATH" "$METALLIB")") [[ -d "$APP_PATH" ]] || fail "Build succeeded but the .app is not at: ${APP_PATH}" [[ -n "$(find_dmg)" ]] || fail "Build succeeded but there is no .dmg in ${BUNDLE_DIR}/dmg" + require_metallib "$APP_PATH" notarize_dmg "$(find_dmg)" ok "Build complete → $(find_dmg)" } diff --git a/packaging/app/scripts/release-lib.sh b/packaging/app/scripts/release-lib.sh index 3553ebe..9e6ded9 100755 --- a/packaging/app/scripts/release-lib.sh +++ b/packaging/app/scripts/release-lib.sh @@ -68,12 +68,33 @@ bundle_version() { date -u +"%Y%m%d.%H%M"; } # the binary (build.rs reads ONDE_DESKTOP_BUILD), so the sidebar can show it. export_build_number() { export ONDE_DESKTOP_BUILD="$1"; } +# MLX loads its Metal kernels from mlx.metallib next to the app binary. Without +# the file, training quietly falls back to the CPU, which is many times slower. +# mlx-sys builds it under the cargo target directory, so compile for Apple +# Silicon first and hand the file's path to the bundle. +prebuild_mlx() { + step "MLX kernels" + (cd "$TAURI_DIR" && cargo build --release --target aarch64-apple-darwin --features tauri/custom-protocol) +} + +# Absolute path of the mlx.metallib that prebuild_mlx left behind. +mlx_metallib() { + (cd "$TAURI_DIR" && "${CLI_ROOT}/packaging/macos/find-mlx-metallib.sh" aarch64-apple-darwin "${1:-release}") +} + +# Fail unless the built .app carries the kernels next to its binary. +require_metallib() { + [[ -f "$1/Contents/MacOS/mlx.metallib" ]] \ + || fail "mlx.metallib is not in $1/Contents/MacOS. Training would fall back to the CPU." +} + # JSON for one extra --config. node is already needed for the frontend, and it -# quotes paths correctly. +# quotes paths correctly. The third argument is the mlx.metallib to bundle. config_json() { - BUNDLE_VERSION="$1" PROFILE="$2" node -e ' + BUNDLE_VERSION="$1" PROFILE="$2" METALLIB="$3" node -e ' const m = { bundleVersion: process.env.BUNDLE_VERSION, - files: { "embedded.provisionprofile": process.env.PROFILE } }; + files: { "embedded.provisionprofile": process.env.PROFILE, + "MacOS/mlx.metallib": process.env.METALLIB } }; process.stdout.write(JSON.stringify({ bundle: { macOS: m } }));' } diff --git a/packaging/app/src-tauri/Cargo.toml b/packaging/app/src-tauri/Cargo.toml index 8f4c5e6..5ff85cd 100644 --- a/packaging/app/src-tauri/Cargo.toml +++ b/packaging/app/src-tauri/Cargo.toml @@ -37,8 +37,16 @@ base64 = "0.22" # calls with no Tauri API, so they are used directly and only on macOS. [target.'cfg(target_os = "macos")'.dependencies] objc2 = "0.6" -objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData", "NSError", "NSString", "NSURL"] } +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData", "NSError", "NSObject", "NSProcessInfo", "NSString", "NSURL"] } objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSOpenPanel", "NSSavePanel", "NSPanel", "NSWindow", "NSResponder", "NSApplication"] } [dev-dependencies] tempfile = "3" + +# `tauri dev` is a debug build, and an unoptimized trainer and GGUF quantizer are +# unusably slow: exporting a 1.7B model took over five minutes where an optimized +# build takes under one. Dependencies, which include the onde-cli pipeline and +# candle, build with optimizations; the app's own code stays unoptimized so +# edits still rebuild quickly. +[profile.dev.package."*"] +opt-level = 3 diff --git a/packaging/app/src-tauri/src/commands/jobs.rs b/packaging/app/src-tauri/src/commands/jobs.rs new file mode 100644 index 0000000..f71d52b --- /dev/null +++ b/packaging/app/src-tauri/src/commands/jobs.rs @@ -0,0 +1,40 @@ +use onde_cli::pipeline::RunProgress; +use tauri::{State, ipc::Channel}; + +use crate::{ + desktop::jobs::{JobInfo, JobRequest, Jobs}, + error::CommandError, +}; + +/// A sink that forwards each event to the webview. A webview that has gone away +/// makes `send` fail, and the job carries on without it. +fn sink(channel: Channel) -> crate::desktop::jobs::Sink { + Box::new(move |event| { + let _ = channel.send(event); + }) +} + +/// Start a census or a training run. Events arrive on `on_event` until the run +/// ends with `done`, `failed` or `cancelled`. +#[tauri::command] +pub fn start_job( + request: JobRequest, + on_event: Channel, + jobs: State<'_, Jobs>, +) -> Result { + jobs.start(&request, sink(on_event)) + .map_err(CommandError::InvalidChoice) +} + +/// The job in progress, if any, and from now on its events go to `on_event`. +/// A webview that reloaded mid-run calls this to pick the run back up. +#[tauri::command] +pub fn attach_job(on_event: Channel, jobs: State<'_, Jobs>) -> Option { + jobs.attach(sink(on_event)) +} + +/// Ask the running job to stop. Training stops after the current step. +#[tauri::command] +pub fn cancel_job(jobs: State<'_, Jobs>) -> bool { + jobs.cancel() +} diff --git a/packaging/app/src-tauri/src/commands/mod.rs b/packaging/app/src-tauri/src/commands/mod.rs index 3d74966..f128b80 100644 --- a/packaging/app/src-tauri/src/commands/mod.rs +++ b/packaging/app/src-tauri/src/commands/mod.rs @@ -1,6 +1,7 @@ pub mod app; pub mod auth; pub mod base_models; +pub mod jobs; pub mod links; pub mod oauth; pub mod projects; diff --git a/packaging/app/src-tauri/src/desktop/jobs.rs b/packaging/app/src-tauri/src/desktop/jobs.rs new file mode 100644 index 0000000..8519c3c --- /dev/null +++ b/packaging/app/src-tauri/src/desktop/jobs.rs @@ -0,0 +1,485 @@ +//! Running one fine-tune job at a time and telling the webview how it goes. +//! +//! A job is a [`pipeline`] run: train, then merge and export a GGUF. A gradient +//! census is the same run with a learning rate of 0, one epoch and no export, so +//! it is only a different request. +//! +//! The manager owns no Tauri types. The caller hands it a sink, a closure that +//! receives each [`RunProgress`], and the commands wrap a Tauri channel in one. +//! A webview that reloads mid-run attaches a new sink and carries on. + +use std::{ + path::PathBuf, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, +}; + +use onde_cli::{ + gguf::GgufDtype, + hf_clone::BASE_MODELS, + models, + pipeline::{self, GgufMeta, RunProgress, RunSpec}, + project::{self, OndeProject}, +}; +use serde::{Deserialize, Serialize}; + +use super::{power::KeepAwake, projects::check_repo_id}; + +/// Receives each event of the running job. Replaced when the webview reattaches. +pub type Sink = Box; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum JobKind { + /// One epoch at a learning rate of 0: it trains nothing and only measures + /// the gradients, which is how a broken backward pass shows up. + Census, + /// A training run that ends in a GGUF. + Run, +} + +/// What the Fine-tune tab asks for. +#[derive(Debug, Clone, Deserialize)] +pub struct JobRequest { + pub repo_id: String, + pub kind: JobKind, + /// Run folder name. Ignored for a census, which names itself. + #[serde(default)] + pub name: String, + pub learning_rate: f64, + pub epochs: usize, + pub lora_rank: usize, + pub lora_alpha: f32, + pub max_seq_len: usize, + pub dtype: GgufDtype, +} + +/// The job in progress, for a webview that has just loaded. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct JobInfo { + pub repo_id: String, + pub run: String, + pub kind: JobKind, +} + +struct Active { + info: JobInfo, + cancel: Arc, + sink: Arc>>, +} + +type Slot = Arc>>; + +#[derive(Default)] +pub struct Jobs { + /// Shared with the thread that forwards a run's events, which empties it + /// when the run ends. + active: Slot, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +fn is_final(event: &RunProgress) -> bool { + matches!( + event, + RunProgress::Done(_) | RunProgress::Failed { .. } | RunProgress::Cancelled + ) +} + +/// The suggested run name: `e2-lr1e-4`, the way the earlier runs were named. +pub fn default_run_name(epochs: usize, learning_rate: f64) -> String { + format!("e{epochs}-lr{learning_rate:e}") +} + +/// Turn a request into a run spec, checking everything a mistake could break. +/// `base_dir` is where the complete base model is, found by the caller. +pub fn build_spec( + req: &JobRequest, + project: &OndeProject, + base_dir: PathBuf, + now_secs: u64, +) -> Result { + let census = req.kind == JobKind::Census; + if !census { + if !(req.learning_rate > 0.0 && req.learning_rate <= 1.0) { + return Err("The learning rate must be above 0 and at most 1.".into()); + } + if !(1..=100).contains(&req.epochs) { + return Err("Epochs must be between 1 and 100.".into()); + } + } + if !(1..=256).contains(&req.lora_rank) { + return Err("LoRA rank must be between 1 and 256.".into()); + } + if !(req.lora_alpha > 0.0 && req.lora_alpha.is_finite()) { + return Err("LoRA alpha must be above 0.".into()); + } + if !(16..=8192).contains(&req.max_seq_len) { + return Err("Max sequence length must be between 16 and 8192.".into()); + } + project::inspect_dataset(&project.dataset_path) + .map_err(|e| format!("The dataset can't be used: {e:#}"))?; + + let name = if census { + format!("census-{now_secs}") + } else if req.name.trim().is_empty() { + default_run_name(req.epochs, req.learning_rate) + } else { + req.name.trim().to_string() + }; + pipeline::validate_run_name(&name).map_err(|e| format!("{e:#}"))?; + + let model_name = project + .repo_id + .rsplit('/') + .next() + .unwrap_or("model") + .to_string(); + let base_name = BASE_MODELS + .iter() + .find(|m| m.repo_id == project.base_model_id) + .map(|m| m.display_name.to_string()); + Ok(RunSpec { + name, + base_dir, + data_path: project.dataset_path.clone(), + lora_rank: req.lora_rank, + lora_alpha: req.lora_alpha, + learning_rate: if census { 0.0 } else { req.learning_rate }, + epochs: if census { 1 } else { req.epochs }, + max_seq_len: req.max_seq_len, + dtype: req.dtype, + gguf: GgufMeta { + name: model_name, + base_model_repo: Some(project.base_model_id.clone()), + base_model_name: base_name, + ..GgufMeta::default() + }, + export: !census, + keep_merged: false, + }) +} + +impl Jobs { + /// Ask the running job to stop. Training stops after the current step; a + /// merge or export that has begun finishes first. Returns whether there was + /// a job to ask. + pub fn cancel(&self) -> bool { + match lock(&self.active).as_ref() { + Some(active) => { + active.cancel.store(true, Ordering::Relaxed); + true + } + None => false, + } + } + + /// Send the running job's events to `sink` from now on. `None` when nothing + /// is running, and the sink is dropped. + pub fn attach(&self, sink: Sink) -> Option { + let active = lock(&self.active); + let active = active.as_ref()?; + *lock(&active.sink) = Some(sink); + Some(active.info.clone()) + } + + /// Start a job. Fails, and starts nothing, when one is already running or the + /// project is not ready. + pub fn start(&self, req: &JobRequest, sink: Sink) -> Result { + check_repo_id(&req.repo_id)?; + let project = project::load_project(&req.repo_id).map_err(|e| format!("{e:#}"))?; + let base_dir = models::base_model_dir(&project.base_model_id).ok_or_else(|| { + format!( + "The base model {} is not downloaded. Download it from the project page first.", + project.base_model_id + ) + })?; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let spec = build_spec(req, &project, base_dir, now)?; + self.start_spec(req.kind, spec, project, sink) + } + + fn start_spec( + &self, + kind: JobKind, + spec: RunSpec, + project: OndeProject, + sink: Sink, + ) -> Result { + let mut guard = lock(&self.active); + if let Some(running) = guard.as_ref() { + return Err(format!( + "{} in {} is still running. Wait for it or cancel it first.", + running.info.run, running.info.repo_id + )); + } + let info = JobInfo { + repo_id: project.repo_id.clone(), + run: spec.name.clone(), + kind, + }; + let cancel = Arc::new(AtomicBool::new(false)); + let sink = Arc::new(Mutex::new(Some(sink))); + // Registered before the run starts, so a second request can never slip in. + *guard = Some(Active { + info: info.clone(), + cancel: cancel.clone(), + sink: sink.clone(), + }); + drop(guard); + + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + pipeline::start_run(spec, &project, Some(cancel), tx); + let reason = format!("Onde Desktop: {} in {}", info.run, info.repo_id); + let slot = self.active.clone(); + std::thread::spawn(move || { + // Held on this thread for the whole run, so it ends with it. + let _awake = KeepAwake::begin(&reason); + forward(rx, &sink, &slot); + }); + Ok(info) + } +} + +/// Pass a run's events to whoever is listening until it ends, then free the slot. +fn forward( + mut rx: tokio::sync::mpsc::UnboundedReceiver, + sink: &Arc>>, + slot: &Slot, +) { + let send = |event: RunProgress| { + if let Some(sink) = lock(sink).as_ref() { + sink(event); + } + }; + loop { + match rx.blocking_recv() { + Some(event) => { + let done = is_final(&event); + if done { + // Freed before the last event goes out, so a webview that + // answers it by starting another job is not refused. + *lock(slot) = None; + } + send(event); + if done { + return; + } + } + // The run's thread ended without saying how. + None => { + *lock(slot) = None; + send(RunProgress::Failed { + message: "The run stopped unexpectedly.".into(), + }); + return; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn project(root: &std::path::Path) -> OndeProject { + OndeProject { + repo_id: "acme/tiny".into(), + base_model_id: "Qwen/Qwen3-0.6B".into(), + base_model_dir: String::new(), + project_dir: root.to_path_buf(), + dataset_path: root.join("dataset/train.jsonl"), + runs_dir: root.join("runs"), + } + } + + fn with_dataset(root: &std::path::Path) -> OndeProject { + let p = project(root); + std::fs::create_dir_all(p.dataset_path.parent().unwrap()).unwrap(); + std::fs::write( + &p.dataset_path, + "{\"messages\":[{\"role\":\"user\",\"content\":\"hi\"},{\"role\":\"assistant\",\"content\":\"hello\"}]}\n", + ) + .unwrap(); + p + } + + fn request(kind: JobKind) -> JobRequest { + JobRequest { + repo_id: "acme/tiny".into(), + kind, + name: String::new(), + learning_rate: 1e-4, + epochs: 2, + lora_rank: 8, + lora_alpha: 16.0, + max_seq_len: 512, + dtype: GgufDtype::Q4KM, + } + } + + #[test] + fn a_census_trains_nothing_for_one_epoch_and_exports_nothing() { + let tmp = tempfile::tempdir().unwrap(); + let p = with_dataset(tmp.path()); + let mut req = request(JobKind::Census); + req.learning_rate = 5.0; // ignored: a census is always lr 0 + req.epochs = 9; + let spec = build_spec(&req, &p, PathBuf::from("/base"), 1234).unwrap(); + assert_eq!(spec.name, "census-1234"); + assert_eq!( + (spec.learning_rate, spec.epochs, spec.export), + (0.0, 1, false) + ); + } + + #[test] + fn a_run_keeps_its_settings_and_gets_a_default_name() { + let tmp = tempfile::tempdir().unwrap(); + let p = with_dataset(tmp.path()); + let spec = build_spec(&request(JobKind::Run), &p, PathBuf::from("/base"), 1).unwrap(); + assert_eq!(spec.name, "e2-lr1e-4"); + assert_eq!( + (spec.learning_rate, spec.epochs, spec.export), + (1e-4, 2, true) + ); + assert_eq!(spec.gguf.name, "tiny"); + assert_eq!( + spec.gguf.base_model_repo.as_deref(), + Some("Qwen/Qwen3-0.6B") + ); + assert_eq!(spec.gguf.base_model_name.as_deref(), Some("Qwen3 0.6B")); + } + + #[test] + fn settings_outside_their_range_are_refused_with_a_reason() { + let tmp = tempfile::tempdir().unwrap(); + let p = with_dataset(tmp.path()); + let refuse = |edit: &dyn Fn(&mut JobRequest)| { + let mut req = request(JobKind::Run); + edit(&mut req); + build_spec(&req, &p, PathBuf::from("/b"), 1).unwrap_err() + }; + assert!(refuse(&|r| r.learning_rate = 0.0).contains("learning rate")); + assert!(refuse(&|r| r.learning_rate = f64::NAN).contains("learning rate")); + assert!(refuse(&|r| r.epochs = 0).contains("Epochs")); + assert!(refuse(&|r| r.lora_rank = 0).contains("rank")); + assert!(refuse(&|r| r.lora_alpha = -1.0).contains("alpha")); + assert!(refuse(&|r| r.max_seq_len = 4).contains("sequence")); + assert!(refuse(&|r| r.name = "../x".into()).contains("run name")); + } + + #[test] + fn a_missing_or_broken_dataset_stops_the_job_before_it_starts() { + let tmp = tempfile::tempdir().unwrap(); + let p = project(tmp.path()); + let err = build_spec(&request(JobKind::Run), &p, PathBuf::from("/b"), 1).unwrap_err(); + assert!(err.contains("dataset"), "{err}"); + } + + #[test] + fn only_one_job_runs_at_a_time_and_a_failed_start_frees_the_slot() { + let tmp = tempfile::tempdir().unwrap(); + let p = with_dataset(tmp.path()); + let jobs = Jobs::default(); + + // The base folder does not exist, so the run fails fast and says why. + let events = Arc::new(Mutex::new(Vec::::new())); + let seen = events.clone(); + let spec = build_spec(&request(JobKind::Run), &p, tmp.path().join("no-base"), 1).unwrap(); + let info = jobs + .start_spec( + JobKind::Run, + spec, + p.clone(), + Box::new(move |e| lock(&seen).push(e)), + ) + .unwrap(); + assert_eq!(info.run, "e2-lr1e-4"); + + // Wait for the terminal event, then the slot must be free again. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while lock(&events).iter().all(|e| !is_final(e)) { + assert!(std::time::Instant::now() < deadline, "the run never ended"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + assert!( + matches!(lock(&events).last(), Some(RunProgress::Failed { .. })), + "{:?}", + lock(&events) + ); + assert!(lock(&jobs.active).is_none(), "the slot is free"); + assert!(!jobs.cancel(), "nothing is left to cancel"); + + // A second job may start now. + let spec = + build_spec(&request(JobKind::Census), &p, tmp.path().join("no-base"), 7).unwrap(); + assert!( + jobs.start_spec(JobKind::Census, spec, p, Box::new(|_| {})) + .is_ok() + ); + } + + #[test] + fn a_second_start_while_one_runs_is_refused() { + let tmp = tempfile::tempdir().unwrap(); + let p = with_dataset(tmp.path()); + let jobs = Jobs::default(); + *lock(&jobs.active) = Some(Active { + info: JobInfo { + repo_id: "acme/other".into(), + run: "e3-lr1e-4".into(), + kind: JobKind::Run, + }, + cancel: Arc::new(AtomicBool::new(false)), + sink: Arc::new(Mutex::new(None)), + }); + let spec = build_spec(&request(JobKind::Run), &p, PathBuf::from("/b"), 1).unwrap(); + let err = jobs + .start_spec(JobKind::Run, spec, p, Box::new(|_| {})) + .unwrap_err(); + assert!( + err.contains("e3-lr1e-4 in acme/other is still running"), + "{err}" + ); + assert!(jobs.cancel(), "cancel reaches the running job"); + assert!( + lock(&jobs.active) + .as_ref() + .unwrap() + .cancel + .load(Ordering::Relaxed) + ); + } + + #[test] + fn a_reattached_webview_gets_the_events_that_follow() { + let jobs = Jobs::default(); + assert!(jobs.attach(Box::new(|_| {})).is_none()); + let sink = Arc::new(Mutex::new(None::)); + *lock(&jobs.active) = Some(Active { + info: JobInfo { + repo_id: "acme/tiny".into(), + run: "r".into(), + kind: JobKind::Run, + }, + cancel: Arc::new(AtomicBool::new(false)), + sink: sink.clone(), + }); + let got = Arc::new(Mutex::new(0)); + let counter = got.clone(); + let info = jobs + .attach(Box::new(move |_| *lock(&counter) += 1)) + .unwrap(); + assert_eq!(info.run, "r"); + lock(&sink).as_ref().unwrap()(RunProgress::Cancelled); + assert_eq!(*lock(&got), 1); + } +} diff --git a/packaging/app/src-tauri/src/desktop/mod.rs b/packaging/app/src-tauri/src/desktop/mod.rs index 479725a..221dbbe 100644 --- a/packaging/app/src-tauri/src/desktop/mod.rs +++ b/packaging/app/src-tauri/src/desktop/mod.rs @@ -3,7 +3,9 @@ pub mod app; pub mod auth; pub mod base_models; pub mod bookmark; +pub mod jobs; pub mod links; pub mod oauth; +pub mod power; pub mod projects; pub mod storage; diff --git a/packaging/app/src-tauri/src/desktop/power.rs b/packaging/app/src-tauri/src/desktop/power.rs new file mode 100644 index 0000000..a9d5c5f --- /dev/null +++ b/packaging/app/src-tauri/src/desktop/power.rs @@ -0,0 +1,86 @@ +//! Keep the Mac awake while a training job runs. +//! +//! A run takes minutes to hours. Left alone, macOS can put an idle Mac to sleep +//! partway through, or slow a background app down (App Nap). An activity +//! assertion tells the system the work is user initiated and must not be +//! interrupted by idle sleep. It does not stop the display from sleeping and it +//! does not stop the user closing the lid. +//! +//! Elsewhere there is nothing to hold, and the guard does nothing. + +#[cfg(target_os = "macos")] +mod imp { + use objc2::{rc::Retained, runtime::ProtocolObject}; + use objc2_foundation::{NSActivityOptions, NSObjectProtocol, NSProcessInfo, NSString}; + + /// Ends the assertion when dropped. Not `Send`: take it and drop it on the + /// same thread. + pub struct KeepAwake { + activity: Retained>, + } + + impl KeepAwake { + pub fn begin(reason: &str) -> Self { + let info = NSProcessInfo::processInfo(); + let activity = info.beginActivityWithOptions_reason( + NSActivityOptions::UserInitiated, + &NSString::from_str(reason), + ); + Self { activity } + } + } + + impl Drop for KeepAwake { + fn drop(&mut self) { + // SAFETY: `activity` came from `beginActivityWithOptions:reason:` on + // this same process info and has not been ended before. + unsafe { NSProcessInfo::processInfo().endActivity(&self.activity) }; + } + } +} + +#[cfg(not(target_os = "macos"))] +mod imp { + pub struct KeepAwake; + + impl KeepAwake { + pub fn begin(_reason: &str) -> Self { + Self + } + } +} + +pub use imp::KeepAwake; + +#[cfg(test)] +mod tests { + use super::KeepAwake; + + /// The assertion is real on macOS: `pmset -g assertions` lists it while the + /// guard is alive and drops it afterwards. + #[cfg(target_os = "macos")] + #[test] + fn the_assertion_is_listed_while_held_and_gone_after() { + let reason = format!("onde-desktop-test-{}", std::process::id()); + let listed = |reason: &str| { + let out = std::process::Command::new("pmset") + .args(["-g", "assertions"]) + .output() + .expect("pmset runs"); + String::from_utf8_lossy(&out.stdout).contains(reason) + }; + let guard = KeepAwake::begin(&reason); + assert!( + listed(&reason), + "the assertion should be visible while held" + ); + drop(guard); + assert!(!listed(&reason), "the assertion should end on drop"); + } + + #[cfg(not(target_os = "macos"))] + #[test] + fn it_does_nothing_off_macos() { + drop(KeepAwake::begin("x")); + } +} diff --git a/packaging/app/src-tauri/src/desktop/projects.rs b/packaging/app/src-tauri/src/desktop/projects.rs index 881877b..59b4a57 100644 --- a/packaging/app/src-tauri/src/desktop/projects.rs +++ b/packaging/app/src-tauri/src/desktop/projects.rs @@ -29,6 +29,8 @@ pub struct ProjectSummary { pub base_model_id: String, pub created_at: u64, pub dataset: DatasetKind, + /// The complete base model is on disk, so a job can start. + pub base_ready: bool, /// Rows of a valid dataset. pub dataset_rows: Option, pub runs: usize, @@ -103,11 +105,13 @@ fn summary(repo_id: String, meta: ProjectMeta) -> ProjectSummary { Ok(p) => (dataset_kind(&p.dataset_path), project::list_runs(&p)), Err(_) => ((DatasetKind::Missing, None), Vec::new()), }; + let base_ready = onde_cli::models::base_model_dir(&meta.base_model_id).is_some(); ProjectSummary { repo_id, base_model_id: meta.base_model_id, created_at: meta.created_at, dataset, + base_ready, dataset_rows, latest_run: runs.first().map(|r| r.name.clone()), runs: runs.len(), diff --git a/packaging/app/src-tauri/src/lib.rs b/packaging/app/src-tauri/src/lib.rs index b20104a..365972d 100644 --- a/packaging/app/src-tauri/src/lib.rs +++ b/packaging/app/src-tauri/src/lib.rs @@ -30,6 +30,7 @@ pub fn run() { .manage(state::PendingSignIn::default()) .manage(links) .manage(state_downloads::Downloads::default()) + .manage(desktop::jobs::Jobs::default()) .invoke_handler(tauri::generate_handler![ commands::app::app_build, commands::links::projects_location, @@ -40,6 +41,9 @@ pub fn run() { commands::base_models::download_base_model, commands::base_models::cancel_base_download, commands::base_models::base_download_running, + commands::jobs::start_job, + commands::jobs::attach_job, + commands::jobs::cancel_job, commands::projects::list_projects, commands::projects::project_detail, commands::projects::run_steps, diff --git a/packaging/app/src/App.tsx b/packaging/app/src/App.tsx index 73ce75f..3f0dd2e 100644 --- a/packaging/app/src/App.tsx +++ b/packaging/app/src/App.tsx @@ -3,6 +3,9 @@ import { AppTopBar } from "@/components/AppTopBar"; import { AppSidebar } from "@/components/AppSidebar"; import { AccountButton, SignInForm } from "@/components/AccountMenu"; import { NAV_ITEMS, type TabId } from "@/components/nav-items"; +import { FinetuneView } from "@/features/finetune/FinetuneView"; +import { isRunning } from "@/features/finetune/job"; +import { useJob } from "@/features/finetune/useJob"; import { ProjectsView } from "@/features/projects/ProjectsView"; import { isDesktop } from "@/lib/os"; import { ipc } from "@/lib/ipc"; @@ -15,6 +18,7 @@ export default function App() { const [tab, setTab] = useState(NAV_ITEMS[0].id); const [profile, setProfile] = useState(null); const [showSignIn, setShowSignIn] = useState(false); + const job = useJob(); useEffect(() => { localStorage.setItem(SIDEBAR_KEY, String(sidebarOpen)); @@ -37,7 +41,7 @@ export default function App() { /> } /> - { setTab(t); setShowSignIn(false); }} /> + { setTab(t); setShowSignIn(false); }} /> {/*
is the only scroller; the document itself never scrolls (index.css). tabIndex makes it focusable so a keyboard user can Tab to it and a click lands focus here, keeping space/arrow-key scrolling that overflow:hidden @@ -54,7 +58,7 @@ export default function App() { {showSignIn && !profile ? ( { setProfile(p); setShowSignIn(false); }} /> ) : ( - tab === "projects" && + tab === "projects" ? : )}
diff --git a/packaging/app/src/components/AppSidebar.tsx b/packaging/app/src/components/AppSidebar.tsx index 7426ffd..551549a 100644 --- a/packaging/app/src/components/AppSidebar.tsx +++ b/packaging/app/src/components/AppSidebar.tsx @@ -20,10 +20,13 @@ function useVersionLabel() { export function AppSidebar({ open, active, + busyTab, onSelect, }: { open: boolean; active: TabId; + /** A tab whose work is running in the background gets a dot. */ + busyTab?: TabId; onSelect: (tab: TabId) => void; }) { const versionLabel = useVersionLabel(); @@ -51,6 +54,13 @@ export function AppSidebar({ className="w-full rounded-md px-3 py-1.5 text-left text-sm hover:bg-fog-line aria-[current=page]:bg-fog-line aria-[current=page]:font-medium" > {item.label} + {busyTab === item.id && ( + + )} ))} diff --git a/packaging/app/src/components/nav-items.ts b/packaging/app/src/components/nav-items.ts index b61b90a..2f2f255 100644 --- a/packaging/app/src/components/nav-items.ts +++ b/packaging/app/src/components/nav-items.ts @@ -2,6 +2,7 @@ // back in the change that builds each one. export const NAV_ITEMS = [ { id: "projects", label: "Projects" }, + { id: "finetune", label: "Fine-tune" }, ] as const; export type TabId = (typeof NAV_ITEMS)[number]["id"]; diff --git a/packaging/app/src/features/finetune/FinetuneView.tsx b/packaging/app/src/features/finetune/FinetuneView.tsx new file mode 100644 index 0000000..b5fd579 --- /dev/null +++ b/packaging/app/src/features/finetune/FinetuneView.tsx @@ -0,0 +1,19 @@ +import { isRunning } from "./job"; +import { JobPanel } from "./JobPanel"; +import { RunForm } from "./RunForm"; +import type { Job } from "./useJob"; + +export function FinetuneView({ job }: { job: Job }) { + const running = isRunning(job.state); + return ( +
+
+

Fine-tune

+

Check the gradients, then train a LoRA adapter and export a GGUF.

+
+ + {/* Hidden while a job's result is on screen, so the result is what you see. */} + {(!job.state.info || running) && } +
+ ); +} diff --git a/packaging/app/src/features/finetune/JobPanel.tsx b/packaging/app/src/features/finetune/JobPanel.tsx new file mode 100644 index 0000000..fddbe8f --- /dev/null +++ b/packaging/app/src/features/finetune/JobPanel.tsx @@ -0,0 +1,185 @@ +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 type { Job } from "./useJob"; + +const BACKEND_NAME = { mlx: "MLX", cpu: "CPU", metal: "Metal" } as const; +const STAGES = [ + { id: "training", label: "Train" }, + { id: "merging", label: "Merge" }, + { id: "exporting", label: "Export" }, +] as const; + +function Bar({ value, label }: { value: number | undefined; label: string }) { + return ( +
+ +
+ ); +} + +export function JobPanel({ job }: { job: Job }) { + const { state, steps } = job; + const { info, position, outcome } = state; + if (!info) return null; + + const running = isRunning(state); + const census = info.kind === "census"; + const total = position ? position.totalEpochs * position.totalSteps : 0; + const elapsed = job.trainingStartedAt ? Date.now() - job.trainingStartedAt : 0; + const left = position ? secondsLeft(position, elapsed) : null; + const skipped = steps.filter((s) => s.skipped != null).length; + const last = steps[steps.length - 1]; + const verdict = census ? censusVerdict(steps) : null; + const leftOut = rowsLeftOut(job.datasetRows, position); + + return ( +
+
+
+

{info.run}

+

+ {census ? "Gradient census" : "Training run"} · {info.repo_id} +

+
+
+ {state.backend && ( + + {BACKEND_NAME[state.backend.name]} + + )} + {running && ( + + )} +
+
+ + {state.backend?.fallback && ( +

Using the CPU, which is much slower. {state.backend.fallback}

+ )} + + {!census && ( +
    + {STAGES.map((s) => ( +
  1. + {s.label} +
  2. + ))} +
+ )} + + {running && state.stopping && ( +

+ {state.stage === "training" || state.stage === null + ? "Stopping after the current step." + : "A merge or export that has started finishes first."} +

+ )} + + {running && state.stage !== "merging" && state.stage !== "exporting" && ( + <> + {position ? ( + <> + +

+ Epoch {position.epoch} of {position.totalEpochs} · step {position.step} of {position.totalSteps} + {left !== null && ` · about ${formatDuration(left)} left`} + {last && ` · loss ${last.loss.toFixed(3)}`} +

+ + ) : ( + <> + +

{state.phase ?? "Starting"}…

+ + )} + + )} + {running && state.stage === "merging" && ( + <> + +

Merging the adapter into the base model…

+ + )} + {running && state.stage === "exporting" && ( + <> + +

Writing the GGUF…

+ + )} + + {leftOut !== null && ( +

+ {leftOut} of {job.datasetRows} rows {leftOut === 1 ? "was" : "were"} left out. A row longer than the max sequence length loses its reply + to the cut, so it teaches nothing. Raise the max sequence under LoRA settings to use them. +

+ )} + {skipped > 0 && ( +

+ {skipped} {skipped === 1 ? "step was" : "steps were"} skipped. +

+ )} + {state.epochLoss.length > 0 && ( +

+ Epoch loss: {state.epochLoss.map((l) => l.toFixed(3)).join(" → ")} +

+ )} + {steps.length > 1 && } + + {verdict && ( +
+

+ {verdict.headline} +

+

{verdict.detail}

+
+ )} + + {outcome?.kind === "done" && ( +

+ {census + ? "Census finished. It trained nothing and made no model." + : `Finished${outcome.record.gguf_size ? `: ${outcome.record.gguf_path?.split("/").pop()} (${formatBytes(outcome.record.gguf_size)})` : ""}. Find it under Projects.`} +

+ )} + {outcome?.kind === "failed" && ( +

+ {outcome.message} +

+ )} + {outcome?.kind === "cancelled" &&

Stopped. No adapter was written.

} + {outcome && ( + + )} +
+ ); +} diff --git a/packaging/app/src/features/finetune/RunForm.tsx b/packaging/app/src/features/finetune/RunForm.tsx new file mode 100644 index 0000000..4dce387 --- /dev/null +++ b/packaging/app/src/features/finetune/RunForm.tsx @@ -0,0 +1,194 @@ +import { useEffect, useState } from "react"; +import { ipc } from "@/lib/ipc"; +import { errorMessage, type JobKind, type JobRequest, type ProjectSummary } from "@/lib/types"; + +const DTYPES = [ + { id: "q4_k_m", label: "Q4_K_M (smallest, the usual choice)" }, + { id: "q8_0", label: "Q8_0 (larger, closer to the original)" }, + { id: "f16", label: "F16 (largest)" }, +] as const; + +/** Why a project cannot start a job, or null when it can. */ +function blocked(p: ProjectSummary): string | null { + if (!p.base_ready) return "its base model is not downloaded (do that on the project page)"; + if (p.dataset === "missing") return "it has no dataset yet"; + if (p.dataset === "invalid") return "its dataset has errors"; + return null; +} + +/** "1e-4" and "0.0001" both work. Anything else is NaN. */ +const num = (text: string) => (text.trim() === "" ? NaN : Number(text)); + +export function RunForm({ + disabled, + onStart, +}: { + /** A job is running, so a second cannot start. */ + disabled: boolean; + onStart: (request: JobRequest, datasetRows: number | null) => Promise; +}) { + const [projects, setProjects] = useState([]); + const [repoId, setRepoId] = useState(""); + const [kind, setKind] = useState("census"); + const [name, setName] = useState(""); + const [lr, setLr] = useState("1e-4"); + const [epochs, setEpochs] = useState("2"); + const [rank, setRank] = useState("8"); + const [alpha, setAlpha] = useState("16"); + const [maxSeq, setMaxSeq] = useState("512"); + const [dtype, setDtype] = useState("q4_k_m"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + ipc + .listProjects() + .then((list) => { + setProjects(list); + const ready = list.find((p) => blocked(p) === null); + setRepoId((current) => current || ready?.repo_id || ""); + }) + .catch((e) => setError(errorMessage(e))); + }, []); + + const project = projects.find((p) => p.repo_id === repoId); + const why = project ? blocked(project) : "there are no projects yet"; + const census = kind === "census"; + + async function submit(e: React.FormEvent) { + e.preventDefault(); + setError(null); + setBusy(true); + try { + await onStart( + { + repo_id: repoId, + kind, + name: census ? "" : name.trim(), + learning_rate: num(lr), + epochs: num(epochs), + lora_rank: num(rank), + lora_alpha: num(alpha), + max_seq_len: num(maxSeq), + dtype, + }, + project?.dataset_rows ?? null, + ); + } catch (err) { + setError(errorMessage(err)); + } finally { + setBusy(false); + } + } + + 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)); + + return ( +
+ + {why && repoId &&

Can't start: {why}.

} + +
+ What to run + + +
+ + {!census && ( +
+ + + + +
+ )} +
+ LoRA settings +
+ + + +
+
+ + {error && ( +

+ {error} +

+ )} +
+ {disabled && A job is running.} + +
+
+ ); +} diff --git a/packaging/app/src/features/finetune/census.test.ts b/packaging/app/src/features/finetune/census.test.ts new file mode 100644 index 0000000..0f122b7 --- /dev/null +++ b/packaging/app/src/features/finetune/census.test.ts @@ -0,0 +1,49 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { censusVerdict } from "./census.ts"; +import type { StepRecord } from "../../lib/types.ts"; + +const step = (grad_norm: number | null, skipped: StepRecord["skipped"] = null): StepRecord => ({ + epoch: 1, + step: 1, + loss: 2, + grad_norm, + skipped, + t_ms: 0, +}); + +test("nothing to judge before the first step", () => { + assert.equal(censusVerdict([]), null); +}); + +test("norms of tens to hundreds with nothing skipped are healthy", () => { + const v = censusVerdict([step(4.9), step(61), step(149)])!; + assert.equal(v.level, "ok"); + assert.match(v.detail, /4\.9 to 149\.0/); +}); + +test("a norm at 1e6 or more means the backward pass is broken", () => { + const v = censusVerdict([step(50), step(2.5e29)])!; + assert.equal(v.level, "broken"); + assert.match(v.detail, /2\.5e\+29/); +}); + +test("skipped steps are a warning and say how many", () => { + const v = censusVerdict([step(40), step(null, "no_masked_tokens"), step(55)])!; + assert.equal(v.level, "warn"); + assert.match(v.headline, /1 of 3 steps were skipped/); +}); + +test("high but finite norms warn", () => { + assert.equal(censusVerdict([step(900), step(700)])!.level, "warn"); +}); + +test("a run where every step was skipped has no usable gradients", () => { + const v = censusVerdict([step(null, "non_finite_loss"), step(null, "bad_grad_norm")])!; + assert.equal(v.level, "broken"); + assert.match(v.headline, /No usable gradients/); +}); + +test("broken wins over skipped", () => { + assert.equal(censusVerdict([step(1e7), step(null, "bad_grad_norm")])!.level, "broken"); +}); diff --git a/packaging/app/src/features/finetune/census.ts b/packaging/app/src/features/finetune/census.ts new file mode 100644 index 0000000..44fe466 --- /dev/null +++ b/packaging/app/src/features/finetune/census.ts @@ -0,0 +1,58 @@ +import type { StepRecord } from "../../lib/types.ts"; + +export interface Verdict { + level: "ok" | "warn" | "broken"; + headline: string; + detail: string; +} + +/** Gradient norms at or above this mean the backward pass is producing garbage. + * Candle's Metal backward gave 1e6 to 1e29 where the CPU gave 40 to 65. */ +export const BROKEN_NORM = 1e6; +/** Healthy norms are around 10 to 100. Well past that is worth a look. */ +export const HIGH_NORM = 500; + +/** Judge a gradient census: one epoch at a learning rate of 0. `null` until + * there is a step to judge. */ +export function censusVerdict(steps: StepRecord[]): Verdict | null { + if (steps.length === 0) return null; + const norms = steps.map((s) => s.grad_norm).filter((n): n is number => n != null && Number.isFinite(n)); + const skipped = steps.filter((s) => s.skipped != null).length; + const max = norms.length ? Math.max(...norms) : 0; + const min = norms.length ? Math.min(...norms) : 0; + const range = `${min.toFixed(1)} to ${max.toFixed(1)}`; + + if (norms.length === 0) { + return { + level: "broken", + headline: "No usable gradients", + detail: `All ${steps.length} steps were skipped. The backward pass is not producing numbers the optimizer can use.`, + }; + } + if (max >= BROKEN_NORM) { + return { + level: "broken", + headline: "Broken backward pass", + detail: `Gradient norms reached ${max.toExponential(1)}, where a healthy run is around 10 to 100. Do not train on this setup.`, + }; + } + if (skipped > 0) { + return { + level: "warn", + headline: `${skipped} of ${steps.length} steps were skipped`, + detail: `Norms on the rest were ${range}. Skipped steps are rows with no loss to learn from, or non-finite values. Check the dataset.`, + }; + } + if (max > HIGH_NORM) { + return { + level: "warn", + headline: "Gradient norms are high", + detail: `They ran ${range}, above the usual 10 to 100. Training clips them, but watch the first epoch's loss.`, + }; + } + return { + level: "ok", + headline: "Gradients look healthy", + detail: `Norms ran ${range} over ${steps.length} steps, and none were skipped.`, + }; +} diff --git a/packaging/app/src/features/finetune/job.test.ts b/packaging/app/src/features/finetune/job.test.ts new file mode 100644 index 0000000..1794e56 --- /dev/null +++ b/packaging/app/src/features/finetune/job.test.ts @@ -0,0 +1,74 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { apply, begin, formatDuration, idle, isRunning, rowsLeftOut, secondsLeft, stepsDone } from "./job.ts"; +import type { JobInfo, RunEvent, RunRecord } from "../../lib/types.ts"; + +const info: JobInfo = { repo_id: "acme/tiny", run: "e2-lr1e-4", kind: "run" }; +const training = (epoch: number, step: number): RunEvent => ({ + event: "training", + epoch, + total_epochs: 2, + step, + total_steps: 4, + loss: 1, +}); + +test("a started job is running until it has an outcome", () => { + assert.equal(isRunning(idle), false); + const s = begin(info); + assert.equal(isRunning(s), true); + assert.equal(s.phase, "Starting"); +}); + +test("events fill in the stage, backend, position and epoch losses", () => { + let s = begin(info); + s = apply(s, { event: "backend", backend: "cpu", fallback: "MLX is unavailable: no metallib" }); + s = apply(s, { event: "stage", stage: "training" }); + s = apply(s, training(2, 3)); + s = apply(s, { event: "epoch_done", epoch: 1, mean_loss: 0.9 }); + s = apply(s, { event: "epoch_done", epoch: 2, mean_loss: 0.4 }); + assert.deepEqual(s.backend, { name: "cpu", fallback: "MLX is unavailable: no metallib" }); + assert.equal(s.stage, "training"); + assert.equal(s.phase, null); + assert.deepEqual(s.epochLoss, [0.9, 0.4]); + assert.equal(stepsDone(s.position!), 7); +}); + +test("a step event changes nothing: steps are collected outside the state", () => { + const s = begin(info); + const e: RunEvent = { event: "step", epoch: 1, step: 1, loss: 1, grad_norm: 2, skipped: null, t_ms: 3 }; + assert.equal(apply(s, e), s); +}); + +test("each way a run can end is recorded and clears the stopping flag", () => { + const stopping = { ...begin(info), stopping: true }; + const done = apply(stopping, { event: "done", name: "r", status: "done" } as RunEvent & RunRecord); + assert.equal(done.outcome?.kind, "done"); + assert.equal(done.stopping, false); + assert.equal(isRunning(done), false); + assert.deepEqual(apply(stopping, { event: "failed", message: "boom" }).outcome, { kind: "failed", message: "boom" }); + assert.deepEqual(apply(stopping, { event: "cancelled" }).outcome, { kind: "cancelled" }); +}); + +test("time left needs a few steps, then follows the rate", () => { + const at = (epoch: number, step: number) => ({ epoch, totalEpochs: 2, step, totalSteps: 4 }); + assert.equal(secondsLeft(at(1, 2), 2000), null, "too early to guess"); + // 4 of 8 steps in 40s: 40 more seconds. + assert.equal(secondsLeft(at(1, 4), 40_000), 40); + assert.equal(secondsLeft(at(2, 4), 80_000), 0); + assert.equal(secondsLeft(at(1, 4), 0), null); +}); + +test("durations read as seconds, minutes or hours", () => { + assert.equal(formatDuration(45), "45s"); + assert.equal(formatDuration(125), "2m 5s"); + assert.equal(formatDuration(3725), "1h 2m"); +}); + +test("rows the trainer left out are counted, and only when it used fewer than the dataset has", () => { + const p = { epoch: 1, totalEpochs: 2, step: 1, totalSteps: 4 }; + assert.equal(rowsLeftOut(12, p), 8); + assert.equal(rowsLeftOut(4, p), null, "every row was used"); + assert.equal(rowsLeftOut(null, p), null, "dataset size unknown"); + assert.equal(rowsLeftOut(12, null), null, "no step yet"); +}); diff --git a/packaging/app/src/features/finetune/job.ts b/packaging/app/src/features/finetune/job.ts new file mode 100644 index 0000000..118e078 --- /dev/null +++ b/packaging/app/src/features/finetune/job.ts @@ -0,0 +1,115 @@ +// What the Fine-tune screen knows about the running job, as pure functions so +// they can be tested without a window. Only `import type` here: the node test +// runner strips types and does not resolve the "@/" alias. +import type { Backend, JobInfo, RunEvent, RunRecord, Stage } from "../../lib/types.ts"; + +export interface Position { + epoch: number; + totalEpochs: number; + step: number; + totalSteps: number; +} + +export type Outcome = + | { kind: "done"; record: RunRecord } + | { kind: "failed"; message: string } + | { kind: "cancelled" }; + +export interface JobState { + info: JobInfo | null; + stage: Stage | null; + backend: { name: Backend; fallback: string | null } | null; + /** Loading, tokenising and saving have no numbers worth charting. */ + phase: string | null; + position: Position | null; + epochLoss: number[]; + merge: { layer: number; total: number } | null; + exportProgress: { index: number; total: number } | null; + /** Set once the run ends, and kept until the next one starts. */ + outcome: Outcome | null; + /** The user asked to stop, and the run has not yet said it did. */ + stopping: boolean; +} + +export const idle: JobState = { + info: null, + stage: null, + backend: null, + phase: null, + position: null, + epochLoss: [], + merge: null, + exportProgress: null, + outcome: null, + stopping: false, +}; + +export function begin(info: JobInfo): JobState { + return { ...idle, info, phase: "Starting" }; +} + +export const isRunning = (s: JobState): boolean => s.info !== null && s.outcome === null; + +/** Fold one event into the state. Steps are not kept here: a long run has far + * too many to copy on every event, so the hook collects them separately. */ +export function apply(s: JobState, e: RunEvent): JobState { + switch (e.event) { + case "stage": + return { ...s, stage: e.stage, phase: null }; + case "backend": + return { ...s, backend: { name: e.backend, fallback: e.fallback } }; + case "phase": + return { ...s, phase: e.label }; + case "training": + return { + ...s, + phase: null, + position: { epoch: e.epoch, totalEpochs: e.total_epochs, step: e.step, totalSteps: e.total_steps }, + }; + case "epoch_done": + return { ...s, epochLoss: [...s.epochLoss, e.mean_loss] }; + case "merge": + return { ...s, merge: { layer: e.layer, total: e.total } }; + case "export": + return { ...s, exportProgress: { index: e.index, total: e.total } }; + case "done": + return { ...s, stopping: false, outcome: { kind: "done", record: e } }; + case "failed": + return { ...s, stopping: false, outcome: { kind: "failed", message: e.message } }; + case "cancelled": + return { ...s, stopping: false, outcome: { kind: "cancelled" } }; + case "step": + return s; + } +} + +/** Optimizer steps finished so far, across all epochs. */ +export function stepsDone(p: Position): number { + return (p.epoch - 1) * p.totalSteps + p.step; +} + +/** Seconds left in training, from the rate so far. `null` until there is a rate + * to go on. `elapsedMs` is the time since the first step. */ +export function secondsLeft(p: Position, elapsedMs: number): number | null { + const done = stepsDone(p); + if (done < 3 || elapsedMs <= 0) return null; + const total = p.totalEpochs * p.totalSteps; + return Math.max(0, Math.round(((total - done) * elapsedMs) / done / 1000)); +} + +/** Rows the trainer left out: those longer than the max sequence length lose + * their reply to the cut, and rows that are too short have nothing to learn + * from. The trainer only logs this, so the screen says it. `null` when nothing + * was left out or the counts are not known. */ +export function rowsLeftOut(datasetRows: number | null, p: Position | null): number | null { + if (datasetRows === null || p === null) return null; + const left = datasetRows - p.totalSteps; + return left > 0 ? left : null; +} + +export function formatDuration(seconds: number): string { + if (seconds < 60) return `${seconds}s`; + const m = Math.floor(seconds / 60); + if (m < 60) return `${m}m ${seconds % 60}s`; + return `${Math.floor(m / 60)}h ${m % 60}m`; +} diff --git a/packaging/app/src/features/finetune/useJob.ts b/packaging/app/src/features/finetune/useJob.ts new file mode 100644 index 0000000..db1fd6c --- /dev/null +++ b/packaging/app/src/features/finetune/useJob.ts @@ -0,0 +1,103 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { ipc } from "@/lib/ipc"; +import type { JobRequest, RunEvent, StepRecord } from "@/lib/types"; +import { apply, idle, type JobState } from "./job"; + +/** 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 + * webview reloaded. */ +export function useJob() { + const [state, setState] = useState(idle); + // A long run has too many steps to copy into state on every event, so they + // are collected here and the screen is told to redraw at most a few times a second. + const steps = useRef([]); + const trainingStartedAt = useRef(null); + // How many rows the dataset has, to notice when the trainer used fewer. + const datasetRows = useRef(null); + const [, redraw] = useState(0); + const timer = useRef(undefined); + + const scheduleRedraw = useCallback(() => { + if (timer.current !== undefined) return; + timer.current = window.setTimeout(() => { + timer.current = undefined; + redraw((n) => n + 1); + }, 200); + }, []); + + const onEvent = useCallback( + (e: RunEvent) => { + if (e.event === "step") { + steps.current.push(e); + scheduleRedraw(); + return; + } + if (e.event === "training" && trainingStartedAt.current === null) { + trainingStartedAt.current = Date.now(); + } + setState((s) => apply(s, e)); + }, + [scheduleRedraw], + ); + + useEffect(() => { + ipc + .attachJob(onEvent) + .then(async (info) => { + if (!info) return; + setState({ ...idle, info, phase: "Reconnected to the running job" }); + steps.current = await ipc.runSteps(info.repo_id, info.run).catch(() => []); + redraw((n) => n + 1); + }) + .catch(() => {}); + return () => { + if (timer.current !== undefined) window.clearTimeout(timer.current); + }; + }, [onEvent]); + + /** Start a job. Rejects, leaving the state idle, when the backend refuses. */ + const start = useCallback( + async (request: JobRequest, rows: number | null = null) => { + steps.current = []; + trainingStartedAt.current = null; + datasetRows.current = rows; + setState({ + ...idle, + info: { repo_id: request.repo_id, run: request.name || "…", kind: request.kind }, + phase: "Starting", + }); + try { + const info = await ipc.startJob(request, onEvent); + setState((s) => ({ ...s, info })); + } catch (e) { + setState(idle); + throw e; + } + }, + [onEvent], + ); + + const cancel = useCallback(() => { + setState((s) => ({ ...s, stopping: true })); + void ipc.cancelJob(); + }, []); + + const dismiss = useCallback(() => { + steps.current = []; + trainingStartedAt.current = null; + datasetRows.current = null; + setState(idle); + }, []); + + return { + state, + steps: steps.current, + trainingStartedAt: trainingStartedAt.current, + datasetRows: datasetRows.current, + start, + cancel, + dismiss, + }; +} + +export type Job = ReturnType; diff --git a/packaging/app/src/lib/ipc.ts b/packaging/app/src/lib/ipc.ts index 6288a69..2f56f06 100644 --- a/packaging/app/src/lib/ipc.ts +++ b/packaging/app/src/lib/ipc.ts @@ -3,6 +3,9 @@ import type { BaseModelView, DatasetInfo, DownloadMsg, + JobInfo, + JobRequest, + RunEvent, OAuthProvider, Profile, ProjectDetail, @@ -43,4 +46,17 @@ export const ipc = { }, cancelBaseDownload: (repoId: string) => invoke("cancel_base_download", { repoId }), baseDownloadRunning: (repoId: string) => invoke("base_download_running", { repoId }), + /** Starts a job. Events arrive on `onEvent` until `done`, `failed` or `cancelled`. */ + startJob: (request: JobRequest, onEvent: (e: RunEvent) => void) => { + const channel = new Channel(); + channel.onmessage = onEvent; + return invoke("start_job", { request, onEvent: channel }); + }, + /** The job in progress, or null. Its events go to `onEvent` from now on. */ + attachJob: (onEvent: (e: RunEvent) => void) => { + const channel = new Channel(); + channel.onmessage = onEvent; + return invoke("attach_job", { onEvent: channel }); + }, + cancelJob: () => invoke("cancel_job"), }; diff --git a/packaging/app/src/lib/types.ts b/packaging/app/src/lib/types.ts index 094fd67..3a597b0 100644 --- a/packaging/app/src/lib/types.ts +++ b/packaging/app/src/lib/types.ts @@ -45,6 +45,8 @@ export interface ProjectSummary { base_model_id: string; created_at: number; dataset: "missing" | "invalid" | "ready"; + /** The complete base model is on disk, so a job can start. */ + base_ready: boolean; dataset_rows: number | null; runs: number; latest_run: string | null; @@ -141,3 +143,42 @@ export interface ProjectDetail { runs: RunRecord[]; has_eval: boolean; } + +export type JobKind = "census" | "run"; +export type Stage = "training" | "merging" | "exporting"; +export type Backend = "mlx" | "cpu" | "metal"; + +/** Mirrors `desktop::jobs::JobRequest`. */ +export interface JobRequest { + repo_id: string; + kind: JobKind; + name: string; + learning_rate: number; + epochs: number; + lora_rank: number; + lora_alpha: number; + max_seq_len: number; + dtype: "f16" | "q8_0" | "q4_k_m"; +} + +/** Mirrors `desktop::jobs::JobInfo`. */ +export interface JobInfo { + repo_id: string; + run: string; + kind: JobKind; +} + +/** Mirrors `onde_cli::pipeline::RunProgress`, which is tagged with `event`. */ +export type RunEvent = + | { event: "stage"; stage: Stage } + | { event: "backend"; backend: Backend; fallback: string | null } + | { event: "phase"; label: string } + | { event: "training"; epoch: number; total_epochs: number; step: number; total_steps: number; loss: number } + | ({ event: "step" } & StepRecord) + | { event: "epoch_done"; epoch: number; mean_loss: number } + | { event: "merge"; layer: number; total: number } + | { event: "export"; index: number; total: number } + | ({ event: "done" } & RunRecord) + | { event: "failed"; message: string } + | { event: "cancelled" }; + diff --git a/packaging/app/tsconfig.json b/packaging/app/tsconfig.json index 782ef17..7134867 100644 --- a/packaging/app/tsconfig.json +++ b/packaging/app/tsconfig.json @@ -22,10 +22,14 @@ "@/*": [ "./src/*" ] - } + }, + "allowImportingTsExtensions": true }, "include": [ "src", "vite.config.ts" + ], + "exclude": [ + "src/**/*.test.ts" ] -} \ No newline at end of file +} diff --git a/packaging/macos/find-mlx-metallib.sh b/packaging/macos/find-mlx-metallib.sh index e84113e..caeebe1 100755 --- a/packaging/macos/find-mlx-metallib.sh +++ b/packaging/macos/find-mlx-metallib.sh @@ -6,20 +6,27 @@ # to copy it from there beside the binary it ships. Run it from the repo # root; it prints an absolute path. # -# packaging/macos/find-mlx-metallib.sh aarch64-apple-darwin +# packaging/macos/find-mlx-metallib.sh aarch64-apple-darwin [release|debug] +# +# The build profile defaults to release. A set CARGO_TARGET_DIR is honoured. set -euo pipefail -target="${1:?usage: find-mlx-metallib.sh }" +target="${1:?usage: find-mlx-metallib.sh [profile]}" +profile="${2:-release}" +root="${CARGO_TARGET_DIR:-target}" # Cargo's build-dir layout changed: older toolchains write # build/mlx-sys-/out/..., newer ones write build/mlx-sys//out/... # Look in both. The cargo cache can hold more than one mlx-sys build; take the # newest. # shellcheck disable=SC2012 -lib="$(ls -t target/"${target}"/release/build/mlx-sys-*/out/build/lib/mlx.metallib \ - target/"${target}"/release/build/mlx-sys/*/out/build/lib/mlx.metallib 2>/dev/null | head -n 1 || true)" +lib="$(ls -t "${root}"/"${target}"/"${profile}"/build/mlx-sys-*/out/build/lib/mlx.metallib \ + "${root}"/"${target}"/"${profile}"/build/mlx-sys/*/out/build/lib/mlx.metallib 2>/dev/null | head -n 1 || true)" if [[ -z "${lib}" || ! -f "${lib}" ]]; then - echo "mlx.metallib not found under target/${target}/release/build" >&2 + echo "mlx.metallib not found under ${root}/${target}/${profile}/build" >&2 exit 1 fi -echo "${PWD}/${lib}" +case "${lib}" in + /*) echo "${lib}" ;; + *) echo "${PWD}/${lib}" ;; +esac diff --git a/src/gguf.rs b/src/gguf.rs index d026762..31d88b2 100644 --- a/src/gguf.rs +++ b/src/gguf.rs @@ -1385,7 +1385,7 @@ mod tests { eprintln!("[e2e] epoch {epoch} step {step}/{total_steps} loss {loss:.4}"); } crate::pipeline::RunProgress::Done(r) => record = Some(*r), - crate::pipeline::RunProgress::Failed(e) => panic!("run failed: {e}"), + crate::pipeline::RunProgress::Failed { message } => panic!("run failed: {message}"), crate::pipeline::RunProgress::Cancelled => panic!("run cancelled"), _ => {} } diff --git a/src/pipeline.rs b/src/pipeline.rs index 46d34ae..ec79382 100644 --- a/src/pipeline.rs +++ b/src/pipeline.rs @@ -178,7 +178,9 @@ pub enum RunProgress { total: usize, }, Done(Box), - Failed(String), + Failed { + message: String, + }, Cancelled, } @@ -233,7 +235,9 @@ pub fn start_run( // A bad name or an existing run is refused before anything is written, // so a mistake can never overwrite an earlier run's record. if let Err(e) = prepare_dir(&spec, &run_dir) { - let _ = tx.send(RunProgress::Failed(format!("{e:#}"))); + let _ = tx.send(RunProgress::Failed { + message: format!("{e:#}"), + }); return; } let mut record = RunRecord::new(&spec); @@ -255,7 +259,7 @@ pub fn start_run( record.status = RunStatus::Failed; record.error = Some(message.clone()); let _ = write_record(&run_dir, &record); - let _ = tx.send(RunProgress::Failed(message)); + let _ = tx.send(RunProgress::Failed { message }); } } }); @@ -673,7 +677,7 @@ mod tests { let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); start_run(spec("broken"), &project, None, tx); let last = std::iter::from_fn(|| rx.blocking_recv()).last().unwrap(); - assert!(matches!(last, RunProgress::Failed(_)), "{last:?}"); + assert!(matches!(last, RunProgress::Failed { .. }), "{last:?}"); let record = read_record(&project.runs_dir.join("broken")).unwrap(); assert_eq!(record.status, RunStatus::Failed); assert!(record.error.is_some()); @@ -681,7 +685,9 @@ mod tests { let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); start_run(spec("broken"), &project, None, tx); match std::iter::from_fn(|| rx.blocking_recv()).last().unwrap() { - RunProgress::Failed(m) => assert!(m.contains("already exists"), "{m}"), + RunProgress::Failed { message } => { + assert!(message.contains("already exists"), "{message}") + } other => panic!("{other:?}"), } // The first run's record is untouched. @@ -724,4 +730,68 @@ mod tests { let again = prepare_dir(&s, &dir).unwrap_err(); assert!(format!("{again:#}").contains("already exists"), "{again:#}"); } + + /// Hosts send these as JSON. An internally tagged enum cannot serialize a + /// newtype variant that holds a plain string, so every variant is checked. + #[test] + fn every_progress_event_serializes_with_its_event_tag() { + let record = RunRecord::new(&spec("a")); + let step = StepRecord { + epoch: 1, + step: 2, + loss: 0.5, + grad_norm: Some(3.0), + skipped: None, + t_ms: 4, + }; + let events = vec![ + ( + RunProgress::Stage { + stage: Stage::Training, + }, + "stage", + ), + ( + RunProgress::Backend { + backend: FineTuneBackend::Mlx, + fallback: None, + }, + "backend", + ), + (RunProgress::Phase { label: "x".into() }, "phase"), + ( + RunProgress::Training { + epoch: 1, + total_epochs: 2, + step: 3, + total_steps: 4, + loss: 1.0, + }, + "training", + ), + (RunProgress::Step(step), "step"), + ( + RunProgress::EpochDone { + epoch: 1, + mean_loss: 0.1, + }, + "epoch_done", + ), + (RunProgress::Merge { layer: 1, total: 2 }, "merge"), + (RunProgress::Export { index: 1, total: 2 }, "export"), + (RunProgress::Done(Box::new(record)), "done"), + ( + RunProgress::Failed { + message: "boom".into(), + }, + "failed", + ), + (RunProgress::Cancelled, "cancelled"), + ]; + for (event, tag) in events { + let json = serde_json::to_value(&event) + .unwrap_or_else(|e| panic!("{tag} does not serialize: {e}")); + assert_eq!(json["event"], tag, "{json}"); + } + } } From 8c409fe484d9833797c376d8f89225ef4e9a9284 Mon Sep 17 00:00:00 2001 From: Seto Elkahfi <1797197+setoelkahfi@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:04:44 +0100 Subject: [PATCH 2/3] app: pick a running job back up after a reload, and keep the window responsive A webview that reloaded mid-run reattached to the job but had lost what the events it missed had carried. The backend now remembers the latest stage and backend of the running job and returns them when the screen attaches, so a merge is not shown as training and the CPU fallback is not forgotten. The training position is rebuilt from the steps the run has recorded (the first epoch's length is only known once it is over), which brings back the time left estimate and the rows-left-out warning, and the dataset row count is read from the project again. A finished run fills in the epoch losses the screen missed. start_job read and parsed the whole dataset on the main thread, which can freeze the window on a large one. It is async now. The header showed an ellipsis until the backend named the run. The webview works out the default name itself, and a test on each side pins the two to the same strings, including Rust's exponent format. Checked in the running app: with a run in its export stage, forcing a full page reload left the sidebar showing it was running, and the Fine-tune tab showed the run name, MLX, the Export stage, the warning, both charts and Cancel, then the final result with the GGUF. 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-tauri/src/commands/jobs.rs | 5 +- packaging/app/src-tauri/src/desktop/jobs.rs | 109 +++++++++++++++++- .../app/src/features/finetune/job.test.ts | 40 ++++++- packaging/app/src/features/finetune/job.ts | 48 +++++++- packaging/app/src/features/finetune/useJob.ts | 37 +++++- packaging/app/src/lib/types.ts | 3 + 6 files changed, 231 insertions(+), 11 deletions(-) diff --git a/packaging/app/src-tauri/src/commands/jobs.rs b/packaging/app/src-tauri/src/commands/jobs.rs index f71d52b..207d386 100644 --- a/packaging/app/src-tauri/src/commands/jobs.rs +++ b/packaging/app/src-tauri/src/commands/jobs.rs @@ -16,7 +16,10 @@ fn sink(channel: Channel) -> crate::desktop::jobs::Sink { /// Start a census or a training run. Events arrive on `on_event` until the run /// ends with `done`, `failed` or `cancelled`. -#[tauri::command] +/// +/// `async` runs it off the main thread. Checking the project reads and parses +/// the whole dataset, which must not freeze the window. +#[tauri::command(async)] pub fn start_job( request: JobRequest, on_event: Channel, diff --git a/packaging/app/src-tauri/src/desktop/jobs.rs b/packaging/app/src-tauri/src/desktop/jobs.rs index 8519c3c..8202656 100644 --- a/packaging/app/src-tauri/src/desktop/jobs.rs +++ b/packaging/app/src-tauri/src/desktop/jobs.rs @@ -17,10 +17,11 @@ use std::{ }; use onde_cli::{ + finetune::FineTuneBackend, gguf::GgufDtype, hf_clone::BASE_MODELS, models, - pipeline::{self, GgufMeta, RunProgress, RunSpec}, + pipeline::{self, GgufMeta, RunProgress, RunSpec, Stage}, project::{self, OndeProject}, }; use serde::{Deserialize, Serialize}; @@ -56,12 +57,23 @@ pub struct JobRequest { pub dtype: GgufDtype, } -/// The job in progress, for a webview that has just loaded. +/// Which backend a job is training on, and why not the default one. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct BackendInfo { + pub backend: FineTuneBackend, + pub fallback: Option, +} + +/// The job in progress, for a webview that has just loaded. `stage` and +/// `backend` are the latest the job reported. A webview that reloads mid-run +/// missed those events and could not tell a merge from training without them. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct JobInfo { pub repo_id: String, pub run: String, pub kind: JobKind, + pub stage: Option, + pub backend: Option, } struct Active { @@ -224,6 +236,8 @@ impl Jobs { repo_id: project.repo_id.clone(), run: spec.name.clone(), kind, + stage: None, + backend: None, }; let cancel = Arc::new(AtomicBool::new(false)); let sink = Arc::new(Mutex::new(Some(sink))); @@ -248,6 +262,23 @@ impl Jobs { } } +/// Remember the latest stage and backend on the job, for a webview that attaches +/// later. +fn remember(slot: &Slot, event: &RunProgress) { + let mut guard = lock(slot); + let Some(active) = guard.as_mut() else { return }; + match event { + RunProgress::Stage { stage } => active.info.stage = Some(*stage), + RunProgress::Backend { backend, fallback } => { + active.info.backend = Some(BackendInfo { + backend: *backend, + fallback: fallback.clone(), + }) + } + _ => {} + } +} + /// Pass a run's events to whoever is listening until it ends, then free the slot. fn forward( mut rx: tokio::sync::mpsc::UnboundedReceiver, @@ -262,6 +293,7 @@ fn forward( loop { match rx.blocking_recv() { Some(event) => { + remember(slot, &event); let done = is_final(&event); if done { // Freed before the last event goes out, so a webview that @@ -325,6 +357,17 @@ mod tests { } } + /// `defaultRunName` in `job.ts` must produce these same strings: the header + /// shows the name before the backend has replied. + #[test] + fn default_run_names_match_the_ones_the_webview_predicts() { + assert_eq!(default_run_name(2, 1e-4), "e2-lr1e-4"); + assert_eq!(default_run_name(3, 5e-5), "e3-lr5e-5"); + assert_eq!(default_run_name(2, 1.5e-4), "e2-lr1.5e-4"); + assert_eq!(default_run_name(1, 0.05), "e1-lr5e-2"); + assert_eq!(default_run_name(1, 1.0), "e1-lr1e0"); + } + #[test] fn a_census_trains_nothing_for_one_epoch_and_exports_nothing() { let tmp = tempfile::tempdir().unwrap(); @@ -437,6 +480,8 @@ mod tests { repo_id: "acme/other".into(), run: "e3-lr1e-4".into(), kind: JobKind::Run, + stage: None, + backend: None, }, cancel: Arc::new(AtomicBool::new(false)), sink: Arc::new(Mutex::new(None)), @@ -469,6 +514,8 @@ mod tests { repo_id: "acme/tiny".into(), run: "r".into(), kind: JobKind::Run, + stage: None, + backend: None, }, cancel: Arc::new(AtomicBool::new(false)), sink: sink.clone(), @@ -482,4 +529,62 @@ mod tests { lock(&sink).as_ref().unwrap()(RunProgress::Cancelled); assert_eq!(*lock(&got), 1); } + + #[test] + fn the_latest_stage_and_backend_are_kept_for_a_webview_that_attaches_late() { + let jobs = Jobs::default(); + *lock(&jobs.active) = Some(Active { + info: JobInfo { + repo_id: "acme/tiny".into(), + run: "r".into(), + kind: JobKind::Run, + stage: None, + backend: None, + }, + cancel: Arc::new(AtomicBool::new(false)), + sink: Arc::new(Mutex::new(None)), + }); + remember( + &jobs.active, + &RunProgress::Backend { + backend: FineTuneBackend::Cpu, + fallback: Some("no metallib".into()), + }, + ); + remember( + &jobs.active, + &RunProgress::Stage { + stage: Stage::Training, + }, + ); + remember( + &jobs.active, + &RunProgress::Stage { + stage: Stage::Merging, + }, + ); + remember( + &jobs.active, + &RunProgress::Phase { + label: "ignored".into(), + }, + ); + + let info = jobs.attach(Box::new(|_| {})).unwrap(); + assert_eq!(info.stage, Some(Stage::Merging), "the newest stage wins"); + assert_eq!( + info.backend, + Some(BackendInfo { + backend: FineTuneBackend::Cpu, + fallback: Some("no metallib".into()) + }) + ); + // Nothing to remember into when no job is running. + remember( + &Slot::default(), + &RunProgress::Stage { + stage: Stage::Exporting, + }, + ); + } } diff --git a/packaging/app/src/features/finetune/job.test.ts b/packaging/app/src/features/finetune/job.test.ts index 1794e56..1c37633 100644 --- a/packaging/app/src/features/finetune/job.test.ts +++ b/packaging/app/src/features/finetune/job.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { apply, begin, formatDuration, idle, isRunning, rowsLeftOut, secondsLeft, stepsDone } from "./job.ts"; +import { apply, begin, defaultRunName, elapsedFromSteps, positionFromSteps, formatDuration, idle, isRunning, rowsLeftOut, secondsLeft, stepsDone } from "./job.ts"; import type { JobInfo, RunEvent, RunRecord } from "../../lib/types.ts"; const info: JobInfo = { repo_id: "acme/tiny", run: "e2-lr1e-4", kind: "run" }; @@ -42,7 +42,7 @@ test("a step event changes nothing: steps are collected outside the state", () = test("each way a run can end is recorded and clears the stopping flag", () => { const stopping = { ...begin(info), stopping: true }; - const done = apply(stopping, { event: "done", name: "r", status: "done" } as RunEvent & RunRecord); + const done = apply(stopping, { event: "done", name: "r", status: "done", epoch_loss: [] } as unknown as RunEvent & RunRecord); assert.equal(done.outcome?.kind, "done"); assert.equal(done.stopping, false); assert.equal(isRunning(done), false); @@ -72,3 +72,39 @@ test("rows the trainer left out are counted, and only when it used fewer than th assert.equal(rowsLeftOut(null, p), null, "dataset size unknown"); assert.equal(rowsLeftOut(12, null), null, "no step yet"); }); + +test("the default run name matches the backend's, including exponents that Rust writes without a sign", () => { + assert.equal(defaultRunName(2, 1e-4), "e2-lr1e-4"); + assert.equal(defaultRunName(3, 5e-5), "e3-lr5e-5"); + assert.equal(defaultRunName(2, 1.5e-4), "e2-lr1.5e-4"); + assert.equal(defaultRunName(1, 0.05), "e1-lr5e-2"); + assert.equal(defaultRunName(1, 1), "e1-lr1e0"); +}); + +test("time spent training is read off the recorded steps when a run is picked back up", () => { + assert.equal(elapsedFromSteps([]), null); + assert.equal(elapsedFromSteps([{ t_ms: 2000 }, { t_ms: 2500 }, { t_ms: 9000 }]), 7000); +}); + +test("training position is rebuilt from recorded steps once the first epoch is over", () => { + const rec = (epoch: number, step: number) => ({ epoch, step }); + const firstEpoch = [rec(1, 1), rec(1, 2), rec(1, 3), rec(1, 4)]; + assert.equal(positionFromSteps([], 2), null); + assert.equal(positionFromSteps(firstEpoch.slice(0, 2), 2), null, "steps per epoch are not known mid first epoch"); + assert.equal(positionFromSteps(firstEpoch, 2), null, "an epoch that has just ended is not yet proof of its length"); + assert.deepEqual(positionFromSteps([...firstEpoch, rec(2, 1), rec(2, 2)], 2), { + epoch: 2, + totalEpochs: 2, + step: 2, + totalSteps: 4, + }); + assert.equal(positionFromSteps(firstEpoch, 0), null); +}); + +test("a finished run fills in the epoch losses a late-attached screen missed, and never shortens them", () => { + const record = { event: "done", name: "r", status: "done", epoch_loss: [0.9, 0.4] } as unknown as RunEvent; + const late = apply(begin(info), record); + assert.deepEqual(late.epochLoss, [0.9, 0.4]); + const watched = apply({ ...begin(info), epochLoss: [0.9, 0.4, 0.2] }, record); + assert.deepEqual(watched.epochLoss, [0.9, 0.4, 0.2]); +}); diff --git a/packaging/app/src/features/finetune/job.ts b/packaging/app/src/features/finetune/job.ts index 118e078..1d36f73 100644 --- a/packaging/app/src/features/finetune/job.ts +++ b/packaging/app/src/features/finetune/job.ts @@ -73,7 +73,14 @@ export function apply(s: JobState, e: RunEvent): JobState { case "export": return { ...s, exportProgress: { index: e.index, total: e.total } }; case "done": - return { ...s, stopping: false, outcome: { kind: "done", record: e } }; + return { + ...s, + stopping: false, + // A screen that attached mid-run missed the epoch events. The finished + // record has them all. + epochLoss: e.epoch_loss.length > s.epochLoss.length ? e.epoch_loss : s.epochLoss, + outcome: { kind: "done", record: e }, + }; case "failed": return { ...s, stopping: false, outcome: { kind: "failed", message: e.message } }; case "cancelled": @@ -107,6 +114,45 @@ export function rowsLeftOut(datasetRows: number | null, p: Position | null): num return left > 0 ? left : null; } +/** The name a run gets when the form leaves it empty. Matches `default_run_name` + * in the backend, so the header shows the real name before the backend replies. + * Rust's `{:e}` and `toExponential()` agree once the sign of the exponent is + * written the same way. */ +export function defaultRunName(epochs: number, learningRate: number): string { + return `e${epochs}-lr${learningRate.toExponential().replace("e+", "e")}`; +} + +/** Where a run that is already going stands, from the steps it has recorded. + * `elapsedMs` is how long training has been going, from the first step to the + * latest. `null` when no step has been recorded yet. */ +export function elapsedFromSteps(steps: { t_ms: number }[]): number | null { + if (steps.length === 0) return null; + return steps[steps.length - 1].t_ms - steps[0].t_ms; +} + +/** Where training stands, rebuilt from the steps a run has recorded. The step + * events that carried this are not replayed when a screen attaches late. + * + * A step is recorded for every row the trainer used, so the first epoch's last + * step number is the steps per epoch. Until the first epoch is over that is not + * known, and this returns `null` rather than guess. */ +export function positionFromSteps( + steps: { epoch: number; step: number }[], + totalEpochs: number, +): Position | null { + if (steps.length === 0 || totalEpochs < 1) return null; + const last = steps[steps.length - 1]; + const firstEpoch = steps.filter((s) => s.epoch === 1); + const firstEpochDone = last.epoch > 1; + // The trainer is on its last epoch's last step, or past training, when the + // run has as many epochs recorded as it was asked for. + const totalSteps = firstEpochDone + ? firstEpoch.reduce((m, s) => Math.max(m, s.step), 0) + : null; + if (totalSteps === null) return null; + return { epoch: last.epoch, totalEpochs, step: last.step, totalSteps }; +} + export function formatDuration(seconds: number): string { if (seconds < 60) return `${seconds}s`; const m = Math.floor(seconds / 60); diff --git a/packaging/app/src/features/finetune/useJob.ts b/packaging/app/src/features/finetune/useJob.ts index db1fd6c..52fbff1 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, idle, type JobState } from "./job"; +import { apply, defaultRunName, elapsedFromSteps, idle, positionFromSteps, type JobState } from "./job"; /** 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 @@ -45,8 +45,26 @@ export function useJob() { .attachJob(onEvent) .then(async (info) => { if (!info) return; - setState({ ...idle, info, phase: "Reconnected to the running job" }); - steps.current = await ipc.runSteps(info.repo_id, info.run).catch(() => []); + setState({ + ...idle, + info, + stage: info.stage, + backend: info.backend ? { name: info.backend.backend, fallback: info.backend.fallback } : null, + phase: info.stage ? null : "Reconnected to the running job", + }); + const [recorded, detail] = await Promise.all([ + ipc.runSteps(info.repo_id, info.run).catch(() => []), + ipc.projectDetail(info.repo_id).catch(() => null), + ]); + steps.current = recorded; + // The time estimate and the rows-left-out warning need what the first + // screen knew: when training began, and how many rows the dataset has. + const elapsed = elapsedFromSteps(recorded); + trainingStartedAt.current = elapsed === null ? null : Date.now() - elapsed; + datasetRows.current = detail?.dataset.state === "ready" ? detail.dataset.rows : null; + const epochs = detail?.runs.find((r) => r.name === info.run)?.spec?.epochs; + const position = epochs ? positionFromSteps(recorded, epochs) : null; + if (position) setState((s) => ({ ...s, phase: null, position })); redraw((n) => n + 1); }) .catch(() => {}); @@ -57,13 +75,22 @@ export function useJob() { /** Start a job. Rejects, leaving the state idle, when the backend refuses. */ const start = useCallback( - async (request: JobRequest, rows: number | null = null) => { + async (request: JobRequest, rows: number | null) => { steps.current = []; trainingStartedAt.current = null; datasetRows.current = rows; setState({ ...idle, - info: { repo_id: request.repo_id, run: request.name || "…", kind: request.kind }, + info: { + repo_id: request.repo_id, + run: + request.kind === "census" + ? "census" + : request.name || defaultRunName(request.epochs, request.learning_rate), + kind: request.kind, + stage: null, + backend: null, + }, phase: "Starting", }); try { diff --git a/packaging/app/src/lib/types.ts b/packaging/app/src/lib/types.ts index 3a597b0..10eafdd 100644 --- a/packaging/app/src/lib/types.ts +++ b/packaging/app/src/lib/types.ts @@ -166,6 +166,9 @@ export interface JobInfo { repo_id: string; run: string; kind: JobKind; + /** The latest stage and backend the job reported, for a screen that attaches late. */ + stage: Stage | null; + backend: { backend: Backend; fallback: string | null } | null; } /** Mirrors `onde_cli::pipeline::RunProgress`, which is tagged with `event`. */ From 9e996cc71e4a0cc65d67c7cf5ffb227c5efb63f6 Mon Sep 17 00:00:00 2001 From: Seto Elkahfi <1797197+setoelkahfi@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:27:34 +0100 Subject: [PATCH 3/3] app: keep live steps after a reattach, narrow the live region, fix census wording Reattaching to a running job fetched the recorded steps and then overwrote the steps that had arrived on the live channel in the meantime, leaving a gap in the chart. The two are now merged, deduped on epoch and step, and a position set by a live event is no longer replaced by the older one from the file. The progress panel no longer announces every step to screen readers. Only the census verdict and the finished and stopped messages are live regions. A census where steps ran but no norm was finite said all steps were skipped. It now says that no step reported a finite norm, and keeps the "all skipped" wording for when that is true. 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 | 7 ++++--- packaging/app/src/features/finetune/census.test.ts | 12 ++++++++++++ packaging/app/src/features/finetune/census.ts | 5 ++++- packaging/app/src/features/finetune/useJob.ts | 12 ++++++++---- 4 files changed, 28 insertions(+), 8 deletions(-) diff --git a/packaging/app/src/features/finetune/JobPanel.tsx b/packaging/app/src/features/finetune/JobPanel.tsx index fddbe8f..106e446 100644 --- a/packaging/app/src/features/finetune/JobPanel.tsx +++ b/packaging/app/src/features/finetune/JobPanel.tsx @@ -35,7 +35,7 @@ export function JobPanel({ job }: { job: Job }) { const leftOut = rowsLeftOut(job.datasetRows, position); return ( -
+

{info.run}

@@ -143,6 +143,7 @@ export function JobPanel({ job }: { job: Job }) { {verdict && (
+

{census ? "Census finished. It trained nothing and made no model." : `Finished${outcome.record.gguf_size ? `: ${outcome.record.gguf_path?.split("/").pop()} (${formatBytes(outcome.record.gguf_size)})` : ""}. Find it under Projects.`} @@ -170,7 +171,7 @@ export function JobPanel({ job }: { job: Job }) { {outcome.message}

)} - {outcome?.kind === "cancelled" &&

Stopped. No adapter was written.

} + {outcome?.kind === "cancelled" &&

Stopped. No adapter was written.

} {outcome && (