Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: write each training metrics flush and its run progress in one transaction (#15871)
Daniel Han497c30256df7
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.pyindex 50bb6840df0..b9c5af781ae 100644--- a/studio/backend/core/training/training.py+++ b/studio/backend/core/training/training.py@@ -3637,9 +3637,10 @@ class TrainingBackend:loss = Noneduration = self._progress.elapsed_secondstry:- from storage.studio_db import insert_metrics_batch, update_run_progress- insert_metrics_batch(target, batch)- update_run_progress(id = target, step = step, loss = loss, duration_seconds = duration)+ from storage.studio_db import insert_metrics_with_progress+ insert_metrics_with_progress(+ target, batch, step = step, loss = loss, duration_seconds = duration+ )except Exception:# Re-queue the claimed batch at the front so it retries on the next flush.with self._lock:@@ -3762,9 +3763,8 @@ class TrainingBackend:returnfrom storage.studio_db import (create_run,- insert_metrics_batch,+ insert_metrics_with_progress,update_run_output_dir,- update_run_progress,update_run_total_steps,)@@ -3800,8 +3800,9 @@ class TrainingBackend:del member["metrics"][: len(batch)]step, loss, elapsed = member["step"], member["loss"], member["elapsed"]try:- insert_metrics_batch(run_id, batch)- update_run_progress(id = run_id, step = step, loss = loss, duration_seconds = elapsed)+ insert_metrics_with_progress(+ run_id, batch, step = step, loss = loss, duration_seconds = elapsed+ )except Exception:with self._lock:member["metrics"][:0] = batchdiff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex c9302832277..fb5cb8f8343 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -1648,39 +1648,68 @@ def finish_run(conn.close()+_INSERT_METRICS_SQL = """+ INSERT INTO training_metrics+ (run_id, step, loss, learning_rate, grad_norm, eval_loss, epoch, num_tokens, elapsed_seconds)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(run_id, step) DO UPDATE SET+ loss = COALESCE(excluded.loss, loss),+ learning_rate = COALESCE(excluded.learning_rate, learning_rate),+ grad_norm = COALESCE(excluded.grad_norm, grad_norm),+ eval_loss = COALESCE(excluded.eval_loss, eval_loss),+ epoch = COALESCE(excluded.epoch, epoch),+ num_tokens = COALESCE(excluded.num_tokens, num_tokens),+ elapsed_seconds = COALESCE(excluded.elapsed_seconds, elapsed_seconds)+"""+++def _insert_metrics_rows(conn: sqlite3.Connection, run_id: str, metrics: list[dict]) -> None:+ conn.executemany(+ _INSERT_METRICS_SQL,+ [+ (+ run_id,+ m.get("step"),+ m.get("loss"),+ m.get("learning_rate"),+ m.get("grad_norm"),+ m.get("eval_loss"),+ m.get("epoch"),+ m.get("num_tokens"),+ m.get("elapsed_seconds"),+ )+ for m in metrics+ ],+ )++def insert_metrics_batch(run_id: str, metrics: list[dict]) -> None:if not metrics:returnconn = get_connection()try:- conn.executemany(- """- INSERT INTO training_metrics- (run_id, step, loss, learning_rate, grad_norm, eval_loss, epoch, num_tokens, elapsed_seconds)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(run_id, step) DO UPDATE SET- loss = COALESCE(excluded.loss, loss),- learning_rate = COALESCE(excluded.learning_rate, learning_rate),- grad_norm = COALESCE(excluded.grad_norm, grad_norm),- eval_loss = COALESCE(excluded.eval_loss, eval_loss),- epoch = COALESCE(excluded.epoch, epoch),- num_tokens = COALESCE(excluded.num_tokens, num_tokens),- elapsed_seconds = COALESCE(excluded.elapsed_seconds, elapsed_seconds)- """,- [- (- run_id,- m.get("step"),- m.get("loss"),- m.get("learning_rate"),- m.get("grad_norm"),- m.get("eval_loss"),- m.get("epoch"),- m.get("num_tokens"),- m.get("elapsed_seconds"),- )- for m in metrics- ],+ _insert_metrics_rows(conn, run_id, metrics)+ conn.commit()+ finally:+ conn.close()+++def insert_metrics_with_progress(+ run_id: str,+ metrics: list[dict],+ *,+ step: int,+ loss: Optional[float],+ duration_seconds: Optional[float],+) -> None:+ """insert_metrics_batch + update_run_progress in one commit: a failure writes neither."""+ conn = get_connection()+ try:+ if metrics:+ _insert_metrics_rows(conn, run_id, metrics)+ conn.execute(+ "UPDATE training_runs SET final_step = ?, final_loss = ?, duration_seconds = ? WHERE id = ?",+ (step, loss, duration_seconds, run_id),)conn.commit()finally:diff --git a/studio/backend/tests/test_training_metrics_flush_transaction.py b/studio/backend/tests/test_training_metrics_flush_transaction.pynew file mode 100644index 00000000000..f2159a07b5f--- /dev/null+++ b/studio/backend/tests/test_training_metrics_flush_transaction.py@@ -0,0 +1,119 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A metric flush writes its batch and the run's progress through one connection and one commit."""++import pytest++import core.training.training as tr+from core.training.training import TrainingBackend+from storage import studio_db+++def backend(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", set())+ monkeypatch.setattr(tr, "account_is_retired", lambda: False)+ studio_db.create_run(+ id = "run-1",+ model_name = "m",+ dataset_name = "d",+ config_json = "{}",+ started_at = "2026-01-01T00:00:00+00:00",+ total_steps = 100,+ )+ b = TrainingBackend()+ b.current_job_id = "run-1"+ b._db_run_created = True+ yield b+ studio_db.close_wal_keeper()+++def _buffer(b, steps):+ b._metric_buffer[:] = [+ {"step": s, "loss": 1.0 / s, "learning_rate": 1e-4, "grad_norm": 0.5} for s in steps+ ]+ b._progress.step = steps[-1]+ b._progress.loss = 1.0 / steps[-1]+ b._progress.elapsed_seconds = float(steps[-1])+++def _rows():+ conn = studio_db.get_connection()+ try:+ metrics = [+ tuple(r)+ for r in conn.execute(+ "SELECT step, loss, learning_rate, grad_norm FROM training_metrics "+ "WHERE run_id = 'run-1' ORDER BY step"+ )+ ]+ run = tuple(+ conn.execute(+ "SELECT final_step, final_loss, duration_seconds FROM training_runs "+ "WHERE id = 'run-1'"+ ).fetchone()+ )+ finally:+ conn.close()+ return metrics, run+++def test_flush_opens_one_connection_and_commits_once(backend, monkeypatch):+ opened = []+ real = studio_db.get_connection++ def counting(*a, **k):+ conn = real(*a, **k)+ opened.append(conn)+ return conn++ monkeypatch.setattr(studio_db, "get_connection", counting)+ _buffer(backend, list(range(1, 11)))+ backend._flush_metrics_to_db()+ assert len(opened) == 1+ monkeypatch.setattr(studio_db, "get_connection", real)+ metrics, run = _rows()+ assert [m[0] for m in metrics] == list(range(1, 11))+ assert run == (10, 0.1, 10.0)+++def test_failed_progress_write_leaves_metrics_unwritten_and_requeued(backend):+ conn = studio_db.get_connection()+ conn.execute(+ "CREATE TRIGGER fail_progress BEFORE UPDATE OF final_step ON training_runs "+ "BEGIN SELECT RAISE(ABORT, 'disk full'); END"+ )+ conn.commit()+ conn.close()+ _buffer(backend, [1, 2, 3])+ backend._flush_metrics_to_db()+ assert [m["step"] for m in backend._metric_buffer] == [1, 2, 3]+ assert _rows()[0] == []++ conn = studio_db.get_connection()+ conn.execute("DROP TRIGGER fail_progress")+ conn.commit()+ conn.close()+ backend._flush_metrics_to_db()+ assert backend._metric_buffer == []+ metrics, run = _rows()+ assert [m[0] for m in metrics] == [1, 2, 3]+ assert run == (3, pytest.approx(1 / 3), 3.0)+++def test_reflushed_step_keeps_upsert_semantics(backend):+ _buffer(backend, [1, 2])+ backend._flush_metrics_to_db()+ backend._metric_buffer[:] = [{"step": 2, "eval_loss": 0.7}]+ backend._flush_metrics_to_db()+ conn = studio_db.get_connection()+ try:+ row = conn.execute(+ "SELECT loss, eval_loss FROM training_metrics WHERE run_id = 'run-1' AND step = 2"+ ).fetchone()+ finally:+ conn.close()+ assert tuple(row) == (0.5, 0.7)diff --git a/studio/backend/tests/test_training_mlx_eval_progress.py b/studio/backend/tests/test_training_mlx_eval_progress.pyindex ddcc65f1a45..e42df31362d 100644--- a/studio/backend/tests/test_training_mlx_eval_progress.py+++ b/studio/backend/tests/test_training_mlx_eval_progress.py@@ -24,6 +24,7 @@ def backend(monkeypatch):monkeypatch.setattr(sdb, "finish_run", lambda **kw: finished.append(kw))monkeypatch.setattr(sdb, "insert_metrics_batch", lambda *a, **k: None)monkeypatch.setattr(sdb, "update_run_progress", lambda **kw: None)+ monkeypatch.setattr(sdb, "insert_metrics_with_progress", lambda *a, **k: None)b = TrainingBackend()monkeypatch.setattr(b, "_start_stop_watchdog", lambda *a, **k: None)b.current_job_id = "job-mlx-eval"diff --git a/studio/backend/tests/test_training_stop_watchdog.py b/studio/backend/tests/test_training_stop_watchdog.pyindex 3315196da8a..d92476e46a3 100644--- a/studio/backend/tests/test_training_stop_watchdog.py+++ b/studio/backend/tests/test_training_stop_watchdog.py@@ -538,6 +538,12 @@ def _install_fake_db(monkeypatch):recs["insert_ids"].append(job_id),)fake_db.update_run_progress = lambda **kw: recs["progress_ids"].append(kw.get("id"))++ def _insert_with_progress(job_id, batch, **kw):+ fake_db.insert_metrics_batch(job_id, batch)+ fake_db.update_run_progress(id = job_id, **kw)++ fake_db.insert_metrics_with_progress = _insert_with_progressfake_db.mark_run_cancel_requested = lambda _run_id: Truefake_storage.studio_db = fake_dbmonkeypatch.setitem(sys.modules, "storage", fake_storage)