Skip to content

Studio images: batch FLUX.3 requests in one modular call (streamed klein 2.69x per 4 images on A100), Anima kept serial - #20071

Open
danielhanchen wants to merge 3 commits into
mainfrom
studio-batch-flux3-anima-v2
Open

danielhanchen wants to merge 3 commits into
mainfrom
studio-batch-flux3-anima-v2

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follows #19837 (merged), which added the batch adapters and the measured race.

Problem

FLUX.3 klein, FLUX.3 klein base and Anima render every image of a list as its own modular pipeline call: the text step encodes one prompt per call, so #19837's request batching has to treat both families as batched_forward = False and runs concurrent requests one at a time. When the denoiser streams weights from host memory, every image pays the full weight transfer again, so four queued requests cost four full passes of streaming.

Change

  • FLUX.3 (diffusion_flux3.py): rows that share a text window run as one modular call. Each row is encoded alone, so its embeddings are exactly what its own call would produce; the text step returns the stacked rows, each row's noise is its own seeded reference noise, and the denoiser runs one forward per step over all rows. Rows land in separate calls when they differ in text window, per-row negative prompt or per-row reference size, and also for caller latents, unseeded rows, or a denoiser whose activation scale is computed from the whole call. A single image takes the unchanged call.
  • FLUX.3 edit, shared reference: within one request (one prompt, a seed list), rows that share the request's reference still run as one call. A neighbour swap on that path was bit-identical (see the follow-up section). The route never coalesces separate edit requests: only plain text-to-image requests share a call.
  • FLUX.3 per-row references (row_images, references per image): held back. Rows that carry their own references always render one at a time until a GPU run shows neighbour invariance. UNSLOTH_DIFFUSION_FLUX3_ROW_REFS_BATCH=1 enables batching for measurement only.
  • Anima (diffusion_anima.py): the facade can run rows with the same conditioned text length as one modular call, but the Anima record keeps batched_forward = False, so Anima requests stay serial on every card (one chunk per image, never coalesced at the route). On an RTX PRO 6000 its batched rows drifted about 0.13 LPIPS from their own solo renders; batching turns on only after a like-for-like G2c passes.
  • Quality gate (diffusion_batch_quality.py, merged in from the infra side): a measured race win serves only with a passing offline G2c verdict for the family, the card's device class and the execution path; missing or failing keeps the serial rule. The race's replay check now compares row 0 with its solo render on the same execution path (b_exact: bit-identical, or within the same-shape rerun noise), and seeded joins need it.
  • diffusion_families.py: DiffusionFamily.batched_forward (None = not stated, the existing default rules). Both FLUX.3 records set it to True, so Studio images: family batch adapters, measured batching race and per-size CUDA graphs #19837's adapter (diffusion_batch_adapters.batched_forward / adapter_for) admits them, _generation_chunks keeps their rows in one chunk, and the race no longer refuses them.
  • Kill switches: UNSLOTH_DIFFUSION_FLUX3_BATCH=0 and UNSLOTH_DIFFUSION_ANIMA_BATCH=0 restore one call per image.

What Auto does by default

Nothing changes for a single-image request. With concurrent requests, #19837's policy decides:

  • Streamed denoiser (Low VRAM / group offload, no CUDA graphs): requests with the same settings share a call (the existing rule for a family that fuses its rows).
  • Resident weights, CUDA graphs, or a static compile: requests stay serial, as they do today, unless Studio images: family batch adapters, measured batching race and per-size CUDA graphs #19837's idle race measures a win on that load, card and shape and an offline G2c verdict passes for that family, card and execution path (eager or graph). Without a passing verdict a race win is persisted but not served. The gate ships with no verdicts, so out of the box these placements stay serial; the race decides speed per card, the G2c verdict decides whether that speed may be served.

Gates

  • G1: an N=1 single-image request is byte-identical to the base. A request with batch_size > 1 now shares one forward across its images, so its bytes may differ from the base by floating-point batch-shape effects; that path is gated by G2a and G2c instead.
  • G2a: a row's bytes do not change when its neighbours change.
  • G2c: paired LPIPS against a bf16 speed-off reference, upper bound of (batched minus solo) at most +0.01.
  • G4: speed lower bound at least 1.05x with p95 at most +3%.

1024 px, Studio Auto settings.

A100 / RTX PRO 6000, batch 4, direct engine calls (the change on an earlier base):

Family G1 (N=1 bytes) G2a (neighbour swap) G2c upper bound Streamed batch-4 Resident batch-4
FLUX.3 klein (16 steps) identical 4/4 bit-identical, targets 0/1/3, max diff 0 +0.0061 (n=24, PASS) 2.69x (31.0 s to 11.6 s per 4, A100-80) 1.018x (A100-80)
FLUX.3 klein base (50 steps) identical 4/4 bit-identical, max diff 0 +0.0050 (n=12, PASS) 1.33x (44.1 s to 33.2 s, RTX PRO 6000) 1.016x (A100-40)
Anima (30 steps) identical 4/4 bit-identical, max diff 0 +0.0006 (n=24, PASS) 2.43x (45.5 s to 18.7 s, A100-40) 1.08x (bf16, A100-40)

