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

fix: don't mislabel mflux preview-image tqdm bar as training steps

[._.]/ Adam Eivybdf82de20863
diff --git a/scripts/train_mflux_lora.py b/scripts/train_mflux_lora.py
index 0b7ae226b4..066b1d9e1c 100644
--- a/scripts/train_mflux_lora.py
+++ b/scripts/train_mflux_lora.py
@@ -220,6 +220,31 @@ FATAL_PATTERNS = [
# the actionable message — one source of truth for that text, on the JS side.
+def is_preview_progress_bar(line, cur, total, *, has_step_loss, preview_steps, training_total):
+ """True if a matched tqdm bar belongs to the preview/sample IMAGE generation
+ rather than the training loop.
+
+ mflux runs `adapter.generate_preview_image` (→ `flux2.generate_image`) once
+ before training (step 0) and again at every sample interval. That diffusion
+ sampler prints its own tqdm bar whose total is the DENOISE step count
+ (`config["steps"]`, e.g. 40) — identical in shape to the training bar except
+ the total differs (training total = epochs × images). If we don't exclude it
+ the wrapper both mislabels denoise ticks as training STEPs and lets them
+ perturb `state["step"]`, which gates the segment-boundary kill (a preview bar
+ reading 38/40 could spuriously satisfy a 150-step boundary).
+
+ Discriminators, all required:
+ - `has_step_loss` False — the explicit "step N/M … loss X" prose is emitted
+ only by the training loop, never the sampler, so it's never a preview.
+ - `preview_steps` known (caller passes None when steps == training_total,
+ the degenerate tiny-dataset case where totals can't disambiguate).
+ - the bar's total equals `preview_steps` and differs from `training_total`.
+ """
+ if has_step_loss or preview_steps is None:
+ return False
+ return total == preview_steps and (training_total is None or total != training_total)
+
+
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
@@ -433,7 +458,8 @@ def compute_effective_total(config: dict, fallback: int) -> int:
def run_segment(cmd, *, segment_target, state, last_reported, output_tail,
- fatal_holder, configured_output, cooldown):
+ fatal_holder, configured_output, cooldown,
+ preview_steps=None, training_total=None):
"""Run ONE mflux invocation and stream its output.
Returns a dict with `reason`:
@@ -455,6 +481,7 @@ def run_segment(cmd, *, segment_target, state, last_reported, output_tail,
CHILD.terminate()
in_training = False
+ preview_logged = {"v": False} # one STAGE:sampling per contiguous preview run
for raw in stream_lines(CHILD.stdout):
line = raw.strip()
if not line or NOISE_RE.search(line):
@@ -469,9 +496,24 @@ def run_segment(cmd, *, segment_target, state, last_reported, output_tail,
fatal_holder["v"] = True
break
- m = STEP_LOSS_RE.search(line) or TQDM_RE.search(line)
+ step_loss_match = STEP_LOSS_RE.search(line)
+ m = step_loss_match or TQDM_RE.search(line)
if m:
cur, total = int(m.group(1)), int(m.group(2))
+ # Skip the preview/sample image generation's own tqdm bar so it isn't
+ # mislabeled as a training step or allowed to trip the segment kill.
+ if is_preview_progress_bar(
+ line, cur, total,
+ has_step_loss=step_loss_match is not None,
+ preview_steps=preview_steps, training_total=training_total,
+ ):
+ if not in_training and not preview_logged["v"]:
+ # Pre-training step-0 preview: surface a distinct stage so the
+ # UI shows "sampling" instead of a frozen "load-model". Emit
+ # once — the bar redraws every denoise tick.
+ preview_logged["v"] = True
+ log("STAGE:sampling")
+ continue
if total > 0 and cur >= 0:
state["step"], state["total"] = cur, total
if m.lastindex and m.lastindex >= 3:
@@ -482,6 +524,12 @@ def run_segment(cmd, *, segment_target, state, last_reported, output_tail,
if not in_training:
in_training = True
log("STAGE:training")
+ # A real training step ends a preview run; re-arm so the NEXT
+ # mid-training sampling phase (step 150, 300…) logs STAGE:sampling
+ # again. Re-announce STAGE:training when we come back from one.
+ elif preview_logged["v"]:
+ log("STAGE:training")
+ preview_logged["v"] = False
# tqdm redraws constantly at the same step — only emit on change.
if cur != last_reported["step"]:
last_reported["step"] = cur
@@ -540,6 +588,15 @@ def main():
cooldown = max(0, args.cooldown_sec)
segmented = seg > 0
+ # The preview/sample image generation prints its own tqdm bar whose total is
+ # the denoise step count (`steps`), distinct from the training total. Pass
+ # both to run_segment so it can tell a preview bar from a training bar. Guard
+ # the rare degenerate case where steps == training total (tiny datasets):
+ # then we can't disambiguate by total, so don't filter (preview_steps=None).
+ preview_steps = config.get("steps")
+ if not isinstance(preview_steps, int) or preview_steps <= 0 or preview_steps == total:
+ preview_steps = None
+
state = {"step": 0, "total": total, "loss": None}
last_reported = {"step": -1}
@@ -601,6 +658,7 @@ def main():
cmd, segment_target=segment_target, state=state, last_reported=last_reported,
output_tail=output_tail, fatal_holder=fatal_holder,
configured_output=configured_output, cooldown=cooldown,
+ preview_steps=preview_steps, training_total=total,
)
segment_index += 1
diff --git a/scripts/train_mflux_lora_test.py b/scripts/train_mflux_lora_test.py
new file mode 100644
index 0000000000..c8d43ab613
--- /dev/null
+++ b/scripts/train_mflux_lora_test.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""Standalone tests for train_mflux_lora.py pure helpers (no pytest, no mflux).
+
+Run: ./data/python/venv/bin/python scripts/train_mflux_lora_test.py
+Exits non-zero on first failure. Mirrors the runnable-test style of
+scripts/generate_ltx2_teacache_test.py.
+"""
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from train_mflux_lora import ( # noqa: E402
+ is_preview_progress_bar,
+ compute_effective_total,
+ TQDM_RE,
+ STEP_LOSS_RE,
+)
+
+FAILS = []
+
+
+def check(name, cond):
+ print(("✅" if cond else "❌") + " " + name)
+ if not cond:
+ FAILS.append(name)
+
+
+# --- is_preview_progress_bar: the preview/sample bar vs the training bar -------
+# Scenario mirrors the live Freydis run: steps=40 (preview denoise), total=600.
+PREVIEW, TRAIN = 40, 600
+
+# A preview bar (total == preview_steps, != training_total, no step/loss prose).
+check(
+ "preview bar (38/40) is detected as preview",
+ is_preview_progress_bar("38/40 [00:19<00:01]", 38, 40,
+ has_step_loss=False, preview_steps=PREVIEW, training_total=TRAIN),
+)
+check(
+ "preview bar at completion (40/40) is detected as preview",
+ is_preview_progress_bar("40/40 [00:20<00:00]", 40, 40,
+ has_step_loss=False, preview_steps=PREVIEW, training_total=TRAIN),
+)
+
+# A training bar (total == training_total) is NOT a preview.
+check(
+ "training bar (151/600) is NOT preview",
+ not is_preview_progress_bar("151/600 [10:00<30:00]", 151, 600,
+ has_step_loss=False, preview_steps=PREVIEW, training_total=TRAIN),
+)
+check(
+ "training bar at a 40-ish step (40/600) is NOT preview (total differs)",
+ not is_preview_progress_bar("40/600 [02:00<28:00]", 40, 600,
+ has_step_loss=False, preview_steps=PREVIEW, training_total=TRAIN),
+)
+
+# Explicit "step N/M ... loss X" prose is training-only, never a preview, even
+# if its total coincidentally equals preview_steps.
+check(
+ "explicit step/loss prose is never preview",
+ not is_preview_progress_bar("step 40/40 loss 0.12", 40, 40,
+ has_step_loss=True, preview_steps=PREVIEW, training_total=TRAIN),
+)
+
+# Degenerate case: caller passes preview_steps=None (steps == training_total on a
+# tiny dataset) → never filter, so no real training step is ever dropped.
+check(
+ "preview_steps=None disables filtering",
+ not is_preview_progress_bar("40/40 [..]", 40, 40,
+ has_step_loss=False, preview_steps=None, training_total=40),
+)
+
+# preview_steps known but training_total unknown (None): filter on total match
+# alone — better to risk a missed preview tick than to mislabel, but we still
+# catch the common case.
+check(
+ "training_total=None still filters an exact preview-total match",
+ is_preview_progress_bar("12/40 [..]", 12, 40,
+ has_step_loss=False, preview_steps=40, training_total=None),
+)
+
+# --- the regexes that feed it --------------------------------------------------
+m = TQDM_RE.search(" 3%|▎ | 12/400 [00:30<16:20, 2.53s/it]")
+check("TQDM_RE parses cur/total", bool(m) and m.group(1) == "12" and m.group(2) == "400")
+check("STEP_LOSS_RE matches explicit prose",
+ bool(STEP_LOSS_RE.search("steps 40/40 loss 0.12")))
+check("STEP_LOSS_RE does NOT match a bare tqdm bar",
+ STEP_LOSS_RE.search("38/40 [00:19<00:01]") is None)
+
+# --- compute_effective_total sanity (unchanged behavior) -----------------------
+# 25 images, batch 1, 24 epochs → 600 (the Freydis config).
+import tempfile, os # noqa: E402
+with tempfile.TemporaryDirectory() as d:
+ for i in range(25):
+ Path(d, f"{i:04d}.png").write_bytes(b"x")
+ cfg = {"training_loop": {"num_epochs": 24, "batch_size": 1}, "data": d}
+ check("compute_effective_total(25 img,24 ep,batch 1) == 600",
+ compute_effective_total(cfg, 999) == 600)
+
+# Unexpected shape → falls back to the requested count.
+check("compute_effective_total falls back on bad config",
+ compute_effective_total({}, 777) == 777)
+
+print()
+if FAILS:
+ print(f"❌ {len(FAILS)} failure(s): {FAILS}")
+ sys.exit(1)
+print("✅ all train_mflux_lora helper tests passed")