Skip to content

Studio diffusion: INT8 attention routes hold their modules weakly, so unload returns the card - #18841

Merged
danielhanchen merged 4 commits into
mainfrom
studio-diffusion-unload-leak
Nov 22, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-diffusion-unload-leak

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Studio diffusion: unloading a model now frees its INT8 attention modules

Problem

When you unload a FLUX.3 klein pipeline (INT8, raced INT8 attention), about 1.77 GB stays allocated on the card until the next load. That load then sees about 2.3 GB less free memory and picks a worse placement. On a 16 GiB card, the text encoder kept on the GPU drops from 2954 to 696 MiB, and the time before the first denoise step goes from 0.240 to 0.410 s. Anyone who switches models and comes back pays this.

Cause

Every raced INT8 attention route is recorded in the process-wide diffusion_int8_attention._ROUTES list. That way a later torch-wins verdict can give the module back its stock processor. The closure stored there (_raise_processor_floor.<locals>.raise_floor) held strong references to the processor and to the Flux3Attention module. Only the next load's forget_plans() cleared the list, so after unload() every routed attention module stayed alive, and with it:

  • its Q / K / V weights,
  • the merged QKV payload: 76 blocks, 1063 MiB, allocated in merge_payloads from merge_qkv,
  • the other INT8 weights it owns: 248 blocks, 703 MiB, allocated in fast_upload from load_prequantized_transformer.

I found this with torch.cuda.memory._record_memory_history, plus a referrer walk from the surviving CUDA tensors after unload():

module core.inference.diffusion_int8_attention ['_ROUTES'] -> tuple -> raise_floor closure -> cell
  -> Flux3Attention -> __dict__['_unsloth_f3_fused_qkv'] -> merged int8 payload

Fix

  • _raise_processor_floor now holds the processor and the module through weak references. If the processor object can't be weak-referenced, it falls back to a strong reference.
  • register_route and _drop_routes prune routes whose processor is gone.
  • A live route behaves as before: a swapped-in processor still hands the module its stock one back, and any other processor still raises its token floor.
  • Nothing global is cleared on unload. Race verdicts, launch plans and the routes of another resident pipeline are untouched, so the next load does no extra work.

Results (Colab L4, 16 GiB simulated card, three loads per process, base = merge base)

FLUX.3 klein (16 steps, INT8 auto, 1024x1024), 3 reps per arm. Medians, with [min-max] across reps:

load arm allocated after unload MiB free before load MiB text encoder resident MiB load s before 1st step s s/image
1 base 1774 [1769-1776] 16234 2954 (cold) 0.243 [0.240-0.245] 8.03
1 head 8 [8-8] 16234 2954 (cold) 0.242 [0.240-0.247] 8.00
2 base 1776 13916 698 14.9 0.416 [0.415-0.420] 8.19
2 head 8 16108 2890 10.9 0.248 [0.247-0.250] 7.91
3 base 1776 13914 696 14.8 0.415 [0.408-0.415] 8.17
3 head 8 16108 2890 11.0 0.246 [0.246-0.247] 7.93
  • On head, the second and third loads plan the same way the first one does.
  • Time before the first step on head stays within 0.006 s of load 1. Base's spread across reps is at most 0.007 s.
  • s/step is unchanged (0.463-0.470 in every cell).
  • Images: all 36 base-vs-head pairs are bit-identical (md5 equal, LPIPS 0), and so are the cross-load repeats of the same prompt and seed.

Qwen-Image-2.1-Turbo (8 steps), 1 rep per arm, as a second family. Nothing pins its pipeline after unload even on base, which already returns to 8 MiB. Head is the same (8 MiB after every unload, same placement, identical images), so this change costs nothing there.

What stays allocated after unload on head is 8 MiB:

  • 8.12 MiB: the cuBLAS workspace. The first GEMM-backed SDPA probe allocates it, and torch keeps it for the life of the handle; the next load reuses it.
  • 0.13 MiB: the ConvRot Hadamard matrices and the preview latent-to-RGB map, both keyed per device and cheap to keep.

Tests

There are three new CPU tests in tests/test_diffusion_int8_attention_auto.py. All three fail on the merge base and pass here:

  • A pipeline raced through install_auto is garbage collected once it is dropped (checked by weakref on every routed module and processor), and _ROUTES ends up empty.
  • A weak route still restores the stock processor or raises the floor while alive, and is a no-op once the processor is gone.
  • register_route prunes dead routes and keeps live ones, including routes without an alive probe (the dispatch route).

The existing INT8 attention suites, test_diffusion_backend.py and the eject and slot-release tests fail on the same test IDs on base and head: five minimax_h3_image download-plan tests, which fail before this change too.

…le weakly

A raced INT8 attention route kept a strong reference to its attention module in the
process-wide _ROUTES list, and only the next load's forget_plans() cleared it. After
unload() every routed attention module, with its Q / K / V weights and the merged QKV
payload, stayed on the card (1774 MiB on FLUX.3 klein INT8, L4), so the next load
planned against 2.3 GB less free memory.

The route closure now holds the processor and module through weak references and
dead routes are pruned on register and on a route drop. A live route behaves as before.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-22T06:12:07.133736Z 0f6a62b 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

Copy link
Copy Markdown

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

Reviewed commit: 411f90fcbf

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

A prune reads _ROUTES, filters it and writes the copy back. Two prunes on different threads (a video load registering
while an image render drops its routes) could interleave: the one switched out mid-iteration resumed over a list the
other had shortened, skipped entries and wrote its copy back, dropping live routes. Measured with four registering
threads and dead routes present: 68 live routes lost in 10 runs without the lock, 0 with it. Before the prune, a
register was a bare append and lost nothing. raise_floor still runs outside the lock.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…18846)

## Summary

`Source lint` (Lint CI) and the risky loader test in `workflow-trigger
lint` are red on `main` since #18807, and on every PR based after it
(#18840, #18841):

```
1 risky loader call site(s) not in the baseline:
  unsloth/_cpu_init.py:54  [dynamic-import] spec_from_file_location
```

#18807 (`UNSLOTH_MEMORY_REPORT` reports host RAM on the CPU backend)
loads `unsloth/utils/run_report.py` with
`importlib.util.spec_from_file_location` instead of importing
`unsloth.utils`, because that package's `__init__` pulls in the GPU
model stack the CPU route skips. The path is fixed, relative to
`_cpu_init.py` inside the installed package, so nothing external chooses
what gets executed. The call is fine and only needs recording.

## Fix

`python scripts/lint_risky_loaders.py --update`, with the new entry's
reason filled in.

## Testing

- `python scripts/lint_risky_loaders.py`: all 124 call sites recorded
(exits 1 on `main`).
- `tests/security/test_lint_risky_loaders.py`: 46 passed.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 0f6a62ba72

ℹ️ 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 95267ce into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-unload-leak branch November 22, 2026 09:41
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.

1 participant