Skip to content

Stop a redundant step-cache engage from tearing the cache down - #11174

Merged
danielhanchen merged 23 commits into
mainfrom
studio-step-cache-guard
Sep 18, 2026
Merged

danielhanchen merged 23 commits into
mainfrom
studio-step-cache-guard

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The bug

diffusers' CacheMixin.enable_cache raises when a cache is already enabled:

ValueError: Caching has already been enabled with <class 'FirstBlockCacheConfig'>.
To apply a new caching technique, please disable the existing one first.

apply_step_cache never checks is_cache_enabled before calling it, so a second call on the same transformer lands in the recovery branch, which calls disable_cache() and returns None. One redundant call and the working First-Block-Cache is gone, reported only at warning level.

The recovery branch also leaves transformer._unsloth_step_cache set. That marker is read well away from here as "this transformer step caches": GraphedForward.__call__ short-circuits straight to eager on it, before it even computes a graph key. A marker left set by a failed engage therefore sends a transformer that is not caching down the caching path for the rest of the process.

I hit this in a benchmark harness that cleared the marker without calling disable_cache. The two states desynced, the per-generate auto re-check then tore the cache off and put it back on across renders, and a whole set of measurements was silently invalid. The harness was wrong, but the guard here would have made it a no-op.

The fix

  • Same mode and threshold on an already-cached transformer is a no-op that returns the engaged mode. enable_cache and disable_cache are not called at all.
  • Different settings are a real reconfigure: disable_cache first, then engage, which is the only order diffusers accepts. The marker ends up describing the new threshold.
  • If the reconfigure itself cannot drop the old cache, report the mode that is still engaged rather than None. The hooks are live either way, and a None there would claim uncached while the transformer caches, which is the same desync this guard exists to prevent.
  • The recovery branch clears the marker alongside the hooks it already restores.

The reverse desync is handled too: a marker set on a transformer whose hooks are gone means the cache is genuinely off, so the engage proceeds and rewrites the marker instead of trusting it.

Scope

Latent, not live. Nothing on main calls apply_step_cache twice on one transformer today, so no shipped path changes behaviour. This closes the gap before something does.

Tests

Four new tests in studio/backend/tests/test_diffusion_cache.py, on a _RealisticCacheMixin fixture that models what diffusers actually does (enable_cache raises when enabled, is_cache_enabled reports live state). The existing stub models neither, which is why the defect was invisible in tests.

Three of the four fail on main and pass with the fix:

FAILED test_a_redundant_engage_keeps_the_running_cache
FAILED test_re_engaging_at_a_new_threshold_reconfigures
FAILED test_a_failed_re_engage_clears_the_marker

The fourth pins the stale-marker direction so the new early return cannot be rewritten to key on the marker alone.

Suites run on this branch:

  • studio/backend/tests/test_diffusion_cache.py: 44 passed
  • test_diffusion_backend.py, test_diffusion_speed.py, test_video_backend.py, test_dynamo_import_window.py: 831 passed
  • ruff check clean

diffusers' enable_cache raises ValueError when a cache is already enabled, so a second
apply_step_cache on the same transformer lands in the recovery branch, which calls
disable_cache() and returns None. One redundant call and the working First-Block-Cache is
gone, reported only at warning level.

Same settings are now a no-op. Different settings go through disable_cache first, which is
the only order diffusers accepts a new config in. The recovery branch also clears
_unsloth_step_cache: that marker is read well away from here as "this transformer step
caches" (the CUDA graph wrapper short-circuits to eager on it), so a marker left set by a
failed engage sends a transformer that is not caching down the caching path for the rest of
the process.

Latent rather than live: nothing on main calls apply_step_cache twice on one transformer
today. Three of the four new tests fail without the fix.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-18T13:17:55.715432Z 8e820aa New commits
🔒 Security Review ✅ Completed 2026-09-17T12:25:42.616926Z e739195 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 3 commits September 17, 2026 04:04
The recovery branch cleared _unsloth_step_cache unconditionally after a failed engage. If
disable_cache() ALSO raises, the hooks are still live, and clearing the marker there reintroduces the
desync this guard exists to remove, only pointing the other way.

The two directions are not equally bad. A marker left set on a transformer that is not caching forces
eager in the CUDA graph wrapper: slower, still correct. A marker cleared while hooks are live lets the
wrapper capture a graph over a cache-hooked forward, which is wrong output. So the marker now tracks
the hooks rather than this function's intent: it comes off when disable_cache succeeded, or when it
raised but the model still reports is_cache_enabled False, meaning the hooks went anyway. When
disable_cache raised and the cache reads as enabled, the marker stays and the slow path is the one we
land on.

Two tests: the preserved case fails without the change, and the paired case pins that a cleanup which
did unhook still clears the marker, so this does not just pin the marker on forever.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: e739195bc7

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

The re-entry guard's cleanup runs two statements, and which one raised changes the answer.
_restore_hooked_block_inners raising means disable_cache never ran, so the cache is still live and
reporting the prior mode is right. disable_cache raising can still have taken the hooks off first, and
there the old behaviour returned the prior mode and left the marker set on a transformer that no
longer caches: pinned to the eager path, and every later auto-cache call skipping the re-enable
because the marker says it is already caching.

So consult is_cache_enabled, as the failure-recovery branch below now does. Still caching keeps the
prior mode. Not caching means the reconfiguration this call asked for is what happened, so the stale
marker is dropped and the engage proceeds at the new settings.

Two tests, one per side. The re-engage case fails without the change.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… they are gone

After a failed enable_cache, neither signal the last round relied on can be trusted. Checked against
the pinned diffusers 0.40: CacheMixin.enable_cache assigns _cache_config as its LAST statement, after
apply_first_block_cache returns, and disable_cache logs a warning and returns when _cache_config is
None. So a raise part-way through hooking leaves the installed hooks LIVE while is_cache_enabled reads
False and disable_cache is a silent no-op. Both say uncached about a transformer that is partly hooked,
and clearing the marker there lets the CUDA graph wrapper capture that forward.

_unhook_first_block_cache removes both FBCache hooks by name through HookRegistry, the layer under
diffusers' own teardown. remove_hook skips a name that is not registered and recurses into every
submodule, so it is safe whatever got installed, and it clears the dangling _cache_config. The marker
now comes off only when that removal is known to have happened; when the registry or the hook names
cannot be reached it stays set and the transformer keeps the eager path, which is slower and not wrong.

The round-one test asserted the best answer available when is_cache_enabled was all we could ask; it
now asserts the stronger property that the hooks were actually removed. Two new tests, one modelling
the silent partial engage above and one the unverifiable teardown. Both new ones fail on the previous
head.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…branch

disable_cache removes the FBC leader and block hooks in SEPARATE remove_hook calls and clears
_cache_config only after both, so a raise between them leaves block hooks installed with no leader to
make the skip decision, while is_cache_enabled still reads True. The guard then reported the prior
cache as healthy when half of it was gone, and the next generation skips blocks on stale state.

Half a cache is not the prior cache, so the guard now runs the same _unhook_first_block_cache the
recovery branch does: finish the removal by name, then re-engage at the new settings. It still reports
the prior mode when the removal cannot be verified at all, which is the only case left where asking
is the best available answer.

