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

refactor([issue-2786]): apply /simplify review to the CUDA trainer fix

[._.]/ Adam Eivyf544725e9307
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
index 1d9d56ed3d..e5881d8c2a 100644
--- a/docs/research/2026-08-05-torch-flux2-lora-cuda-validation.md
+++ b/docs/research/2026-08-05-torch-flux2-lora-cuda-validation.md
@@ -83,10 +83,29 @@ at 7.77 GB.
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).
+**Fix.** Two layers, because the region-level fix alone leaves the class of bug
+alive:
+
+- **Root cause — freeze at load.** `pipe.text_encoder.requires_grad_(False)` and
+ `pipe.vae.requires_grad_(False)` right after `from_pretrained`, joining the
+ `transformer.requires_grad_(False)` the trainer already did (hoisted up beside
+ them, so one place states the real invariant: nothing is trainable until
+ `add_adapter` runs). `requires_grad` is a property of the *module*, so
+ clearing it makes "an inference forward silently built a graph" unreachable
+ from every call site — where a `no_grad` block only protects the one region
+ someone remembered to wrap. Both encoders take grad-free inputs (token ids; a
+ tensor built from numpy), so this alone is sufficient.
+- **Belt — `torch.no_grad()` on precompute.** Kept, because it additionally
+ suppresses graph-building when an *input* carries a `grad_fn`, which clearing
+ the params cannot.
+
+Separately, the allocator cache is now cleared on CUDA as well as MPS. That
+became `empty_device_cache(device, *, synchronize=False)` in
+`scripts/_runner_common.py` — the shared runner module — rather than a local
+helper, since `flux2_macos.py` and `z_image_turbo.py` already carry their own
+copies of the same dispatch. It keys on the **resolved device string** rather
+than `torch.cuda.is_available()`, so a `--device cpu` run on a CUDA box no
+longer clears a cache it never filled.
## Bug 2 — sample render decoded the VAE on CPU in bf16 (reads as a hang)
@@ -110,6 +129,13 @@ 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**.
+Both the move and the decode sit inside the `try` whose `finally` restores the
+VAE. `.to()` walks parameters one at a time, so a throw partway through the move
+would otherwise leave the VAE straddling two devices with the `finally` never
+entered — and since the caller treats samples as best-effort and swallows the
+exception, the next sample would read the now-`cuda` resting place as its
+"home" and latch the VAE on-device for the rest of the run.
+
## Result — full end-to-end run
```
@@ -173,13 +199,26 @@ 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.
+the trainer's AST) pins the invariants: the three modules are frozen at load,
+precompute's `encode_prompt`/`_encode_vae_image` run under `torch.no_grad()`,
+`render_sample` moves the VAE on-device inside the `try` and restores it in the
+`finally`, and no bare `torch.{mps,cuda}.empty_cache` survives anywhere in the
+module. Behavioral tests aren't possible here — exercising these paths needs
+torch, a ~16 GB download, and a CUDA card.
+
+Each check was **mutation-tested**, since a guard that cannot fail is worthless:
+all seven regressions (stripping the `try/finally`, a bare
+`torch.cuda.empty_cache()`, re-declaring the helper locally as MPS-only,
+dropping `no_grad`, dropping either `requires_grad_(False)`, decoding off-device)
+are caught, while two legitimate refactors that change no behavior — nesting the
+`with` guards, and the `pipe.vae.to(device=device)` keyword form — stay green.
+That last pair matters: an earlier draft of this test keyed on one `with`
+statement's shape and went red on the nesting refactor while *passing* three of
+the regressions above.
+
+`scripts/_runner_common_test.py` covers the relocated helper directly, stubbing
+`sys.modules["torch"]` (the helper defers its import) to assert it dispatches on
+the resolved device and clears nothing on `cpu`.
## Outcome
diff --git a/scripts/_runner_common.py b/scripts/_runner_common.py
index cb4638e044..b0051cac02 100644
--- a/scripts/_runner_common.py
+++ b/scripts/_runner_common.py
@@ -231,6 +231,31 @@ def pick_device(requested: str) -> str:
return requested
+def empty_device_cache(device: str, *, synchronize: bool = False) -> None:
+ """Return cached-but-free blocks to the driver for the RESOLVED device.
+
+ The caching allocator otherwise holds them, which starves a later large
+ contiguous allocation (moving a multi-GB transformer onto the card) even
+ though the memory is nominally free.
+
+ Keyed on the device string `pick_device` resolved — NOT on
+ `torch.cuda.is_available()`. A capability probe is the wrong predicate: on a
+ box that *has* a CUDA card but is running `--device cpu`, probing would clear
+ a cache this process never filled.
+
+ `synchronize=True` also drains the queue first, for callers that want the
+ reclaim to have actually happened before they measure or allocate."""
+ import torch
+ if device == "mps":
+ torch.mps.empty_cache()
+ if synchronize:
+ torch.mps.synchronize()
+ elif device == "cuda":
+ torch.cuda.empty_cache()
+ if synchronize:
+ torch.cuda.synchronize()
+
+
def make_generator(device: str, seed: int) -> "torch.Generator":
"""Seed a torch Generator on the right device. Accelerator generators
must be initialised with the device string; the CPU fallback uses the
diff --git a/scripts/_runner_common_test.py b/scripts/_runner_common_test.py
index 0255d15dd5..55e6c82b9a 100644
--- a/scripts/_runner_common_test.py
+++ b/scripts/_runner_common_test.py
@@ -9,9 +9,15 @@ scripts/train_mflux_lora_test.py.
import sys
from pathlib import Path
+# ✅/❌ are cp1252-unencodable on a Windows console, which would abort the run
+# before the first result printed — these runners are used on CUDA/Windows too.
+if hasattr(sys.stdout, "reconfigure"):
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _runner_common import ( # noqa: E402
apply_memory_optimizations,
+ empty_device_cache,
set_vae_tiling,
_VAE_TILING_MIN_PIXELS,
)
@@ -152,6 +158,61 @@ set_vae_tiling(p, False)
check("set_vae_tiling on bare pipe is a no-op (no crash)", p.calls == [])
+# --- empty_device_cache: dispatches on the RESOLVED device, not on capability -
+# `empty_device_cache` defers its `import torch`, so a stub in sys.modules is
+# enough to observe the dispatch without needing real torch (or a GPU).
+
+
+class _FakeBackend:
+ def __init__(self):
+ self.emptied = self.synced = 0
+
+ def empty_cache(self):
+ self.emptied += 1
+
+ def synchronize(self):
+ self.synced += 1
+
+
+class _FakeTorch:
+ def __init__(self):
+ self.cuda = _FakeBackend()
+ self.mps = _FakeBackend()
+
+
+def _clear(device, **kw):
+ """Run empty_device_cache against a stub torch; return it for assertions."""
+ fake = _FakeTorch()
+ saved = sys.modules.get("torch")
+ sys.modules["torch"] = fake
+ try:
+ empty_device_cache(device, **kw)
+ finally:
+ if saved is None:
+ del sys.modules["torch"]
+ else:
+ sys.modules["torch"] = saved
+ return fake
+
+
+_cuda = _clear("cuda")
+check("empty_device_cache('cuda') clears the CUDA cache", _cuda.cuda.emptied == 1)
+check("empty_device_cache('cuda') leaves MPS alone", _cuda.mps.emptied == 0)
+
+_mps = _clear("mps")
+check("empty_device_cache('mps') clears the MPS cache", _mps.mps.emptied == 1)
+check("empty_device_cache('mps') leaves CUDA alone", _mps.cuda.emptied == 0)
+
+# The resolved-device predicate is the point: a `--device cpu` run on a machine
+# that HAS a CUDA card must not clear a cache this process never filled.
+_cpu = _clear("cpu")
+check("empty_device_cache('cpu') clears nothing",
+ _cpu.cuda.emptied == 0 and _cpu.mps.emptied == 0)
+
+check("empty_device_cache does not synchronize by default", _clear("cuda").cuda.synced == 0)
+check("empty_device_cache(synchronize=True) drains the queue",
+ _clear("cuda", synchronize=True).cuda.synced == 1)
+
if FAILS:
print(f"\n❌ {len(FAILS)} test(s) failed:")
for f in FAILS:
diff --git a/scripts/train_flux2_lora.py b/scripts/train_flux2_lora.py
index 11a34fab99..4f163fcb0f 100644
--- a/scripts/train_flux2_lora.py
+++ b/scripts/train_flux2_lora.py
@@ -6,8 +6,10 @@ 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's unified memory and,
-just as much, on a consumer CUDA card (a 24 GB 3090 has no headroom to spare):
+Two phases keep peak memory survivable on a consumer CUDA card (a 24 GB 3090
+has no headroom to spare). The split was written for Apple Silicon's unified
+memory, but `main()` now refuses MPS outright — see the guard below — so CUDA
+and CPU are the runtimes this actually serves:
1. STAGE:precompute-latents — encode every dataset image to VAE latents
and every caption to Qwen3 text embeddings ONCE, then free the text
@@ -42,6 +44,7 @@ from PIL import Image
sys.path.insert(0, str(Path(__file__).resolve().parent))
from _runner_common import ( # noqa: E402
+ empty_device_cache,
heartbeat,
install_hf_error_handler,
pick_device,
@@ -63,19 +66,6 @@ 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)")
@@ -196,11 +186,15 @@ def render_sample(pipe, transformer, embeds, text_ids, resolution, device, dtype
# 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.
+ # device for one decode is cheap.
+ # The move goes INSIDE the try: `.to()` walks parameters one at a time, so a
+ # throw partway leaves the VAE straddling both devices. Outside the try the
+ # `finally` would never run, and the next sample would read the now-`cuda`
+ # resting place as `vae_home` — silently latching it on-device for the rest
+ # of the run, on the card that just proved it has no headroom to spare.
vae_home = next(pipe.vae.parameters()).device
- pipe.vae.to(device)
try:
+ pipe.vae.to(device)
image = pipe.vae.decode(unpacked.to(device, pipe.vae.dtype), return_dict=False)[0]
finally:
pipe.vae.to(vae_home)
@@ -251,19 +245,34 @@ def main():
with heartbeat("load-pipeline"):
pipe = Flux2KleinPipeline.from_pretrained(args.model_repo, torch_dtype=dtype)
+ # Nothing in this pipeline is trainable until `add_adapter` introduces the
+ # LoRA below — say so once, here, rather than leaving it to whatever
+ # `from_pretrained` happened to return. This is the root-cause form of the
+ # precompute leak described further down: `requires_grad` is a property of
+ # the module, so clearing it makes the whole class of "inference forward
+ # silently built an autograd graph" unreachable from EVERY call site,
+ # present and future — where a `torch.no_grad()` block only protects the one
+ # region someone remembered to wrap. Both encoders take grad-free inputs
+ # (token ids; a tensor built from numpy), so this alone is sufficient; the
+ # `no_grad` below is kept as the belt to this pair of braces.
+ pipe.text_encoder.requires_grad_(False)
+ pipe.vae.requires_grad_(False)
+ pipe.transformer.requires_grad_(False)
+
# ---- Phase 1: precompute text embeddings + image latents ----
log("STAGE:precompute-latents")
sample_prompt = args.sample_prompt or f"{args.trigger_word} portrait, neutral background"
examples = []
- # `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.
+ # `no_grad` is load-bearing here, not a micro-optimization — it is the
+ # second half of the `requires_grad_(False)` pair above. Left unguarded with
+ # trainable params, every encode builds and keeps a full autograd graph, and
+ # the `.to("cpu")` cache copy inherits that `grad_fn` and pins it on-device:
+ # ~2.6 GB of Qwen3 activations PER UNIQUE CAPTION on FLUX.2-klein-4B. A
+ # 128 GB unified-memory Mac absorbs that silently; 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. Keeping both is
+ # deliberate: `no_grad` additionally suppresses graph-building when an INPUT
+ # carries a `grad_fn`, which clearing the params cannot.
with torch.no_grad(), heartbeat("precompute-latents"):
pipe.text_encoder.to(device)
embed_cache = {}
@@ -302,8 +311,7 @@ def main():
# ---- Phase 2: training ----
log("STAGE:training")
- transformer = pipe.transformer
- transformer.requires_grad_(False)
+ transformer = pipe.transformer # already frozen at load, with the encoders
targets = lora_target_modules(transformer)
log(f"STATUS:LoRA targets: {', '.join(targets)} (rank {args.rank})")
# Always create the single trainable `default` adapter (gaussian init). On
diff --git a/scripts/train_flux2_lora_test.py b/scripts/train_flux2_lora_test.py
index 6071deb2c7..1efddd4c04 100644
--- a/scripts/train_flux2_lora_test.py
+++ b/scripts/train_flux2_lora_test.py
@@ -2,23 +2,16 @@
"""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
+Exits non-zero if any check fails. 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).
+exercising the real paths needs torch, a ~16 GB base download and a CUDA card,
+which no test suite can carry. So they pin *structural* invariants only — each
+one chosen because breaking it silently reintroduces a fault that made this
+trainer unusable on a 24 GB card, and because no reasonable refactor breaks it
+without also breaking the invariant. Background and measurements: issue #2786
+and docs/research/2026-08-05-torch-flux2-lora-cuda-validation.md.
"""
import ast
import sys
@@ -43,14 +36,16 @@ def check(name, cond):
def func(name):
+ """The named top-level function, or exit — a missing function would make
+ every check about it vacuously pass."""
for node in ast.walk(TREE):
if isinstance(node, ast.FunctionDef) and node.name == name:
return node
- return None
+ sys.exit(f"❌ {name}() not found in {SRC.name} — the file was restructured")
def calls(node):
- """Every call in `node`, rendered as a dotted name (e.g. torch.no_grad)."""
+ """Every call under `node` as (dotted_name, Call), e.g. pipe.vae.to."""
out = []
for n in ast.walk(node):
if isinstance(n, ast.Call):
@@ -64,86 +59,99 @@ def calls(node):
return out
-# --- 1. precompute is wrapped in torch.no_grad() -----------------------------
+def names_in(call):
+ """Identifiers passed to `call`, positionally or by keyword — so a check
+ isn't defeated by `.to(device=device)` vs `.to(device)`."""
+ args = list(call.args) + [k.value for k in call.keywords]
+ return {a.id for a in args if isinstance(a, ast.Name)}
+
+
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,
+main_calls = calls(main)
+
+# --- 1. inference-only modules are frozen at load ----------------------------
+# The root-cause form of the precompute leak: `requires_grad` is a property of
+# the module, so clearing it makes "an inference forward silently built an
+# autograd graph" unreachable from every call site, not just the wrapped one.
+frozen = {
+ name.rsplit(".", 2)[-2]
+ for name, c in main_calls
+ if name.endswith(".requires_grad_")
+ and c.args and isinstance(c.args[0], ast.Constant) and c.args[0].value is False
+}
+for module in ("text_encoder", "vae", "transformer"):
+ check(f"main() freezes {module} with requires_grad_(False) at load "
+ f"(root-cause guard for the ~2.6 GB/caption leak — issue #2786)",
+ module in frozen)
+
+# --- 2. precompute's inference runs under torch.no_grad() --------------------
+# Belt to the braces above. Located by walking every no_grad block in main()
+# rather than by matching one `with` statement's shape, so nesting the guard or
+# extracting precompute into its own block keeps passing.
+no_grad_blocks = [
+ n for n in ast.walk(main)
+ if isinstance(n, ast.With) and any(
+ isinstance(i.context_expr, ast.Call)
+ and getattr(i.context_expr.func, "attr", None) == "no_grad"
+ for i in n.items
)
- # 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 -------------------------
+]
+check("main() has a torch.no_grad() block", bool(no_grad_blocks))
+for fn in ("encode_prompt", "_encode_vae_image"):
+ check(f"precompute's {fn} runs under torch.no_grad()",
+ any(any(n.endswith(fn) for n, _ in calls(b)) for b in no_grad_blocks))
+
+# --- 3. render_sample decodes on the training device, and always restores ----
+# Precompute parks the VAE on CPU, but the pipeline is bf16 and x86 has no fast
+# bf16 conv path, so decoding there reads as a hang (>18 min for one 512-px
+# decode). The restore must be in a `finally`: the caller treats samples as
+# best-effort and swallows exceptions, so a throw mid-decode would otherwise
+# strand the VAE on-device for the rest of the run.
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)
+decode_try = None
+for node in ast.walk(rs):
+ if isinstance(node, ast.Try) and any(
+ n.endswith("vae.decode") for n, _ in calls(node)
+ ):
+ decode_try = node
+
+check("render_sample wraps vae.decode in a try (issue #2786)", decode_try is not None)
+
+if decode_try:
+ check("render_sample moves the VAE onto `device` inside that try "
+ "(bf16 conv on CPU hangs — issue #2786)",
+ any(n.endswith("vae.to") and "device" in names_in(c)
+ for n, c in calls(ast.Module(body=decode_try.body, type_ignores=[]))))
+ check("render_sample restores the VAE to `vae_home` in the try's finally",
+ any(n.endswith("vae.to") and "vae_home" in names_in(c)
+ for n, c in calls(ast.Module(body=decode_try.finalbody, type_ignores=[]))))
+
+# --- 4. cache clearing goes through the shared, device-agnostic helper -------
+# The original bug was an MPS-only `torch.mps.empty_cache()`, so a bare clear of
+# EITHER backend is the regression — banning only the MPS spelling would let the
+# mirror image straight back in.
+module_calls = [n for n, _ in calls(TREE)]
+check("no bare torch.mps/cuda.empty_cache anywhere in the module — "
+ "clears route through _runner_common.empty_device_cache",
+ not ({"torch.mps.empty_cache", "torch.cuda.empty_cache"} & set(module_calls)))
+check("the trainer actually calls empty_device_cache",
+ "empty_device_cache" in module_calls)
+imported_from_common = any(
+ isinstance(n, ast.ImportFrom) and n.module == "_runner_common"
+ and any(a.name == "empty_device_cache" for a in n.names)
+ for n in ast.walk(TREE)
+)
+redeclared_locally = any(
+ isinstance(n, ast.FunctionDef) and n.name == "empty_device_cache"
+ for n in ast.walk(TREE)
+)
+check("empty_device_cache comes from _runner_common, not a local re-declaration",
+ imported_from_common and not redeclared_locally)
print()
if FAILS:
- print(f"❌ {len(FAILS)} check(s) failed: {', '.join(FAILS)}")
+ print(f"❌ {len(FAILS)} check(s) failed:")
+ for f in FAILS:
+ print(f" - {f}")
sys.exit(1)
print("✅ all train_flux2_lora.py invariants hold")