Skip to content

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.

Studio: preserve training config values across YAML load and save (#7942)

oobabooga113a2cff297b
diff --git a/studio/backend/assets/configs/model_defaults/gemma/unsloth_gemma-3-4b-pt.yaml b/studio/backend/assets/configs/model_defaults/gemma/unsloth_gemma-3-4b-pt.yaml
index 54c7dd6cd43..9c153c12544 100644
--- a/studio/backend/assets/configs/model_defaults/gemma/unsloth_gemma-3-4b-pt.yaml
+++ b/studio/backend/assets/configs/model_defaults/gemma/unsloth_gemma-3-4b-pt.yaml
@@ -17,7 +17,7 @@ training:
random_seed: 3407
packing: false
train_on_completions: true
- gradient_checkpointing: true
+ gradient_checkpointing: "unsloth"
optim: "adamw_torch_fused"
lr_scheduler_type: "cosine"
diff --git a/studio/backend/assets/configs/model_defaults/gemma/unsloth_gemma-3n-E4B.yaml b/studio/backend/assets/configs/model_defaults/gemma/unsloth_gemma-3n-E4B.yaml
index d08e5e95477..c9b612415db 100644
--- a/studio/backend/assets/configs/model_defaults/gemma/unsloth_gemma-3n-E4B.yaml
+++ b/studio/backend/assets/configs/model_defaults/gemma/unsloth_gemma-3n-E4B.yaml
@@ -17,7 +17,7 @@ training:
random_seed: 3407
packing: false
train_on_completions: true
- gradient_checkpointing: true
+ gradient_checkpointing: "unsloth"
optim: "adamw_torch_fused"
lr_scheduler_type: "cosine"
diff --git a/studio/backend/assets/configs/model_defaults/llama/unsloth_Llama-3.2-1B-Instruct.yaml b/studio/backend/assets/configs/model_defaults/llama/unsloth_Llama-3.2-1B-Instruct.yaml
index 3c7fc7f238f..3f07c214d69 100644
--- a/studio/backend/assets/configs/model_defaults/llama/unsloth_Llama-3.2-1B-Instruct.yaml
+++ b/studio/backend/assets/configs/model_defaults/llama/unsloth_Llama-3.2-1B-Instruct.yaml
@@ -16,7 +16,7 @@ training:
random_seed: 3407
packing: false
train_on_completions: true
- gradient_checkpointing: true
+ gradient_checkpointing: "unsloth"
optim: "adamw_torch"
lr_scheduler_type: "cosine"
diff --git a/studio/frontend/src/features/training/api/models-api.ts b/studio/frontend/src/features/training/api/models-api.ts
index 91c83e48806..d85acbe9490 100644
--- a/studio/frontend/src/features/training/api/models-api.ts
+++ b/studio/frontend/src/features/training/api/models-api.ts
@@ -18,6 +18,7 @@ interface BackendTrainingDefaults {
max_seq_length?: number;
num_epochs?: number;
learning_rate?: number | string;
+ embedding_learning_rate?: number | string | null;
optim?: string;
lr_scheduler_type?: string;
batch_size?: number;
@@ -31,7 +32,8 @@ interface BackendTrainingDefaults {
vision_image_size?: number | string | null;
packing?: boolean;
train_on_completions?: boolean;
- gradient_checkpointing?: "none" | "true" | "unsloth";
+ // Shipped YAML may decode this value as a boolean.
+ gradient_checkpointing?: "none" | "true" | "unsloth" | boolean;
trust_remote_code?: boolean;
}
diff --git a/studio/frontend/src/features/training/lib/model-defaults-edit-policy.ts b/studio/frontend/src/features/training/lib/model-defaults-edit-policy.ts
index 98b59e8980d..247748df814 100644
--- a/studio/frontend/src/features/training/lib/model-defaults-edit-policy.ts
+++ b/studio/frontend/src/features/training/lib/model-defaults-edit-policy.ts
@@ -7,6 +7,7 @@ export const MODEL_DEFAULT_STATE_KEYS = [
"epochs",
"contextLength",
"learningRate",
+ "embeddingLearningRate",
"optimizerType",
"lrSchedulerType",
"loraRank",
diff --git a/studio/frontend/src/features/training/lib/model-defaults.ts b/studio/frontend/src/features/training/lib/model-defaults.ts
index 9d8fd20de7b..d87a9ccb90e 100644
--- a/studio/frontend/src/features/training/lib/model-defaults.ts
+++ b/studio/frontend/src/features/training/lib/model-defaults.ts
@@ -9,7 +9,10 @@ import type { ModelDefaultsPatch } from "./model-defaults-edit-policy";
function toNumber(value: unknown): number | undefined {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string") {
- const parsed = Number(value);
+ // Do not coerce blank strings to 0.
+ const trimmed = value.trim();
+ if (trimmed === "") return undefined;
+ const parsed = Number(trimmed);
if (Number.isFinite(parsed)) return parsed;
}
return undefined;
@@ -35,17 +38,45 @@ function toStringArray(value: unknown): string[] | undefined {
return result.length > 0 ? result : undefined;
}
+// The spellings studio/backend/core/training/trainer.py accepts, so a file means
+// the same thing to the picker as it does to the trainer. A quoted "false" read
+// as "leave it at the default" is how a config asking for no checkpointing ended
+// up training with Unsloth GC.
+const GRADIENT_CHECKPOINTING_ALIASES = new Map<
+ string,
+ TrainingConfigState["gradientCheckpointing"]
+>([
+ ["true", "true"],
+ ["1", "true"],
+ ["yes", "true"],
+ ["false", "none"],
+ ["0", "none"],
+ ["no", "none"],
+ ["none", "none"],
+ ["off", "none"],
+ ["unsloth", "unsloth"],
+ ["mlx", "mlx"],
+]);
+
function toGradientCheckpointing(
value: unknown,
): TrainingConfigState["gradientCheckpointing"] | undefined {
- if (value === "none" || value === "true" || value === "unsloth" || value === "mlx") {
- // On Mac, map "unsloth" → "mlx" since Unsloth GC is GPU-only
- if (usePlatformStore.getState().deviceType === "mac" && value === "unsloth") {
- return "mlx";
- }
- return value;
+ // Shipped YAML may decode this value as a boolean.
+ if (typeof value === "boolean") return value ? "true" : "none";
+ if (typeof value !== "string") return undefined;
+ // Blank means absent here too, so it keeps whatever is selected.
+ const resolved = GRADIENT_CHECKPOINTING_ALIASES.get(
+ value.trim().toLowerCase(),
+ );
+ if (resolved === undefined) return undefined;
+ // On Mac, map "unsloth" → "mlx" since Unsloth GC is GPU-only
+ if (
+ resolved === "unsloth" &&
+ usePlatformStore.getState().deviceType === "mac"
+ ) {
+ return "mlx";
}
- return undefined;
+ return resolved;
}
export function mapBackendModelConfigToTrainingPatch(
@@ -67,6 +98,19 @@ export function mapBackendModelConfigToTrainingPatch(
const learningRate = toNumber(training?.learning_rate);
if (learningRate !== undefined) patch.learningRate = learningRate;
+ // Preserve explicit null ("derive it") versus an absent or invalid value.
+ if (Object.hasOwn(training ?? {}, "embedding_learning_rate")) {
+ const raw = training?.embedding_learning_rate;
+ if (raw === null) {
+ patch.embeddingLearningRate = null;
+ } else {
+ const embeddingLearningRate = toNumber(raw);
+ if (embeddingLearningRate !== undefined) {
+ patch.embeddingLearningRate = embeddingLearningRate;
+ }
+ }
+ }
+
const optim = toStringValue(training?.optim);
if (optim !== undefined) patch.optimizerType = optim;
@@ -176,7 +220,8 @@ export function mapBackendModelConfigToTrainingPatch(
if (wandbProject !== undefined) patch.wandbProject = wandbProject;
const enableTensorboard = toBoolean(logging?.enable_tensorboard);
- if (enableTensorboard !== undefined) patch.enableTensorboard = enableTensorboard;
+ if (enableTensorboard !== undefined)
+ patch.enableTensorboard = enableTensorboard;
const tensorboardDir = toStringValue(logging?.tensorboard_dir);
if (tensorboardDir !== undefined) patch.tensorboardDir = tensorboardDir;
diff --git a/studio/frontend/src/features/training/lib/yaml-config.ts b/studio/frontend/src/features/training/lib/yaml-config.ts
index d2eef17efed..3be434330d9 100644
--- a/studio/frontend/src/features/training/lib/yaml-config.ts
+++ b/studio/frontend/src/features/training/lib/yaml-config.ts
@@ -83,6 +83,7 @@ export function serializeConfigToYaml(
max_seq_length: state.contextLength,
num_epochs: state.epochs,
learning_rate: state.learningRate,
+ embedding_learning_rate: state.embeddingLearningRate,
batch_size: state.batchSize,
gradient_accumulation_steps: state.gradientAccumulation,
warmup_steps: state.warmupSteps,
@@ -105,6 +106,14 @@ export function serializeConfigToYaml(
const config = {
training,
lora,
+ // Include every non-secret logging field read by parseYamlConfig.
+ logging: {
+ enable_wandb: state.enableWandb,
+ wandb_project: state.wandbProject,
+ enable_tensorboard: state.enableTensorboard,
+ tensorboard_dir: state.tensorboardDir,
+ log_frequency: state.logFrequency,
+ },
};
return yaml.dump(config, { lineWidth: -1, noRefs: true });
diff --git a/studio/frontend/tests/helpers/kit.ts b/studio/frontend/tests/helpers/kit.ts
index abfe3af14ce..a2533b6deee 100644
--- a/studio/frontend/tests/helpers/kit.ts
+++ b/studio/frontend/tests/helpers/kit.ts
@@ -14,6 +14,11 @@ export function registerBundlerResolver(): void {
register("../bundler-resolver.mjs", import.meta.url);
}
+/** Register the bundler resolver with store dependency stubs. */
+export function registerStoreStubResolver(): void {
+ register("../store-stub-resolver.mjs", import.meta.url);
+}
+
export type StorageFake = {
getItem: (key: string) => string | null;
setItem: (key: string, value: string) => void;
@@ -40,7 +45,13 @@ export function installLocalStorageFake(): {
};
Object.assign(globalThis, {
// A location too: lib/api-base reads its protocol, pulled in transitively.
- window: { localStorage: storage, location: { protocol: "http:" } },
+ // Stores that sync across tabs subscribe to "storage" on construction.
+ window: {
+ localStorage: storage,
+ location: { protocol: "http:" },
+ addEventListener: () => undefined,
+ removeEventListener: () => undefined,
+ },
localStorage: storage,
});
return { store, storage };
diff --git a/studio/frontend/tests/helpers/store-stubs/auth.ts b/studio/frontend/tests/helpers/store-stubs/auth.ts
new file mode 100644
index 00000000000..d3d832f1a4b
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/auth.ts
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Fail any unexpected network access. */
+export function authFetch(): Promise<Response> {
+ throw new Error("authFetch: no network in tests");
+}
diff --git a/studio/frontend/tests/helpers/store-stubs/env.ts b/studio/frontend/tests/helpers/store-stubs/env.ts
new file mode 100644
index 00000000000..aedb8739bf8
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/env.ts
@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Minimal settable platform store. */
+let deviceType: string | null = null;
+
+export const usePlatformStore = {
+ getState: () => ({ deviceType }),
+ setState: (next: { deviceType: string | null }) => {
+ deviceType = next.deviceType;
+ },
+};
diff --git a/studio/frontend/tests/helpers/store-stubs/hub.ts b/studio/frontend/tests/helpers/store-stubs/hub.ts
new file mode 100644
index 00000000000..6724a5ce6c8
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/hub.ts
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Real logic, re-exported: only the barrel it normally comes from needs stubbing.
+export { normalizeModelIdentity } from "../../../src/features/hub/lib/model-identity.ts";
+
+/** Minimal HF-token store. */
+let token = "";
+
+export function getHfToken(): string {
+ return token;
+}
+
+export function hubTokenHeader(): Record<string, string> {
+ return {};
+}
+
+export function mirrorHfTokenInto(): void {
+ // Token state is local to this stub.
+}
+
+export const useHfTokenStore = {
+ getState: () => ({
+ setToken: (next: string) => {
+ token = next;
+ },
+ }),
+};
diff --git a/studio/frontend/tests/helpers/store-stubs/toast.ts b/studio/frontend/tests/helpers/store-stubs/toast.ts
new file mode 100644
index 00000000000..65565eb6a08
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/toast.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Swallow notifications; the real module pulls in a TSX component. */
+export const toast = {
+ info: () => undefined,
+ error: () => undefined,
+ warning: () => undefined,
+ success: () => undefined,
+ loading: () => undefined,
+ dismiss: () => undefined,
+};
+
+export function createLoadingToastIcon(): null {
+ return null;
+}
diff --git a/studio/frontend/tests/store-stub-resolver.mjs b/studio/frontend/tests/store-stub-resolver.mjs
new file mode 100644
index 00000000000..bac6b479b55
--- /dev/null
+++ b/studio/frontend/tests/store-stub-resolver.mjs
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Bare Node needs stubs for Vite-only and TSX barrel dependencies.
+import { resolve as resolveBundler } from "./bundler-resolver.mjs";
+
+const STUBS = new Map([
+ ["@/features/auth", "./helpers/store-stubs/auth.ts"],
+ ["@/features/hub", "./helpers/store-stubs/hub.ts"],
+ ["@/config/env", "./helpers/store-stubs/env.ts"],
+ ["@/lib/toast", "./helpers/store-stubs/toast.ts"],
+]);
+
+export function resolve(specifier, context, next) {
+ const stub = STUBS.get(specifier);
+ if (stub) {
+ return next(new URL(stub, import.meta.url).href, context);
+ }
+ return resolveBundler(specifier, context, next);
+}
diff --git a/studio/frontend/tests/training-config-platforms.test.ts b/studio/frontend/tests/training-config-platforms.test.ts
new file mode 100644
index 00000000000..d5c051dea04
--- /dev/null
+++ b/studio/frontend/tests/training-config-platforms.test.ts
@@ -0,0 +1,240 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The config plumbing reads the platform store, and config files travel between
+// machines, so pin the value mapping against every device type and every shipped
+// model config rather than the one config the round-trip test seeds from.
+
+import assert from "node:assert/strict";
+import { readFileSync, readdirSync } from "node:fs";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerStoreStubResolver,
+} from "./helpers/kit.ts";
+
+registerStoreStubResolver();
+installLocalStorageFake();
+
+const yaml = await import("js-yaml");
+const { usePlatformStore } = await import("@/config/env");
+const { mapBackendModelConfigToTrainingPatch } = await import(
+ "../src/features/training/lib/model-defaults.ts"
+);
+const { parseYamlConfig, serializeConfigToYaml } = await import(
+ "../src/features/training/lib/yaml-config.ts"
+);
+const { useTrainingConfigStore } = await import(
+ "../src/features/training/stores/training-config-store.ts"
+);
+
+// main.py maps sys.platform, so WSL arrives as "linux" and anything exotic
+// arrives verbatim; the browser fallback in env.ts only ever guesses these three.
+const DEVICE_TYPES = ["linux", "windows", "mac", "freebsd"];
+
+const MODEL_DEFAULTS_DIR = new URL(
+ "../../backend/assets/configs/model_defaults/",
+ import.meta.url,
+);
+
+const SHIPPED_CONFIGS = readdirSync(MODEL_DEFAULTS_DIR, { recursive: true })
+ .map(String)
+ .filter((name) => name.endsWith(".yaml"))
+ .sort();
+
+function setDeviceType(deviceType: string): void {
+ (
+ usePlatformStore as unknown as {
+ setState: (next: { deviceType: string }) => void;
+ }
+ ).setState({ deviceType });
+}
+
+function patchFor(training: Record<string, unknown>): Record<string, unknown> {
+ return mapBackendModelConfigToTrainingPatch({ training } as never) as Record<
+ string,
+ unknown
+ >;
+}
+
+test("gradient_checkpointing only ever maps to a value the picker can show", () => {
+ // Whatever a hand-written or shipped file holds, the store must not end up
+ // with a value <Select> cannot render.
+ const rawValues: unknown[] = [
+ true,
+ false,
+ "true",
+ "none",
+ "unsloth",
+ "mlx",
+ "None",
+ "TRUE",
+ " true ",
+ 1,
+ 0,
+ null,
+ "",
+ "yes",
+ [],
+ {},
+ ];
+ for (const deviceType of DEVICE_TYPES) {
+ setDeviceType(deviceType);
+ for (const value of rawValues) {
+ const mapped = patchFor({
+ gradient_checkpointing: value,
+ }).gradientCheckpointing;
+ if (mapped !== undefined) {
+ assert.ok(
+ ["none", "true", "unsloth", "mlx"].includes(mapped as string),
+ `${deviceType}: ${JSON.stringify(value)} mapped to ${String(mapped)}`,
+ );
+ }
+ if (typeof value === "boolean") {
+ assert.equal(mapped, value ? "true" : "none", deviceType);
+ }
+ }
+ }
+});
+
+test("Unsloth GC is still never selected on a Mac", () => {
+ setDeviceType("mac");
+ assert.equal(
+ patchFor({ gradient_checkpointing: "unsloth" }).gradientCheckpointing,
+ "mlx",
+ );
+ // The boolean path must not sneak past that remap either.
+ assert.equal(
+ patchFor({ gradient_checkpointing: true }).gradientCheckpointing,
+ "true",
+ );
+ assert.equal(
+ patchFor({ gradient_checkpointing: false }).gradientCheckpointing,
+ "none",
+ );
+});
+
+test("every shipped config's checkpointing survives a save and a reload", () => {
+ assert.ok(SHIPPED_CONFIGS.length > 50, "expected the shipped config set");
+ let booleanConfigs = 0;
+ for (const deviceType of DEVICE_TYPES) {
+ setDeviceType(deviceType);
+ for (const file of SHIPPED_CONFIGS) {
+ const config = yaml.load(
+ readFileSync(new URL(file, MODEL_DEFAULTS_DIR), "utf8"),
+ ) as { training?: { gradient_checkpointing?: unknown } };
+ const shipped = config.training?.gradient_checkpointing;
+ const seeded = mapBackendModelConfigToTrainingPatch(config as never);
+ if (typeof shipped === "boolean") {
+ booleanConfigs++;
+ assert.equal(
+ seeded.gradientCheckpointing,
+ shipped ? "true" : "none",
+ file,
+ );
+ }
+ useTrainingConfigStore.setState(seeded);
+ const selected = useTrainingConfigStore.getState().gradientCheckpointing;
+ const saved = serializeConfigToYaml(
+ useTrainingConfigStore.getState(),
+ false,
+ );
+ useTrainingConfigStore
+ .getState()
+ .applyConfigPatch(parseYamlConfig(saved));
+ assert.equal(
+ useTrainingConfigStore.getState().gradientCheckpointing,
+ selected,
+ `${file} on ${deviceType}`,
+ );
+ }
+ }
+ assert.ok(
+ booleanConfigs > 0,
+ "some shipped configs still decode as booleans; this is what covers them",
+ );
+});
+
+test("a blank value is ignored for every numeric field, a real 0 is not", () => {
+ setDeviceType("linux");
+ const numericFields = [
+ ["max_seq_length", "contextLength"],
+ ["num_epochs", "epochs"],
+ ["learning_rate", "learningRate"],
+ ["embedding_learning_rate", "embeddingLearningRate"],
+ ["batch_size", "batchSize"],
+ ["gradient_accumulation_steps", "gradientAccumulation"],
+ ["warmup_steps", "warmupSteps"],
+ ["max_steps", "maxSteps"],
+ ["save_steps", "saveSteps"],
+ ["eval_steps", "evalSteps"],
+ ["weight_decay", "weightDecay"],
+ ["random_seed", "randomSeed"],
+ ] as const;
+ for (const [yamlKey, stateKey] of numericFields) {
+ for (const blank of ["", " ", "\t"]) {
+ assert.ok(
+ !Object.hasOwn(patchFor({ [yamlKey]: blank }), stateKey),
+ `${yamlKey}: ${JSON.stringify(blank)} must not be applied`,
+ );
+ }
+ assert.equal(patchFor({ [yamlKey]: 0 })[stateKey], 0, yamlKey);
+ }
+});
+
+test("a config file written on another OS still imports", () => {
+ setDeviceType("windows");
+ useTrainingConfigStore.setState({ epochs: 3, gradientCheckpointing: "none" });
+ const saved = serializeConfigToYaml(useTrainingConfigStore.getState(), false);
+ // A file saved on Windows, or one an editor wrote with a byte order mark.
+ const bom = "\uFEFF";
+ const variants: [string, string][] = [
+ ["CRLF", saved.replace(/\n/g, "\r\n")],
+ ["UTF-8 BOM", `${bom}${saved}`],
+ ["BOM and CRLF", `${bom}${saved.replace(/\n/g, "\r\n")}`],
+ ];
+ for (const [name, text] of variants) {
+ const patch = mapBackendModelConfigToTrainingPatch(parseYamlConfig(text));
+ assert.equal(patch.epochs, 3, name);
+ assert.equal(patch.gradientCheckpointing, "none", name);
+ }
+});
+
+test("the WandB token never reaches the file, whatever the state", () => {
+ for (const deviceType of DEVICE_TYPES) {
+ setDeviceType(deviceType);
+ for (const enableWandb of [true, false]) {
+ useTrainingConfigStore.setState({
+ enableWandb,
+ wandbToken: "wandb-secret-value",
+ wandbProject: "p",
+ });
+ const saved = serializeConfigToYaml(
+ useTrainingConfigStore.getState(),
+ false,
+ );
+ assert.ok(!saved.includes("wandb-secret-value"), deviceType);
+ assert.ok(!saved.includes("wandb_token"), deviceType);
+ }
+ }
+});
+
+test("saving a reloaded config reproduces the same file", () => {
+ setDeviceType("linux");
+ useTrainingConfigStore.setState({
+ embeddingLearningRate: 3e-5,
+ enableWandb: true,
+ wandbProject: "my-project",
+ enableTensorboard: true,
+ tensorboardDir: "my-runs",
+ logFrequency: 25,
+ });
+ const first = serializeConfigToYaml(useTrainingConfigStore.getState(), false);
+ useTrainingConfigStore.getState().applyConfigPatch(parseYamlConfig(first));
+ const second = serializeConfigToYaml(
+ useTrainingConfigStore.getState(),
+ false,
+ );
+ assert.equal(second, first);
+});
diff --git a/studio/frontend/tests/training-config-roundtrip.test.ts b/studio/frontend/tests/training-config-roundtrip.test.ts
new file mode 100644
index 00000000000..cff83c84d89
--- /dev/null
+++ b/studio/frontend/tests/training-config-roundtrip.test.ts
@@ -0,0 +1,254 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Exercise the Save/Load path through the real store action.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import type { BackendModelConfig } from "../src/features/training/api/models-api.ts";
+import {
+ installLocalStorageFake,
+ registerStoreStubResolver,
+} from "./helpers/kit.ts";
+
+registerStoreStubResolver();
+installLocalStorageFake();
+
+const yaml = await import("js-yaml");
+const { useTrainingConfigStore } = await import(
+ "../src/features/training/stores/training-config-store.ts"
+);
+const { parseYamlConfig, serializeConfigToYaml } = await import(
+ "../src/features/training/lib/yaml-config.ts"
+);
+const { mapBackendModelConfigToTrainingPatch } = await import(
+ "../src/features/training/lib/model-defaults.ts"
+);
+
+// A tuned shipped config: non-default LR, batch size, optimizer and scheduler.
+const TUNED_MODEL_CONFIG = new URL(
+ "../../backend/assets/configs/model_defaults/llama/unsloth_Llama-3.2-1B-Instruct.yaml",
+ import.meta.url,
+);
+
+/** Seed the store as model selection does. */
+function seedTunedModelDefaults(): void {
+ const config = yaml.load(
+ readFileSync(TUNED_MODEL_CONFIG, "utf8"),
+ ) as BackendModelConfig;
+ useTrainingConfigStore.setState(mapBackendModelConfigToTrainingPatch(config));
+}
+
+/**
+ * Snapshot every non-action store value. userEditRevision is edit bookkeeping every
+ * user edit bumps, not a config value, so it stays out of the comparison.
+ */
+function snapshot(): Record<string, unknown> {
+ const state = useTrainingConfigStore.getState() as unknown as Record<
+ string,
+ unknown
+ >;
+ return Object.fromEntries(
+ Object.entries(state).filter(
+ ([key, value]) =>
+ typeof value !== "function" && key !== "userEditRevision",
+ ),
+ );
+}
+
+function keysChangedBy(action: () => void): string[] {
+ const before = snapshot();
+ action();
+ const after = snapshot();
+ return Object.keys(after).filter(
+ (key) => !Object.is(after[key], before[key]),
+ );
+}
+
+function importConfig(text: string): void {
+ useTrainingConfigStore.getState().applyConfigPatch(parseYamlConfig(text));
+}
+
+test("a partial import patches only the keys the file names", () => {
+ seedTunedModelDefaults();
+
+ const changed = keysChangedBy(() =>
+ importConfig("training:\n max_seq_length: 4096\n"),
+ );
+
+ assert.deepEqual(
+ changed,
+ ["contextLength"],
+ "a file naming one key must not reset the selected model's other tuned values",
+ );
+ assert.equal(useTrainingConfigStore.getState().contextLength, 4096);
+});
+
+test("a tuned model recipe survives an unrelated import", () => {
+ seedTunedModelDefaults();
+ const tuned = snapshot();
+
+ // Ensure sparse import preserves unrelated seeded values.
+ assert.equal(tuned.learningRate, 2e-5);
+ assert.equal(tuned.batchSize, 1);
+ assert.equal(tuned.optimizerType, "adamw_torch");
+ assert.equal(tuned.lrSchedulerType, "cosine");
+ assert.equal(tuned.trainOnCompletions, true);
+ assert.equal(tuned.loraAlpha, 16);
+
+ importConfig("lora:\n lora_r: 64\n");
+
+ const after = useTrainingConfigStore.getState();
+ assert.equal(after.loraRank, 64, "the imported key applies");
+ assert.equal(after.learningRate, 2e-5);
+ assert.equal(after.batchSize, 1);
+ assert.equal(after.optimizerType, "adamw_torch");
+ assert.equal(after.lrSchedulerType, "cosine");
+ assert.equal(after.trainOnCompletions, true);
+ assert.equal(after.loraAlpha, 16);
+});
+
+test("gradient_checkpointing is read from a YAML boolean as well as a string", () => {
+ seedTunedModelDefaults();
+ assert.equal(
+ useTrainingConfigStore.getState().gradientCheckpointing,
+ "unsloth",
+ "the shipped config asks for Unsloth checkpointing",
+ );
+
+ importConfig("training:\n gradient_checkpointing: false\n");
+ assert.equal(useTrainingConfigStore.getState().gradientCheckpointing, "none");
+
+ importConfig("training:\n gradient_checkpointing: true\n");
+ assert.equal(useTrainingConfigStore.getState().gradientCheckpointing, "true");
+
+ importConfig("training:\n gradient_checkpointing: unsloth\n");
+ assert.equal(
+ useTrainingConfigStore.getState().gradientCheckpointing,
+ "unsloth",
+ );
+});
+
+test("a quoted checkpointing value means what the trainer says it means", () => {
+ // trainer.py accepts these spellings, so the picker must not silently ignore
+ // one and leave Unsloth GC selected on a config that asked for none.
+ for (const off of ["false", '"false"', "'0'", "no", "OFF", '" none "']) {
+ seedTunedModelDefaults();
+ importConfig(`training:\n gradient_checkpointing: ${off}\n`);
+ assert.equal(
+ useTrainingConfigStore.getState().gradientCheckpointing,
+ "none",
+ off,
+ );
+ }
+ for (const on of ['"true"', "'1'", "yes", "TRUE"]) {
+ seedTunedModelDefaults();
+ importConfig(`training:\n gradient_checkpointing: ${on}\n`);
+ assert.equal(
+ useTrainingConfigStore.getState().gradientCheckpointing,
+ "true",
+ on,
+ );
+ }
+ // Anything unrecognised, or blank, leaves the selection alone.
+ for (const ignored of ['""', '" "', "maybe", "[]"]) {
+ seedTunedModelDefaults();
+ importConfig(`training:\n gradient_checkpointing: ${ignored}\n`);
+ assert.equal(
+ useTrainingConfigStore.getState().gradientCheckpointing,
+ "unsloth",
+ ignored,
+ );
+ }
+});
+
+test("a blank number is treated as absent, not as zero", () => {
+ seedTunedModelDefaults();
+ useTrainingConfigStore.setState({
+ epochs: 5,
+ warmupSteps: 7,
+ embeddingLearningRate: 4e-5,
+ });
+
+ importConfig(
+ 'training:\n num_epochs: ""\n warmup_steps: " "\n embedding_learning_rate: ""\n',
+ );
+
+ const after = useTrainingConfigStore.getState();
+ assert.equal(after.epochs, 5);
+ assert.equal(after.warmupSteps, 7);
+ assert.equal(after.embeddingLearningRate, 4e-5);
+
+ importConfig('training:\n embedding_learning_rate: "not-a-number"\n');
+ assert.equal(useTrainingConfigStore.getState().embeddingLearningRate, 4e-5);
+
+ importConfig("training:\n num_epochs: 0\n");
+ assert.equal(
+ useTrainingConfigStore.getState().epochs,
+ 0,
+ "a real 0 still applies; only the blank is ignored",
+ );
+
+ importConfig("training:\n embedding_learning_rate: null\n");
+ assert.equal(useTrainingConfigStore.getState().embeddingLearningRate, null);
+});
+
+test("saving and reloading a config keeps the logging settings", () => {
+ seedTunedModelDefaults();
+ useTrainingConfigStore.setState({
+ enableWandb: true,
+ wandbProject: "my-project",
+ enableTensorboard: true,
+ tensorboardDir: "my-runs",
+ logFrequency: 25,
+ });
+
+ const saved = serializeConfigToYaml(useTrainingConfigStore.getState(), false);
+
+ useTrainingConfigStore.setState({
+ enableWandb: false,
+ wandbProject: "",
+ enableTensorboard: false,
+ tensorboardDir: "",
+ logFrequency: 1,
+ });
+ importConfig(saved);
+
+ const after = useTrainingConfigStore.getState();
+ assert.equal(after.enableWandb, true);
+ assert.equal(after.wandbProject, "my-project");
+ assert.equal(after.enableTensorboard, true);
+ assert.equal(after.tensorboardDir, "my-runs");
+ assert.equal(after.logFrequency, 25);
+});
+
+test("saving and reloading a config keeps the embedding learning rate", () => {
+ seedTunedModelDefaults();
+ useTrainingConfigStore.setState({ embeddingLearningRate: 3e-5 });
+
+ const saved = serializeConfigToYaml(useTrainingConfigStore.getState(), false);
+
+ useTrainingConfigStore.setState({ embeddingLearningRate: null });
+ importConfig(saved);
+ assert.equal(useTrainingConfigStore.getState().embeddingLearningRate, 3e-5);
+
+ // Preserve null as "derive it", distinct from an absent key.
+ useTrainingConfigStore.setState({ embeddingLearningRate: null });
+ const clearedSave = serializeConfigToYaml(
+ useTrainingConfigStore.getState(),
+ false,
+ );
+ useTrainingConfigStore.setState({ embeddingLearningRate: 9e-5 });
+ importConfig(clearedSave);
+ assert.equal(useTrainingConfigStore.getState().embeddingLearningRate, null);
+});
+
+test("a file with no embedding learning rate leaves the current one alone", () => {
+ seedTunedModelDefaults();
+ useTrainingConfigStore.setState({ embeddingLearningRate: 4e-5 });
+
+ importConfig("training:\n max_seq_length: 4096\n");
+ assert.equal(useTrainingConfigStore.getState().embeddingLearningRate, 4e-5);
+});