Both cleanup paths now go through one primitive instead of two different readings of is_cache_enabled.
The round-two test asserted the old diagnose-only behaviour and now covers the unverifiable case,
which is what it was really pinning; the new test for the mid-teardown raise fails on the previous head.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

_cache_config is GENERIC across every cache CacheMixin supports, and disable_cache dispatches on its
type. So a transformer running MagCache, FasterCache or PAB whose teardown raises arrives in this
fallback looking exactly like a broken FBC one. Removing FBC's two hook names does nothing for it, and
clearing the state made diffusers forget a cache that is still installed, after which enable_cache
stacks FBC on top of the live hooks.

The unhook now declines when _cache_config is some other config type, which the caller already reads
as unverified: it reports the cache that is actually running and leaves it alone. Matched by class
name because the config is exported from two different modules depending on the diffusers version.

One test, failing without the change. The mid-teardown fixture from the last round used a bare object
as the stand-in config and is now an FBC-named one, which is what it was always meant to represent.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

The fast path compared _unsloth_step_cache against the requested settings, so a transformer whose
cache someone else engaged, or whose marker went stale, took the reconfigure path even when the live
FirstBlockCacheConfig already carried this exact threshold. That tears down a healthy cache and
rebuilds an identical one, which is the thing this guard exists to prevent, and loses it outright if
the rebuild then fails.

The live _cache_config decides now, and the marker is repaired on the way out rather than being
trusted as the source of truth. That is the same direction as the rest of the PR: every earlier round
established a way the marker can disagree with the hooks, so it is the derived value, not the fact.

One test, failing without the change: a transformer cached by hand, with no marker at all, keeps its
cache untouched and comes back with the marker written.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

A cache adopted from apply_first_block_cache has no _cache_config, so diffusers'
disable_cache warns and returns having removed nothing. maybe_toggle_step_cache
cleared the marker on the strength of that call, leaving it clear over live FBCache
hooks and reporting the transformer uncached, which is the state GraphedForward
reads as safe to capture. Take the hooks off by name and clear the marker only once
they are known gone; an unverifiable teardown keeps the marker and stays engaged.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 18, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b199c39380

ℹ️ 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".

Comments only, AST verified. diffusion_cache.py 111 comment lines to 71 (24.1% to
17.1% of non-blank); the merge base was 11.9%, so the excess was this branch's.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 18, 2026

@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: 8e820aac60

ℹ️ 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 +159 to +160
registry.remove_hook(_FBC_LEADER_BLOCK_HOOK, recurse = True)
registry.remove_hook(_FBC_BLOCK_HOOK, recurse = True)

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 Invalidate the child-registry cache before recursive teardown

If an uncached generation previously populated _child_registries_cache with the empty list described above and enable_cache then fails after installing hooks on some blocks, these recursive removals traverse that stale empty list and never reach the live child hooks. The helper nevertheless clears _cache_config, returns True, and lets callers clear the marker, leaving partially hooked forwards active and potentially causing generation failures or unsafe graph capture. Clear the registry cache before removal and verify that no FBC hooks remain before reporting success.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 9cf1f6e into main Sep 18, 2026
28 of 38 checks passed
@danielhanchen
danielhanchen deleted the studio-step-cache-guard branch September 18, 2026 13:40
danielhanchen added a commit that referenced this pull request Sep 18, 2026
…1263)

