Repository navigation
Studio images: batch FLUX.3 requests in one modular call (streamed klein 2.69x per 4 images on A100), Anima kept serial - #20071
danielhanchen wants to merge 3 commits into
Conversation
…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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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)): |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…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.
… 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.
…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.
…tatic skip trajectory [skip ci]
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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 = Falseand 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
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.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=1enables batching for measurement only.diffusion_anima.py): the facade can run rows with the same conditioned text length as one modular call, but the Anima record keepsbatched_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.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_chunkskeeps their rows in one chunk, and the race no longer refuses them.UNSLOTH_DIFFUSION_FLUX3_BATCH=0andUNSLOTH_DIFFUSION_ANIMA_BATCH=0restore one call per image.What Auto does by default
Nothing changes for a single-image request. With concurrent requests, #19837's policy decides:
Gates
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.1024 px, Studio Auto settings.
A100 / RTX PRO 6000, batch 4, direct engine calls (the change on an earlier base):
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):
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:
Tests
CPU,
studio/backend:tests/test_diffusion_flux3_batch_rows.pyandtests/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.tests/test_diffusion_flux3.py(FLUX.3 images share one generation chunk; a record that does not statebatched_forwardkeeps one chunk per image) andtests/test_image_batch_infra.py(the route's family check now admits FLUX.3).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.pyand everytest_diffusion_flux3_*/ Anima test, plus the quality gate tests (test_image_batch_quality.py): 938 passed, 14 skipped.Not proven here