Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: rework mflux LoRA training to the real mflux ≥0.17 surface (verified live)

Adam Eivy362c364a2133
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 92aecd098b..4da4847937 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## Added
-- **Character LoRA training — train consistent character adapters from your universe canon** — Create → Media Gen gains a **Training** tab (`/media/training`) that closes the loop from "character exists in a universe" to "every render of that character looks the same." Per character, a **dataset workbench** builds reference material three ways: batch-generate single-subject training renders from the character's canon descriptors (deterministic view/pose/expression/outfit variation matrix, queued through the normal image lane), upload your own images (normalized to PNG via sharp), or slice the character's existing reference-sheet turnaround into grid crops. A **vision-LLM captioner** (same provider pathway as the voice agent's visual describe) auto-captions every image prefixed with the character's trigger word, with per-image caption editing and re-captioning. Once ≥10 captioned images are ready, **train a LoRA locally** on either runtime: FLUX.1-dev via mflux's own MLX dreambooth CLI (wrapped by `scripts/train_mflux_lora.py`) or FLUX.2 Klein via a vendored diffusers+peft trainer (`scripts/train_flux2_lora.py` — bf16 bases only, precompute-then-free text/VAE encoding so the MPS memory peak stays survivable, gradient checkpointing, SIGTERM saves a cancel checkpoint). Training runs ride the media-job GPU lane (serialized with renders, SSE progress with per-step loss, mid-training sample previews, 30-min idle watchdog, cancel). The finished adapter lands in `data/loras/` with a sidecar carrying the character link + trigger word + size-variant compat key, so it appears in the existing LoRA library and picker with the right base-model gating immediately. **Auto-apply:** pipeline comic-page and storyboard renders that match a character with a trained LoRA automatically attach the adapter and weave its trigger word into the prompt (local mode; per-stage opt-out in Generation settings). Character cards in the universe editor and catalog detail pages show a trained-LoRA chip + dataset entry point; trained LoRAs in the library link back to their dataset. Datasets are machine-local (like the LoRA files themselves — never federated) and fully backed up; training checkpoints/caches are excluded as regenerable. Run records live in PostgreSQL (`lora_training_runs`). (`server/services/loraTraining/`, `server/services/loraDatasets.js`, `server/services/loraDatasetGenerate.js`, `server/services/loraDatasetCaption.js`, `server/services/characterLoraResolver.js`, `client/src/pages/LoraTraining.jsx`, `client/src/pages/LoraDatasetDetail.jsx`)
+- **Character LoRA training — train consistent character adapters from your universe canon** — Create → Media Gen gains a **Training** tab (`/media/training`) that closes the loop from "character exists in a universe" to "every render of that character looks the same." Per character, a **dataset workbench** builds reference material three ways: batch-generate single-subject training renders from the character's canon descriptors (deterministic view/pose/expression/outfit variation matrix, queued through the normal image lane), upload your own images (normalized to PNG via sharp), or slice the character's existing reference-sheet turnaround into grid crops. A **vision-LLM captioner** (same provider pathway as the voice agent's visual describe) auto-captions every image prefixed with the character's trigger word, with per-image caption editing and re-captioning. Once ≥10 captioned images are ready, **train a FLUX.2 Klein LoRA locally** through one of two engines, picked automatically: mflux's MLX-native trainer (`mflux-train`, mflux ≥0.17 — wrapped by `scripts/train_mflux_lora.py`, preferred on Apple Silicon; the dataset stages in mflux's `NNNN.png`+`NNNN.txt` auto-discovery layout, and quantize/low-ram knobs derive from total RAM so a 48 GB machine trains QLoRA-style instead of OOMing) or a vendored torch/diffusers+peft trainer (`scripts/train_flux2_lora.py` — bf16 bases only, precompute-then-free text/VAE encoding, gradient checkpointing) as the fallback. Either engine exports diffusers-format adapters. Training runs ride the media-job GPU lane (serialized with renders, SSE progress with per-step loss, mid-training sample previews, 30-min idle watchdog, cancel saves a checkpoint). The finished adapter lands in `data/loras/` with a sidecar carrying the character link + trigger word + size-variant compat key (`flux2-4b`/`flux2-9b`), so it appears in the existing LoRA library and picker with the right base-model gating immediately. **Auto-apply:** pipeline comic-page and storyboard renders that match a character with a trained LoRA automatically attach the adapter and weave its trigger word into the prompt (local mode; per-stage opt-out in Generation settings). Character cards in the universe editor and catalog detail pages show a trained-LoRA chip + dataset entry point; trained LoRAs in the library link back to their dataset. Datasets are machine-local (like the LoRA files themselves — never federated) and fully backed up; training checkpoints/caches are excluded as regenerable. Run records live in PostgreSQL (`lora_training_runs`). (`server/services/loraTraining/`, `server/services/loraDatasets.js`, `server/services/loraDatasetGenerate.js`, `server/services/loraDatasetCaption.js`, `server/services/characterLoraResolver.js`, `client/src/pages/LoraTraining.jsx`, `client/src/pages/LoraDatasetDetail.jsx`)
## Changed
diff --git a/client/src/components/loraTraining/TrainingPanel.jsx b/client/src/components/loraTraining/TrainingPanel.jsx
index e7658c5e82..7e05c5684b 100644
--- a/client/src/components/loraTraining/TrainingPanel.jsx
+++ b/client/src/components/loraTraining/TrainingPanel.jsx
@@ -7,7 +7,7 @@
* frames. Completed runs surface the registered LoRA with a deep link.
*/
-import { useState, useEffect, useMemo, useCallback } from 'react';
+import { useState, useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import { Dumbbell, Loader2, Square, CheckCircle2, XCircle, Sparkles } from 'lucide-react';
import toast from '../ui/Toast';
@@ -38,9 +38,9 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
setParams((prev) => prev || { ...s.defaults });
}).catch(() => setStatus({ runtimes: {}, defaults: {} }));
listImageModels().then((list) => {
- const trainable = (Array.isArray(list) ? list : []).filter(
- (m) => m.id === 'dev' || m.runner === 'flux2',
- );
+ // FLUX.2 Klein only — mflux ≥0.17 dropped FLUX.1 training, and the
+ // torch fallback trains the same bf16 Klein bases.
+ const trainable = (Array.isArray(list) ? list : []).filter((m) => m.runner === 'flux2');
setModels(trainable);
setBaseModelId((prev) => prev || trainable[0]?.id || '');
}).catch(() => setModels([]));
@@ -65,11 +65,9 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
onRunFinished?.();
}, [closed, activeRun, refreshRuns, onRunFinished]);
- const runtimeForModel = useMemo(() => {
- const model = models.find((m) => m.id === baseModelId);
- return model?.runner === 'flux2' ? 'flux2' : 'mflux';
- }, [models, baseModelId]);
- const runtimeReady = status?.runtimes?.[runtimeForModel]?.ready;
+ // Engine pick mirrors the server: mflux (MLX) when its trainer is
+ // installed, else the torch venv. Either being ready unblocks training.
+ const engineReady = !!(status?.runtimes?.mflux?.ready || status?.runtimes?.flux2?.ready);
const start = async () => {
setStarting(true);
@@ -99,7 +97,7 @@ export default function TrainingPanel({ dataset, readiness, triggerSaving, onRun
? `Needs ${readiness?.required ?? 10} captioned images (have ${readiness?.captioned ?? 0})`
: triggerSaving ? 'Saving trigger word…'
: !baseModelId ? 'Pick a base model'
- : runtimeReady === false ? `${runtimeForModel} environment not ready — run scripts/setup-image-video.sh`
+ : (status && !engineReady) ? 'No training engine — install mflux ≥0.17 or run scripts/setup-image-video.sh'
: null;
if (activeRun) {
diff --git a/scripts/train_mflux_lora.py b/scripts/train_mflux_lora.py
index 56faf4e0ed..1cb4234054 100644
--- a/scripts/train_mflux_lora.py
+++ b/scripts/train_mflux_lora.py
@@ -1,36 +1,40 @@
#!/usr/bin/env python3
-"""mflux FLUX.1-dev LoRA training wrapper (PortOS).
-
-Wraps mflux's own DreamBooth training CLI in a subprocess and translates
-its native output into the PortOS trainer line protocol (see
-train_flux2_lora.py header / server/services/loraTraining/progress.js).
-We deliberately do NOT import mflux's training internals in-process —
-their API churns across versions; the CLI + train-config JSON is the
-stable-ish surface (same wrap-don't-import strategy as generate_wan22.py).
-
-Entrypoint probing (mflux moved this across versions):
- 1. <venv python> -m mflux.dreambooth --train-config <json>
- 2. mflux-train (console script next to the interpreter)
-
-Artifacts: mflux writes checkpoints (zips) + validation images into the
-config's save.output_path (our <runDir>/checkpoints). A watcher thread
-surfaces new checkpoints as CHECKPOINT: lines and copies validation PNGs
-into <runDir>/samples for SAMPLE: lines. On success, the newest adapter
-.safetensors (extracted from the newest checkpoint zip when necessary) is
-reported via RESULT: JSON.
-
-SIGTERM → forwarded to the mflux child; exit 143 after it stops.
+"""mflux FLUX.2 LoRA training wrapper (PortOS).
+
+Wraps mflux's own trainer (`mflux-train`, mflux ≥0.17 — FLUX.1 training
+was removed upstream) in a subprocess and translates its native output
+into the PortOS trainer line protocol (see train_flux2_lora.py header /
+server/services/loraTraining/progress.js). We deliberately do NOT import
+mflux's training internals in-process — their API churns across versions;
+the CLI + config JSON is the stable surface (same wrap-don't-import
+strategy as generate_wan22.py).
+
+Verified against mflux 0.17.5:
+ - CLI: `mflux-train --config <json>` (resume: `--resume <checkpoint.zip>`).
+ - Progress: a tqdm bar over total iterations (epochs × images), written
+ with carriage returns — the reader splits on \\r AND \\n.
+ - Outputs under the config's checkpoint.output_path:
+ checkpoints/NNNNNNN_checkpoint.zip (adapter + optimizer + config)
+ preview/NNNNNNN_preview_*.png (when monitoring is enabled)
+ loss/loss.html
+ - The trained adapter inside each zip is `NNNNNNN_adapter.safetensors`
+ with diffusers-style key naming (`transformer.<module>.lora_A.weight`),
+ so the extracted file loads directly in diffusers flux2 pipelines.
+
+SIGTERM → forwarded to the mflux child; exit 143 after it stops (mflux
+checkpoints at save_frequency boundaries; mid-interval cancels keep the
+last saved checkpoint).
"""
import argparse
import json
+import os
import re
import shutil
import signal
import subprocess
import sys
import threading
-import time
import zipfile
from pathlib import Path
@@ -55,170 +59,191 @@ signal.signal(signal.SIGTERM, _on_sigterm)
def parse_args():
p = argparse.ArgumentParser(description="mflux LoRA training wrapper")
- p.add_argument("--train-config", required=True)
- p.add_argument("--output-dir", required=True)
+ p.add_argument("--config", required=True, help="mflux-train config JSON")
+ p.add_argument("--output-dir", required=True, help="PortOS run dir (samples/ lives here)")
p.add_argument("--total-steps", type=int, default=1000,
- help="step budget for progress mapping when mflux reports epoch-relative counts")
- p.add_argument("--resume-checkpoint", default=None)
+ help="expected total iterations — used only for logging sanity")
+ p.add_argument("--resume-checkpoint", default=None, help="checkpoint zip to resume from")
return p.parse_args()
def build_command(config_path: str, resume: str | None) -> list:
- """Probe for mflux's training entrypoint. Prefer the module form (uses
- THIS interpreter, no PATH ambiguity); fall back to the console script."""
- module_probe = subprocess.run(
- [sys.executable, "-c", "import importlib.util as u; raise SystemExit(0 if u.find_spec('mflux.dreambooth') else 1)"],
- capture_output=True,
- )
- if module_probe.returncode == 0:
- cmd = [sys.executable, "-m", "mflux.dreambooth", "--train-config", config_path]
+ """`mflux-train` console script next to THIS interpreter (no PATH
+ ambiguity); fallback to the module behind it."""
+ console = Path(sys.executable).parent / "mflux-train"
+ if console.exists():
+ cmd = [str(console)]
else:
- console = Path(sys.executable).parent / "mflux-train"
- if not console.exists():
+ probe = subprocess.run(
+ [sys.executable, "-c",
+ "import importlib.util as u; raise SystemExit(0 if u.find_spec('mflux.models.common.cli.train') else 1)"],
+ capture_output=True,
+ )
+ if probe.returncode != 0:
print(
- "USER_ERROR:MODULE_NOT_FOUND:mflux training entrypoint not found "
- "(neither mflux.dreambooth module nor mflux-train script) — "
- "update mflux via scripts/setup-image-video.sh",
+ "USER_ERROR:MODULE_NOT_FOUND:mflux trainer not found (no mflux-train script and no "
+ "mflux.models.common.cli.train module) — update mflux to ≥0.17",
file=sys.stderr, flush=True,
)
sys.exit(2)
- cmd = [str(console), "--train-config", config_path]
+ cmd = [sys.executable, "-m", "mflux.models.common.cli.train"]
if resume:
- cmd += ["--resume-checkpoint", resume]
+ cmd += ["--resume", resume]
+ else:
+ cmd += ["--config", config_path]
return cmd
-# mflux progress lines vary by version — try, in order:
-# "... step 12/400 ... loss: 0.123" / "Step 12/400, loss=0.123"
-# "Epoch 3/100 ... loss 0.123" (epoch-relative; scaled by --total-steps)
-STEP_RES = [
- re.compile(r"[Ss]teps?[\s:=]+(\d+)\s*/\s*(\d+).*?[Ll]oss[\s:=]+([\d.eE+-]+)"),
- re.compile(r"(\d+)\s*/\s*(\d+).*?[Ll]oss[\s:=]+([\d.eE+-]+)"),
-]
-EPOCH_RE = re.compile(r"[Ee]poch[\s:=]+(\d+)\s*/\s*(\d+)")
+# tqdm renders like ` 3%|▎ | 12/400 [00:30<16:20, 2.53s/it]`.
+TQDM_RE = re.compile(r"(\d+)\s*/\s*(\d+)\s*\[")
+# Belt-and-suspenders for any explicit "step N/M ... loss X" prose a future
+# mflux version might print.
+STEP_LOSS_RE = re.compile(r"[Ss]teps?[\s:=]+(\d+)\s*/\s*(\d+).*?[Ll]oss[\s:=]+([\d.eE+-]+)")
NOISE_RE = re.compile(r"FutureWarning|UserWarning|DeprecationWarning", re.I)
+def resolve_mflux_output(configured: Path) -> Path:
+ """mflux appends `_YYYYMMDD_HHMMSS` to checkpoint.output_path when the
+ configured dir already exists (its new-run-folder behavior) — a killed
+ previous attempt leaving the dir behind is enough to trigger it. Pick
+ the newest candidate among the configured path and its timestamped
+ siblings so the watcher + adapter discovery track where mflux actually
+ wrote."""
+ candidates = [p for p in [configured, *configured.parent.glob(f"{configured.name}_2*")] if p.is_dir()]
+ if not candidates:
+ return configured
+ return max(candidates, key=lambda p: p.stat().st_mtime)
+
+
class ArtifactWatcher(threading.Thread):
- """Poll the checkpoints dir for new checkpoint files + validation PNGs.
- PNGs copy into samples/ so the server's sample route can serve them."""
+ """Poll mflux's output dir: new checkpoint zips → CHECKPOINT lines; new
+ preview PNGs → copied into the run's samples/ (where the server's
+ sample route serves from) + SAMPLE lines. The output dir is re-resolved
+ each scan — it may materialize (possibly timestamp-suffixed) only after
+ mflux finishes loading the model."""
- def __init__(self, checkpoints_dir: Path, samples_dir: Path, get_step):
+ def __init__(self, configured_output: Path, samples_dir: Path, get_step):
super().__init__(daemon=True)
- self.checkpoints_dir = checkpoints_dir
+ self.configured_output = configured_output
self.samples_dir = samples_dir
self.get_step = get_step
self.seen = set()
self.stop_event = threading.Event()
def scan(self):
- if not self.checkpoints_dir.exists():
- return
- for f in sorted(self.checkpoints_dir.rglob("*")):
- if not f.is_file() or f in self.seen:
+ output = resolve_mflux_output(self.configured_output)
+ checkpoints_dir = output / "checkpoints"
+ preview_dir = output / "preview"
+ for f in sorted(checkpoints_dir.glob("*.zip")) if checkpoints_dir.exists() else []:
+ if f in self.seen:
+ continue
+ self.seen.add(f)
+ log(f"CHECKPOINT:{f}:{self.get_step()}")
+ for f in sorted(preview_dir.glob("*.png")) if preview_dir.exists() else []:
+ if f in self.seen:
continue
self.seen.add(f)
- step = self.get_step()
- if f.suffix in (".zip", ".safetensors") and "checkpoint" in f.name.lower() or f.suffix == ".zip":
- log(f"CHECKPOINT:{f}:{step}")
- elif f.suffix == ".png":
- dest = self.samples_dir / f"step-{step:06d}-{f.name}"
- try:
- shutil.copyfile(f, dest)
- log(f"SAMPLE:{dest}:{step}")
- except OSError as err:
- log(f"STATUS:sample copy failed: {err}")
+ dest = self.samples_dir / f.name
+ try:
+ shutil.copyfile(f, dest)
+ log(f"SAMPLE:{dest}:{self.get_step()}")
+ except OSError as err:
+ log(f"STATUS:sample copy failed: {err}")
def run(self):
while not self.stop_event.wait(5.0):
self.scan()
- self.scan() # final sweep
+ self.scan() # final sweep after the child exits
def find_adapter(checkpoints_dir: Path, output_dir: Path) -> Path | None:
- """Newest adapter .safetensors — direct file first, else extract from
- the newest checkpoint zip."""
- direct = sorted(checkpoints_dir.rglob("*.safetensors"), key=lambda f: f.stat().st_mtime)
- if direct:
- return direct[-1]
- zips = sorted(checkpoints_dir.rglob("*.zip"), key=lambda f: f.stat().st_mtime)
+ """Extract the lora adapter (`*_adapter.safetensors`, NOT the optimizer
+ state) from the newest checkpoint zip."""
+ zips = sorted(checkpoints_dir.glob("*.zip"), key=lambda f: f.stat().st_mtime)
for z in reversed(zips):
with zipfile.ZipFile(z) as zf:
- members = [m for m in zf.namelist() if m.endswith(".safetensors")]
+ members = [m for m in zf.namelist()
+ if m.endswith("_adapter.safetensors") and "optimizer" not in m]
if not members:
continue
extract_dir = output_dir / "adapter"
extract_dir.mkdir(parents=True, exist_ok=True)
- zf.extract(members[0], extract_dir)
- return extract_dir / members[0]
+ zf.extract(members[-1], extract_dir)
+ return extract_dir / members[-1]
return None
+def stream_lines(pipe):
+ """Yield logical lines split on BOTH \\n and \\r — tqdm redraws its bar
+ with carriage returns, so newline-only iteration would buffer the whole
+ bar until completion."""
+ buf = ""
+ while True:
+ chunk = pipe.read(256)
+ if not chunk:
+ if buf:
+ yield buf
+ return
+ buf += chunk
+ while True:
+ cut = min((i for i in (buf.find("\n"), buf.find("\r")) if i >= 0), default=-1)
+ if cut < 0:
+ break
+ yield buf[:cut]
+ buf = buf[cut + 1:]
+
+
def main():
global CHILD
args = parse_args()
output_dir = Path(args.output_dir)
samples_dir = output_dir / "samples"
samples_dir.mkdir(parents=True, exist_ok=True)
- config = json.loads(Path(args.train_config).read_text())
- checkpoints_dir = Path(config.get("save", {}).get("output_path") or (output_dir / "checkpoints"))
- checkpoints_dir.mkdir(parents=True, exist_ok=True)
+ config = json.loads(Path(args.config).read_text())
+ configured_output = Path(config["checkpoint"]["output_path"])
- total_steps = max(1, args.total_steps)
- state = {"step": 0, "loss": None}
+ state = {"step": 0, "total": max(1, args.total_steps), "loss": None}
+ last_reported = {"step": -1}
- watcher = ArtifactWatcher(checkpoints_dir, samples_dir, lambda: state["step"])
+ watcher = ArtifactWatcher(configured_output, samples_dir, lambda: state["step"])
watcher.start()
- cmd = build_command(args.train_config, args.resume_checkpoint)
+ cmd = build_command(args.config, args.resume_checkpoint)
log("STAGE:load-model")
- log(f"STATUS:launching {' '.join(Path(cmd[0]).name if i == 0 else c for i, c in enumerate(cmd))}")
+ log(f"STATUS:launching {Path(cmd[0]).name}")
CHILD = subprocess.Popen(
- cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1,
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
)
if STOP_REQUESTED: # SIGTERM raced the spawn
CHILD.terminate()
in_training = False
- for raw in CHILD.stdout:
- line = raw.rstrip("\n")
- if not line.strip() or NOISE_RE.search(line):
+ for raw in stream_lines(CHILD.stdout):
+ line = raw.strip()
+ if not line or NOISE_RE.search(line):
continue
- matched = False
- for step_re in STEP_RES:
- m = step_re.search(line)
- if m:
- cur, total = int(m.group(1)), int(m.group(2))
- # mflux totals can be epoch-relative; trust them when they
- # look like our budget, else scale into --total-steps space.
- if total != total_steps and total > 0:
- cur = round(cur / total * total_steps)
- total = total_steps
- state["step"] = cur
- try:
- state["loss"] = float(m.group(3))
- except ValueError:
- pass
+ m = STEP_LOSS_RE.search(line) or TQDM_RE.search(line)
+ if m:
+ cur, total = int(m.group(1)), int(m.group(2))
+ if total > 0 and cur >= 0:
+ state["step"], state["total"] = cur, total
+ if m.lastindex and m.lastindex >= 3:
+ try:
+ state["loss"] = float(m.group(3))
+ except ValueError:
+ pass
if not in_training:
in_training = True
log("STAGE:training")
- log(f"STEP:{cur}:{total}:{state['loss'] if state['loss'] is not None else 'nan'}")
- matched = True
- break
- if matched:
- continue
-
- em = EPOCH_RE.search(line)
- if em:
- if not in_training:
- in_training = True
- log("STAGE:training")
- log(f"STATUS:epoch {em.group(1)}/{em.group(2)}")
+ # tqdm redraws constantly at the same step — only emit on change.
+ if cur != last_reported["step"]:
+ last_reported["step"] = cur
+ log(f"STEP:{cur}:{total}:{state['loss'] if state['loss'] is not None else 'nan'}")
continue
# Forward everything else (truncated) — keeps the JS idle watchdog
- # fed during model load/quantize phases and aids debugging.
+ # fed during model download/load phases and aids debugging.
log(f"STATUS:{line[:300]}")
code = CHILD.wait()
@@ -226,23 +251,24 @@ def main():
watcher.join(timeout=10)
if STOP_REQUESTED:
- log("STATUS:canceled-checkpoint-saved" if state["step"] else "STATUS:canceled")
+ log("STATUS:canceled — last saved checkpoint retained")
sys.exit(143)
if code != 0:
print(f"❌ mflux trainer exited with code {code}", file=sys.stderr, flush=True)
sys.exit(code or 1)
+ checkpoints_dir = resolve_mflux_output(configured_output) / "checkpoints"
adapter = find_adapter(checkpoints_dir, output_dir)
if not adapter:
print(
- "USER_ERROR:TRAINING_FAILED:mflux finished but no adapter .safetensors found under "
+ "USER_ERROR:TRAINING_FAILED:mflux finished but no *_adapter.safetensors found in "
f"{checkpoints_dir}", file=sys.stderr, flush=True,
)
sys.exit(1)
log("RESULT:" + json.dumps({
"adapter_path": str(adapter),
- "steps": state["step"] or total_steps,
+ "steps": state["step"] or args.total_steps,
"final_loss": state["loss"],
}))
diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.js
index 53a91459a5..219a2420b7 100644
--- a/server/routes/loraTraining.js
+++ b/server/routes/loraTraining.js
@@ -19,6 +19,7 @@ import { attachSseClient, cancelJob } from '../services/mediaJobQueue/index.js';
import {
deleteRun,
getRunRequired,
+ isMfluxTrainAvailable,
listRuns,
runDir,
runSamplesDir,
@@ -29,15 +30,17 @@ import { deleteLora } from '../services/loras.js';
const router = Router();
-// Runtime readiness + defaults — drives the launch panel's enable/disable
-// state and the params form's initial values.
+// Engine readiness + defaults — drives the launch panel's enable/disable
+// state and the params form's initial values. Both engines train FLUX.2
+// Klein LoRAs; mflux (MLX-native) is preferred when its trainer ships
+// with the user's install, the torch venv is the fallback.
router.get('/status', asyncHandler(async (_req, res) => {
const settings = await getSettings();
const mfluxPython = settings?.imageGen?.local?.pythonPath || null;
const flux2Python = resolveFlux2Python();
res.json({
runtimes: {
- mflux: { ready: !!mfluxPython, pythonPath: mfluxPython },
+ mflux: { ready: isMfluxTrainAvailable(mfluxPython), pythonPath: mfluxPython },
flux2: { ready: !!flux2Python && await isFlux2VenvHealthy(), venvPython: flux2Python },
},
defaults: { ...TRAINING_DEFAULTS, ...(settings?.loraTraining?.defaults || {}) },
diff --git a/server/services/backup.js b/server/services/backup.js
index 834e6db0d6..224b276028 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -44,8 +44,12 @@ export const DEFAULT_EXCLUDES = [
{ path: '/cos/worktrees/', reason: 'Ephemeral agent git worktrees — recreated on demand', overridable: false },
{ path: '/cos/feature-agents/*/worktree/', reason: 'Per-feature-agent git worktrees — recreated on demand', overridable: false },
{ path: '/loras/*.safetensors', reason: 'LoRA adapter weight files — large, re-downloadable. .metadata.json sidecars (Civitai metadata, user-editable name/notes) ARE backed up.', overridable: true },
- { path: '/training-runs/*/checkpoints/', reason: 'LoRA training checkpoints — large intermediate adapter state, resumable-but-regenerable. Final trained adapters land in data/loras/ (weights excluded there too); run samples + configs ARE backed up.', overridable: true },
+ // `**` (not `*`) so both engines' checkpoint dirs match: the torch trainer
+ // writes training-runs/<id>/checkpoints/, mflux writes
+ // training-runs/<id>/mflux/checkpoints/.
+ { path: '/training-runs/**/checkpoints/', reason: 'LoRA training checkpoints — large intermediate adapter state, resumable-but-regenerable. Final trained adapters land in data/loras/ (weights excluded there too); run samples + configs ARE backed up.', overridable: true },
{ path: '/training-runs/*/cache/', reason: 'Precomputed latent/text-embedding training cache — regenerated from the dataset on the next run', overridable: false },
+ { path: '/training-runs/*/data/.mflux_cache/', reason: 'mflux low_ram disk-backed encode cache (written inside the staged training data dir) — regenerable', overridable: false },
{ path: '/repos/', reason: 'Cloned git repositories — large, re-cloneable from origin', overridable: true },
{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },
{ path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true }
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 05f84a7c5b..4b3bafca14 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -14,9 +14,10 @@
*/
import { spawn } from 'child_process';
+import { existsSync } from 'fs';
import { copyFile, mkdir, stat, writeFile } from 'fs/promises';
-import { join, basename } from 'path';
-import { platform } from 'os';
+import { join, basename, dirname } from 'path';
+import { platform, totalmem } from 'os';
import { PATHS, ensureDir, atomicWrite, shortId } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { v4 as uuidv4 } from '../../lib/uuid.js';
@@ -53,6 +54,15 @@ const TRAINER_SCRIPTS = {
export const runDir = (runId) => join(PATHS.trainingRuns, runId);
export const runSamplesDir = (runId) => join(runDir(runId), 'samples');
+/**
+ * mflux ships its trainer as the `mflux-train` console script — probe for
+ * it next to the configured local-image-gen python (e.g.
+ * /opt/miniconda3/bin/python3 → /opt/miniconda3/bin/mflux-train). Present
+ * only on mflux ≥0.17 installs.
+ */
+export const isMfluxTrainAvailable = (pythonPath) =>
+ !!pythonPath && existsSync(join(dirname(pythonPath), 'mflux-train'));
+
// GPU lane serializes training with renders, so at most one trainer child
// exists at a time. Keyed by jobId anyway so a stale cancel can't kill a
// newer run.
@@ -87,25 +97,22 @@ const mergeParams = (settings, requestParams = {}) => ({
* `{ runId, jobId, position }` (202-shaped).
*/
export async function startTrainingRun({ datasetId, baseModelId, name = null, params = {} }) {
- const routing = resolveTrainingRuntime(baseModelId, getImageModels());
- const { dataset } = await validateDatasetReady(datasetId);
const settings = await getSettings();
+ const pythonPath = settings?.imageGen?.local?.pythonPath || null;
+ // Engine pick: prefer mflux's MLX trainer when the user's mflux install
+ // ships it (Apple Silicon native, no second venv); fall back to the
+ // torch/diffusers trainer in venv-flux2.
+ const mlxAvailable = isMfluxTrainAvailable(pythonPath);
+ const routing = resolveTrainingRuntime(baseModelId, getImageModels(), { mlxAvailable });
+ const { dataset } = await validateDatasetReady(datasetId);
- let pythonPath = null;
if (routing.runtime === TRAINING_RUNTIMES.FLUX2) {
const healthy = await isFlux2VenvHealthy();
if (!healthy) {
throw new ServerError(
- 'FLUX.2 python environment is not ready — run `bash scripts/setup-image-video.sh` (FLUX.2 option) first',
- { status: 412, code: 'FLUX2_VENV_MISSING' },
- );
- }
- } else {
- pythonPath = settings?.imageGen?.local?.pythonPath || null;
- if (!pythonPath) {
- throw new ServerError(
- 'mflux python environment is not configured — set Settings → Image Gen → Local python path (or run `bash scripts/setup-image-video.sh`)',
- { status: 412, code: 'MFLUX_VENV_MISSING' },
+ 'No training engine available — install mflux ≥0.17 in your local image-gen python (Settings → Image Gen) '
+ + 'or set up the FLUX.2 venv via `bash scripts/setup-image-video.sh`',
+ { status: 412, code: 'TRAINING_ENGINE_MISSING' },
);
}
}
@@ -120,6 +127,7 @@ export async function startTrainingRun({ datasetId, baseModelId, name = null, pa
baseModelId,
fluxVariant: routing.variant,
trainRepo: routing.trainRepo,
+ mfluxModel: routing.mfluxModel,
name: name || null,
character: dataset.character,
datasetId,
@@ -230,17 +238,39 @@ export async function runTraining({ jobId, runId, pythonPath = null }) {
});
} else {
bin = pythonPath;
- if (!bin) {
- await runsDb.updateRun(runId, { status: 'failed', error: 'mflux python path not configured' }).catch(() => {});
- return fail('mflux python path not configured — set it in Settings → Image Gen');
+ if (!bin || !isMfluxTrainAvailable(bin)) {
+ await runsDb.updateRun(runId, { status: 'failed', error: 'mflux trainer not available' }).catch(() => {});
+ return fail('mflux-train not found next to the configured python — update mflux (≥0.17) or set up the FLUX.2 venv');
+ }
+ // Stage the dataset in mflux's auto-discovery layout: NNNN.png +
+ // NNNN.txt caption pairs, plus preview_1.txt for the periodic sample
+ // render. mflux resolves everything from the config's `data` dir.
+ const dataDir = join(dir, 'data');
+ await mkdir(dataDir, { recursive: true });
+ for (let i = 0; i < manifest.images.length; i += 1) {
+ const stem = String(i + 1).padStart(4, '0');
+ await copyFile(manifest.images[i].path, join(dataDir, `${stem}.png`));
+ await writeFile(join(dataDir, `${stem}.txt`), `${manifest.images[i].caption}\n`);
}
+ if ((run.params?.sampleEvery ?? TRAINING_DEFAULTS.sampleEvery) > 0) {
+ const samplePrompt = run.params?.samplePrompt || `${run.triggerWord} portrait, neutral background`;
+ await writeFile(join(dataDir, 'preview_1.txt'), `${samplePrompt}\n`);
+ }
+ // output_path must NOT pre-exist — mflux appends a timestamp suffix to
+ // an existing dir (its new_folder behavior), which would break the
+ // wrapper's artifact watcher. mflux creates checkpoints/ + preview/
+ // (+ loss/) inside it.
+ const mfluxOutputDir = join(dir, 'mflux');
const config = buildMfluxTrainConfig({
params: run.params,
- triggerWord: run.triggerWord,
- samplePrompt: run.params?.samplePrompt || null,
- datasetImagesDir: manifest.imagesDir,
- manifestImages: manifest.images,
- checkpointsDir,
+ variant: run.fluxVariant,
+ mfluxModel: run.mfluxModel,
+ dataDir,
+ imageCount: manifest.images.length,
+ outputDir: mfluxOutputDir,
+ // Memory-derived quantize/low_ram (see deriveMfluxMemoryConfig) —
+ // a bf16 base + in-RAM latent cache OOM-killed a 48 GB machine.
+ totalMemGb: totalmem() / 2 ** 30,
});
const configPath = join(dir, 'mflux-train.json');
await atomicWrite(configPath, config);
diff --git a/server/services/loraTraining/runtimes.js b/server/services/loraTraining/runtimes.js
index 5e9fe9fa14..05b523df29 100644
--- a/server/services/loraTraining/runtimes.js
+++ b/server/services/loraTraining/runtimes.js
@@ -1,21 +1,28 @@
/**
* LoRA training runtime routing + argument/config builders. Pure — no I/O.
*
- * Two runtimes ship:
- * - 'mflux' — FLUX.1-dev MLX training via mflux's own dreambooth CLI,
- * wrapped by scripts/train_mflux_lora.py (runs in the user's mflux venv,
- * the same python the image renders use).
- * - 'flux2' — FLUX.2 Klein diffusers+peft training via the vendored
- * scripts/train_flux2_lora.py (runs in ~/.portos/venv-flux2).
+ * Both runtimes train FLUX.2 Klein character LoRAs; they are two ENGINES
+ * for the same output (verified against mflux 0.17.5, which removed
+ * FLUX.1 training entirely):
*
- * FLUX.2 training ALWAYS targets the bf16 base repos — never the SDNQ/int8
- * quantized inference repos (no useful gradients through quant layers). The
- * trained LoRA still loads onto quantized pipelines of the same size
- * variant because the transformer hidden dims match.
+ * - 'mflux' — MLX-native training via mflux's `mflux-train` CLI,
+ * wrapped by scripts/train_mflux_lora.py. Preferred on Apple Silicon
+ * when the user's mflux install ships the trainer. Trains the
+ * non-distilled `flux2-klein-base-{4b,9b}` models (mflux's documented
+ * recommendation) and exports adapters with diffusers-style key
+ * naming (`transformer.transformer_blocks.N...lora_A.weight`), so
+ * the result loads in PortOS's diffusers-based flux2 renderer.
+ * - 'flux2' — torch/diffusers+peft training via the vendored
+ * scripts/train_flux2_lora.py in ~/.portos/venv-flux2. The fallback
+ * when mflux's trainer is unavailable (non-Darwin installs, older
+ * mflux). Trains against the bf16 base repos.
+ *
+ * Either way the trained LoRA is gated to its size variant via the
+ * `flux2-4b` / `flux2-9b` compat key (hidden dims differ between sizes).
*/
import { ServerError } from '../../lib/errorHandler.js';
-import { RUNNER_FAMILIES, isFlux2, flux2VariantFromModel } from '../../lib/runners.js';
+import { isFlux2, flux2VariantFromModel } from '../../lib/runners.js';
export const TRAINING_RUNTIMES = Object.freeze({ MFLUX: 'mflux', FLUX2: 'flux2' });
@@ -28,107 +35,166 @@ export const TRAINING_DEFAULTS = Object.freeze({
sampleEvery: 250,
});
-// bf16 training bases per FLUX.2 size variant. Inference may run quantized
-// repos; training resolves to these regardless of which flux2-* model id
-// the user picked.
+// bf16 training bases per FLUX.2 size variant (torch runtime). Inference
+// may run quantized repos; training resolves to these regardless of which
+// flux2-* model id the user picked.
export const FLUX2_TRAIN_REPOS = Object.freeze({
'4b': 'black-forest-labs/FLUX.2-klein-4B',
'9b': 'black-forest-labs/FLUX.2-klein-9B',
});
+// mflux model ids per size variant. mflux's flux2 README recommends the
+// non-distilled base models for training; the resulting adapter applies to
+// the distilled inference models of the same size (identical module names
+// and hidden dims).
+export const MFLUX_TRAIN_MODELS = Object.freeze({
+ '4b': 'flux2-klein-base-4b',
+ '9b': 'flux2-klein-base-9b',
+});
+
+// Noise-schedule shape for mflux base-model training — mirrors the official
+// flux2 README example (steps 40, guidance 1.0, train the high-noise window
+// [25, 40)). These are INFERENCE-schedule steps, distinct from the training
+// duration (num_epochs × images).
+const MFLUX_SCHED = Object.freeze({ steps: 40, guidance: 1.0, timestepLow: 25, timestepHigh: 40 });
+
+/**
+ * Memory-derived training knobs — mirrors the FFLF pixel-budget pattern
+ * (videoGen/local.js): pure, with total RAM injected by the caller.
+ * Training a bf16 base + in-RAM latent cache OOM-killed a 48 GB machine
+ * during verification, so anything under 96 GB trains QLoRA-style against
+ * an on-the-fly-quantized base, and under 64 GB also spills the encoded
+ * dataset cache to disk (`low_ram`). Quantizing the FROZEN base is the
+ * standard QLoRA recipe — the LoRA weights themselves stay full precision.
+ */
+export function deriveMfluxMemoryConfig(totalMemGb) {
+ const gb = Number.isFinite(totalMemGb) ? totalMemGb : 0; // unknown → most conservative
+ if (gb >= 96) return { quantize: null, low_ram: false };
+ if (gb >= 64) return { quantize: 8, low_ram: false };
+ return { quantize: 4, low_ram: true };
+}
+
/**
- * Resolve which training runtime a base model id routes to. `models` is the
- * getImageModels() registry (injected so this stays pure/testable).
+ * Resolve the runtime + repos for a base model id. `models` is the
+ * getImageModels() registry; `mlxAvailable` says whether the user's mflux
+ * install ships `mflux-train` (probed by the caller — this stays pure).
*/
-export function resolveTrainingRuntime(baseModelId, models) {
+export function resolveTrainingRuntime(baseModelId, models, { mlxAvailable = false } = {}) {
const entry = (models || []).find((m) => m.id === baseModelId);
if (!entry) {
throw new ServerError(`Unknown image model: ${baseModelId}`, {
status: 400, code: 'TRAINING_UNSUPPORTED_MODEL',
});
}
- if (isFlux2(entry)) {
- const variant = flux2VariantFromModel(entry);
- if (!variant || !FLUX2_TRAIN_REPOS[variant]) {
- throw new ServerError(
- `Cannot determine FLUX.2 size variant for ${baseModelId} — training needs a klein-4B/9B model`,
- { status: 400, code: 'TRAINING_UNSUPPORTED_MODEL' },
- );
- }
- return { runtime: TRAINING_RUNTIMES.FLUX2, entry, variant, trainRepo: FLUX2_TRAIN_REPOS[variant] };
+ if (!isFlux2(entry)) {
+ // mflux ≥0.17 removed FLUX.1 training ("Flux1 training is no longer
+ // supported"), so dev/schnell and the diffusers families are all out.
+ throw new ServerError(
+ `LoRA training supports FLUX.2 Klein models only — not ${baseModelId}`,
+ { status: 400, code: 'TRAINING_UNSUPPORTED_MODEL' },
+ );
}
- // mflux family (no `runner` field). Only FLUX.1-dev trains — schnell is
- // guidance-distilled and not a supported mflux fine-tune target.
- if (!entry.runner && entry.id === 'dev') {
- return { runtime: TRAINING_RUNTIMES.MFLUX, entry, variant: null, trainRepo: null };
+ const variant = flux2VariantFromModel(entry);
+ if (!variant || !FLUX2_TRAIN_REPOS[variant]) {
+ throw new ServerError(
+ `Cannot determine FLUX.2 size variant for ${baseModelId} — training needs a klein-4B/9B model`,
+ { status: 400, code: 'TRAINING_UNSUPPORTED_MODEL' },
+ );
}
- throw new ServerError(
- `LoRA training supports FLUX.1-dev (mflux) and FLUX.2 Klein (flux2) — not ${baseModelId}`,
- { status: 400, code: 'TRAINING_UNSUPPORTED_MODEL' },
- );
+ return {
+ runtime: mlxAvailable ? TRAINING_RUNTIMES.MFLUX : TRAINING_RUNTIMES.FLUX2,
+ entry,
+ variant,
+ trainRepo: FLUX2_TRAIN_REPOS[variant],
+ mfluxModel: MFLUX_TRAIN_MODELS[variant],
+ };
}
-/** Runner family stamped into the trained LoRA's sidecar per runtime. */
-export const runnerFamilyForRuntime = (runtime) =>
- (runtime === TRAINING_RUNTIMES.FLUX2 ? RUNNER_FAMILIES.FLUX2 : RUNNER_FAMILIES.MFLUX);
-
const mergedParams = (params = {}) => ({ ...TRAINING_DEFAULTS, ...params });
+// The full attention + feed-forward target set from mflux's flux2 training
+// README, parameterized by rank and the variant's block counts. Klein 4B:
+// 5 double + 20 single blocks; 9B: 8 double + 24 single (counts from the
+// model configs; an over-long range would throw at injection, so these are
+// pinned per variant).
+const FLUX2_BLOCK_COUNTS = Object.freeze({
+ '4b': { double: 5, single: 20 },
+ '9b': { double: 8, single: 24 },
+});
+
+export function buildMfluxLoraTargets(variant, rank) {
+ const counts = FLUX2_BLOCK_COUNTS[variant] || FLUX2_BLOCK_COUNTS['4b'];
+ const doubleRange = { start: 0, end: counts.double };
+ const singleRange = { start: 0, end: counts.single };
+ const doublePaths = [
+ 'attn.to_q', 'attn.to_k', 'attn.to_v', 'attn.to_out',
+ 'attn.add_q_proj', 'attn.add_k_proj', 'attn.add_v_proj', 'attn.to_add_out',
+ 'ff.linear_in', 'ff.linear_out', 'ff_context.linear_in', 'ff_context.linear_out',
+ ];
+ const singlePaths = ['attn.to_qkv_mlp_proj', 'attn.to_out'];
+ return [
+ ...doublePaths.map((p) => ({ module_path: `transformer_blocks.{block}.${p}`, blocks: doubleRange, rank })),
+ ...singlePaths.map((p) => ({ module_path: `single_transformer_blocks.{block}.${p}`, blocks: singleRange, rank })),
+ ];
+}
+
/**
- * Build the mflux dreambooth train-config JSON. The wrapper script hands
- * this to `python -m mflux.dreambooth --train-config <file>`. mflux trains
- * in epochs over the example set; we translate the requested step budget
- * into epochs (steps / images, min 1) so "steps" means the same thing
- * across both runtimes. Shape follows mflux's documented dreambooth config;
- * the wrapper tolerates unknown-key errors by surfacing mflux's own
- * message (USER_ERROR) rather than guessing.
+ * Build the mflux-train config JSON (mflux ≥0.17 schema — verified against
+ * TrainingSpec.from_conf). Captions are NOT in the config: mflux
+ * auto-discovers `NNNN.png` + `NNNN.txt` pairs under `data`, and preview
+ * prompts come from `data/preview*.txt` — the run-staging step lays those
+ * files out. "steps" in OUR params means total training iterations; mflux
+ * counts epochs over the example set, so we translate.
*/
export function buildMfluxTrainConfig({
params = {},
- triggerWord,
- samplePrompt = null,
- datasetImagesDir,
- manifestImages = [],
- checkpointsDir,
+ variant,
+ mfluxModel,
+ dataDir,
+ imageCount,
+ outputDir,
+ totalMemGb = null,
}) {
const p = mergedParams(params);
- if (!manifestImages.length) {
+ if (!Number.isInteger(imageCount) || imageCount < 1) {
throw new ServerError('mflux train config needs at least one example image', {
status: 400, code: 'VALIDATION_ERROR',
});
}
const totalSteps = p.steps;
- const epochs = Math.max(1, Math.round(totalSteps / manifestImages.length));
+ const epochs = Math.max(1, Math.round(totalSteps / imageCount));
+ // save_frequency must be > 0; 0/absent checkpointEvery → only the final
+ // save (frequency = total).
+ const saveFrequency = p.checkpointEvery > 0 ? p.checkpointEvery : totalSteps;
+ const memory = deriveMfluxMemoryConfig(totalMemGb);
return {
- model: 'dev',
+ model: mfluxModel,
+ data: dataDir,
seed: Number.isInteger(p.seed) ? p.seed : 42,
- steps: 20,
- guidance: 3.0,
- quantize: null,
- width: p.resolution,
- height: p.resolution,
- training_loop: { num_epochs: epochs, batch_size: 1 },
- optimizer: { name: 'AdamW', learning_rate: p.learningRate },
- save: {
- output_path: checkpointsDir,
- checkpoint_frequency: p.checkpointEvery > 0 ? p.checkpointEvery : totalSteps,
- },
- instrumentation: {
- plot_frequency: 0,
- generate_image_frequency: p.sampleEvery > 0 ? p.sampleEvery : 0,
- validation_prompt: samplePrompt || `${triggerWord} portrait, neutral background`,
+ steps: MFLUX_SCHED.steps,
+ guidance: MFLUX_SCHED.guidance,
+ quantize: memory.quantize,
+ max_resolution: p.resolution,
+ low_ram: memory.low_ram,
+ training_loop: {
+ num_epochs: epochs,
+ batch_size: 1,
+ timestep_low: MFLUX_SCHED.timestepLow,
+ timestep_high: MFLUX_SCHED.timestepHigh,
},
- lora_layers: {
- transformer_blocks: {
- block_range: { start: 0, end: 19 },
- layer_types: ['attn.to_q', 'attn.to_k', 'attn.to_v', 'attn.to_out'],
- lora_rank: p.rank,
+ optimizer: { name: 'AdamW', learning_rate: p.learningRate },
+ checkpoint: { save_frequency: saveFrequency, output_path: outputDir },
+ // monitoring omitted entirely when samples are off — mflux treats the
+ // whole block as optional and skips previews/plots without it.
+ ...(p.sampleEvery > 0 ? {
+ monitoring: {
+ preview_width: p.resolution,
+ preview_height: p.resolution,
+ plot_frequency: p.sampleEvery,
+ generate_image_frequency: p.sampleEvery,
},
- },
- examples: {
- path: datasetImagesDir,
- images: manifestImages.map((img) => ({ image: img.file, prompt: img.caption })),
- },
+ } : {}),
+ lora_layers: { targets: buildMfluxLoraTargets(variant, p.rank) },
};
}
@@ -136,7 +202,7 @@ export function buildMfluxTrainConfig({
export function buildMfluxTrainArgs({ scriptPath, configPath, runDir, totalSteps, resumeCheckpoint = null }) {
const args = [
scriptPath,
- '--train-config', configPath,
+ '--config', configPath,
'--output-dir', runDir,
'--total-steps', String(totalSteps),
];
@@ -144,7 +210,7 @@ export function buildMfluxTrainArgs({ scriptPath, configPath, runDir, totalSteps
return args;
}
-/** Argv for the vendored FLUX.2 trainer. */
+/** Argv for the vendored torch FLUX.2 trainer. */
export function buildFlux2TrainArgs({
scriptPath,
trainRepo,
diff --git a/server/services/loraTraining/runtimes.test.js b/server/services/loraTraining/runtimes.test.js
index f60acf6d99..995f359ffb 100644
--- a/server/services/loraTraining/runtimes.test.js
+++ b/server/services/loraTraining/runtimes.test.js
@@ -2,10 +2,11 @@ import { describe, it, expect } from 'vitest';
import {
TRAINING_DEFAULTS,
buildFlux2TrainArgs,
+ buildMfluxLoraTargets,
buildMfluxTrainArgs,
buildMfluxTrainConfig,
+ deriveMfluxMemoryConfig,
resolveTrainingRuntime,
- runnerFamilyForRuntime,
} from './runtimes.js';
const MODELS = [
@@ -17,68 +18,99 @@ const MODELS = [
];
describe('resolveTrainingRuntime', () => {
- it('routes dev to mflux', () => {
- const out = resolveTrainingRuntime('dev', MODELS);
+ it('routes flux2 models to mflux when its trainer is available', () => {
+ const out = resolveTrainingRuntime('flux2-klein-4b', MODELS, { mlxAvailable: true });
expect(out.runtime).toBe('mflux');
- expect(out.trainRepo).toBeNull();
+ expect(out.mfluxModel).toBe('flux2-klein-base-4b');
+ expect(out.trainRepo).toBe('black-forest-labs/FLUX.2-klein-4B');
+ expect(out.variant).toBe('4b');
});
- it('routes flux2 models to the bf16 train repo for their variant', () => {
- expect(resolveTrainingRuntime('flux2-klein-4b', MODELS).trainRepo)
- .toBe('black-forest-labs/FLUX.2-klein-4B');
- expect(resolveTrainingRuntime('flux2-klein-9b-bf16', MODELS).trainRepo)
- .toBe('black-forest-labs/FLUX.2-klein-9B');
+ it('falls back to the torch runtime without mflux', () => {
+ const out = resolveTrainingRuntime('flux2-klein-9b-bf16', MODELS, { mlxAvailable: false });
+ expect(out.runtime).toBe('flux2');
+ expect(out.mfluxModel).toBe('flux2-klein-base-9b');
+ expect(out.trainRepo).toBe('black-forest-labs/FLUX.2-klein-9B');
});
- it('rejects schnell, diffusers families, and unknown ids', () => {
- expect(() => resolveTrainingRuntime('schnell', MODELS)).toThrow(/training supports/);
- expect(() => resolveTrainingRuntime('z-image-turbo', MODELS)).toThrow(/training supports/);
+ it('rejects FLUX.1 (training removed upstream), diffusers families, and unknown ids', () => {
+ expect(() => resolveTrainingRuntime('dev', MODELS)).toThrow(/FLUX\.2 Klein models only/);
+ expect(() => resolveTrainingRuntime('schnell', MODELS)).toThrow(/FLUX\.2 Klein models only/);
+ expect(() => resolveTrainingRuntime('z-image-turbo', MODELS)).toThrow(/FLUX\.2 Klein models only/);
expect(() => resolveTrainingRuntime('ghost', MODELS)).toThrow(/Unknown image model/);
});
+});
- it('maps runtimes to runner families', () => {
- expect(runnerFamilyForRuntime('mflux')).toBe('mflux');
- expect(runnerFamilyForRuntime('flux2')).toBe('flux2');
+describe('buildMfluxLoraTargets', () => {
+ it('pins block ranges per size variant (4b: 5+20, 9b: 8+24)', () => {
+ const t4 = buildMfluxLoraTargets('4b', 16);
+ const double4 = t4.find((t) => t.module_path === 'transformer_blocks.{block}.attn.to_q');
+ const single4 = t4.find((t) => t.module_path === 'single_transformer_blocks.{block}.attn.to_qkv_mlp_proj');
+ expect(double4.blocks).toEqual({ start: 0, end: 5 });
+ expect(single4.blocks).toEqual({ start: 0, end: 20 });
+ const t9 = buildMfluxLoraTargets('9b', 8);
+ expect(t9.find((t) => t.module_path.startsWith('transformer_blocks')).blocks.end).toBe(8);
+ expect(t9.find((t) => t.module_path.startsWith('single_transformer_blocks')).blocks.end).toBe(24);
+ expect(t9.every((t) => t.rank === 8)).toBe(true);
});
});
describe('buildMfluxTrainConfig', () => {
const base = {
- triggerWord: 'kessa',
- datasetImagesDir: '/data/lora-datasets/ds1/images',
- checkpointsDir: '/data/training-runs/r1/checkpoints',
- manifestImages: [
- { file: 'a.png', caption: 'kessa, front view' },
- { file: 'b.png', caption: 'kessa, side view' },
- ],
+ variant: '4b',
+ mfluxModel: 'flux2-klein-base-4b',
+ dataDir: '/data/training-runs/r1/data',
+ imageCount: 2,
+ outputDir: '/data/training-runs/r1/mflux',
};
- it('translates the step budget into epochs over the example set', () => {
+ it('matches the mflux ≥0.17 schema and translates steps → epochs', () => {
const config = buildMfluxTrainConfig({ ...base, params: { steps: 100 } });
- expect(config.training_loop.num_epochs).toBe(50); // 100 steps / 2 images
- expect(config.examples.images).toEqual([
- { image: 'a.png', prompt: 'kessa, front view' },
- { image: 'b.png', prompt: 'kessa, side view' },
- ]);
+ expect(config.model).toBe('flux2-klein-base-4b');
+ expect(config.data).toBe(base.dataDir);
+ expect(config.training_loop).toEqual({
+ num_epochs: 50, batch_size: 1, timestep_low: 25, timestep_high: 40,
+ });
+ expect(config.steps).toBe(40); // noise-schedule steps, not training duration
+ expect(config.guidance).toBe(1.0);
+ expect(config.checkpoint.output_path).toBe(base.outputDir);
+ expect(config.lora_layers.targets.length).toBeGreaterThan(10);
+ // mflux rejects unknown keys like the legacy `examples`/`save` shapes.
+ expect(config.examples).toBeUndefined();
+ expect(config.save).toBeUndefined();
});
- it('applies defaults and per-run params', () => {
- const config = buildMfluxTrainConfig({ ...base, params: { rank: 8, learningRate: 0.0002, resolution: 768 } });
- expect(config.lora_layers.transformer_blocks.lora_rank).toBe(8);
+ it('applies params and disables monitoring when samples are off', () => {
+ const config = buildMfluxTrainConfig({
+ ...base,
+ params: { steps: 200, rank: 8, learningRate: 0.0002, resolution: 768, checkpointEvery: 0, sampleEvery: 0 },
+ });
expect(config.optimizer.learning_rate).toBe(0.0002);
- expect(config.width).toBe(768);
- expect(config.model).toBe('dev');
- expect(config.save.checkpoint_frequency).toBe(TRAINING_DEFAULTS.checkpointEvery);
+ expect(config.max_resolution).toBe(768);
+ expect(config.checkpoint.save_frequency).toBe(200); // only the final save
+ expect(config.monitoring).toBeUndefined();
+ expect(config.lora_layers.targets[0].rank).toBe(8);
});
- it('disables checkpoint/sample frequency at 0', () => {
- const config = buildMfluxTrainConfig({ ...base, params: { steps: 200, checkpointEvery: 0, sampleEvery: 0 } });
- expect(config.save.checkpoint_frequency).toBe(200); // only the final save
- expect(config.instrumentation.generate_image_frequency).toBe(0);
+ it('enables monitoring with sample dimensions when sampleEvery > 0', () => {
+ const config = buildMfluxTrainConfig({ ...base, params: { sampleEvery: 50, resolution: 512 } });
+ expect(config.monitoring).toEqual({
+ preview_width: 512, preview_height: 512, plot_frequency: 50, generate_image_frequency: 50,
+ });
});
it('throws on an empty example set', () => {
- expect(() => buildMfluxTrainConfig({ ...base, manifestImages: [] })).toThrow(/at least one/);
+ expect(() => buildMfluxTrainConfig({ ...base, imageCount: 0 })).toThrow(/at least one/);
+ });
+
+ it('derives quantize/low_ram from total RAM (unknown → most conservative)', () => {
+ expect(deriveMfluxMemoryConfig(128)).toEqual({ quantize: null, low_ram: false });
+ expect(deriveMfluxMemoryConfig(64)).toEqual({ quantize: 8, low_ram: false });
+ expect(deriveMfluxMemoryConfig(48)).toEqual({ quantize: 4, low_ram: true });
+ expect(deriveMfluxMemoryConfig(null)).toEqual({ quantize: 4, low_ram: true });
+ const config = buildMfluxTrainConfig({ ...base, totalMemGb: 48 });
+ expect(config.quantize).toBe(4);
+ expect(config.low_ram).toBe(true);
});
});
@@ -88,7 +120,7 @@ describe('buildMfluxTrainArgs / buildFlux2TrainArgs', () => {
scriptPath: '/x/train_mflux_lora.py', configPath: '/r/cfg.json', runDir: '/r', totalSteps: 500,
});
expect(args).toEqual([
- '/x/train_mflux_lora.py', '--train-config', '/r/cfg.json',
+ '/x/train_mflux_lora.py', '--config', '/r/cfg.json',
'--output-dir', '/r', '--total-steps', '500',
]);
});
diff --git a/server/services/loraTraining/sidecar.js b/server/services/loraTraining/sidecar.js
index 6aac02baf7..5a25d0cf51 100644
--- a/server/services/loraTraining/sidecar.js
+++ b/server/services/loraTraining/sidecar.js
@@ -6,7 +6,7 @@
*/
import { slugifyForFilename } from '../../lib/civitai.js';
-import { TRAINING_RUNTIMES, runnerFamilyForRuntime } from './runtimes.js';
+import { RUNNER_FAMILIES } from '../../lib/runners.js';
/** `lora-trained-<slug>-<runId8>.safetensors` — runId suffix prevents collisions. */
export function trainedLoraFilename({ name, characterName, runId }) {
@@ -26,10 +26,11 @@ export function buildTrainedSidecar({ run, result = {}, filename, previewImageUr
datasetId: run.datasetId || null,
runId: run.id,
civitai: null,
- runnerFamily: runnerFamilyForRuntime(runtime),
- // '4b' | '9b' for flux2 (composeCompatKey → flux2-4b/flux2-9b in the
- // picker); null for mflux (bare 'mflux' compat key).
- fluxVariant: runtime === TRAINING_RUNTIMES.FLUX2 ? (run.fluxVariant || null) : null,
+ // Both runtimes (mflux MLX + torch diffusers) train FLUX.2 adapters
+ // with diffusers-style key naming, so the family is always flux2 and
+ // the size variant gates the compat key (flux2-4b / flux2-9b).
+ runnerFamily: RUNNER_FAMILIES.FLUX2,
+ fluxVariant: run.fluxVariant || null,
triggerWords: run.triggerWord ? [run.triggerWord] : [],
recommendedScale: 1.0,
training: {
diff --git a/server/services/loraTraining/sidecar.test.js b/server/services/loraTraining/sidecar.test.js
index b3679369e0..999501945f 100644
--- a/server/services/loraTraining/sidecar.test.js
+++ b/server/services/loraTraining/sidecar.test.js
@@ -4,8 +4,8 @@ import { buildTrainedSidecar, trainedLoraFilename } from './sidecar.js';
const baseRun = {
id: '3f9a21c0-aaaa-bbbb-cccc-dddddddddddd',
runtime: 'mflux',
- baseModelId: 'dev',
- fluxVariant: null,
+ baseModelId: 'flux2-klein-4b',
+ fluxVariant: '4b',
name: null,
character: { entryId: 'char-1', ingredientId: 'ing-1', universeId: 'uni-1', name: 'Kessa Brightwater' },
datasetId: 'ds-1',
@@ -32,8 +32,10 @@ describe('buildTrainedSidecar', () => {
// Fields the existing listLoras mapEntry consumes:
expect(sidecar.name).toBe('Kessa Brightwater (trained)');
expect(sidecar.civitai).toBeNull();
- expect(sidecar.runnerFamily).toBe('mflux');
- expect(sidecar.fluxVariant).toBeNull();
+ // Both engines train FLUX.2 adapters — family is always flux2, gated
+ // by size variant.
+ expect(sidecar.runnerFamily).toBe('flux2');
+ expect(sidecar.fluxVariant).toBe('4b');
expect(sidecar.triggerWords).toEqual(['kessa_brightwater']);
expect(sidecar.recommendedScale).toBe(1.0);
expect(sidecar.installedAt).toBeTruthy();
@@ -46,12 +48,12 @@ describe('buildTrainedSidecar', () => {
expect(sidecar.file.sizeKB).toBe(51200);
});
- it('stamps fluxVariant for flux2 runs so the compat key gates by size', () => {
+ it('stamps the size variant for the torch runtime too', () => {
const sidecar = buildTrainedSidecar({
- run: { ...baseRun, runtime: 'flux2', baseModelId: 'flux2-klein-4b', fluxVariant: '4b' },
+ run: { ...baseRun, runtime: 'flux2', baseModelId: 'flux2-klein-9b-bf16', fluxVariant: '9b' },
filename: 'x.safetensors',
});
expect(sidecar.runnerFamily).toBe('flux2');
- expect(sidecar.fluxVariant).toBe('4b');
+ expect(sidecar.fluxVariant).toBe('9b');
});
});