* Stop a redundant step-cache engage from tearing the cache down (#11174)

* Stop a redundant step-cache engage from tearing the cache down

diffusers' enable_cache raises ValueError when a cache is already enabled, so a second
apply_step_cache on the same transformer lands in the recovery branch, which calls
disable_cache() and returns None. One redundant call and the working First-Block-Cache is
gone, reported only at warning level.

Same settings are now a no-op. Different settings go through disable_cache first, which is
the only order diffusers accepts a new config in. The recovery branch also clears
_unsloth_step_cache: that marker is read well away from here as "this transformer step
caches" (the CUDA graph wrapper short-circuits to eager on it), so a marker left set by a
failed engage sends a transformer that is not caching down the caching path for the rest of
the process.

Latent rather than live: nothing on main calls apply_step_cache twice on one transformer
today. Three of the four new tests fail without the fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the step-cache marker when the cleanup could not take the hooks off

The recovery branch cleared _unsloth_step_cache unconditionally after a failed engage. If
disable_cache() ALSO raises, the hooks are still live, and clearing the marker there reintroduces the
desync this guard exists to remove, only pointing the other way.

The two directions are not equally bad. A marker left set on a transformer that is not caching forces
eager in the CUDA graph wrapper: slower, still correct. A marker cleared while hooks are live lets the
wrapper capture a graph over a cache-hooked forward, which is wrong output. So the marker now tracks
the hooks rather than this function's intent: it comes off when disable_cache succeeded, or when it
raised but the model still reports is_cache_enabled False, meaning the hooks went anyway. When
disable_cache raised and the cache reads as enabled, the marker stays and the slow path is the one we
land on.

Two tests: the preserved case fails without the change, and the paired case pins that a cleanup which
did unhook still clears the marker, so this does not just pin the marker on forever.

* Ask the model whether the re-configure cleanup actually unhooked

The re-entry guard's cleanup runs two statements, and which one raised changes the answer.
_restore_hooked_block_inners raising means disable_cache never ran, so the cache is still live and
reporting the prior mode is right. disable_cache raising can still have taken the hooks off first, and
there the old behaviour returned the prior mode and left the marker set on a transformer that no
longer caches: pinned to the eager path, and every later auto-cache call skipping the re-enable
because the marker says it is already caching.

So consult is_cache_enabled, as the failure-recovery branch below now does. Still caching keeps the
prior mode. Not caching means the reconfiguration this call asked for is what happened, so the stale
marker is dropped and the engage proceeds at the new settings.

Two tests, one per side. The re-engage case fails without the change.

* Take the cache hooks off directly instead of asking diffusers whether they are gone

After a failed enable_cache, neither signal the last round relied on can be trusted. Checked against
the pinned diffusers 0.40: CacheMixin.enable_cache assigns _cache_config as its LAST statement, after
apply_first_block_cache returns, and disable_cache logs a warning and returns when _cache_config is
None. So a raise part-way through hooking leaves the installed hooks LIVE while is_cache_enabled reads
False and disable_cache is a silent no-op. Both say uncached about a transformer that is partly hooked,
and clearing the marker there lets the CUDA graph wrapper capture that forward.

_unhook_first_block_cache removes both FBCache hooks by name through HookRegistry, the layer under
diffusers' own teardown. remove_hook skips a name that is not registered and recurses into every
submodule, so it is safe whatever got installed, and it clears the dangling _cache_config. The marker
now comes off only when that removal is known to have happened; when the registry or the hook names
cannot be reached it stays set and the transformer keeps the eager path, which is slower and not wrong.

The round-one test asserted the best answer available when is_cache_enabled was all we could ask; it
now asserts the stronger property that the hooks were actually removed. Two new tests, one modelling
the silent partial engage above and one the unverifiable teardown. Both new ones fail on the previous
head.

* Finish the teardown in the re-entry guard too, not just the recovery branch

disable_cache removes the FBC leader and block hooks in SEPARATE remove_hook calls and clears
_cache_config only after both, so a raise between them leaves block hooks installed with no leader to
make the skip decision, while is_cache_enabled still reads True. The guard then reported the prior
cache as healthy when half of it was gone, and the next generation skips blocks on stale state.

Half a cache is not the prior cache, so the guard now runs the same _unhook_first_block_cache the
recovery branch does: finish the removal by name, then re-engage at the new settings. It still reports
the prior mode when the removal cannot be verified at all, which is the only case left where asking
is the best available answer.

Both cleanup paths now go through one primitive instead of two different readings of is_cache_enabled.
The round-two test asserted the old diagnose-only behaviour and now covers the unverifiable case,
which is what it was really pinning; the new test for the mid-teardown raise fails on the previous head.

* Do not tear down a cache that is not ours

_cache_config is GENERIC across every cache CacheMixin supports, and disable_cache dispatches on its
type. So a transformer running MagCache, FasterCache or PAB whose teardown raises arrives in this
fallback looking exactly like a broken FBC one. Removing FBC's two hook names does nothing for it, and
clearing the state made diffusers forget a cache that is still installed, after which enable_cache
stacks FBC on top of the live hooks.

The unhook now declines when _cache_config is some other config type, which the caller already reads
as unverified: it reports the cache that is actually running and leaves it alone. Matched by class
name because the config is exported from two different modules depending on the diffusers version.

One test, failing without the change. The mid-teardown fixture from the last round used a bare object
as the stand-in config and is now an FBC-named one, which is what it was always meant to represent.

* Ask the model, not the marker, whether the call is redundant

The fast path compared _unsloth_step_cache against the requested settings, so a transformer whose
cache someone else engaged, or whose marker went stale, took the reconfigure path even when the live
FirstBlockCacheConfig already carried this exact threshold. That tears down a healthy cache and
rebuilds an identical one, which is the thing this guard exists to prevent, and loses it outright if
the rebuild then fails.

The live _cache_config decides now, and the marker is repaired on the way out rather than being
trusted as the source of truth. That is the same direction as the rest of the PR: every earlier round
established a way the marker can disagree with the hooks, so it is the derived value, not the fact.

One test, failing without the change: a transformer cached by hand, with no marker at all, keeps its
cache untouched and comes back with the marker written.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let only the live cache config authorize the no-op, and integrate one we adopt

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Leave an FBCache installed through the low-level API alone

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Integrate and mark a low-level cache before reporting it engaged

Adopting hooks installed through apply_first_block_cache ran neither post-enable
step and left _unsloth_step_cache clear over live hooks, which is the marker
GraphedForward.__call__ short-circuits to eager on: the CUDA graph wrapper could
capture a cache-hooked forward whose skip decision is data-dependent. Run the
same integration the live-config branch runs, and set the marker (mode only,
since the adopted cache's threshold is its installer's) before returning.

* Unhook an adopted cache in auto mode instead of trusting disable_cache

A cache adopted from apply_first_block_cache has no _cache_config, so diffusers'
disable_cache warns and returns having removed nothing. maybe_toggle_step_cache
cleared the marker on the strength of that call, leaving it clear over live FBCache
hooks and reporting the transformer uncached, which is the state GraphedForward
reads as safe to capture. Take the hooks off by name and clear the marker only once
they are known gone; an unverifiable teardown keeps the marker and stays engaged.

* Trim the comments added by this branch

Comments only, AST verified. diffusion_cache.py 111 comment lines to 71 (24.1% to
17.1% of non-blank); the merge base was 11.9%, so the excess was this branch's.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Wait for the diffusion run record instead of sleeping 0.1s for it

_pump_loop publishes the terminal status through _apply_event and only then calls
_persist_run_record, from its own thread, so _wait_status can return before the
file exists. Two history tests bridged that with time.sleep(0.1) and a comment
saying "give the thread a beat", which is a bet on the pump being scheduled
inside the sleep.

_wait_record polls for the file with a 5s bound and returns the parsed record, so
the tests state the precondition they actually depend on and fail with "the pump
never persisted <path>" rather than FileNotFoundError on a file that is about to
appear. No behaviour change when the pump is prompt.

This is a robustness change, not a claimed fix: I could not reproduce the
(Python 3.13, a-k) failure it was found next to. See the pull request for what
that leaves open.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Sep 18, 2026
…#11257)

* Stop a redundant step-cache engage from tearing the cache down (#11174)

* Stop a redundant step-cache engage from tearing the cache down

diffusers' enable_cache raises ValueError when a cache is already enabled, so a second
apply_step_cache on the same transformer lands in the recovery branch, which calls
disable_cache() and returns None. One redundant call and the working First-Block-Cache is
gone, reported only at warning level.

Same settings are now a no-op. Different settings go through disable_cache first, which is
the only order diffusers accepts a new config in. The recovery branch also clears
_unsloth_step_cache: that marker is read well away from here as "this transformer step
caches" (the CUDA graph wrapper short-circuits to eager on it), so a marker left set by a
failed engage sends a transformer that is not caching down the caching path for the rest of
the process.

Latent rather than live: nothing on main calls apply_step_cache twice on one transformer
today. Three of the four new tests fail without the fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the step-cache marker when the cleanup could not take the hooks off

The recovery branch cleared _unsloth_step_cache unconditionally after a failed engage. If
disable_cache() ALSO raises, the hooks are still live, and clearing the marker there reintroduces the
desync this guard exists to remove, only pointing the other way.

The two directions are not equally bad. A marker left set on a transformer that is not caching forces
eager in the CUDA graph wrapper: slower, still correct. A marker cleared while hooks are live lets the
wrapper capture a graph over a cache-hooked forward, which is wrong output. So the marker now tracks
the hooks rather than this function's intent: it comes off when disable_cache succeeded, or when it
raised but the model still reports is_cache_enabled False, meaning the hooks went anyway. When
disable_cache raised and the cache reads as enabled, the marker stays and the slow path is the one we
land on.

Two tests: the preserved case fails without the change, and the paired case pins that a cleanup which
did unhook still clears the marker, so this does not just pin the marker on forever.

* Ask the model whether the re-configure cleanup actually unhooked

The re-entry guard's cleanup runs two statements, and which one raised changes the answer.
_restore_hooked_block_inners raising means disable_cache never ran, so the cache is still live and
reporting the prior mode is right. disable_cache raising can still have taken the hooks off first, and
there the old behaviour returned the prior mode and left the marker set on a transformer that no
longer caches: pinned to the eager path, and every later auto-cache call skipping the re-enable
because the marker says it is already caching.

So consult is_cache_enabled, as the failure-recovery branch below now does. Still caching keeps the
prior mode. Not caching means the reconfiguration this call asked for is what happened, so the stale
marker is dropped and the engage proceeds at the new settings.

Two tests, one per side. The re-engage case fails without the change.

* Take the cache hooks off directly instead of asking diffusers whether they are gone

After a failed enable_cache, neither signal the last round relied on can be trusted. Checked against
the pinned diffusers 0.40: CacheMixin.enable_cache assigns _cache_config as its LAST statement, after
apply_first_block_cache returns, and disable_cache logs a warning and returns when _cache_config is
None. So a raise part-way through hooking leaves the installed hooks LIVE while is_cache_enabled reads
False and disable_cache is a silent no-op. Both say uncached about a transformer that is partly hooked,
and clearing the marker there lets the CUDA graph wrapper capture that forward.

_unhook_first_block_cache removes both FBCache hooks by name through HookRegistry, the layer under
diffusers' own teardown. remove_hook skips a name that is not registered and recurses into every
submodule, so it is safe whatever got installed, and it clears the dangling _cache_config. The marker
now comes off only when that removal is known to have happened; when the registry or the hook names
cannot be reached it stays set and the transformer keeps the eager path, which is slower and not wrong.

The round-one test asserted the best answer available when is_cache_enabled was all we could ask; it
now asserts the stronger property that the hooks were actually removed. Two new tests, one modelling
the silent partial engage above and one the unverifiable teardown. Both new ones fail on the previous
head.

* Finish the teardown in the re-entry guard too, not just the recovery branch

disable_cache removes the FBC leader and block hooks in SEPARATE remove_hook calls and clears
_cache_config only after both, so a raise between them leaves block hooks installed with no leader to
make the skip decision, while is_cache_enabled still reads True. The guard then reported the prior
cache as healthy when half of it was gone, and the next generation skips blocks on stale state.

Half a cache is not the prior cache, so the guard now runs the same _unhook_first_block_cache the
recovery branch does: finish the removal by name, then re-engage at the new settings. It still reports
the prior mode when the removal cannot be verified at all, which is the only case left where asking
is the best available answer.

Both cleanup paths now go through one primitive instead of two different readings of is_cache_enabled.
The round-two test asserted the old diagnose-only behaviour and now covers the unverifiable case,
which is what it was really pinning; the new test for the mid-teardown raise fails on the previous head.

* Do not tear down a cache that is not ours

_cache_config is GENERIC across every cache CacheMixin supports, and disable_cache dispatches on its
type. So a transformer running MagCache, FasterCache or PAB whose teardown raises arrives in this
fallback looking exactly like a broken FBC one. Removing FBC's two hook names does nothing for it, and
clearing the state made diffusers forget a cache that is still installed, after which enable_cache
stacks FBC on top of the live hooks.

The unhook now declines when _cache_config is some other config type, which the caller already reads
as unverified: it reports the cache that is actually running and leaves it alone. Matched by class
name because the config is exported from two different modules depending on the diffusers version.

One test, failing without the change. The mid-teardown fixture from the last round used a bare object
as the stand-in config and is now an FBC-named one, which is what it was always meant to represent.

* Ask the model, not the marker, whether the call is redundant

The fast path compared _unsloth_step_cache against the requested settings, so a transformer whose
cache someone else engaged, or whose marker went stale, took the reconfigure path even when the live
FirstBlockCacheConfig already carried this exact threshold. That tears down a healthy cache and
rebuilds an identical one, which is the thing this guard exists to prevent, and loses it outright if
the rebuild then fails.

The live _cache_config decides now, and the marker is repaired on the way out rather than being
trusted as the source of truth. That is the same direction as the rest of the PR: every earlier round
established a way the marker can disagree with the hooks, so it is the derived value, not the fact.

One test, failing without the change: a transformer cached by hand, with no marker at all, keeps its
cache untouched and comes back with the marker written.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let only the live cache config authorize the no-op, and integrate one we adopt

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Leave an FBCache installed through the low-level API alone

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Integrate and mark a low-level cache before reporting it engaged

Adopting hooks installed through apply_first_block_cache ran neither post-enable
step and left _unsloth_step_cache clear over live hooks, which is the marker
GraphedForward.__call__ short-circuits to eager on: the CUDA graph wrapper could
capture a cache-hooked forward whose skip decision is data-dependent. Run the
same integration the live-config branch runs, and set the marker (mode only,
since the adopted cache's threshold is its installer's) before returning.

* Unhook an adopted cache in auto mode instead of trusting disable_cache

A cache adopted from apply_first_block_cache has no _cache_config, so diffusers'
disable_cache warns and returns having removed nothing. maybe_toggle_step_cache
cleared the marker on the strength of that call, leaving it clear over live FBCache
hooks and reporting the transformer uncached, which is the state GraphedForward
reads as safe to capture. Take the hooks off by name and clear the marker only once
they are known gone; an unverifiable teardown keeps the marker and stays engaged.

* Trim the comments added by this branch

Comments only, AST verified. diffusion_cache.py 111 comment lines to 71 (24.1% to
17.1% of non-blank); the merge base was 11.9%, so the excess was this branch's.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Wait for the claim release, not the teardown, in the idle-unload test

test_idle_auto_unload_releases_chat_ownership fails on main in Backend CI
(Python 3.13, rest) with

  AssertionError: phantom resident after idle unload:
  {'loaded': [], 'loading': [], 'yours': False}

and passes everywhere else. That body is exactly
account_access.hidden_chat_status_response(), so bob was shown the mask, which
means alice's CHAT claim was still held. The product is right and the test was
watching the wrong signal.

FakeLlama.unload_model runs through asyncio.to_thread, so `unloaded` becomes
visible to the polling loop the instant the worker thread sets it, which can be
before the keepwarm task is rescheduled. The test broke its wait there and
cancelled, and the CancelledError was delivered at the await the loop was still
suspended on, so clear_resident and release_chat_gpu_claim never ran at all.
On an idle box the loop wins that race inside one 10ms tick every time; on a
loaded runner it does not.

The wait now watches the release. Polling with sleep(0) instead of sleep(0.01)
wins the race deterministically, so the window gets a test of its own rather
than a comment, and the A/B is exact: old condition reproduces the CI failure
text verbatim, new condition passes.

Also fixes the comment above the assertions in both teardown tests. It said the
masked answer is {"loaded": True, "yours": False}, which is the generic mask;
this route's mask is the chat-shaped one with an EMPTY "loaded", so `loaded ==
[]` does not discriminate here and only the "yours" key does. A new test pins
the masked body so neither assertion can be dropped as redundant.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Hold the release window open with a hook, not a scheduler race

The window test asserted the claim was still held after breaking on
chat_resident.unloaded with sleep(0), which made it depend on undocumented
asyncio wakeup order. Worse, it would fail against an implementation that made
teardown and release atomic, so a genuine improvement would have looked like a
regression.

The hook goes on release_chat_gpu_claim itself: the loop reaches it, signals,
and blocks until the test lets it through. Inside that window the test asserts
the backend is down, the claim is alice's and bob gets the mask; then it opens
the gate and asserts the claim is gone and bob gets the real answer. An atomic
teardown-and-release still calls the release, so the hook still fires and the
test keeps asking its question instead of becoming a tripwire.

20 consecutive runs, 4 passed each.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Sep 18, 2026
* Disengage FBCache on the word of whoever owns it

test_video_backend.py::test_video_step_cache_auto_toggles_on_actual_steps is red on
main. Bisected: it passes at 9cf1f6e^ and fails at 9cf1f6e (unslothai#11174). CI's captured
log names the branch outright:

    diffusion.cache: fbcache disable unavailable (cache hooks could not be verified
    removed); running uncached

unslothai#11174 made the auto disengage refuse to clear the marker until the private-name hook
sweep confirms the hooks are gone. That is right for the case it was written for: an
ADOPTED low-level cache, installed through apply_first_block_cache, leaves _cache_config
None, so diffusers' own disable_cache removes nothing and trusting it would clear the
marker over live hooks. Clearing it there would let the CUDA graph wrapper capture across
them, so "cannot verify" has to mean "still engaged".

But the veto was applied unconditionally. When diffusers owns the cache, disable_cache
returning without raising IS the evidence: it removed both hooks and cleared the config
itself. Requiring the sweep on top makes every disengage depend on
diffusers.hooks.first_block_cache staying importable, and where it is not, FBCache stays
engaged on short trajectories forever -- the quality regression the auto policy exists to
prevent. The veto now applies only where the code's own comment says it is needed.

The test's diffusers stub was wrong too, and in a way that hid this: FirstBlockCacheConfig
was a lambda returning ("fbcache", threshold). The cache layer matches on
type(...).__name__ to tell its own config from a MagCache / PAB one, so a plain tuple read
as "some other cache" and made the teardown unverifiable by construction. It is now a
class named FirstBlockCacheConfig, as test_diffusion_cache.py already does, and the fake
DiT records _cache_config the way diffusers does.

Two regression tests cover both directions, since unslothai#11174's 618 lines of tests never
reached this: its harness always makes the sweep succeed.

Sabotage, each half independently necessary:
  revert the product fix only -> 2 failed (the new test, and the video one)
  revert the stub only        -> 1 failed (the video one)
  both restored               -> 365 passed

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…thai#11174)

* Stop a redundant step-cache engage from tearing the cache down

diffusers' enable_cache raises ValueError when a cache is already enabled, so a second
apply_step_cache on the same transformer lands in the recovery branch, which calls
disable_cache() and returns None. One redundant call and the working First-Block-Cache is
gone, reported only at warning level.

Same settings are now a no-op. Different settings go through disable_cache first, which is
the only order diffusers accepts a new config in. The recovery branch also clears
_unsloth_step_cache: that marker is read well away from here as "this transformer step
caches" (the CUDA graph wrapper short-circuits to eager on it), so a marker left set by a
failed engage sends a transformer that is not caching down the caching path for the rest of
the process.

Latent rather than live: nothing on main calls apply_step_cache twice on one transformer
today. Three of the four new tests fail without the fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the step-cache marker when the cleanup could not take the hooks off

The recovery branch cleared _unsloth_step_cache unconditionally after a failed engage. If
disable_cache() ALSO raises, the hooks are still live, and clearing the marker there reintroduces the
desync this guard exists to remove, only pointing the other way.

The two directions are not equally bad. A marker left set on a transformer that is not caching forces
eager in the CUDA graph wrapper: slower, still correct. A marker cleared while hooks are live lets the
wrapper capture a graph over a cache-hooked forward, which is wrong output. So the marker now tracks
the hooks rather than this function's intent: it comes off when disable_cache succeeded, or when it
raised but the model still reports is_cache_enabled False, meaning the hooks went anyway. When
disable_cache raised and the cache reads as enabled, the marker stays and the slow path is the one we
land on.

Two tests: the preserved case fails without the change, and the paired case pins that a cleanup which
did unhook still clears the marker, so this does not just pin the marker on forever.

* Ask the model whether the re-configure cleanup actually unhooked

The re-entry guard's cleanup runs two statements, and which one raised changes the answer.
_restore_hooked_block_inners raising means disable_cache never ran, so the cache is still live and
reporting the prior mode is right. disable_cache raising can still have taken the hooks off first, and
there the old behaviour returned the prior mode and left the marker set on a transformer that no
longer caches: pinned to the eager path, and every later auto-cache call skipping the re-enable
because the marker says it is already caching.

So consult is_cache_enabled, as the failure-recovery branch below now does. Still caching keeps the
prior mode. Not caching means the reconfiguration this call asked for is what happened, so the stale
marker is dropped and the engage proceeds at the new settings.

Two tests, one per side. The re-engage case fails without the change.

* Take the cache hooks off directly instead of asking diffusers whether they are gone

After a failed enable_cache, neither signal the last round relied on can be trusted. Checked against
the pinned diffusers 0.40: CacheMixin.enable_cache assigns _cache_config as its LAST statement, after
apply_first_block_cache returns, and disable_cache logs a warning and returns when _cache_config is
None. So a raise part-way through hooking leaves the installed hooks LIVE while is_cache_enabled reads
False and disable_cache is a silent no-op. Both say uncached about a transformer that is partly hooked,
and clearing the marker there lets the CUDA graph wrapper capture that forward.

_unhook_first_block_cache removes both FBCache hooks by name through HookRegistry, the layer under
diffusers' own teardown. remove_hook skips a name that is not registered and recurses into every
submodule, so it is safe whatever got installed, and it clears the dangling _cache_config. The marker
now comes off only when that removal is known to have happened; when the registry or the hook names
cannot be reached it stays set and the transformer keeps the eager path, which is slower and not wrong.

The round-one test asserted the best answer available when is_cache_enabled was all we could ask; it
now asserts the stronger property that the hooks were actually removed. Two new tests, one modelling
the silent partial engage above and one the unverifiable teardown. Both new ones fail on the previous
head.

* Finish the teardown in the re-entry guard too, not just the recovery branch

disable_cache removes the FBC leader and block hooks in SEPARATE remove_hook calls and clears
_cache_config only after both, so a raise between them leaves block hooks installed with no leader to
make the skip decision, while is_cache_enabled still reads True. The guard then reported the prior
cache as healthy when half of it was gone, and the next generation skips blocks on stale state.

Half a cache is not the prior cache, so the guard now runs the same _unhook_first_block_cache the
recovery branch does: finish the removal by name, then re-engage at the new settings. It still reports
the prior mode when the removal cannot be verified at all, which is the only case left where asking
is the best available answer.

Both cleanup paths now go through one primitive instead of two different readings of is_cache_enabled.
The round-two test asserted the old diagnose-only behaviour and now covers the unverifiable case,
which is what it was really pinning; the new test for the mid-teardown raise fails on the previous head.

* Do not tear down a cache that is not ours

_cache_config is GENERIC across every cache CacheMixin supports, and disable_cache dispatches on its
type. So a transformer running MagCache, FasterCache or PAB whose teardown raises arrives in this
fallback looking exactly like a broken FBC one. Removing FBC's two hook names does nothing for it, and
clearing the state made diffusers forget a cache that is still installed, after which enable_cache
stacks FBC on top of the live hooks.

The unhook now declines when _cache_config is some other config type, which the caller already reads
as unverified: it reports the cache that is actually running and leaves it alone. Matched by class
name because the config is exported from two different modules depending on the diffusers version.

One test, failing without the change. The mid-teardown fixture from the last round used a bare object
as the stand-in config and is now an FBC-named one, which is what it was always meant to represent.

* Ask the model, not the marker, whether the call is redundant

The fast path compared _unsloth_step_cache against the requested settings, so a transformer whose
cache someone else engaged, or whose marker went stale, took the reconfigure path even when the live
FirstBlockCacheConfig already carried this exact threshold. That tears down a healthy cache and
rebuilds an identical one, which is the thing this guard exists to prevent, and loses it outright if
the rebuild then fails.

The live _cache_config decides now, and the marker is repaired on the way out rather than being
trusted as the source of truth. That is the same direction as the rest of the PR: every earlier round
established a way the marker can disagree with the hooks, so it is the derived value, not the fact.

One test, failing without the change: a transformer cached by hand, with no marker at all, keeps its
cache untouched and comes back with the marker written.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let only the live cache config authorize the no-op, and integrate one we adopt

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Leave an FBCache installed through the low-level API alone

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Integrate and mark a low-level cache before reporting it engaged

Adopting hooks installed through apply_first_block_cache ran neither post-enable
step and left _unsloth_step_cache clear over live hooks, which is the marker
GraphedForward.__call__ short-circuits to eager on: the CUDA graph wrapper could
capture a cache-hooked forward whose skip decision is data-dependent. Run the
same integration the live-config branch runs, and set the marker (mode only,
since the adopted cache's threshold is its installer's) before returning.

* Unhook an adopted cache in auto mode instead of trusting disable_cache

A cache adopted from apply_first_block_cache has no _cache_config, so diffusers'
disable_cache warns and returns having removed nothing. maybe_toggle_step_cache
cleared the marker on the strength of that call, leaving it clear over live FBCache
hooks and reporting the transformer uncached, which is the state GraphedForward
reads as safe to capture. Take the hooks off by name and clear the marker only once
they are known gone; an unverifiable teardown keeps the marker and stays engaged.

* Trim the comments added by this branch

Comments only, AST verified. diffusion_cache.py 111 comment lines to 71 (24.1% to
17.1% of non-blank); the merge base was 11.9%, so the excess was this branch's.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…slothai#11263)

* Stop a redundant step-cache engage from tearing the cache down (unslothai#11174)

* Stop a redundant step-cache engage from tearing the cache down

diffusers' enable_cache raises ValueError when a cache is already enabled, so a second
apply_step_cache on the same transformer lands in the recovery branch, which calls
disable_cache() and returns None. One redundant call and the working First-Block-Cache is
gone, reported only at warning level.

Same settings are now a no-op. Different settings go through disable_cache first, which is
the only order diffusers accepts a new config in. The recovery branch also clears
_unsloth_step_cache: that marker is read well away from here as "this transformer step
caches" (the CUDA graph wrapper short-circuits to eager on it), so a marker left set by a
failed engage sends a transformer that is not caching down the caching path for the rest of
the process.

Latent rather than live: nothing on main calls apply_step_cache twice on one transformer
today. Three of the four new tests fail without the fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the step-cache marker when the cleanup could not take the hooks off

The recovery branch cleared _unsloth_step_cache unconditionally after a failed engage. If
disable_cache() ALSO raises, the hooks are still live, and clearing the marker there reintroduces the
desync this guard exists to remove, only pointing the other way.

The two directions are not equally bad. A marker left set on a transformer that is not caching forces
eager in the CUDA graph wrapper: slower, still correct. A marker cleared while hooks are live lets the
wrapper capture a graph over a cache-hooked forward, which is wrong output. So the marker now tracks
the hooks rather than this function's intent: it comes off when disable_cache succeeded, or when it
raised but the model still reports is_cache_enabled False, meaning the hooks went anyway. When
disable_cache raised and the cache reads as enabled, the marker stays and the slow path is the one we
land on.

Two tests: the preserved case fails without the change, and the paired case pins that a cleanup which
did unhook still clears the marker, so this does not just pin the marker on forever.

* Ask the model whether the re-configure cleanup actually unhooked

The re-entry guard's cleanup runs two statements, and which one raised changes the answer.
_restore_hooked_block_inners raising means disable_cache never ran, so the cache is still live and
reporting the prior mode is right. disable_cache raising can still have taken the hooks off first, and
there the old behaviour returned the prior mode and left the marker set on a transformer that no
longer caches: pinned to the eager path, and every later auto-cache call skipping the re-enable
because the marker says it is already caching.

So consult is_cache_enabled, as the failure-recovery branch below now does. Still caching keeps the
prior mode. Not caching means the reconfiguration this call asked for is what happened, so the stale
marker is dropped and the engage proceeds at the new settings.

Two tests, one per side. The re-engage case fails without the change.

* Take the cache hooks off directly instead of asking diffusers whether they are gone

After a failed enable_cache, neither signal the last round relied on can be trusted. Checked against
the pinned diffusers 0.40: CacheMixin.enable_cache assigns _cache_config as its LAST statement, after
apply_first_block_cache returns, and disable_cache logs a warning and returns when _cache_config is
None. So a raise part-way through hooking leaves the installed hooks LIVE while is_cache_enabled reads
False and disable_cache is a silent no-op. Both say uncached about a transformer that is partly hooked,
and clearing the marker there lets the CUDA graph wrapper capture that forward.

_unhook_first_block_cache removes both FBCache hooks by name through HookRegistry, the layer under
diffusers' own teardown. remove_hook skips a name that is not registered and recurses into every
submodule, so it is safe whatever got installed, and it clears the dangling _cache_config. The marker
now comes off only when that removal is known to have happened; when the registry or the hook names
cannot be reached it stays set and the transformer keeps the eager path, which is slower and not wrong.

The round-one test asserted the best answer available when is_cache_enabled was all we could ask; it
now asserts the stronger property that the hooks were actually removed. Two new tests, one modelling
the silent partial engage above and one the unverifiable teardown. Both new ones fail on the previous
head.

* Finish the teardown in the re-entry guard too, not just the recovery branch

disable_cache removes the FBC leader and block hooks in SEPARATE remove_hook calls and clears
_cache_config only after both, so a raise between them leaves block hooks installed with no leader to
make the skip decision, while is_cache_enabled still reads True. The guard then reported the prior
cache as healthy when half of it was gone, and the next generation skips blocks on stale state.

Half a cache is not the prior cache, so the guard now runs the same _unhook_first_block_cache the
recovery branch does: finish the removal by name, then re-engage at the new settings. It still reports
the prior mode when the removal cannot be verified at all, which is the only case left where asking
is the best available answer.

Both cleanup paths now go through one primitive instead of two different readings of is_cache_enabled.
The round-two test asserted the old diagnose-only behaviour and now covers the unverifiable case,
which is what it was really pinning; the new test for the mid-teardown raise fails on the previous head.

* Do not tear down a cache that is not ours

_cache_config is GENERIC across every cache CacheMixin supports, and disable_cache dispatches on its
type. So a transformer running MagCache, FasterCache or PAB whose teardown raises arrives in this
fallback looking exactly like a broken FBC one. Removing FBC's two hook names does nothing for it, and
clearing the state made diffusers forget a cache that is still installed, after which enable_cache
stacks FBC on top of the live hooks.

The unhook now declines when _cache_config is some other config type, which the caller already reads
as unverified: it reports the cache that is actually running and leaves it alone. Matched by class
name because the config is exported from two different modules depending on the diffusers version.

One test, failing without the change. The mid-teardown fixture from the last round used a bare object
as the stand-in config and is now an FBC-named one, which is what it was always meant to represent.

* Ask the model, not the marker, whether the call is redundant

The fast path compared _unsloth_step_cache against the requested settings, so a transformer whose
cache someone else engaged, or whose marker went stale, took the reconfigure path even when the live
FirstBlockCacheConfig already carried this exact threshold. That tears down a healthy cache and
rebuilds an identical one, which is the thing this guard exists to prevent, and loses it outright if
the rebuild then fails.

The live _cache_config decides now, and the marker is repaired on the way out rather than being
trusted as the source of truth. That is the same direction as the rest of the PR: every earlier round
established a way the marker can disagree with the hooks, so it is the derived value, not the fact.

One test, failing without the change: a transformer cached by hand, with no marker at all, keeps its
cache untouched and comes back with the marker written.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let only the live cache config authorize the no-op, and integrate one we adopt

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Leave an FBCache installed through the low-level API alone

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Integrate and mark a low-level cache before reporting it engaged

Adopting hooks installed through apply_first_block_cache ran neither post-enable
step and left _unsloth_step_cache clear over live hooks, which is the marker
GraphedForward.__call__ short-circuits to eager on: the CUDA graph wrapper could
capture a cache-hooked forward whose skip decision is data-dependent. Run the
same integration the live-config branch runs, and set the marker (mode only,
since the adopted cache's threshold is its installer's) before returning.

* Unhook an adopted cache in auto mode instead of trusting disable_cache

A cache adopted from apply_first_block_cache has no _cache_config, so diffusers'
disable_cache warns and returns having removed nothing. maybe_toggle_step_cache
cleared the marker on the strength of that call, leaving it clear over live FBCache
hooks and reporting the transformer uncached, which is the state GraphedForward
reads as safe to capture. Take the hooks off by name and clear the marker only once
they are known gone; an unverifiable teardown keeps the marker and stays engaged.

* Trim the comments added by this branch

Comments only, AST verified. diffusion_cache.py 111 comment lines to 71 (24.1% to
17.1% of non-blank); the merge base was 11.9%, so the excess was this branch's.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Wait for the diffusion run record instead of sleeping 0.1s for it

_pump_loop publishes the terminal status through _apply_event and only then calls
_persist_run_record, from its own thread, so _wait_status can return before the
file exists. Two history tests bridged that with time.sleep(0.1) and a comment
saying "give the thread a beat", which is a bet on the pump being scheduled
inside the sleep.

_wait_record polls for the file with a 5s bound and returns the parsed record, so
the tests state the precondition they actually depend on and fail with "the pump
never persisted <path>" rather than FileNotFoundError on a file that is about to
appear. No behaviour change when the pump is prompt.

This is a robustness change, not a claimed fix: I could not reproduce the
(Python 3.13, a-k) failure it was found next to. See the pull request for what
that leaves open.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…unslothai#11257)

* Stop a redundant step-cache engage from tearing the cache down (unslothai#11174)

* Stop a redundant step-cache engage from tearing the cache down

diffusers' enable_cache raises ValueError when a cache is already enabled, so a second
apply_step_cache on the same transformer lands in the recovery branch, which calls
disable_cache() and returns None. One redundant call and the working First-Block-Cache is
gone, reported only at warning level.

Same settings are now a no-op. Different settings go through disable_cache first, which is
the only order diffusers accepts a new config in. The recovery branch also clears
_unsloth_step_cache: that marker is read well away from here as "this transformer step
caches" (the CUDA graph wrapper short-circuits to eager on it), so a marker left set by a
failed engage sends a transformer that is not caching down the caching path for the rest of
the process.

Latent rather than live: nothing on main calls apply_step_cache twice on one transformer
today. Three of the four new tests fail without the fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the step-cache marker when the cleanup could not take the hooks off

The recovery branch cleared _unsloth_step_cache unconditionally after a failed engage. If
disable_cache() ALSO raises, the hooks are still live, and clearing the marker there reintroduces the
desync this guard exists to remove, only pointing the other way.

The two directions are not equally bad. A marker left set on a transformer that is not caching forces
eager in the CUDA graph wrapper: slower, still correct. A marker cleared while hooks are live lets the
wrapper capture a graph over a cache-hooked forward, which is wrong output. So the marker now tracks
the hooks rather than this function's intent: it comes off when disable_cache succeeded, or when it
raised but the model still reports is_cache_enabled False, meaning the hooks went anyway. When
disable_cache raised and the cache reads as enabled, the marker stays and the slow path is the one we
land on.

Two tests: the preserved case fails without the change, and the paired case pins that a cleanup which
did unhook still clears the marker, so this does not just pin the marker on forever.

* Ask the model whether the re-configure cleanup actually unhooked

The re-entry guard's cleanup runs two statements, and which one raised changes the answer.
_restore_hooked_block_inners raising means disable_cache never ran, so the cache is still live and
reporting the prior mode is right. disable_cache raising can still have taken the hooks off first, and
there the old behaviour returned the prior mode and left the marker set on a transformer that no
longer caches: pinned to the eager path, and every later auto-cache call skipping the re-enable
because the marker says it is already caching.

So consult is_cache_enabled, as the failure-recovery branch below now does. Still caching keeps the
prior mode. Not caching means the reconfiguration this call asked for is what happened, so the stale
marker is dropped and the engage proceeds at the new settings.

Two tests, one per side. The re-engage case fails without the change.

* Take the cache hooks off directly instead of asking diffusers whether they are gone

After a failed enable_cache, neither signal the last round relied on can be trusted. Checked against
the pinned diffusers 0.40: CacheMixin.enable_cache assigns _cache_config as its LAST statement, after
apply_first_block_cache returns, and disable_cache logs a warning and returns when _cache_config is
None. So a raise part-way through hooking leaves the installed hooks LIVE while is_cache_enabled reads
False and disable_cache is a silent no-op. Both say uncached about a transformer that is partly hooked,
and clearing the marker there lets the CUDA graph wrapper capture that forward.

_unhook_first_block_cache removes both FBCache hooks by name through HookRegistry, the layer under
diffusers' own teardown. remove_hook skips a name that is not registered and recurses into every
submodule, so it is safe whatever got installed, and it clears the dangling _cache_config. The marker
now comes off only when that removal is known to have happened; when the registry or the hook names
cannot be reached it stays set and the transformer keeps the eager path, which is slower and not wrong.

The round-one test asserted the best answer available when is_cache_enabled was all we could ask; it
now asserts the stronger property that the hooks were actually removed. Two new tests, one modelling
the silent partial engage above and one the unverifiable teardown. Both new ones fail on the previous
head.

* Finish the teardown in the re-entry guard too, not just the recovery branch

disable_cache removes the FBC leader and block hooks in SEPARATE remove_hook calls and clears
_cache_config only after both, so a raise between them leaves block hooks installed with no leader to
make the skip decision, while is_cache_enabled still reads True. The guard then reported the prior
cache as healthy when half of it was gone, and the next generation skips blocks on stale state.

Half a cache is not the prior cache, so the guard now runs the same _unhook_first_block_cache the
recovery branch does: finish the removal by name, then re-engage at the new settings. It still reports
the prior mode when the removal cannot be verified at all, which is the only case left where asking
is the best available answer.

Both cleanup paths now go through one primitive instead of two different readings of is_cache_enabled.
The round-two test asserted the old diagnose-only behaviour and now covers the unverifiable case,
which is what it was really pinning; the new test for the mid-teardown raise fails on the previous head.

* Do not tear down a cache that is not ours

_cache_config is GENERIC across every cache CacheMixin supports, and disable_cache dispatches on its
type. So a transformer running MagCache, FasterCache or PAB whose teardown raises arrives in this
fallback looking exactly like a broken FBC one. Removing FBC's two hook names does nothing for it, and
clearing the state made diffusers forget a cache that is still installed, after which enable_cache
stacks FBC on top of the live hooks.

The unhook now declines when _cache_config is some other config type, which the caller already reads
as unverified: it reports the cache that is actually running and leaves it alone. Matched by class
name because the config is exported from two different modules depending on the diffusers version.

One test, failing without the change. The mid-teardown fixture from the last round used a bare object
as the stand-in config and is now an FBC-named one, which is what it was always meant to represent.

* Ask the model, not the marker, whether the call is redundant

The fast path compared _unsloth_step_cache against the requested settings, so a transformer whose
cache someone else engaged, or whose marker went stale, took the reconfigure path even when the live
FirstBlockCacheConfig already carried this exact threshold. That tears down a healthy cache and
rebuilds an identical one, which is the thing this guard exists to prevent, and loses it outright if
the rebuild then fails.

The live _cache_config decides now, and the marker is repaired on the way out rather than being
trusted as the source of truth. That is the same direction as the rest of the PR: every earlier round
established a way the marker can disagree with the hooks, so it is the derived value, not the fact.

One test, failing without the change: a transformer cached by hand, with no marker at all, keeps its
cache untouched and comes back with the marker written.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let only the live cache config authorize the no-op, and integrate one we adopt

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Leave an FBCache installed through the low-level API alone

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Integrate and mark a low-level cache before reporting it engaged

Adopting hooks installed through apply_first_block_cache ran neither post-enable
step and left _unsloth_step_cache clear over live hooks, which is the marker
GraphedForward.__call__ short-circuits to eager on: the CUDA graph wrapper could
capture a cache-hooked forward whose skip decision is data-dependent. Run the
same integration the live-config branch runs, and set the marker (mode only,
since the adopted cache's threshold is its installer's) before returning.

* Unhook an adopted cache in auto mode instead of trusting disable_cache

A cache adopted from apply_first_block_cache has no _cache_config, so diffusers'
disable_cache warns and returns having removed nothing. maybe_toggle_step_cache
cleared the marker on the strength of that call, leaving it clear over live FBCache
hooks and reporting the transformer uncached, which is the state GraphedForward
reads as safe to capture. Take the hooks off by name and clear the marker only once
they are known gone; an unverifiable teardown keeps the marker and stays engaged.

* Trim the comments added by this branch

Comments only, AST verified. diffusion_cache.py 111 comment lines to 71 (24.1% to
17.1% of non-blank); the merge base was 11.9%, so the excess was this branch's.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

* Wait for the claim release, not the teardown, in the idle-unload test

test_idle_auto_unload_releases_chat_ownership fails on main in Backend CI
(Python 3.13, rest) with

  AssertionError: phantom resident after idle unload:
  {'loaded': [], 'loading': [], 'yours': False}

and passes everywhere else. That body is exactly
account_access.hidden_chat_status_response(), so bob was shown the mask, which
means alice's CHAT claim was still held. The product is right and the test was
watching the wrong signal.

FakeLlama.unload_model runs through asyncio.to_thread, so `unloaded` becomes
visible to the polling loop the instant the worker thread sets it, which can be
before the keepwarm task is rescheduled. The test broke its wait there and
cancelled, and the CancelledError was delivered at the await the loop was still
suspended on, so clear_resident and release_chat_gpu_claim never ran at all.
On an idle box the loop wins that race inside one 10ms tick every time; on a
loaded runner it does not.

The wait now watches the release. Polling with sleep(0) instead of sleep(0.01)
wins the race deterministically, so the window gets a test of its own rather
than a comment, and the A/B is exact: old condition reproduces the CI failure
text verbatim, new condition passes.

Also fixes the comment above the assertions in both teardown tests. It said the
masked answer is {"loaded": True, "yours": False}, which is the generic mask;
this route's mask is the chat-shaped one with an EMPTY "loaded", so `loaded ==
[]` does not discriminate here and only the "yours" key does. A new test pins
the masked body so neither assertion can be dropped as redundant.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Hold the release window open with a hook, not a scheduler race

The window test asserted the claim was still held after breaking on
chat_resident.unloaded with sleep(0), which made it depend on undocumented
asyncio wakeup order. Worse, it would fail against an implementation that made
teardown and release atomic, so a genuine improvement would have looked like a
regression.

The hook goes on release_chat_gpu_claim itself: the loop reaches it, signals,
and blocks until the test lets it through. Inside that window the test asserts
the backend is down, the claim is alice's and bob gets the mask; then it opens
the gate and asserts the claim is gone and bob gets the real answer. An atomic
teardown-and-release still calls the release, so the hook still fires and the
test keeps asking its question instead of becoming a tripwire.

20 consecutive runs, 4 passed each.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Disengage FBCache on the word of whoever owns it

test_video_backend.py::test_video_step_cache_auto_toggles_on_actual_steps is red on
main. Bisected: it passes at 9cf1f6e^ and fails at 9cf1f6e (unslothai#11174). CI's captured
log names the branch outright:

    diffusion.cache: fbcache disable unavailable (cache hooks could not be verified
    removed); running uncached

unslothai#11174 made the auto disengage refuse to clear the marker until the private-name hook
sweep confirms the hooks are gone. That is right for the case it was written for: an
ADOPTED low-level cache, installed through apply_first_block_cache, leaves _cache_config
None, so diffusers' own disable_cache removes nothing and trusting it would clear the
marker over live hooks. Clearing it there would let the CUDA graph wrapper capture across
them, so "cannot verify" has to mean "still engaged".

But the veto was applied unconditionally. When diffusers owns the cache, disable_cache
returning without raising IS the evidence: it removed both hooks and cleared the config
itself. Requiring the sweep on top makes every disengage depend on
diffusers.hooks.first_block_cache staying importable, and where it is not, FBCache stays
engaged on short trajectories forever -- the quality regression the auto policy exists to
prevent. The veto now applies only where the code's own comment says it is needed.

The test's diffusers stub was wrong too, and in a way that hid this: FirstBlockCacheConfig
was a lambda returning ("fbcache", threshold). The cache layer matches on
type(...).__name__ to tell its own config from a MagCache / PAB one, so a plain tuple read
as "some other cache" and made the teardown unverifiable by construction. It is now a
class named FirstBlockCacheConfig, as test_diffusion_cache.py already does, and the fake
DiT records _cache_config the way diffusers does.

Two regression tests cover both directions, since unslothai#11174's 618 lines of tests never
reached this: its harness always makes the sweep succeed.

Sabotage, each half independently necessary:
  revert the product fix only -> 2 failed (the new test, and the video one)
  revert the stub only        -> 1 failed (the video one)
  both restored               -> 365 passed

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants