Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Studio: trim comments in batched FLUX.3 and Anima rows
[skip ci]
  • Loading branch information
danielhanchen committed Nov 27, 2026
commit b5d9014baba3ddb5f9667b95ea6900837cb6cc0c
22 changes: 4 additions & 18 deletions studio/backend/core/inference/diffusion_anima.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,26 +171,23 @@ class _AnimaInterrupted(Exception):


class _AnimaRowsMismatch(Exception):
"""A batched modular call's text steps did not match the rows it was built for: run those rows one by one."""
"""Batched text steps did not match the rows: run them one by one."""


# The per-row text record of the batched modular call in flight on this thread (None outside one).
_ROW_TEXT = contextvars.ContextVar("unsloth_anima_row_text", default = None)

BATCH_ROWS_ENV = "UNSLOTH_DIFFUSION_ANIMA_BATCH"
# The text step's default ``max_sequence_length`` (the length its tokenizers truncate at).
# The text step's default max_sequence_length.
_T5_MAX_LENGTH = 512
_ROW_BRIDGE = "_unsloth_row_bridge"


def batch_rows_disabled() -> bool:
"""``UNSLOTH_DIFFUSION_ANIMA_BATCH=0``: every image of a list runs as its own modular call again."""
import os
return (os.environ.get(BATCH_ROWS_ENV) or "").strip().lower() in ("0", "off", "false", "no")


def _pad_rows(tensors: list) -> Any:
"""Right-pad ``(1, L_i, ...)`` row tensors with zeros to the longest and stack them."""
import torch
import torch.nn.functional as F

Expand All @@ -206,9 +203,7 @@ def _pad_rows(tensors: list) -> Any:


def _bridge_row_steps(mp: Any) -> bool:
"""Route the text step and the text conditioning step through per-row bridges, inert outside a batched call:
inside one (``_ROW_TEXT`` set) each row is encoded and conditioned alone, exactly as its own call would, and
the rows' conditioned embeddings are stacked for the denoiser."""
"""Per-row text bridges (inert unless _ROW_TEXT is set): each row is encoded and conditioned alone, then stacked."""
text_steps, cond_steps = [], []
seen: set = set()

Expand Down Expand Up @@ -323,7 +318,6 @@ def bridged(components: Any, **kwargs: Any) -> Any:
row_kwargs["t5_attention_mask"] = t5_mask[i : i + 1, :n_t5]
outs.append(original(components, **row_kwargs))
if any(o.shape[1:] != outs[0].shape[1:] for o in outs):
# A row past the conditioner's minimum length keeps its own length.
raise _AnimaRowsMismatch("rows condition to different text lengths")
return torch.cat(outs, dim = 0)

Expand All @@ -332,7 +326,6 @@ def bridged(components: Any, **kwargs: Any) -> Any:


def _per_call_scaled(module: Any) -> Optional[str]:
"""As diffusion_flux3._per_call_scaled (the same cached record)."""
from .diffusion_flux3 import _per_call_scaled as scaled
return scaled(module)

Expand Down Expand Up @@ -449,8 +442,6 @@ def __call__(
raise ValueError("Anima takes a text prompt (str) per image.")
generators = list(generator) if isinstance(generator, (list, tuple)) else None
negatives = list(negative_prompt) if isinstance(negative_prompt, (list, tuple)) else None
# One entry per image, each with its own generator and negative prompt; _rows_batch then runs them as ONE
# batched modular call (each row's text encoded alone) where it can.
if len(prompts) > 1 or generators is not None:
count = max(len(prompts), len(generators or ()))
if len(prompts) == 1:
Expand Down Expand Up @@ -506,8 +497,6 @@ def run(
return out if isinstance(out, list) else [out]

def run_rows(group: list, first: bool) -> list:
"""The rows of ``group`` in ONE modular call: each row's text is encoded and conditioned alone (its own
call's embeddings), its noise drawn from its own generator, and the denoiser runs once per step for all."""
kwargs = call_kwargs(group[0])
kwargs["prompt"] = [calls[i][0] for i in group]
kwargs["generator"] = [calls[i][1] for i in group]
Expand Down Expand Up @@ -561,10 +550,7 @@ def _row_groups(
generators: Optional[list],
negative: Callable[[int], Any],
) -> list:
"""Call indexes that share one batched modular call, in first-row order. Rows batch when each has its own
generator, there are no caller latents, the row bridges are installed and no denoiser layer takes its
activation scale from the whole call; they group by the conditioned length of their prompt and negative prompt
(the conditioner pads to its minimum, so only a row past it stands apart). Otherwise every call renders alone."""
"""Call indexes per batched call, grouped by conditioned (prompt, negative) length; else one call each."""
alone = [[i] for i in range(len(calls))]
if len(calls) < 2 or latents is not None or generators is None or batch_rows_disabled():
return alone
Expand Down
4 changes: 1 addition & 3 deletions studio/backend/core/inference/diffusion_batch_quality.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@
# (family name, device class, path) -> verdict. Only PASS verdicts measured on a release build belong here.
SHIPPED: dict[tuple[str, str, str], dict] = {}

# FLUX.3 klein on an RTX PRO 6000 Blackwell (Colab G4), streamed Low VRAM, int8 Auto, 16 steps, batch 2: 8 held-out
# prompts x 3 seeds, batched vs solo on the same path against an eager bf16 reference. Both paths scored alike (the
# solo renders were byte-identical across paths).
# FLUX.3 klein, RTX PRO 6000 (G4), Low VRAM int8, 16 steps, batch 2, 8 prompts x 3 seeds vs eager bf16.
_KLEIN_G4 = {
"verdict": "PASS",
"n": 24,
Expand Down
3 changes: 1 addition & 2 deletions studio/backend/core/inference/diffusion_families.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,7 @@ class DiffusionFamily:
fp16_guard: Optional[str] = None
# false only for a family whose denoiser block does not compile cleanly with regional torch.compile
supports_torch_compile: bool = True
# True when the family's list call runs several images in ONE denoiser forward with each row its own computation
# (proved by the neighbour-invariance gates), False when it never does; None = not stated (the default rules).
# True: list call batches rows in one forward (neighbour-invariance proven); False: never; None: default rules.
batched_forward: Optional[bool] = None
# False keeps cudnn.benchmark off (as VideoFamily.cudnn_benchmark): its per-process conv pick changes pixels.
cudnn_benchmark: bool = True
Expand Down
47 changes: 12 additions & 35 deletions studio/backend/core/inference/diffusion_flux3.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,14 @@ def _text_step(mp: Any) -> tuple[Any, Any]:


class _Flux3RowsMismatch(Exception):
"""A batched modular call's text step did not match the rows it was built for: run those rows one by one."""
"""Batched text step did not match the rows: run them one by one."""


# The rows of the batched modular call in flight on this thread: the text step returns their stacked embeddings.
_ROW_TEXT = contextvars.ContextVar("unsloth_flux3_row_text", default = None)


class _RowText:
"""Per-row prompts of one batched modular call: the step's first text call takes ``positive``, its second (the
base model's unconditional branch) ``negative``. ``encoded`` holds this call's positive embeddings, encoded
beforehand with ``args`` by text (each row alone, exactly as its own call would)."""
"""Rows of one batched call: text call 1 takes ``positive``, call 2 (unconditional branch) ``negative``."""

__slots__ = ("positive", "negative", "encoded", "args", "calls", "references", "processed")

Expand All @@ -109,13 +106,12 @@ def __init__(
self.encoded = encoded
self.args = args
self.calls = 0
# per row, its own resized reference images (None: the call's references are shared by every row)
# None: references shared by every row
self.references = references
self.processed = 0


def _row_text_embeds(owner: Any, rows: _RowText, a: dict) -> Any:
"""The stacked ``(rows, window, dim)`` embeddings for the text step call ``a``; every row's window must match."""
import torch

which = rows.calls
Expand Down Expand Up @@ -153,7 +149,6 @@ def _row_text_embeds(owner: Any, rows: _RowText, a: dict) -> Any:


def _text_defaults(step: Any, pad_multiple: Optional[int], hidden_states_layers: Any) -> tuple:
"""``(pad_multiple, layers)`` the text step encodes with when the call names neither."""
if pad_multiple is None:
pad_multiple = step.pad_multiple
if hidden_states_layers is None:
Expand All @@ -168,8 +163,7 @@ def _text_defaults(step: Any, pad_multiple: Optional[int], hidden_states_layers:

def _bridge_text_step(pipe: Any, mp: Any) -> bool:
"""Route the text step's per-prompt encode through ``pipe.encode_prompt`` (prompt cache, dead-tail probe).
Only for this pipe's own encoder and tokenizer; a foreign encoder runs the step's helper unchanged. Inside a
batched modular call (``_ROW_TEXT`` set) it returns every row's embeddings, stacked."""
Only for this pipe's own encoder and tokenizer; a foreign encoder runs the step's helper unchanged."""
import inspect
import weakref

Expand Down Expand Up @@ -212,9 +206,7 @@ def bridged(*args: Any, **kwargs: Any) -> Any:


def _bridge_reference_preprocess(mp: Any) -> bool:
"""Inside a batched modular call with per-row references, the image step's per-reference ``preprocess`` returns
that reference of EVERY row, stacked (each row preprocessed alone, so the VAE encodes each row's own pixels).
Outside one it is the processor's own method."""
"""In a batched call with per-row references, ``preprocess`` returns every row's reference, each alone, stacked."""
import weakref

processor = getattr(mp, "image_processor", None)
Expand Down Expand Up @@ -637,8 +629,7 @@ def __call__(
guidance_stop: Optional[float] = None,
row_images: Optional[list] = None,
):
"""``row_images``: one reference image (or list of them) per image of the list, instead of ``image`` (the
references every image shares)."""
"""``row_images``: per-image references, instead of shared ``image``."""
self._interrupt = False
mp = self.modular_pipeline()
if row_images is not None and image is not None:
Expand All @@ -654,7 +645,6 @@ def __call__(
raise ValueError("FLUX.3 takes a text prompt (str) per image.")
generators = generator if isinstance(generator, (list, tuple)) else None
negatives = list(negative_prompt) if isinstance(negative_prompt, (list, tuple)) else None
# One prompt per call (text encoder sizes per prompt); _row_groups batches calls sharing a text window.
if len(prompts) > 1 or generators is not None:
count = max(len(prompts), len(generators or ()))
if len(prompts) == 1:
Expand Down Expand Up @@ -734,7 +724,6 @@ def run_modular(
first: bool,
rows: Optional[_RowText] = None,
) -> Any:
# The base model's text and reference streams run once per call, not once per step and branch.
transformer = getattr(self, "transformer", None)
if not self.is_distilled:
cond_blocks.begin_render(transformer, guided = lambda: _guider_runs_both(mp))
Expand All @@ -754,8 +743,6 @@ def run_modular(
cond_blocks.end_render(transformer)

def run_rows(group: list, first: bool) -> list:
"""One modular call over every row of ``group`` (same text window): each row keeps its own prompt
embeddings, noise and negative prompt, so it is the computation of its own call at a larger batch."""
kwargs = call_kwargs(group[0])
kwargs["num_images_per_prompt"] = 1
row_generators = [calls[i][1] for i in group]
Expand Down Expand Up @@ -843,12 +830,8 @@ def _row_groups(
seeded_noise: bool,
references: Optional[list] = None,
) -> tuple:
"""``(groups, encoded, text_args)``: the call indexes that share one batched modular call, in first-row
order. A group shares its text window (the transformer attends to the padding, so a longer window is not
the shorter row's computation), its negative prompt and its reference sizes; each row's embeddings
are encoded alone, once, here. Every call renders alone when rows cannot be told apart exactly: caller latents, a row without a
readable seed, a denoiser whose activation scale comes from the whole call, no row bridge, or per-row
references (unless ``ROW_REFS_BATCH_ENV``)."""
"""``(groups, encoded, text_args)``. Groups share text window (the transformer attends to padding),
negative and reference sizes; anything that could couple rows renders every call alone."""
alone = ([[i] for i in range(len(calls))], {}, None)
if len(calls) < 2 or latents is not None or batch_rows_disabled():
return alone
Expand All @@ -872,7 +855,7 @@ def _row_groups(
encoded: dict = {}
texts = [prompt for prompt, _, _ in calls]
if negative is not None and getattr(mp, "requires_unconditional_embeds", False):
# the unconditional branch's prompts too, so a later group never brings the encoder back
# negatives too, so a later group never reloads the encoder
texts += [negative(i) for i in range(len(calls))]
for prompt in texts:
if prompt not in encoded:
Expand All @@ -889,7 +872,6 @@ def _row_groups(
keyed: dict = {}
for i, (prompt, _, _) in enumerate(calls):
embeds = encoded[prompt]
# per-row references batch at one canvas: the same count and sizes on every row of the call
key = (
tuple(embeds.shape[1:]),
None if negative is None else negative(i),
Expand Down Expand Up @@ -973,9 +955,7 @@ def flux3_row_key(
prompt: str,
max_sequence_length: int = 8192,
) -> Optional[tuple]:
"""What a row must share with batch neighbours to join their modular call: its text window (the prompt's chat
templated token count rounded up to the step's pad multiple, as the text step sizes it). None when it cannot be
measured; rows of other windows still render correctly, in their own call."""
"""A row's batch key: its padded chat-templated text window, or None if unmeasurable."""
import math
try:
step, _helper = _text_step(pipe.modular_pipeline())
Expand All @@ -997,13 +977,11 @@ def flux3_row_key(


def batch_rows_disabled() -> bool:
"""``UNSLOTH_DIFFUSION_FLUX3_BATCH=0``: every image of a list runs as its own modular call again."""
import os
return (os.environ.get(BATCH_ROWS_ENV) or "").strip().lower() in ("0", "off", "false", "no")


# Rows with their own references (``row_images``) render one by one: a row's bytes are not yet shown independent of
# a neighbour's reference on GPU. ``=1`` batches rows whose references share one canvas (for measuring that).
# Per-row references render one by one until GPU-proven neighbour-independent; ``=1`` batches them (to measure).
ROW_REFS_BATCH_ENV = "UNSLOTH_DIFFUSION_FLUX3_ROW_REFS_BATCH"


Expand All @@ -1013,8 +991,7 @@ def row_refs_batch_enabled() -> bool:


def _per_call_scaled(module: Any) -> Optional[str]:
"""The denoiser's first layer whose activation scale comes from the whole call (cached on the module, the
same record the request batcher reads), or None."""
"""The denoiser's first layer whose activation scale comes from the whole call (cached), or None."""
if module is None or not hasattr(module, "named_modules"):
return None
cached = module.__dict__.get("_unsloth_per_call_scaled")
Expand Down
5 changes: 1 addition & 4 deletions studio/backend/tests/test_diffusion_anima_batch_rows.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Anima runs the images of a list as ONE batched modular call: each row's text is encoded and conditioned alone
(the conditioner pads every row to its minimum length), its noise comes from its own generator, and the denoiser runs
one forward per step and CFG branch over every row. Real diffusers modular blocks over a tiny random Anima, CPU fp32."""
"""Anima batched-row modular calls over a tiny random Anima, CPU fp32."""

import numpy as np
import pytest
Expand Down Expand Up @@ -135,7 +133,6 @@ def test_a_neighbour_never_changes_a_row(pipe, target):
assert _maxabs(batched[target], again[target]) == 0.0
neighbour = (target + 1) % 4
prompts, seeds = list(PROMPTS), list(SEEDS)
# A different prompt of another text length, a different seed and negative, at the same batch shape.
prompts[neighbour] = "a neon robot dancing"
seeds[neighbour] = 99
negatives = ["blurry"] * 4
Expand Down
2 changes: 0 additions & 2 deletions studio/backend/tests/test_diffusion_flux3.py
Original file line number Diff line number Diff line change
Expand Up @@ -860,14 +860,12 @@ def test_split_calls_pair_each_prompt_with_its_own_negative():


def test_flux3_images_share_one_generation_chunk():
# The facade batches the rows of one text window in one modular call (diffusion_flux3 _row_groups).
from core.inference.diffusion import _generation_chunks

jobs = [("a", 1), ("a", 2), ("b", 3)]
for name in (FLUX3_KLEIN_FAMILY_NAME, FLUX3_KLEIN_BASE_FAMILY_NAME):
assert _family(name).batched_forward is True
assert _generation_chunks(_family(name), jobs, 1) == [jobs]
# A FLUX.3 record that does not say it batches keeps one chunk per image.
unstated = SimpleNamespace(name = FLUX3_KLEIN_FAMILY_NAME)
assert _generation_chunks(unstated, jobs, 1) == [[j] for j in jobs]
# Other families keep one forward for the whole list.
Expand Down
9 changes: 1 addition & 8 deletions studio/backend/tests/test_diffusion_flux3_batch_rows.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""FLUX.3 runs the images of a list that share a text window as ONE batched modular call: one denoiser forward
per step over every row, each row its own embeddings, noise and negative prompt. Real diffusers modular blocks over a
tiny random FLUX.3 (Qwen3-VL encoder, Flux2 VAE, Flux3 DiT), CPU fp32."""
"""FLUX.3 batched-row modular calls over a tiny random FLUX.3, CPU fp32."""

import numpy as np
import pytest
Expand Down Expand Up @@ -42,7 +40,6 @@ def _tiny_pipe(distilled: bool):
pytest.skip(f"{REPO} not in the Hub cache: {exc}")
torch.manual_seed(0)
config = transformers.Qwen3VLConfig.from_pretrained(path)
# The text step stacks hidden states 4, 8, ..., 32.
config.text_config.num_hidden_layers = 32
text_encoder = transformers.Qwen3VLForConditionalGeneration(config).eval()
processor = transformers.AutoProcessor.from_pretrained(path)
Expand Down Expand Up @@ -183,7 +180,6 @@ def test_the_kill_switch_and_unseeded_rows_render_one_by_one(distilled, monkeypa
assert rows == [1] * STEPS * 3
monkeypatch.delenv(f3.BATCH_ROWS_ENV)
distilled._test_rows.clear()
# Caller latents are one tensor for the call: no per-row noise to keep apart.
distilled(
prompt = PROMPTS[:2],
generator = [torch.Generator().manual_seed(s) for s in SEEDS[:2]],
Expand Down Expand Up @@ -236,7 +232,6 @@ def test_edit_rows_with_different_references_never_share_a_forward(distilled):
assert rows == [1] * STEPS * 3
solo, _ = _render(distilled, [PROMPTS[1]], [SEEDS[1]], image = refs[1])
assert _maxabs(images[1], solo[0]) < 1e-4
# Two references of one canvas but different pixels: still one forward per row.
_, rows = _render(distilled, PROMPTS[:2], SEEDS[:2], row_images = refs[:2])
assert rows == [1] * STEPS * 2

Expand Down Expand Up @@ -278,7 +273,6 @@ def test_per_row_references_at_one_canvas_batch(distilled, monkeypatch):
for i in range(3):
solo, _ = _render(distilled, [PROMPTS[i]], [SEEDS[i]], image = refs[i])
assert _maxabs(images[i], solo[0]) < 1e-4
# A neighbour's reference never reaches a row.
swapped = list(refs)
swapped[1] = _ref((250, 250, 0))
again, rows = _render(distilled, PROMPTS, SEEDS, row_images = swapped)
Expand All @@ -301,7 +295,6 @@ def test_per_row_references_of_other_sizes_render_apart(distilled, monkeypatch):


def test_klein_ships_a_g2c_pass_for_g4_only():
# Measured on an RTX PRO 6000 (Colab G4): a race win there may serve; any other card still needs its own verdict.
from types import SimpleNamespace

from core.inference import diffusion_batch_quality as quality
Expand Down
3 changes: 1 addition & 2 deletions studio/backend/tests/test_image_batch_infra.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,7 @@ async def run():
assert all(r.status_code == 200 for r in responses)
assert _alone(backend) == ["a fox", "a cat"]
assert _batched_calls(backend) == []
# The FLUX.3 record says its call fuses the rows, so the route's family check admits it; this load's family
# (no ``batched_forward``) is refused by the engine plan instead.
# The route admits FLUX.3; this load's family (no batched_forward) is refused by the engine plan.
from core.inference.diffusion_families import detect_family

assert adapters.batched_forward(detect_family("", name))
Expand Down