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([issue-2786]): make the torch FLUX.2 LoRA trainer work on CUDA

[._.]/ Adam Eivy2f989b612fb4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bdab35d0d0..5e2e577236 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -188,3 +188,7 @@
- **YouTube videos can be ingested into the Brain — transcript to your Obsidian vault, with an agent queued to act on it.** Paste a single-video YouTube link into Quick Capture on the dashboard and a sliders button appears next to the input; it expands into the ingest options. Three independent checkboxes decide what is pulled in: the **transcript** (on by default), the full **video** into the media library, and the **audio** as an mp3 kept next to the transcript — at least one is required. Below them, a free-text box asks what an agent should do with the content, and a tags field. Whatever the switches say, the ingest always records that you consumed and kept the video: a Brain link record, which federates to your other machines, and a `media.watch` event so the video shows on the Timeline next to the watch history that syncs passively. Transcripts land as a note in your Obsidian vault with frontmatter carrying the title, source, channel, duration, publish date and tags. YouTube's auto-generated captions are a rolling two-line display where each cue repeats most of the one before it, so a naive strip-the-timings pass yields a transcript with every sentence in it two or three times; the captions are de-duplicated and their inline markup removed before they are written, which took a 14-minute talk from 128KB of caption file down to 14KB of readable prose. Whether the captions were human-written or machine-generated is read from the video's metadata rather than guessed from the file yt-dlp produced — it writes both kinds under the same name — and recorded alongside the transcript, because auto-captions get proper nouns wrong often enough to be worth knowing about later. A video with no captions at all is not treated as a failure: the ingest finishes, says so, and still stores everything else you asked for. Filling in the agent prompt queues a Chief of Staff task pointed at the freshly-stored transcript with your prompt as its brief; leaving it blank queues nothing, so an ingest never starts AI work you did not ask for. Which vault and folder transcripts go to, and what the checkboxes default to, are configurable under Brain → Config; an unset vault inherits the Daily Log's, so anyone who has already pointed the journal at Obsidian needs no setup at all. Playlists and channel URLs are deliberately not accepted — they fall through to ordinary link capture rather than quietly starting a 300-video download. `yt-dlp` is required for any ingest and `ffmpeg` additionally for the video/audio options, so a transcript-only ingest still works on a machine that has only the first.
- **The Daily Log's first note into a new Obsidian folder no longer silently fails to write.** Mirroring a record into a vault tried to update the note first and only created it if the update reported the note missing — but a note whose *folder* does not exist yet cannot be containment-checked at all: the path can't be resolved, so it falls back to the raw path, which fails the check against the realpath'd vault root whenever the vault is reached through a symlink. On macOS that is any vault under a `/var`-rooted path, and more generally any vault behind a symlinked home or mount. The update therefore reported "invalid path" rather than "not found", the create fallback never ran, and the day was never mirrored. Creating first and updating only on "already exists" sidesteps it entirely — the folder is ensured before the path is resolved. The two vault mirrors (Daily Log and the new YouTube transcript) now share one `upsertNote` in the Obsidian adapter instead of each carrying its own copy of that ordering rule, and it is tested against a real vault on disk rather than against stubbed calls, which is how the failure surfaced in the first place.
+
+## Character LoRA training
+
+- **[issue-2786] Training a character LoRA on an NVIDIA GPU now works.** The torch/diffusers trainer is the path every non-Apple machine takes, but it had only ever been exercised on a 128 GB Mac — where two memory faults did no visible harm, and where the run died at an unrelated Metal limitation before it could reach one of them. On a 24 GB card both were fatal. Preparing the dataset held on to roughly 2.6 GB of scratch memory for every distinct caption it read, so a six-image set exhausted the card before training began; depending on how the driver reacted, that surfaced either as a run that sat at "precompute" for twenty minutes doing nothing visible, or as an out-of-memory abort blaming an allocation far smaller than the space that should have been free. Separately, the preview image the trainer renders at each checkpoint was being decoded on the CPU in a numeric format no CPU has a fast path for, which read as a hang — a single 512-pixel preview took over eighteen minutes. Both are fixed, and a run that previously never finished now trains, checkpoints, previews, resumes from a checkpoint, and produces an adapter that loads cleanly for image generation; a 20-step smoke run completes in about twenty seconds and peaks at 8.8 GB of the card's 24 GB. Apple Silicon behaviour is unchanged — it still refuses up front and points at the mflux runtime, which remains the right choice there.
diff --git a/docs/research/2026-07-18-lora-training-e2e-validation.md b/docs/research/2026-07-18-lora-training-e2e-validation.md
index 73734bbeac..33f9dd6b3b 100644
--- a/docs/research/2026-07-18-lora-training-e2e-validation.md
+++ b/docs/research/2026-07-18-lora-training-e2e-validation.md
@@ -114,3 +114,13 @@ precomputes latents for minutes only to crash, the fallback now refuses up front
the current pinned stack. The user's real character LoRAs train on this hardware.
- torch fallback: confirmed non-viable on MPS and now guarded with actionable
guidance; CUDA/CPU e2e validation deferred to appropriate hardware.
+
+> **Update 2026-08-05 (#2786):** the CUDA validation is done — see
+> [2026-08-05-torch-flux2-lora-cuda-validation.md](./2026-08-05-torch-flux2-lora-cuda-validation.md).
+> bf16 `linear_backward` does exist on CUDA and the fallback trains, resumes,
+> and round-trips there. Getting it working first required fixing two memory
+> bugs this 128 GB unified-memory machine had silently absorbed: precompute ran
+> without `torch.no_grad()` (leaking ~2.6 GB per caption), and `render_sample`
+> decoded the VAE on CPU in bf16 (>18 min for one 512-px decode). Both were
+> latent here too — the MPS run just died at the first backward, before either
+> could bite.
diff --git a/docs/research/2026-08-05-torch-flux2-lora-cuda-validation.md b/docs/research/2026-08-05-torch-flux2-lora-cuda-validation.md
new file mode 100644
index 0000000000..1d9d56ed3d
--- /dev/null
+++ b/docs/research/2026-08-05-torch-flux2-lora-cuda-validation.md
@@ -0,0 +1,197 @@
+# Validation: torch FLUX.2 LoRA trainer on CUDA
+
+**Status:** Closed — torch/diffusers fallback validated end-to-end on CUDA; two
+memory bugs found and fixed
+**Date:** 2026-08-05
+**Hardware:** Windows 11, NVIDIA RTX 3090 (24 GB), 32 GB system RAM, driver 596.36
+**Closes:** #2786 (split out of #1227)
+**Companion:** [2026-07-18-lora-training-e2e-validation.md](./2026-07-18-lora-training-e2e-validation.md)
+(mflux runtime + the Apple-Silicon MPS finding)
+
+The 2026-07-18 validation established that the mflux (MLX) runtime works
+end-to-end on Apple Silicon and that the torch/diffusers fallback **cannot**
+train there — PyTorch's MPS backend has no `linear_backward` for the FLUX.2
+transformer's Linear layers, so the run dies at the first `loss.backward()`.
+That left one open question, deferred for want of hardware: **does the torch
+fallback actually work on its real target, a CUDA box?**
+
+It does — but not as shipped. Getting there required fixing two memory bugs that
+a 128 GB unified-memory Mac had silently absorbed.
+
+## Environment
+
+The existing shared image-gen venv (`~/.portos/venv-flux2`) already had the
+whole stack; nothing needed rebuilding:
+
+- torch **2.12.0+cu130** (`torch.cuda.is_available() == True`), diffusers
+ **0.39.0.dev0** (`Flux2KleinPipeline` present), peft **0.19.1**,
+ transformers **5.10.2**
+- `pick_device("auto")` → `cuda`
+- Base weights: `black-forest-labs/FLUX.2-klein-4B` bf16 (~16 GB of
+ diffusers-format shards; the repo's redundant single-file
+ `flux-2-klein-4b.safetensors` was skipped). Not a gated repo.
+
+Dataset: 6 procedurally-generated placeholder images (a flat-color robot
+mascot, trigger word `zqxbot`), captioned and fed through the real manifest
+schema. Synthetic on purpose — the goal is pipeline mechanics, and no real
+user data belongs in a validation artifact.
+
+The trainer was invoked with exactly the argv `buildFlux2TrainArgs`
+(`server/services/loraTraining/runtimes.js`) constructs: 20 steps, rank 16,
+lr 1e-4, resolution 512, `--checkpoint-every 10`, `--sample-every 10`,
+`--device auto`.
+
+## Bug 1 — precompute leaked ~2.6 GB per caption (no `torch.no_grad()`)
+
+**Symptom.** The first run sat in `STAGE:precompute-latents` for 18+ minutes
+emitting nothing but heartbeats, with VRAM pinned at 24.3/24.6 GB and the GPU at
+100%. A `py-spy` dump put it inside the **first** Qwen3 caption encode. A later
+run got through precompute and then aborted at `transformer.to(device)`:
+
+```
+torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 162.00 MiB.
+GPU 0 has a total capacity of 24.00 GiB of which 0 bytes is free.
+Of the allocated memory 37.95 GiB is allocated by PyTorch
+```
+
+37.95 GiB "allocated" on a 24 GiB card is Windows' WDDM shared-memory fallback:
+rather than failing, the driver spills into system RAM over PCIe, which is what
+turned the encode into a crawl before it eventually hit a hard wall.
+
+**Root cause.** Precompute is pure inference, but it ran **without**
+`torch.no_grad()`. The freshly-loaded text encoder still has
+`requires_grad=True` params, so every `encode_prompt` built and kept a full
+autograd graph — and the `.to("cpu")` cache copy inherited that `grad_fn`,
+pinning the whole graph on-device permanently. Measured directly:
+
+| encode_prompt call | alloc | grad_fn |
+|---|---|---|
+| baseline (text encoder resident) | 8.10 GB | — |
+| 0 | 10.72 GB | `ViewBackward0` |
+| 1 | 13.31 GB | `ViewBackward0` |
+| 2 | 15.92 GB | `ViewBackward0` |
+| 3 | 18.52 GB | `ViewBackward0` |
+| 4 | 21.12 GB | `ViewBackward0` |
+
+~2.6 GB retained per unique caption. Six captions exhaust a 24 GB card. Under
+`torch.no_grad()` the same seven calls hold **flat at 8.12 GB**, `grad_fn` is
+`None`, and each call runs ~4× faster (0.09 s vs 0.38 s); freeing the text
+encoder afterwards then drops to 0.02 GB and `transformer.to("cuda")` succeeds
+at 7.77 GB.
+
+**Why Apple Silicon never caught it.** 128 GB of unified memory absorbs a
+2.6 GB × N leak without complaint, and the MPS run died at the first backward —
+well after precompute — so the leak never had consequences there.
+
+**Fix.** Wrap precompute in `torch.no_grad()`, and clear the allocator cache on
+CUDA as well as MPS (a new `empty_device_cache(device)` helper replaces three
+`if device == "mps"`-only call sites — the leftover reserve was otherwise enough
+to starve the one big contiguous `transformer.to(device)` allocation).
+
+## Bug 2 — sample render decoded the VAE on CPU in bf16 (reads as a hang)
+
+**Symptom.** With bug 1 fixed, training ran clean through step 10, wrote its
+checkpoint, and then hung. `py-spy` put it in `pipe.vae.decode` →
+`torch.nn.modules.conv._conv_forward`. One 512-px decode had been running
+**>18 minutes**.
+
+**Root cause.** Phase 1 deliberately parks the VAE on CPU to keep it out of the
+training footprint, and `render_sample` decoded wherever it found it
+(`vae_device = next(pipe.vae.parameters()).device`). But the pipeline is bf16 on
+an accelerator, and x86 has no fast bf16 convolution path — so the decode falls
+back to a reference implementation and effectively never finishes.
+
+This was never reachable on Apple Silicon: the MPS run died at the first
+backward, long before the first sample. It is latent on **any** accelerator
+backend, not just CUDA.
+
+**Fix.** `render_sample` moves the VAE onto the training device for the decode
+and returns it to where precompute parked it. The VAE is ~0.17 GB against a
+~8 GB resident transformer, so borrowing the device costs nothing and the
+training loop's footprint is unchanged. Decode time: >18 min → **~2 s**.
+
+## Result — full end-to-end run
+
+```
+STAGE:load-pipeline
+STAGE:precompute-latents
+STATUS:encoded 1/6 … 6/6 dataset images (11 s total)
+STAGE:training
+STATUS:LoRA targets: add_k_proj, add_q_proj, add_v_proj, to_add_out,
+ to_k, to_out.0, to_q, to_v (rank 16)
+STEP:1:20:0.0231 … STEP:10:20:0.0370
+CHECKPOINT:…/checkpoints/step-000010:10
+SAMPLE:…/samples/step-000010.png:10
+STEP:11:20:0.0278 … STEP:20:20:0.0199
+SAMPLE:…/samples/step-000020.png:20
+RESULT:{"adapter_path": "…/adapter/pytorch_lora_weights.safetensors",
+ "steps": 20, "final_loss": 0.0199, "last_checkpoint": "…/step-000010"}
+```
+
+| Contract | Result |
+|---|---|
+| `loss.backward()` on CUDA | ✅ works in bf16 — the MPS blocker does not apply |
+| `STAGE:` / `STEP:` / `CHECKPOINT:` / `SAMPLE:` / `RESULT:` protocol | ✅ all emitted as `progress.js` expects |
+| `checkpoints/step-NNNNNN/` layout | ✅ `pytorch_lora_weights.safetensors` + `optimizer.pt` + `state.json` |
+| Adapter export | ✅ 80 tensors, rank 16, diffusers key naming (`transformer.transformer_blocks.N.attn.*.lora_{A,B}.weight`) |
+| Sample renders | ✅ 512×512, mean 130 / std 69 — real images, no collapse-to-black |
+| Peak VRAM | 8.8 GB of 24 GB — comfortable headroom |
+| Wall clock | ~20 s for 20 steps (~0.7 s/step) after an 11 s precompute |
+
+### Resume — VALIDATED
+
+Resuming from `checkpoints/step-000010` with the same `--steps 20`:
+
+```
+STATUS:resumed adapter + optimizer state — continuing from step 10
+STEP:11:20:0.0228 … STEP:20:20:0.0373
+RESULT:{… "steps": 20 …}
+```
+
+It continued **11→20** rather than restarting a fresh 1→20, confirming the
+`optimizer.pt` bundle restores the adapter, the AdamW state, and the step offset.
+
+### Inference round-trip — VALIDATED
+
+The trained adapter loaded through `scripts/flux2_macos.py --lora-paths` on the
+bf16 pipeline (same base it trained on):
+
+```
+🎚️ loading LoRA: pytorch_lora_weights.safetensors (adapter=lora_0)
+✅ active LoRA adapters: [('lora_0', 1.0)]
+🎨 flux2 generate seed=42 512x512 steps=8 guidance=3.5 device=cuda
+✅ flux2 saved roundtrip.png (seed=42)
+```
+
+Produced a coherent 512-px portrait. Note the mflux→diffusers `to_out` key remap
+(`scripts/lora_utils.py`) does **not** fire here and should not: a torch/peft
+adapter is already in diffusers key form, unlike the mflux adapter in the
+2026-07-18 run. 20 steps is far too few to bind identity — same caveat as that
+run's 50 — so the render is a generic portrait, not the mascot. Pipeline
+mechanics and a clean LoRA load were the goal; both confirmed.
+
+## Regression guard
+
+`scripts/train_flux2_lora_test.py` (standalone, no pytest, no torch — it parses
+the trainer's AST) pins both invariants: precompute stays inside
+`torch.no_grad()`, `render_sample` decodes on the training device and restores
+the VAE, and every cache clear routes through `empty_device_cache`. Verified to
+fail on a deliberately reverted copy, not just to pass on the fixed one.
+
+Behavioral tests aren't possible here — exercising these paths needs torch, a
+~16 GB download, and a CUDA card.
+
+## Outcome
+
+- **The torch/diffusers fallback is validated on CUDA.** bf16 `linear_backward`
+ exists there, as predicted; training, checkpointing, resume, adapter export,
+ and the inference round-trip all work.
+- **Two real bugs fixed** — both invisible on the 128 GB Mac that originally
+ validated this code, and both fatal (one immediately, one as an apparent hang)
+ on a 24 GB consumer card.
+- The Apple-Silicon guard (`TRAINING_MPS_UNSUPPORTED` at request time,
+ `USER_ERROR:TRAINING_UNSUPPORTED_DEVICE` in the trainer) is unchanged and
+ still correct.
+- **Not covered:** the 9B base (this box has the VRAM for 4B training with room
+ to spare, but 9B was out of scope), long runs where LoRA quality is the
+ question rather than mechanics, and the `--device cpu` path.
diff --git a/scripts/train_flux2_lora.py b/scripts/train_flux2_lora.py
index 286a71fab0..11a34fab99 100644
--- a/scripts/train_flux2_lora.py
+++ b/scripts/train_flux2_lora.py
@@ -6,7 +6,8 @@ quantized inference repos — no useful gradients through quant layers).
The trained adapter loads onto quantized inference pipelines of the same
size variant because the transformer hidden dims match.
-Two phases keep peak memory survivable on Apple Silicon:
+Two phases keep peak memory survivable — on Apple Silicon's unified memory and,
+just as much, on a consumer CUDA card (a 24 GB 3090 has no headroom to spare):
1. STAGE:precompute-latents — encode every dataset image to VAE latents
and every caption to Qwen3 text embeddings ONCE, then free the text
@@ -62,6 +63,19 @@ def log(msg: str) -> None:
print(msg, flush=True)
+def empty_device_cache(device: str) -> None:
+ """Return freed blocks to the driver on whichever accelerator we're on.
+
+ The caching allocator otherwise keeps them reserved, which starves the one
+ big contiguous `transformer.to(device)` allocation that follows precompute.
+ CUDA needs this as much as MPS does — on a 24 GB card the leftover reserve
+ is the difference between a clean move and an out-of-memory abort."""
+ if device == "mps":
+ torch.mps.empty_cache()
+ elif device == "cuda":
+ torch.cuda.empty_cache()
+
+
def parse_args():
p = argparse.ArgumentParser(description="FLUX.2 Klein LoRA trainer")
p.add_argument("--model-repo", required=True, help="bf16 base repo (black-forest-labs/FLUX.2-klein-4B|9B)")
@@ -176,8 +190,20 @@ def render_sample(pipe, transformer, embeds, text_ids, resolution, device, dtype
)
unpacked = unpacked * bn_std + bn_mean
unpacked = pipe._unpatchify_latents(unpacked)
- vae_device = next(pipe.vae.parameters()).device
- image = pipe.vae.decode(unpacked.to(vae_device, pipe.vae.dtype), return_dict=False)[0]
+ # Decode on the training device, not wherever precompute parked the VAE.
+ # Phase 1 deliberately leaves the VAE on CPU to keep it out of the training
+ # footprint, but the pipeline is bf16 on an accelerator — and x86 has no
+ # fast bf16 convolution path, so decoding there reads as a hang (a single
+ # 512-px decode ran >18 min on CUDA/Windows before this moved it back).
+ # The VAE is ~0.17 GB against a ~8 GB resident transformer, so borrowing the
+ # device for one decode is cheap; it goes straight back so the training
+ # loop's footprint is unchanged.
+ vae_home = next(pipe.vae.parameters()).device
+ pipe.vae.to(device)
+ try:
+ image = pipe.vae.decode(unpacked.to(device, pipe.vae.dtype), return_dict=False)[0]
+ finally:
+ pipe.vae.to(vae_home)
image = pipe.image_processor.postprocess(image, output_type="pil")[0]
image.save(out_path)
@@ -229,7 +255,16 @@ def main():
log("STAGE:precompute-latents")
sample_prompt = args.sample_prompt or f"{args.trigger_word} portrait, neutral background"
examples = []
- with heartbeat("precompute-latents"):
+ # `no_grad` here is load-bearing, not a micro-optimization. Precompute is
+ # pure inference, but the freshly-loaded text encoder and VAE still carry
+ # `requires_grad=True` params — so without it every encode builds and keeps
+ # a full autograd graph, and the `.to("cpu")` cache copy inherits that
+ # `grad_fn`, pinning the whole graph on-device. Measured on FLUX.2-klein-4B:
+ # ~2.6 GB of Qwen3 activations retained PER UNIQUE CAPTION. A 128 GB
+ # unified-memory Mac silently absorbs that; a 24 GB CUDA card spills into
+ # driver shared memory (encode slows from 0.09 s to minutes) and then aborts
+ # with OOM at `transformer.to(device)` below.
+ with torch.no_grad(), heartbeat("precompute-latents"):
pipe.text_encoder.to(device)
embed_cache = {}
for entry in images + [{"caption": sample_prompt, "path": None}]:
@@ -238,12 +273,12 @@ def main():
embeds, text_ids = pipe.encode_prompt(caption, device=device)
embed_cache[caption] = (embeds.to("cpu"), text_ids.to("cpu"))
sample_embeds = embed_cache[sample_prompt]
- # Free the text encoder — the make-or-break memory move on MPS.
+ # Free the text encoder — the make-or-break memory move on every
+ # backend: its ~8 GB has to be gone before the transformer moves on.
pipe.text_encoder.to("cpu")
pipe.text_encoder = None
gc.collect()
- if device == "mps":
- torch.mps.empty_cache()
+ empty_device_cache(device)
pipe.vae.to(device)
gen = torch.Generator(device="cpu").manual_seed(args.seed)
@@ -263,8 +298,7 @@ def main():
# VAE only needed again for samples — keep it, but off-device.
pipe.vae.to("cpu")
gc.collect()
- if device == "mps":
- torch.mps.empty_cache()
+ empty_device_cache(device)
# ---- Phase 2: training ----
log("STAGE:training")
@@ -387,8 +421,7 @@ def main():
log(f"STATUS:sample render failed (training continues): {err}")
finally:
transformer.train()
- if device == "mps":
- torch.mps.empty_cache()
+ empty_device_cache(device)
# ---- Finalize ----
adapter_dir = out_dir / "adapter"
diff --git a/scripts/train_flux2_lora_test.py b/scripts/train_flux2_lora_test.py
new file mode 100644
index 0000000000..6071deb2c7
--- /dev/null
+++ b/scripts/train_flux2_lora_test.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+"""Standalone tests for train_flux2_lora.py's memory-discipline invariants.
+
+Run: python3 scripts/train_flux2_lora_test.py
+Exits non-zero on first failure. Mirrors the runnable-test style of
+scripts/train_mflux_lora_test.py.
+
+These are AST checks on the source rather than behavioral tests, deliberately:
+exercising the real code paths needs torch + a ~16 GB base download + a CUDA
+card, which no test suite can carry. What they pin are the two invariants whose
+absence made the torch trainer unusable on a 24 GB CUDA card (issue #2786) —
+both silently survivable on a 128 GB unified-memory Mac, which is why neither
+was caught by the original Apple-Silicon validation:
+
+ 1. Precompute runs under `torch.no_grad()`. Without it every `encode_prompt`
+ retains its autograd graph — measured ~2.6 GB of Qwen3 activations pinned
+ PER UNIQUE CAPTION, because the `.to("cpu")` cache copy inherits the
+ `grad_fn`. Six captions exhausted the card.
+ 2. `render_sample` decodes on the training device. Precompute parks the VAE
+ on CPU, and the pipeline is bf16 — x86 has no fast bf16 convolution path,
+ so decoding there reads as a hang (>18 min for one 512-px decode).
+"""
+import ast
+import sys
+from pathlib import Path
+
+# The ✅/❌ prefixes are cp1252-unencodable on a Windows console, which would
+# abort the run before the first result printed. This trainer's whole point is
+# the CUDA path, and that is where Windows lives — so force UTF-8 on stdout.
+if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
+SRC = Path(__file__).resolve().parent / "train_flux2_lora.py"
+TREE = ast.parse(SRC.read_text(encoding="utf-8"))
+
+FAILS = []
+
+
+def check(name, cond):
+ print(("✅" if cond else "❌") + " " + name)
+ if not cond:
+ FAILS.append(name)
+
+
+def func(name):
+ for node in ast.walk(TREE):
+ if isinstance(node, ast.FunctionDef) and node.name == name:
+ return node
+ return None
+
+
+def calls(node):
+ """Every call in `node`, rendered as a dotted name (e.g. torch.no_grad)."""
+ out = []
+ for n in ast.walk(node):
+ if isinstance(n, ast.Call):
+ parts, f = [], n.func
+ while isinstance(f, ast.Attribute):
+ parts.append(f.attr)
+ f = f.value
+ if isinstance(f, ast.Name):
+ parts.append(f.id)
+ out.append((".".join(reversed(parts)), n))
+ return out
+
+
+# --- 1. precompute is wrapped in torch.no_grad() -----------------------------
+main = func("main")
+check("main() exists", main is not None)
+
+precompute_with = None
+for node in ast.walk(main):
+ if not isinstance(node, ast.With):
+ continue
+ for item in node.items:
+ c = item.context_expr
+ if (isinstance(c, ast.Call) and isinstance(c.func, ast.Name)
+ and c.func.id == "heartbeat"
+ and c.args and isinstance(c.args[0], ast.Constant)
+ and c.args[0].value == "precompute-latents"):
+ precompute_with = node
+
+check("precompute-latents runs inside a `with` block", precompute_with is not None)
+
+if precompute_with:
+ guards = []
+ for item in precompute_with.items:
+ c = item.context_expr
+ if isinstance(c, ast.Call) and isinstance(c.func, ast.Attribute):
+ guards.append(c.func.attr)
+ check(
+ "precompute `with` includes torch.no_grad() "
+ "(else ~2.6 GB leaks per caption — issue #2786)",
+ "no_grad" in guards,
+ )
+ # The encode calls must be INSIDE that block, not merely nearby.
+ inner = [n for n, _ in calls(precompute_with)]
+ check("encode_prompt is inside the no_grad block",
+ any(n.endswith("encode_prompt") for n in inner))
+ check("_encode_vae_image is inside the no_grad block",
+ any(n.endswith("_encode_vae_image") for n in inner))
+
+# --- 2. render_sample decodes on the training device -------------------------
+rs = func("render_sample")
+check("render_sample() exists", rs is not None)
+
+if rs:
+ vae_to_device = False
+ for name, call in calls(rs):
+ # pipe.vae.to(device) — the move back onto the accelerator before decode.
+ if name.endswith("vae.to") and any(
+ isinstance(a, ast.Name) and a.id == "device" for a in call.args
+ ):
+ vae_to_device = True
+ check(
+ "render_sample moves the VAE onto `device` before decoding "
+ "(bf16 conv on CPU hangs — issue #2786)",
+ vae_to_device,
+ )
+ check("render_sample still calls vae.decode",
+ any(n.endswith("vae.decode") for n, _ in calls(rs)))
+ # It must be returned to where precompute parked it, or the training loop's
+ # footprint silently grows by the VAE for the rest of the run.
+ check("render_sample restores the VAE to its original device",
+ any(n.endswith("vae.to") and any(
+ isinstance(a, ast.Name) and a.id != "device" for a in c.args)
+ for n, c in calls(rs)))
+
+# --- 3. cache clearing is device-agnostic ------------------------------------
+edc = func("empty_device_cache")
+check("empty_device_cache() exists", edc is not None)
+
+if edc:
+ names = [n for n, _ in calls(edc)]
+ check("empty_device_cache clears the MPS cache", "torch.mps.empty_cache" in names)
+ check("empty_device_cache clears the CUDA cache", "torch.cuda.empty_cache" in names)
+
+# No call site may go back to clearing only MPS — that was the original bug.
+main_calls = [n for n, _ in calls(main)]
+check("main() routes cache clears through empty_device_cache",
+ main_calls.count("empty_device_cache") >= 3)
+check("main() never calls torch.mps.empty_cache directly",
+ "torch.mps.empty_cache" not in main_calls)
+
+print()
+if FAILS:
+ print(f"❌ {len(FAILS)} check(s) failed: {', '.join(FAILS)}")
+ sys.exit(1)
+print("✅ all train_flux2_lora.py invariants hold")