Skip to content

Studio diffusion training: persistent conditioning cache on by default, wired into MiniMax-H3 - #18519

Merged
danielhanchen merged 4 commits into
mainfrom
studio-train-cond-cache-default
Nov 20, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-train-cond-cache-default

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

The persistent training conditioning cache (VAE latent stats and caption embeddings) is now on by default, and the MiniMax-H3 video and MiniMax-H3-Image trainers use it. Before this change it was opt-in, and only the DiT trainer read it. Both H3 trainers refused a cond_cache_dir, so every H3 re-run reloaded the 25 to 66 GB text encoder and re-encoded every clip or picture.

What changes

  • Default location. An unset or blank cond_cache_dir now means <account workspace>/cache/diffusion-train-cond. For the owner account that is <studio home>/cache/diffusion-train-cond, next to the other Studio caches.
    • The start route resolves this path, because the trainer subprocess does not carry the account context. Direct trainer calls fall back to the same helper.
    • The directory is outside the outputs root, so run listings, validate_job_paths and the outputs-root refusal behave as before.
    • An explicit directory is resolved and contained exactly as before. A value that resolves to the outputs root now falls back to the default directory instead of the in-memory cache.
  • Off switch.
    • cond_cache_dir: "off" (also none, 0, false, disabled) turns the cache off for one run.
    • UNSLOTH_DIFFUSION_TRAIN_COND_CACHE=0 turns off the default location. An explicit directory is still honoured.
  • Disk floor. A cache write that would leave under 2 GiB free on that disk is skipped, so the cache never takes the room the run needs to save its adapter; a failed write removes its temporary file.
  • Size cap. Each cache directory is capped by UNSLOTH_DIFFUSION_TRAIN_COND_CACHE_MAX_GB (default 20, 0 = no cap).
    • When a write goes over the cap, the least recently used entries are evicted down to 90% of the cap. Recency is the file mtime, refreshed on every hit.
    • Only files the cache wrote are ever removed. Eviction is best-effort and never fatal.
  • MiniMax-H3 video.
    • Caches caption embeddings, plus one entry per clip: video mean, video std and audio latents. These are the exact tensors and dtypes the in-memory path holds.
    • The clip key covers the canvas, frame count, fps, audio sample rate, channel count, audio latent count, the clip's bytes and a format version.
    • The namespace covers the base model and its revision. The caption key also covers the text encoder read layer.
    • On a full hit, neither the conditioner nor the VAEs are loaded.
  • MiniMax-H3-Image.
    • Caches caption and sample-prompt embeddings. Their key covers the conditioner repo, its revision, the int8 / bf16 encoder scheme and the read layer.
    • Caches one entry per picture (mean, std). Its key covers the base revision, resolution and picture bytes.
    • On a full hit, the conditioner is not loaded. The VAE still loads when previews are on, so previews keep rendering.
  • Revision changes. In both H3 trainers, if loading the model changes the revision (a first run reads unresolved before the download), the cache is re-keyed. Anything served under the old namespace is dropped.
  • DiT cold path. The DiT trainer now re-keys right after the conditioner load and before it encodes. Before this, it encoded under the pre-load namespace and copied the results across, so a fetch that moved refs/main could serve, and copy forward, the previous revision's caption embeddings. That was an opt-in path on main; it matters now that the cache is on by default.
  • RNG isolation. Loads and encodes run RNG-isolated, so a warm run and a cold run hand the same random streams to training.
  • Long names. Long cache namespaces, such as local base paths, are shortened with a hash, so keys stay under the 255-byte file-name limit. Before this, a deep local path could raise ENAMETOOLONG in the DiT trainer. A name that still cannot be used counts as a miss instead of an error.
  • Local base fingerprint. audio_vae/ is now part of the local-directory revision fingerprint.
  • SDXL still refuses an explicit directory and never gets the default.

Tests

New file: tests/test_diffusion_train_cond_cache_default.py. The route tests in tests/test_diffusion_training.py and the H3 knob test are updated. All of the following fail on the merge base and pass here:

  • An unset value picks the default directory, which sits outside the outputs root.
  • The off values and the env switch work, and the env switch leaves an explicit directory alone.
  • The size cap holds, with oldest-first eviction, touch-on-hit, and no removal of files the cache did not write.
  • A long local-path namespace still fits a file name.
  • The DiT trainer uses the default cache when unset, and a warm hit skips the conditioner load.
  • DiT: when the load moves the revision, the caption is encoded by the new weights, written under the new namespace, and the old namespace is left untouched (tests/test_diffusion_cond_cache_rekey.py).
  • MiniMax-H3 video: a warm re-run is torch.equal to the fresh encode and makes zero conditioner loads. A miss is forced by each of: caption, clip bytes, canvas, frame count, audio layout, base revision, format version. An unresolved first run is found by the resolved second run, and _train_h3 itself goes through the cache.
  • MiniMax-H3-Image: keys miss on encoder scheme, conditioner revision, base revision, resolution, picture bytes and format version. An end-to-end tiny-release run trained twice makes one conditioner load, the loss trajectory and the saved adapter are identical, and previews render on the warm run.
  • The route fills in the default, passes the off value through, and maps the outputs root to the default.

Regression run on CPU: the cond-cache, DiT trainer (all families), H3, H3-Image, SDXL trainer, samples, train extras, training route and download-phase suites. 878 passed, 1 skipped.

Not measured here

The time saved before the first training step on a warm re-run needs a GPU run with the real H3 encoder.

…t, wired into MiniMax-H3

The persistent conditioning cache (latent stats + caption embeddings) was opt-in and only read by
the DiT trainer; MiniMax-H3 video and MiniMax-H3-Image refused a cond_cache_dir. A re-run therefore
reloaded and re-ran the 25-66 GB H3 text encoder and every VAE encode.

- Unset cond_cache_dir now means a default directory: <account workspace>/cache/diffusion-train-cond
  (resolved by the start route, which holds the account context; the trainer falls back to the same
  helper for direct calls). Outside the outputs root, so run listings and the outputs-root checks are
  unaffected. An explicit directory behaves as before.
- Off switch: cond_cache_dir "off" (also none / 0 / false / disabled), or
  UNSLOTH_DIFFUSION_TRAIN_COND_CACHE=0 for the default location.
- Size cap per cache directory, UNSLOTH_DIFFUSION_TRAIN_COND_CACHE_MAX_GB (default 20, 0 = no cap):
  least recently used entries (mtime, refreshed on every hit) are evicted down to 90% of the cap.
  Only files the cache wrote are ever removed; best-effort, never fatal.
- MiniMax-H3 video: caption embeddings and per-clip (video mean, video std, audio latents) entries,
  keyed on base revision, read layer, canvas, frame count, fps, audio sample rate / channels / latent
  count, clip bytes and a format version. A full hit never loads the conditioner or the VAEs.
- MiniMax-H3-Image: caption and sample prompt embeddings keyed on the conditioner repo, its revision,
  the int8 / bf16 scheme and the read layer; per-picture (mean, std) keyed on base revision,
  resolution and picture bytes. A full hit never loads the conditioner; the VAE still loads for
  previews.
- Both H3 paths re-key when the load moves the revision (first run reads "unresolved"), dropping
  anything served under the old namespace, and run their loads and encodes RNG-isolated so a warm and
  a cold run train identically.
- Long namespaces (local base paths) are shortened with a hash so keys stay under the 255-byte file
  name limit; an unusable name is a miss instead of an error. audio_vae joins the local-dir revision
  fingerprint.
- SDXL keeps refusing an explicit directory and never gets the default.
…he cold encode, so a moved revision never serves or copies the old revision's embeddings
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T21:07:58.563027Z 689e4f7 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 660f113da7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +3814 to +3815
if cond_cache_off:
config["cond_cache_dir"] = "off"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exempt the cache-off sentinel from job path validation

For managed accounts, setting cond_cache_dir to "off" prevents training from starting. DiffusionTrainingService.start() calls validate_job_paths(config), which passes cond_cache_dir to account_jobs.account_path() as a filesystem path. The relative name off resolves against the backend working directory, outside the account workspace, and is rejected with HTTP 403. The same happens when the default cache is disabled through the environment, since this route also converts that case to "off". Teach the path validator about the sentinel or represent the disabled state separately from the path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 489b735: the job path check skips the off value, so managed accounts (and UNSLOTH_DIFFUSION_TRAIN_COND_CACHE=0) start normally; test added.

Comment on lines +627 to +631
for i, path in enumerate(clip_paths):
key = _h3_clip_key(pcache, path, width, height, num_frames, num_audio_latents)
hit = _cache_get(pcache, key)
if hit is not None:
clip_entries[i] = tuple(hit)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check the H3 memory budget before loading all cached clips

When a dataset exceeds the 4 GiB latent-cache budget but its clips already have persistent entries—for example, after combining several smaller datasets—this loop loads every clip's tensors into host memory before _check_h3_cache_budget() runs. Both the full-hit and partial-hit paths therefore allocate the oversized cache before rejecting it, potentially exhausting host memory instead of issuing the intended budget error. The previous cold path checked the estimate after encoding only the first clip; apply that check after the first cache hit as well, before retaining the remaining entries.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4c7f8d8359: the H3 budget check runs on the first cached clip, before any other entry is read (all clips share one canvas); tests cover full and partial hits.