Every batched render ran one denoiser forward per step over 4 rows (trace: 16 / 100 / 60 calls per batch, the same as one solo image). A/A repeats of the same batch were byte-identical.

G4 (RTX PRO 6000 Blackwell), through #19837's route and race, this branch merged with #19837, streamed (Low VRAM):

Family G1 (N=1 bytes vs #19837) G2a (race neighbour check) G2c upper bound Race Concurrent N=4 after the race
FLUX.3 klein identical 8/8 exact (max diff 0), A/A exact +0.0061 (n=24, PASS) on both the eager and the graph path (an earlier n=8 run read +0.0136, under-powered) size 2 won, lower bound 1.141x (eager arm); size 4 skipped (no static-compile graph at 4) 34.2 vs 32.3 images/min (+6%)
Anima 0/10 identical (this load has cudnn benchmark on, which picks conv kernels per process; an A/A base-vs-base arm is queued to tell that apart from a change) exact (max diff 0), A/A exact; row 0 vs its solo max 227 px +0.036 vs eager reference (n=8, FAIL); +0.207 strict vs solo size 2 lost on speed, lower bound 1.036x; size 4 skipped 22.2 vs 22.2 images/min (no change: stays serial)

On G4 a streamed klein render is already fast (1.85 s per image), so streaming saves little and the speedup is small; the measured race decides per card. This PR ships the klein G2c PASS for this card (RTX PRO 6000 Blackwell, eager and graph path) as a stored quality verdict, so a klein race win there may serve, and only where that card's own race measures a lower bound of at least 1.05x. Every other card, and klein base, still needs its own verdict.

Like for like on G4 (n=24): solo renders are byte-identical on the eager and the graph path, and batched rows score the same on both, so the earlier drift was not a path mix. Batched rows are not byte-identical to their solo renders (mean LPIPS 0.010), so seeded requests do not join: the first batch-shape divergence is the bf16 timestep embedder and the text input projection, both run at M = batch rows. Running those row by row is being measured as an exact path and is not part of this PR. On G4 the Anima race also found no speedup, and its batched rows drift far from their solo renders, so this PR keeps Anima serial everywhere (see Change).

Follow-up: edit batching

Batching edits across requests, and rows with per-row references, is left for a follow-up. Evidence so far, kept for that PR:

  • FLUX.3 klein edit, shared reference, batch 4: G1 identical 4/4; G2a bit-identical (max diff 0, RTX PRO 6000); G2c upper bound +0.00003 (n=12, PASS); resident 1.018x; streamed not measured.
  • Per-row references: own-row LPIPS at most 0.0044, but in one earlier run one of four targets changed bytes when a neighbour's reference was swapped, so strict G2a is not shown. That is why this PR keeps them serial.

Tests

CPU, studio/backend:

  • New tests/test_diffusion_flux3_batch_rows.py and tests/test_diffusion_anima_batch_rows.py. They check that edit rows with different references never share a forward and that edit requests with references never coalesce at the route, as well as one forward per step for every row, that each row is its own render, that a neighbour never changes a row, that different text windows / negatives / reference sizes render apart, the kill switch, unseeded rows and per-call scaled denoisers, and that a single image is the unbatched call.
  • Updated tests/test_diffusion_flux3.py (FLUX.3 images share one generation chunk; a record that does not state batched_forward keeps one chunk per image) and tests/test_image_batch_infra.py (the route's family check now admits FLUX.3).
  • Run together with test_image_batch_infra.py, test_image_batching_followups.py, test_diffusion_batched.py, test_batch_sizes_per_load.py, test_openai_images_batching.py, test_take_rows_batched.py, test_diffusion_cfg_batch_policy.py and every test_diffusion_flux3_* / Anima test, plus the quality gate tests (test_image_batch_quality.py): 938 passed, 14 skipped.

Not proven here

  • The A100 table comes from the same change on an earlier base. The G4 table ran this branch merged with Studio images: family batch adapters, measured batching race and per-size CUDA graphs #19837, before the edit hold-back and the quality gate commits (neither changes a plain text-to-image render).
  • The quality gate ships with no G2c verdicts, so no family is promoted beyond today's rules until verdicts are measured and added.
  • Edit batching across requests and per-row references: see the follow-up section above.
  • No G4 lower bound or p95 was computed. Only medians of 3 interleaved repeats.
  • No AMD, Apple Silicon or Windows runs. The change is backend Python with no platform-specific code.

…lar call

Rows are encoded one by one and stacked, each with its own seeded noise, so the denoiser runs one forward per step over all rows. Anima gets the same facade path but stays serial (batched_forward = False) until its quality gate passes. Kill switches: UNSLOTH_DIFFUSION_FLUX3_BATCH=0, UNSLOTH_DIFFUSION_ANIMA_BATCH=0.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 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-28T00:41:29.907945Z 00610f2 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 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: a660d84926

ℹ️ 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 +813 to +817
for group_index, group in enumerate(groups):
first = group_index == 0
if len(group) > 1:
try:
for i, img in zip(group, run_rows(group, first)):

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 Reset the static skip schedule for each modular call

When static step skipping is enabled and a FLUX.3 prompt list spans multiple text windows, this loop runs multiple denoising trajectories inside one generation chunk. However, DiffusionBackend.generate resets the static skip schedule only once per chunk, and its _on_step callback increments StaticStepSkip.steps_ended throughout every trajectory. After the first group finishes, subsequent groups start beyond the schedule's end and compute every step instead of applying the requested skips. This changes their rendering settings and removes the expected speedup depending on group order. Reset the schedule at each modular-call boundary, or expose these groups as separate engine chunks.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 00610f2. The facade now rewinds the static skip schedule before every modular call after the first in a chunk (new rewind_static_step_skip: step count back to 0 and cached residuals dropped, the plan and the stats carry on), so each text-window group and each one-by-one row gets the requested skips. Tests: test_each_modular_call_starts_its_own_static_skip_trajectory (two windows rewind once, one batched call never, one call per image rewinds per extra image) and test_rewind_restarts_the_step_count_and_keeps_the_plan; 340 FLUX.3 and step-skip tests pass.

danielhanchen added a commit that referenced this pull request Nov 28, 2026
…d guard every global the generic save loads (red on main since #20022) (#20075)

## Summary

`tests/saving/test_save_method_lora_routing.py` has 18 failures on
`main` since #20022 (`Train LoRA on packed GGUF weights`), in every Core
job (HF 4.57.6 + TRL<1 and HF latest + TRL latest). The most recent
staging example is #20071, which does not touch saving:

```
NameError: name 'ExitStack' is not defined
AssertionError: unsloth_generic_save calls ['_shard_bytes'] from save.py, which the routing harness neither loads nor stubs
```

The routing harness execs `unsloth_generic_save` from `save.py` source
into a namespace it builds by hand. #20022 wrapped the merge in an
`ExitStack` (a module-level import) and added a GGUF-packed branch that
calls `_shard_bytes` and reads `_GGUF_PACKED_STATE_DICT_REFUSAL`. The
harness defines none of these, so every routing test that reaches the
merge dies with a `NameError` before asserting anything. #20022 is
correct, and the harness is behind it.

## Changes

- The harness now defines:
  - `ExitStack`;
  - `_shard_bytes` and the refusal constant;
  - `sys`;
- `save_inkling2_merged_16bit`, as an overridable default that tests
replace when they exercise the Inkling 2 writer.
- `unsloth.models.gguf_packed`, which the save imports lazily, is
stubbed in `sys.modules` for each routing test, the same way
`unsloth_zoo.saving_utils` already is. No fixture is GGUF-packed:
  - `is_gguf_packed_model` answers `False`;
- `gguf_dense_base_for_merge` yields `None`, so the merge resolves its
base exactly as before #20022;
  - `write_gguf_dense_base` raises if it is ever reached.
- `_shard_bytes` is listed as a stubbed helper, so the existing helper
coverage check passes for the right reason.
- New guard
`test_every_global_the_generic_save_reads_is_in_the_harness`. The
existing helper check only sees calls to `save.py`'s own functions, so
it could not see a module-level import like `ExitStack`. The new guard
walks the bytecode of the exec'd `unsloth_generic_save` (nested code
objects included) for every `LOAD_GLOBAL`, and fails if the harness
namespace or builtins do not define one. A future import or constant
added to the save then fails one test that names it, instead of a wall
of `NameError`s.

## Verification

- On `main`, 18 tests fail. With this change the file passes: 112
passed, on both transformers 5.18 and 4.57.6.
- Sabotage check: removing `ExitStack` from the harness fails the new
guard with `unsloth_generic_save reads ['ExitStack'], which the routing
harness does not define`.
- Only the test file changes. `unsloth/save.py` is untouched.
danielhanchen added a commit that referenced this pull request Nov 28, 2026
… work (red on main since #20022) (#20077)

## Summary


`tests/test_import_keeps_plain_model_backends.py::test_every_from_pretrained_starts_with_the_load_hook`
has failed on `main` since #20022 (`Train LoRA on packed GGUF weights`).
It fails in the `Repo tests (CPU, rest-2)` shard, most recently on
#20071's staging run:

```
AssertionError: ('unsloth/models/loader.py', 'FastLanguageModel')
assert '_unsloth_load_begins' in []
```

The guard makes sure `_unsloth_load_begins()` (the cuDNN SDPA switch for
Unsloth loads) runs before any loading work in each `from_pretrained`.
It looked for the call among the first three statements. #20022 added a
third local import (`from .gguf_packed import
check_gguf_packed_request`) to `FastLanguageModel.from_pretrained` and
`FastModel.from_pretrained`, which pushed the hook to the fourth
statement. Nothing runs before the hook: the statements ahead of it only
bind names. So #20022 is correct, and the guard was counting statements
rather than checking the property it is named for.

## Changes

- `_first_work_is_the_load_hook(fn)` skips local imports and a
docstring. It then requires the first remaining statement to be the
`_unsloth_load_begins()` call. This is stricter than before about real
work: an assignment or call ahead of the hook now fails, where the old
check let up to two of them through. It is also indifferent to how many
imports a load path needs.
- The test now asserts that it found all four `from_pretrained` methods
(`FastLanguageModel`, `FastModel`, `FastLlamaModel`, `FastBaseModel`),
so a rename cannot make it pass vacuously.
- A parametrised table pins the checker itself:
  - accepted: imports before the hook, and a docstring before the hook;
- rejected: an assignment before the hook, a call before the hook, and
no hook at all.

## Verification

- On `main` the test fails for `FastLanguageModel` and `FastModel`. With
this change the file passes (13 passed).
- Sabotage check: moving `require_gguf_package(...)` above
`_unsloth_load_begins()` in `FastLanguageModel.from_pretrained` fails
the guard with `('unsloth/models/loader.py', 'FastLanguageModel')`.
- Only the test file changes.
danielhanchen added a commit that referenced this pull request Nov 28, 2026
…ked check in the loader fixture, hint check per failure path (red on main since #20022) (#20078)

## Summary

Three more checks in `Repo tests (CPU, rest)` have been red on `main`
since #20022 (`Train LoRA on packed GGUF weights`). They account for 22
failures, most recently on #20071's staging run. Each one was judged
separately:

| Test | Failure | Which side is wrong |
|---|---|---|
| `test_runtime_text_encoding.py::test_shipping_code_names_an_encoding`
| `unsloth/models/gguf_packed.py:1237` and `:1243` open
`model.safetensors.index.json` and `config.json` for writing without an
encoding | **The code.** The repo rule is that shipping text I/O names
`utf-8`, so the Windows locale cannot decide. |
| `test_optimized_precision_conflicts.py` (20 cases) | `from_pretrained
reached from .gguf_packed import check_gguf_packed_request: stub it in
the loader fixture` | **The test.** `FastLanguageModel.from_pretrained`
now validates a `gguf_packed` request at its entry point, which is
correct. The fixture's relative-import guard did its job and named the
missing binding. |
|
`test_offloaded_parameter_hint.py::test_both_save_failure_paths_use_it`
| `assert 3 == 2` | **The test.** #20022 added a third GGUF save failure
path (the packed dense write), and it correctly carries the
offloaded-parameter hint. The test pinned the call count instead of the
property. |

## Changes

- `unsloth/models/gguf_packed.py`: both JSON writes in the dense writer
pass `encoding = "utf-8"`.
- Loader fixture:
- It binds the real `check_gguf_packed_request`, compiled from source
like `gguf_drop_bitsandbytes`, instead of a stub.
- `_real_function` now brings along the module-level literal constants
the function reads (`GGUF_PACKED_KWARG` here). Without that, the real
function would fail on a `NameError`.
- New test `test_the_real_gguf_packed_check_runs_at_the_entry_point`:
`gguf_packed = True` without a `gguf_file` is refused with a
`ValueError` before any config probe or dispatch. This proves the real
check runs, rather than a stub that always says "off".
- Hint test: `test_every_save_failure_path_uses_it` walks every `raise
RuntimeError(f"Failed to save...")` in `save.py`. It requires each
message to include `_offloaded_parameter_hint(...)`, and requires both
the merge and the plain-save messages to still exist. A new failure path
then has to carry the hint, whatever the count.

## Verification

- On `main` these three files have 22 failures. With this change they
pass (44 passed).
- Sabotage checks:
- Dropping the hint from the GGUF-packed failure path fails the new hint
test, which names line 5590.
- Replacing the real check with `lambda kwargs, **flags: False` in the
fixture fails `test_the_real_gguf_packed_check_runs_at_the_entry_point`.
- Removing `encoding = "utf-8"` is the state on `main`, which the
encoding guard reports.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review the static skip rewind at 00610f2

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 00610f204f

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

This branch has not been deployed

No deployments
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