Skip to content

Studio FLUX.3: load float16 builds on 12 GB hosts by reading bf16 as stored - #17642

Merged
danielhanchen merged 3 commits into
mainfrom
studio-lowram-t4
Nov 13, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-lowram-t4

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

FLUX.3 klein with the int8 transformer could not load on a standard Colab T4 VM (12.7 GB host RAM): the process was SIGKILLed during the load. On fp16-only cards the FLUX.3 loader converted the bf16 text encoder and transformer to float16 on the host before anything moved to the GPU. Each conversion is a second private host copy of the component, about 20 GB for klein, plus transient copies while converting.

This PR makes float16 FLUX.3 builds read the bf16 weights as stored (memory mapped, no copy), the same route float32 builds already take. Output is unchanged: every image is byte-identical to the current build.

Cause

  • diffusion_flux3.flux3_storage_dtype (diffusion_flux3.py:592-603) returned bf16 storage only for float32 loads. A float16 load got None, so _manual_cast_load fell through to loader(dtype) (:689).
  • That widened Qwen3VLForConditionalGeneration.from_pretrained(..., dtype=float16) (:771, 8.9 GB of bf16) and then Flux3Transformer2DModel.from_pretrained(..., torch_dtype=float16) (:785, 11.1 GB). Both sat in anonymous host memory together. The call site is diffusion.py:9950.
  • On a CPU repro with the real klein configs (fewer layers), a float16 load of a bf16 checkpoint peaks at 1.6x (transformer) and 2.3x (text encoder) its parameter bytes. The same load at bf16 stays memory mapped and is not even resident.
  • On a high-RAM T4, base anonymous memory climbs to about 20 GiB in this window (host drop 20.1 GiB). The int8 quantise then runs on the host and the transformer moves to the GPU.

Change

  • flux3_storage_dtype also returns bf16 for float16 CUDA loads. The text encoder keeps its bf16 Linear / Embedding weights and casts per call with the existing ManualCastLinear / ManualCastEmbedding, which is exact. Kill switch: UNSLOTH_DIFFUSION_FLUX3_HALF_STORAGE=0 restores the widened load.
  • The transformer is read as stored only when the fp16-card native quant rebuilds its Linears (the existing fp16_card_quant_storage_enabled() clause), or when storage saves memory (float32). A dense float16 transformer still loads widened, so it never casts per step. transformer_storage is now tri-state (True / None = only when it saves memory / False), routed by transformer_storage_dtype.
  • NativeWeightOnlyLinear rounds a manual-cast weight to its compute dtype before quantising. bf16 to float16 is not exact below float16's normal range, so quantising the raw bf16 values would change some int8 codes. With the round, the codes match a widened load bit for bit.
  • After a native quant with a compute dtype (fp16-only cards), undo_same_width_manual_cast_ turns the Linears left dense back into plain float16 modules. This is 1.65 GiB on klein: the embedders, modulations and timestep MLPs. It also drops the manual-cast marker, so the transformer is exactly what a float16 load holds. It never reads .weight of a quantised Linear, since that dequantises it.

Results

Settings: FLUX.3 klein, transformer_quant=int8, 1024x1024, 16 steps, 3 images per run, fresh process and Studio home per run. Base = 3221ed08b0.

Standard Colab T4 (12.7 GB host RAM, about 11.5 GiB available at start)

arm result load s s/img (median of 3) peak host PSS GiB min MemAvailable GiB
base, VM 1 SIGKILL (rc -9) 59 s into the component load - - 10.9 at the kill 0.58
base, VM 2 VM unresponsive in the same load for 50+ min (stopped) - - - -
head r1 (includes the download) loads and renders 359.7 65.0 8.6 3.68
head r2 loads and renders 182.3 62.6 9.4 3.72

Images are byte-identical (md5) to the high-RAM base images below.

On this VM the text encoder cannot be pinned (0 MiB of pinnable host RAM). Its weights stream from the memory-mapped checkpoint, so the prompt encode costs 21 to 27 s per image (3 s once its pages are cached) against 0.7 s on a high-RAM host. Denoise is the same as on the high-RAM VM (38 to 40 s). Keeping those streamed weights in host RAM after the transformer leaves the host is a possible follow-up.

High-RAM Colab T4 (no-regression)

Order: base, head, head, base, base on one VM, so base is repeated for A/A.

arm load s s/img (median of 3) host drop GiB images
base r1 (includes download) 153.5 44.15 20.1 reference
head r1 67.7 44.18 9.6 identical
head r2 50.7 44.21 9.6 identical
base r2 59.5 44.36 20.1 identical
base r3 54.7 44.39 20.1 identical
  • s/img: head is inside the base spread (44.15 to 44.39). Clock-normalised denoise is 26.6 to 27.0 G SM cycles per image in every run.
  • Load: head 50.7 / 67.7 s against warm base 54.7 / 59.5 s, within run-to-run noise.
  • Host RAM: the drop during the load halves, from 20.1 to 9.6 GiB.

Tests

  • New tests/test_diffusion_flux3_half_storage.py, 9 tests, all CPU:
    • the float16 manual-cast FLUX.3 transformer and Qwen3-VL encoder are bit-identical to the float16 load;
    • the native int8 build from stored bf16 equals the float16 build, tensor for tensor, with the module types restored and the marker dropped;
    • the round through the compute dtype is required (a direct bf16 quantise gives other codes);
    • the undo leaves a float32 manual cast alone and never reads a quantised weight;
    • routing and the kill switch.
  • Updated tests/test_diffusion_flux3_manual_cast.py for float16 storage and the new routing.
  • Related suites (flux3, manual cast, fp16-card int8 / fp8 / storage, native quant, transformer quant, TE prequant, streamed residency, fp16 guard): 886 passed on head and 877 passed on base (the extra 9 are the new tests), no failures on either.

…t16 builds

A float16 FLUX.3 load (fp16-only cards such as T4) converted the bf16 text
encoder and transformer to float16 on the host, a private copy of each
(about 20 GB for klein, more while converting), which killed the process on a
12.7 GB host. The float16 build now reads both components as stored (memory
mapped, no copy) with the exact per-call cast the float32 build already uses.

- flux3_storage_dtype returns bf16 for float16 CUDA loads too
  (UNSLOTH_DIFFUSION_FLUX3_HALF_STORAGE=0 restores the widened load).
- The transformer is read as stored only when a native quant rebuilds its
  Linears, or when storage saves memory (float32); a dense float16
  transformer still loads widened so it never casts per step.
- The native quantiser rounds a manual-cast weight to the compute dtype before
  quantising, so the int8 codes match a widened load bit for bit.
- After a native quant on an fp16-only card, the Linears left dense become
  plain float16 modules again, exactly what a float16 load holds.
…r's weight

Reading .weight on a native quantised Linear dequantises it, so the undo
pass after the FLUX.3 klein int8 build dequantised all 228 quantised Linears
(about 22 s of the load and a dense transient on the host). Only manual-cast
modules are inspected now.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 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-13T11:23:00.031146Z d20ff79 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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: d20ff79627

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

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. You're on a roll.

Reviewed commit: d20ff79627

ℹ️ 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 3e7eadf into main Nov 13, 2026
@danielhanchen
danielhanchen deleted the studio-lowram-t4 branch November 13, 2026 13:12
danielhanchen added a commit that referenced this pull request Nov 13, 2026
… (low-RAM hosts) (#17644)

Stacked on #17642 (base branch `studio-lowram-t4`). Retarget to `main`
once that merges.

## Summary

On a standard Colab T4 (12.7 GB host RAM) FLUX.3 klein int8 rendered at
62 to 63 s/img, against 37 s/img on a high-RAM T4. The gap was all in
the text encoder: 24 to 27 s of encode per image, against 0.7 s on
high-RAM. Denoise was the same 35 to 36 s on both.

This PR pins the streamed text encoder once the load has placed the
denoiser on the GPU, when host RAM allows it. On the standard T4 it now
renders at 36.6 to 37.0 s/img with 0.8 to 1.2 s of encode per image.
Images are byte-identical, and the high-RAM path is unchanged.

## Cause

- The image load decides what to pin (`_streamed_pin_plan`,
`diffusion_memory.py`) while it still holds the int8 transformer's host
copy. On the 12.7 GB VM that reading was `encoders=False (7696 MiB)
against 0 MiB of pinnable host RAM`. The plan-time prefix
(`_streamed_pin_leftover_mib`) was 0 too, so no pinner was queued for
the encoder.
- The 6.0 GiB of streamed encoder groups stayed as views of the
memory-mapped safetensors file. Each onload ran
`ModuleGroup._pinned_memory_tensors` (diffusers
`group_offloading.py:202`), which calls `tensor.pin_memory()` on those
views. A py-spy profile puts 26.5 s of a 27.0 s encode window on that
line.
- The page cache could not keep those pages between prompts. During
renders the VM had about 8.8 GiB of page cache, about 2.8 GiB of it
active (libraries and other mapped files), and the encoder's streamed
set is just larger than what was left. A sequential scan over a working
set slightly larger than the cache misses almost every page. Each prompt
re-read 5.7 to 6.4 GB from disk (process `read_bytes`), about 25k major
faults.
- Once the load had moved the transformer to the GPU and returned its
freed heap (2.4 to 2.6 GiB), the same host had about 10.5 GiB available.
That was enough to pin the encoder within the usual reserve.

## Change

- Image loads whose streamed text encoders miss the pin budget at plan
time now defer the encoder pin with a cap that is read when the pinner
starts, not at plan time. This reuses the existing `_GroupPinner` byte
cap and `_late_encoder_pin_cap`, which video loads already use.
- Before reading the budget, the cap returns the load's freed heap to
the OS (`trim_host_heap_after_load`), so the budget counts the denoiser
host copy the load has already dropped.
- The budget is `_pin_budget_mib()`, unchanged: it keeps `max(4 GiB,
15%)` of host RAM free. Only the prefix of offload groups that fits is
pinned. When nothing fits (under 256 MiB), nothing is pinned and the
encoder streams as before.
- Resident encoder groups drop their host copy first (`lazy_resident`,
as on the existing image path).
- Unchanged:
  - whole plan-time pins (every high-RAM host);
- the small-host route, which keeps its memory-mapped bytes out of host
RAM on purpose;
  - torchao-weight encoders;
  - Windows / WSL;
  - integrated GPUs;
  - a forced `UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN`.
- Kill switch: `UNSLOTH_DIFFUSION_LATE_IMAGE_ENCODER_PIN=0` restores the
plan-time prefix. The existing `UNSLOTH_DIFFUSION_PARTIAL_ENCODER_PIN=0`
also turns it off.

## Results

Settings:
- FLUX.3 klein, `transformer_quant=int8`, 1024x1024, 16 steps, 3 images
per run after one warmup image.
- Every run is a fresh process with a fresh Studio home.
- Arms alternate on one VM: before, after, before, after, before, after.
- Before = the current branch head.
- Encode = prompt start to denoise start, per image.

### Standard Colab T4 (12.7 GB host RAM)

| arm | load s | s/img (median) | encode s per image | denoise s per
image | disk read GB per image | peak PSS GiB | min MemAvailable GiB
during renders |
|---|---|---|---|---|---|---|---|
| before r1 (includes download) | 369.2 | 62.34 | 26.9 / 26.1 / 23.7 |
36.2 / 35.2 / 36.0 | 6.4 / 6.2 / 5.7 | 8.40 | 8.23 |
| before r2 | 184.7 | 61.99 | 25.5 / 25.6 / 25.4 | 35.6 / 35.5 / 35.5 |
5.9 / 5.9 / 5.9 | 8.92 | 8.50 |
| before r3 | 181.0 | 63.45 | 26.9 / 26.8 / 26.8 | 35.6 / 35.7 / 35.7 |
6.2 / 6.2 / 6.2 | 9.11 | 8.51 |
| after r1 | 212.3 | 36.90 | 0.8 / 0.9 / 1.0 | 35.2 / 34.9 / 35.2 | 0.0
| 8.52 | 3.42 |
| after r2 | 212.6 | 37.04 | 1.2 / 0.8 / 0.8 | 35.2 / 34.7 / 35.3 | 0.0
| 9.00 | 3.48 |
| after r3 | 213.4 | 36.62 | 0.8 / 0.8 / 0.8 | 34.9 / 34.8 / 35.1 | 0.0
| 9.15 | 3.48 |

- **s/img:** 62.3 to 37.0 (median of medians). The before A/A spread is
1.5 s.
- **Load:** about 28 s longer. The pin itself (6.0 GiB in 23 to 27 s)
reads the encoder from disk once, during the load.
- **Host memory:** peak PSS is unchanged. The lowest MemAvailable over
the whole run was 3.41 GiB, against 3.74 to 4.02 GiB before.
- **Images:** md5s identical in all six runs (`bc8107ba`, `952ea0be`,
`a8876fe8`).
- **Engagement:** each after run logs `pins up to 6.6 GiB of its offload
groups (cap read at pin start)` and `pinned 6.0 GiB of
Qwen3VLForConditionalGeneration host weights ... (onloads waited 0.0 s,
registered)`.

### High-RAM Colab T4 (53 GB host RAM), no-regression check

| arm | load s | s/img (median) | encode s per image | md5 |
|---|---|---|---|---|
| before r1 (includes download) | 149.5 | 37.01 | 0.7 / 0.7 / 0.7 |
identical |
| before r2 | 54.9 | 37.39 | 0.7 / 0.7 / 0.7 | identical |
| before r3 | 54.7 | 37.64 | 0.7 / 0.7 / 0.7 | identical |
| after r1 | 59.7 | 37.72 | 0.8 / 0.7 / 0.8 | identical |
| after r2 | 54.7 | 37.56 | 0.7 / 0.7 / 0.7 | identical |

On this host the plan pins the whole encoder up front (`encoders=True
(7696 MiB) against 34590 MiB`), so the new branch is never taken: no run
logs it. The s/img difference is run-to-run noise.

## Tests

- **New:** `tests/test_image_encoder_late_pin.py`, 11 CPU tests. They
cover:
- routing: a plan-time miss defers with the late cap; the kill switch
keeps the plan-time prefix; whole pins and the small-host route are
unchanged;
- the cap is read at pin start after a heap trim, earlier pinners'
outstanding bytes come off it, and a forced plan or a budget under the
minimum pins nothing;
  - a pinner pins the prefix that fits the budget at pin start.
- On the current branch head these tests fail. With this change they
pass, together with `tests/test_image_encoder_background_pin.py`.
- **Wider suite:** every backend test touching `diffusion_memory` or
group offload (14,000+ tests) fails the same 4 tests with and without
this change. Those failures already exist on the branch head.
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.

1 participant