"qwen3vl",
te_repo,
source_revision(te_repo),
text_encoder_scheme(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Key cached H3 captions by the encoder that produced them

text_encoder_scheme() still returns int8 when the hosted INT8 file is unavailable and load_h3_image_text_encoder() falls back to BF16. That writes BF16 embeddings under the INT8 key. Once the file is available again, a warm run skips the encoder. If the user adds a caption, the old one stays BF16 while the new one uses INT8 in the same training run.

I reproduced this on an RTX 3090 with a reduced-width H3 model, real BF16 and ConvRot INT8 weights derived from the same checkpoint, and a simulated download failure. After recovery, the cached caption differed from a fresh INT8 encode by 2.70% in relative L2. Four seed-matched steps produced different LoRA weights. Two fresh runs matched bit for bit.

Please carry the loader’s returned engaged scheme into the cache key after loading and re-read any earlier hits if the scheme changed. With that change, both the recovered and mixed-caption runs matched fresh INT8 training bit for bit.

danielhanchen added a commit that referenced this pull request Nov 19, 2026
…der (#18525)

## Summary

`Repo tests (CPU, rest)` fails intermittently (seen on #18519, which
only touches Studio diffusion training):

```
FAILED tests/test_packed_host_lengths_and_eval_flush.py::test_carry_leaves_other_moves_alone
tests/test_packed_host_lengths_and_eval_flush.py:65: in test_carry_leaves_other_moves_alone
    assert accelerate_data_loader.send_to_device._unsloth_host_lengths_carry
E   AttributeError: 'function' object has no attribute '_unsloth_host_lengths_carry'
```

Reproduced on `main` by running that test on its own: `1 failed`.

## Root cause

#18494 added the test. It asserts that
`accelerate.data_loader.send_to_device` carries Unsloth's host-lengths
wrapper, but nothing in the test installs it: the wrapper is installed
by `packing.enable_padding_free_metadata()`, which only the test above
it calls. Under xdist the two tests can land on different workers, or
run in the other order, and then the assertion reads the stock
`send_to_device`. The product code is fine; the test depended on its
neighbour.

## Changes

- The test calls `packing._install_host_lengths_carry()` first. It is
idempotent (it returns early when the wrapper is already in place), so
the test now states its own precondition and keeps checking the same
three things: no tuple on an unrelated move, none on a plain batch, and
the wrapper marker.

## Testing

- `test_carry_leaves_other_moves_alone` alone: passes (fails on `main`).
- The whole file, in order and under `-n 3`: 3 passed.
…g cache off, and keep cache writes off a nearly full disk

The start route now writes cond_cache_dir "off" for a run without the persistent cache, and the
service re-checks job paths before spawning, so for a non-owner account that value was resolved as a
relative path and refused with 403 (every run with "off" or UNSLOTH_DIFFUSION_TRAIN_COND_CACHE=0).
The off value names no directory and is no longer path-checked.

A cache write that would leave under 2 GiB free on its disk is skipped, so the default-on cache
cannot fill the disk the run saves its adapter to, and a write that fails (full disk, stop) no
longer leaves a partial .tmp file the size cap never counts.
… first persistent hit, before loading the rest

The warm-cache pre-scan read every clip's entry into host memory and only then ran the 4 GiB
latent-cache budget check, so an over-budget dataset with persistent entries allocated the whole
cache before being refused. Clips share one canvas, so the first hit sizes the cache: check it there.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 689e4f73a2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 5c77a16 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the studio-train-cond-cache-default branch November 20, 2026 03:31
danielhanchen added a commit that referenced this pull request Nov 20, 2026
#18519 added a size cap to the persistent training conditioning cache,
with least recently used eviction. Eviction decided ownership from the
file name alone: any `*.safetensors` starting with `lat_v`, `txt_v`,
`h3clip_v` or `h3img_v` was counted and could be unlinked. The cache
directory can be set by the user (`cond_cache_dir`), so a user's own
file in that directory such as `txt_vintage.safetensors` or
`txt_v1_my_embeddings.safetensors` was deleted once a write crossed the
cap.

## Change

- Every entry written by `PersistentConditioningCache.put` now carries
an owner marker (`unsloth_cond_cache: 1`) in its safetensors metadata.
- `_entries()` only considers a file that passes all of these checks:
  - it is a regular file, not a symlink;
- its name matches a cache key (`lat|txt|h3clip|h3img`, then `_v` and a
version digit);
- its safetensors header has the marker. Entries written before this
change are also accepted when their header holds exactly the metadata
the cache wrote then (`version`, `family`, `none_slots`, `count` over
`t<i>` tensors), so existing caches stay bounded.
- Only the header is read, at most 1 MiB. Files that are unreadable or
unexpected are never counted or removed.
- Files already confirmed are remembered per instance by name, inode and
size, so a rescan does not read their headers again.

Reads, keys and stored tensors are unchanged.

## Tests

- `test_eviction_never_touches_a_user_file_named_like_a_cache_key`
writes valid user safetensors files named with every cache prefix, plus
one with a partial lookalike header. It then fills the cache past a 1
byte cap. It fails on main (the user files are unlinked) and passes
here.
- `test_entries_written_before_the_owner_marker_are_still_evicted`
checks that an entry with the pre-marker metadata is still evicted
oldest first. It passes on both.
- `tests/test_diffusion_train_cond_cache_default.py`,
`test_diffusion_cond_cache.py`, `test_diffusion_cond_cache_rekey.py`,
`test_diffusion_h3_trainer.py`, `test_diffusion_train_extras.py`,
`test_diffusion_bucketing.py`, `test_diffusion_cond_blocks.py`,
`test_diffusion_dit_trainer_ltx25.py` and
`test_diffusion_prompt_cache.py`:
  - main: 348 passed, 15 failed;
  - this branch: 350 passed, 15 failed.

The same 15 test IDs fail on both. They are environment failures
(missing `jwt` and similar optional modules on the CPU test host).

## Not proven

- The cost of the header read on a very large cache directory (tens of
thousands of entries) was not timed. It runs once per instance and again
only when eviction triggers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants