Skip to content

Studio: prepare FLUX.2 edit references on the GPU, byte-identical to the CPU path - #18917

Merged
danielhanchen merged 6 commits into
mainfrom
studio-klein-ref-gpu-preprocess
Nov 22, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
studio-klein-ref-gpu-preprocess

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Summary

FLUX.2 edits (klein 4B / 9B, FLUX.2 dev) prepare every reference image on the CPU inside the pipeline: a Pillow Lanczos resize to about 1 MP when the image is larger, a centre crop to a multiple of 16, then / 255 and 2x - 1 in float32. That costs 28-36 ms per 2-4 MP image on one core, before the GPU does anything.

This PR does that work on the GPU and keeps the result byte-identical:

  • New core/inference/diffusion_ref_preprocess.py patches the pipeline's own Flux2ImageProcessor instance at load:
    • _resize_to_target_area returns a deferred resize (the source image plus the size Pillow would produce). Any attribute other than its size materialises the Pillow resize, so other callers see a normal image.
    • preprocess(..., resize_mode="crop") for one image uploads the uint8 pixels once, then does the Lanczos resize and the crop in Triton. It maps the codes through a 256-entry table built with the processor's own ops.
    • Anything else runs the stock method: lists, other resize modes, crop coordinates, a non-default processor config, no CUDA execution device, or any GPU error.
  • New core/inference/diffusion_lanczos_triton.py is the resize kernel. It uses Pillow's normalised 22-bit fixed-point coefficients and rounding, so the integer pixels match exactly. It is adapted from the Apache-2.0 SGLang Lanczos kernel (sglang python/sglang/kernels/ops/mm/process/lanczos.py, commit 9667988e), with attribution in the file header. One change from that source: the output height and width are runtime arguments, so one compile serves every reference size.
  • On the first GPU call per device, a probe compares one resize + crop against the CPU path. A mismatch keeps that device on the CPU path for the process.
  • Scope: NVIDIA CUDA only; ROCm, MPS and CPU are unchanged. Kill switch: UNSLOTH_DIFFUSION_GPU_REF_PREPROCESS=0.

Results

RTX PRO 6000 Blackwell (sm120), torch 2.14.1, diffusers 0.42.1. FLUX.2 klein 4B through Studio's own load and generate (reference workflow, int8 compiled default, 1024x1024, 4 steps, seed 1234). One process with the kill switch toggled per request, ABBA, 4 reps per cell, medians in ms. JPEG inputs: 1920x1080, 2048x1536, 1536x2048, 1600x1200. "new sizes" uses a different set of image sizes every rep, so each request pays a fresh coefficient build.

references images CPU path e2e GPU path e2e e2e change preprocessing CPU / GPU
2 repeated sizes 1071.9 (1069.0-1075.8) 1012.7 (1009.6-1023.2) -5.5% 64.8 / 8.2
2 new sizes 1078.3 1030.9 -4.4% 67.3 / 26.3
4 repeated sizes 2062.7 (2056.6-2076.4) 1948.8 (1944.6-1956.8) -5.5% 128.4 / 15.3
4 new sizes 2078.5 1989.2 -4.3% 134.9 / 47.0
  • Output pixels are identical in all 16 paired requests. They also match an unpatched main build of the same requests (md5 equal for 2 and 4 references).
  • Denoise, VAE encode and VAE decode are unchanged (884 / 45 / 37 ms for 2 references in both arms). Only the preprocessing moved.
  • Engagement: 8 and 16 GPU-prepared images on the GPU arms, 0 on the CPU arms, probe passed, 0 fallbacks.
  • Unit check on 16 sizes (517x1999 up to 6000x4000, including images at or under 1 MP that only crop): torch.equal and equal strides for all 16. Warm GPU time is 0.4-24 ms against 2-179 ms on the CPU.
  • One-time cost: the first GPU call in a fresh process on a cold VM took 1.2 s, which is the Triton compile. Later processes reuse Triton's disk cache.

Tests

  • tests/test_diffusion_ref_preprocess.py (22 CPU tests):
    • env switch, install scope (CUDA only, Flux2 processor only, idempotent);
    • the deferred resize matching Pillow;
    • the installed processor with no CUDA device giving the stock tensor;
    • the crop and table branch matching the stock tensor bit for bit for RGB / RGBA / L inputs;
    • the table matching the processor's normalise;
    • the config gate, the kernel source contract, and the load-time install.

Not covered

  • Exactness and timing were measured on sm120 only. Other NVIDIA cards are covered by the runtime probe, not by a measurement here.
  • The first-call compile is not moved off the first request (no prewarm).
  • Only FLUX.2 klein 4B was run end to end. klein 9B and FLUX.2 dev share the same processor and pipeline code but were not run.

Cross-card check and fixes after review

klein 4B, 1024x1024, 4 steps, kill switch toggled per request, ABBA x3, fixed-image md5 equal to the merge base on every card:

card 2 references e2e (CPU path -> GPU path) preprocessing stage
T4 sm75 22925 -> 22764 ms (-0.7%, inside noise) 143 -> 14 ms
L4 sm89 8547 -> 8394 ms (-1.8%, inside noise) about 7x faster
A100-40 sm80 2051 -> 1918 ms (-6.5%) 149 -> 20 ms
RTX PRO 6000 sm120 1071.9 -> 1012.7 ms (-5.5%) 64.8 -> 8.2 ms

The gain is end to end only where the denoise is fast; on T4 and L4 it is a tie and never slower.

Fixes made during review:

  • Pillow 13 runs the vertical Lanczos pass first when the height shrinks by more than twice the width. The kernel now follows the installed Pillow's order, and the first-call probe checks a tall image too. Before this, a tall reference over 1 MP (for example a 1080x2400 screenshot) was not byte-identical; it is now equal to the CPU path on T4, L4 and A100.
  • Only RGB sources defer to the GPU resize, so other modes keep Pillow's resize-then-convert order.
  • The kernel launches under the image's device.
  • ROCm is detected with is_rocm_torch, and the torch-only gate tests live in test_diffusion_ref_preprocess_gate.py so CPU CI runs them.

…the CPU path

The FLUX.2 pipelines resize (Lanczos to about 1 MP), crop and normalise every
condition image on the CPU. On CUDA, do the resize and crop in a Triton
kernel that reproduces Pillow's fixed-point Lanczos, and normalise through a
table built with the image processor's own ops. The tensor is torch.equal to
the CPU one; a probe against the CPU path on first use per device keeps a
mismatching card on the stock path. UNSLOTH_DIFFUSION_GPU_REF_PREPROCESS=0
turns it off.
@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-22T17:55:49.135384Z 42676b8 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. 🎉

Reviewed commit: 8336abc33d

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

…torch-only gate tests run without diffusers

[skip ci]
…r tall images, defers only RGB sources, launches on the image's device

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 42676b85ed

ℹ️ 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 a368037 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-klein-ref-gpu-preprocess branch November 22, 2026 19:09
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…r the two-card Wan decode with the VAE seam guard (main reds) (#18945)

## Summary

Two checks are red on `main` and fail on every PR that runs them, for
example the staging run for #18941:

| Failing check | Introduced by | Which side was wrong | Fix |
|---|---|---|---|
|
`tests/test_python39_compatibility.py::test_studio_evaluated_unions_do_not_grow`
(`Core`, all three combos): "36 studio files now evaluate PEP 604 unions
on the floor, against 35 recorded" | #18917 added
`core/inference/diffusion_lanczos_triton.py` | Code. Its public entry
point declares `crop`, `mean` and `std` as `tuple[...] \| None`, which
is evaluated when the function is defined and raises `TypeError` on
Python 3.9. | Those three parameters become `Optional[tuple[...]]`. No
`from __future__ import annotations`: the module's Triton kernels read
their `tl.constexpr` annotations, which that import would turn into
strings. |
|
`studio/backend/tests/test_vae_tile_geometry.py::test_every_tiled_decode_patch_is_probed`
(`seam-guard`): "['video_vae_multigpu'] rebind a VAE's tiled_decode but
expose no install(vae) this guard applies" | #18829 added
`core/inference/video_vae_multigpu.py` | Test registry. The module
mirrors the stock `AutoencoderKLWan.tiled_decode` body (checked by AST
fingerprint) and only shares its tiles between two cards. It keeps the
stock tile grid, and
`test_video_vae_multigpu.py::test_split_tiles_match_the_stock_tiled_decode_bitwise`
proves it. Its `install(pipe, partner)` takes a pipeline, not a VAE, so
the guard cannot apply it. | Listed in `GEOMETRY_PRESERVING` with that
reason, which is the remedy the guard's message names for a module that
keeps the stock tiles. |

Neither fix changes behaviour.

## Testing

- `tests/test_python39_compatibility.py`: fails on `main` with the
message above, 8 passed with this change.
- `tests/test_vae_tile_geometry.py` and
`tests/test_video_vae_multigpu.py`:
`test_every_tiled_decode_patch_is_probed` fails on `main`. With this
change, 55 passed, 2 skipped, 2 xfailed (the recorded known seams).
- `tests/test_diffusion_ref_preprocess.py` and
`tests/test_diffusion_ref_preprocess_gate.py`, the suites that exercise
the Lanczos module: 33 passed.
- `ruff check --select F` on the Lanczos module: clean.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…ng guard red on main) (#18947)

## Summary

`Repo tests (CPU, rest-2)` is red on `main` since #18917:

```
tests/test_source_read_encoding.py:1029: in test_checked_in_file_reads_name_an_encoding
E   AssertionError: 2 file reads in the test trees touch a checked-in file with the platform default encoding,
    so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8":
    ['studio/backend/tests/test_diffusion_ref_preprocess_gate.py:34: read_text()',
     'studio/backend/tests/test_diffusion_ref_preprocess_gate.py:40: read_text()']
```

#18917 added `test_diffusion_ref_preprocess_gate.py`, whose source
checks read `diffusion_lanczos_triton.py` and `diffusion.py` with a bare
`read_text()`. The guard is right: on Windows that uses the locale code
page.

## Fix

Both reads pass `encoding = "utf-8"`. Only the test changes.

## Testing

- `tests/test_source_read_encoding.py`: 1 failed on `main` (the two
reads above), 16 passed with this change.
- `studio/backend/tests/test_diffusion_ref_preprocess_gate.py`: 5
passed.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…*31 guard, CUTLASS race key covers its helpers (#18968)

## Summary

Follow-ups from a kernel-rules pass over the recent INT8 attention,
CUTLASS race cache and FLUX.2 reference preprocessing PRs (#18917,
#18797, #18786). Three commits, one per fix:

1. **FLUX.2 edits: the GPU reference preprocess probe runs at load, not
inside the first edit request (#18917).**
`install()` patches the image processor before placement, so the
per-device probe (Triton compile of the two Lanczos kernels plus two
Pillow comparison images) ran on the first edit request under the module
lock. A new `diffusion_ref_preprocess.warm(pipe)` runs the same probe
for the pipe's execution device right after placement (after the graph
arming, before the load record). It is a no-op for families without the
installed preprocess. The lazy probe stays as the fallback for a device
`warm()` never saw.
2. **FLUX.2 edits: references past 2**31 elements stay off the 32-bit
Lanczos kernels (#18917).**
The kernels index one image with int32 flat offsets. `lanczos_resize`
now refuses a resize whose source, intermediate (either pass order) or
output reaches 2**31 elements, about 715 MP. The FLUX.2 preprocess
checks before it uploads the pixels, so such an image takes the CPU
path.
3. **INT8 GEMM: CUTLASS race verdicts are keyed on the helpers the race
code calls (#18797).**
`_RACE_SOURCES` hashed the listed race functions but not the helpers
they call. An edit to `_xs_dtype` (the activation-scale dtype the race
times), `_payload`, the act quant, the row-bucket bookkeeping or the
race switches therefore kept stale verdicts.
   - Those helpers are now keyed.
- The few left out on purpose are listed in `_RACE_UNKEYED`: the key
builders, the library loader (the library is hashed by its bytes) and
the tile probe's own persistence.
- A new test walks the call closure across the three keyed modules,
including `cut.x` calls, and fails on any helper that is in neither
list.
- Performance only: tile correctness is still the per-card bit-exact
probe. Every card re-races once after this update.

## Evidence

### 1. First edit request, L4 (Colab, torch 2.14.1+cu130, Triton 3.8.0,
diffusers 0.43.0)

Each run is a fresh process with base (main) and head interleaved, 5
runs per arm. The images are 2048x1536 and then 1800x2400, resized to 1
MP and cropped. "Cold" uses an empty Triton cache per process; "warm"
uses a pre-populated one.

| Triton cache | Arm | Load step (install + warm), ms | First request,
ms | Second request, ms |
|---|---|---|---|---|
| cold | main | 0.68 [0.64, 0.70] | 2601.6 [2577.2, 2609.3] | 28.2
[27.4, 28.7] |
| cold | head | 2564.8 [2553.5, 2569.1] | 33.5 [32.9, 34.7] | 28.3
[27.9, 30.0] |
| warm | main | 0.65 [0.63, 0.68] | 1639.4 [1637.0, 1646.5] | 28.1
[27.6, 30.5] |
| warm | head | 1606.5 [1604.1, 1614.7] | 32.7 [32.3, 34.7] | 27.5
[27.2, 27.8] |

- The first request drops from 2.6 s to 34 ms with a cold Triton cache,
and from 1.6 s to 33 ms with a warm one. The base spread is 1.2%, so
this is far outside the noise.
- The same time now lands in the load step.
- The second request is a tie (A/A control).
- Output tensors hash the same on main, on head and on the stock CPU
path, for both images and all 10 runs per arm. `STATS` shows `gpu 2,
fallback 0` in every run, so the GPU path ran.

### 2. Folded sink kernel at head dim 128 on sm80 and sm120 (#18786)

The question was whether the folded sink path is right on cards where it
had only been checked offline. It is, so the code is unchanged.

- **Setup:** current main, fold on vs
`UNSLOTH_DIFFUSION_INT8_ATTENTION_RESID_FOLD=0`, each arm twice. 15
cases: Flux shape, 40 sink keys, long calls, fp16 / fp32, strided, batch
2, no-clip, hd64. Compared against fp32 reference attention.
- **A100-40GB (sm80, qreg 1):**
- Covers both hd128 configs: wpc 4 below 4608 keys and wpc 8 from 4608
on.
- The fold engaged on every clipping hd128 case: one launch instead of
two.
- Fold on vs off differs by at most 0.125 in bf16. The 40-key case
reaches 0.5, which is one bf16 step at those magnitudes.
- The folded output is nearer fp32 in every bf16 clipping case. Flux
shape rel_l2 0.0130402 -> 0.0129988; 8192 keys 0.0085737 -> 0.0085072.
  - Non-clipping and non-sink cases are bit-identical.
- **RTX PRO 6000 (sm120, qreg 0, native probability pack from #18870):**
- Same picture. Flux shape rel_l2 0.0144564 -> 0.0144301; 8192 keys
0.0160356 -> 0.0160310.
- The 40-key case is a tie: 0.0208967 vs 0.0209146, with mean abs error
lower.
- **GPU pytest subset:** 57 passed on both cards in both arms, plus one
failure that is also there with the fold off:
`test_a_plan_whose_sink_path_loses_its_race_runs_torch_attention`.
- **sm86 has no cloud tier.** Its hd128 config compiles the same defines
as the A100 long-call config: HD 128, BN 128, NQ 1, WPC 8, STAGES 2,
QREG 1. The only arch branch in the kernel source is `__CUDA_ARCH__ <
800`, so sm86 runs the same fold code path that passed on A100. It stays
enabled.

## Tests

- `tests/test_diffusion_ref_preprocess.py`:
- The probe runs in `warm()` and not on the first request (the probe is
mocked to raise).
  - An unwarmed device still probes lazily.
  - `warm()` is a no-op without the install.
  - The load calls `warm` after placement.
- The int32 size limit, including that it is checked before the pixel
upload.
- `tests/test_diffusion_int8_cutlass_race_key.py`:
- Every function the keyed race code reaches is keyed or listed as
deliberately unkeyed.
  - The unkeyed names still exist.
- Each new test fails on main.
- Targeted CPU files pass: `test_diffusion_ref_preprocess.py` 34,
`test_diffusion_ref_preprocess_gate.py` 5,
`test_diffusion_int8_cutlass_race_key.py` 29,
`test_diffusion_int8_cutlass_lib_digest.py` 5,
`test_diffusion_int8_cutlass_probe_persist.py` 8.

## Not covered

- No real FLUX.2 model load was timed end to end. The L4 numbers come
from the image processor with the real kernels, on a pipe placed on the
GPU.
- sm86 was not run on hardware. The case for it rests on the identical
compiled defines above.
- Windows was not run. Nothing here is OS specific.
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