Skip to content
Merged
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
Trim comments in H3 image batched forward
[skip ci]
  • Loading branch information
danielhanchen committed Nov 27, 2026
commit b99c949aa5f4f7834de876180150b45fabfdb444
34 changes: 9 additions & 25 deletions studio/backend/core/inference/diffusion_minimax_h3_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1376,9 +1376,7 @@ def _h3_image_block_inputs(


def _per_row(fn: Callable, x: Any) -> Any:
"""``fn`` over each row of a batch as its own batch-1 call: the fp32 patch projection and output head of a batched
forward run at the batch-1 GEMM shape of each image's own forward, so the batch changes none of their
roundings (the sampler amplifies a 1e-7 head difference to a visible one in 6 steps)."""
"""``fn`` per row at batch 1: keeps batch-1 GEMM roundings (the sampler amplifies a 1e-7 head diff in 6 steps)."""
import torch

if int(x.shape[0]) == 1:
Expand Down Expand Up @@ -1758,7 +1756,6 @@ def lockstep_state_gb(


def _module_gb_off(module: Any, device: Any) -> float:
"""GB of ``module``'s parameters and buffers that are not on ``device`` (what bringing it in will take)."""
try:
import torch

Expand Down Expand Up @@ -2787,8 +2784,7 @@ def __call__(
max_sequence_length: int = H3_IMAGE_MAX_SEQUENCE_LENGTH,
row_images: Any = None,
) -> Any:
"""``row_images``: per prompt, its own reference image(s) (None = text-to-image), in place of ``image`` shared
by every prompt (a coalesced batch of edits); images with equal layouts still run one batched forward."""
"""``row_images``: per-prompt reference image(s) (None = text-to-image), replacing the shared ``image``."""
import torch

steps = H3_IMAGE_STEPS if num_inference_steps is None else num_inference_steps
Expand Down Expand Up @@ -2909,8 +2905,7 @@ def __call__(

@staticmethod
def _output_size(image: Any, vae_refs: list, height: Any, width: Any) -> tuple:
"""(height, width): no size, an edit takes the reference edit size of Picture 1 (as the API and UI);
text-to-image 2048x2048."""
"""No size: an edit takes Picture 1's reference edit size (as the API and UI); text-to-image 2048x2048."""
if not vae_refs:
default_w, default_h = H3_IMAGE_DEFAULT_SIZE, H3_IMAGE_DEFAULT_SIZE
elif source_resize_enabled():
Expand Down Expand Up @@ -2941,8 +2936,7 @@ def _render_together(
"""Render ``jobs`` in lockstep groups the plan has room for: ``(images done, their pixels)``, -1 done when
interrupted. Jobs are set up one at a time and join the group while the plan has room for every image's
state (one that does not fit is set up again for the next group); a group of one, or one that runs out of
memory, leaves the rest to separate renders. ``per_job``: each image's ``(vae_refs, vision_refs, height,
width)`` in place of the shared ones."""
memory, leaves the rest to separate renders. ``per_job`` overrides the shared refs and size per image."""
import torch

def setup(index: int) -> dict:
Expand Down Expand Up @@ -3302,8 +3296,7 @@ def _lockstep_refusal(self, images: int) -> Optional[str]:
return None

def _together_refusal(self, images: int) -> Optional[str]:
"""Why ``images`` images of one request cannot denoise together; None = they can. The stream tier shares its
block uploads (lockstep); a resident DiT runs same-layout images as one batched forward."""
"""Why ``images`` images cannot denoise together; None = they can."""
if images < 2 or self._placement() == PLACE_STREAM:
return self._lockstep_refusal(images)
if self._placement() == PLACE_SEQUENTIAL:
Expand All @@ -3325,9 +3318,7 @@ def _together_refusal(self, images: int) -> Optional[str]:
return None

def _sequential_refusal(self) -> Optional[str]:
"""Why images of one request on the sequential tier cannot denoise together; None = they can. Together, the
DiT comes onto the card once for every image instead of once per image; each image runs each block as its own
batch-1 call (lockstep), so its pixels are those of its own render."""
"""Sequential tier: why images cannot denoise together (one DiT upload for all); None = they can."""
if not lockstep_enabled():
return f"{LOCKSTEP_ENV}=0"
if not h3_image_forward_active(self.transformer):
Expand All @@ -3344,18 +3335,15 @@ def _compiled_blocks(self) -> bool:
return "h3_compiled" in (getattr(self, "_unsloth_h3_speed_levers", None) or ())

def _together_room(self, job: dict) -> Optional[float]:
"""GB the device leaves for more images beside ``job``: the stream plan's priced room, else (resident) the
free device memory less the stream reserve."""
if self._placement() == PLACE_STREAM:
return self._lockstep_room(job)
room = resident_room_gb(job["device"])
if room is not None and self._placement() == PLACE_SEQUENTIAL:
# set up with the DiT on the host: it takes its room when the group's denoise brings it in
# DiT is on the host now: its room is taken when the denoise brings it in
room = max(0.0, room - _module_gb_off(self.transformer, job["device"]))
return room

def _batch_cap(self, jobs: list, room: Optional[float]) -> int:
"""Rows per batched block call ``room`` leaves beside every image's lockstep state; 1 = lockstep."""
if room is None or len(jobs) < 2 or self._compiled_blocks():
return 1
if self._placement() == PLACE_SEQUENTIAL and not h3_batch.batched_forward_enabled():
Expand Down Expand Up @@ -3425,11 +3413,8 @@ def _render_lockstep(
width: int,
cap: int = 1,
) -> Optional[list]:
"""Denoise set-up ``jobs`` together: every step runs one transformer forward. Images of one packed layout run
each block as one batched call of up to ``cap`` rows (``diffusion_minimax_h3_image_batch``); the batches
(``cap`` 1: each image) run each block in turn (``lockstep_blocks``), so a streamed block is uploaded once per
step for all of them. Each image keeps its own noise, scheduler and conditioning; at ``cap`` 1 its pixels are
those of its own render. The callback runs once per step with the first image's latents. None = interrupted."""
"""Denoise ``jobs`` together, same-layout images batched up to ``cap`` rows per block call; a streamed block
uploads once per step. Callback gets the first image's latents. None = interrupted."""
transformer = self._enter("transformer")
t1 = time.perf_counter()
gate = None
Expand All @@ -3445,7 +3430,6 @@ def _render_lockstep(
for job in jobs:
job["t1"] = t1
self._denoise_setup(job, transformer)
# same-layout images run each block as one call over all their rows (cap 1: one call per image)
if cap > 1:
batches = h3_batch.batch_groups(jobs, cap)
statics = None
Expand Down
55 changes: 16 additions & 39 deletions studio/backend/core/inference/diffusion_minimax_h3_image_batch.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,15 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""MiniMax-H3-Image batched forward: images of one request (or coalesced requests) whose packed layouts match run
every block as ONE call over all their rows, instead of one batch-1 call per image (lockstep).

Two images share a layout when their packed sequences are the same shape and order: equal canvas, equal text token
count and tags (the prompt template plus the vision blocks of their references), equal reference latent grids and
the same step count. Their position ids, AdaLN indices, rotary tables and per-step timesteps and heads are then
equal, so a block call over ``(B, S, D)`` hidden states computes each row as its own forward does: nothing in a block
mixes rows (no mask, no shared scale). Rows keep their own noise, reference noise, refined text and scheduler. Images
whose layouts differ run as separate batches inside one lockstep forward (a streamed block is still uploaded once per
step for all of them). The fp32 patch projection and the output head run per row at the batch-1 GEMM shape (the
6-step sampler turns their 1e-7 batch-shape roundings into a visible change), so each batched image measured
bit-identical to its own render on CUDA.

Opt-in: ``UNSLOTH_H3_IMAGE_BATCHED=1``. Unset (or ``0``) keeps one batch-1 call per image (lockstep on the stream
tier, separate renders on a resident DiT). A block call takes at most ``UNSLOTH_H3_IMAGE_BATCH_TOKENS`` (4608) packed
rows: batching pays where one image leaves the GEMMs short of rows. Batch of 4 against the incumbent, int8: RTX PRO
6000 1024x1024 1.11x resident and 1.11x streamed, 2048x2048 resident 0.88x (one image per call under the budget);
A100-80 1024x1024 resident 1.00x."""
"""MiniMax-H3-Image batched forward: same-layout images run every block as ONE call over all their rows.

Same layout (canvas, text tokens and tags, reference grids, steps) means equal position ids, AdaLN indices, rotary
tables and timesteps, and no block op mixes rows, so each row computes as its own forward. The fp32 patch projection
and output head run per row at batch-1 GEMM shape (the 6-step sampler amplifies 1e-7 roundings), so batched images
are bit-identical to their own renders on CUDA.

Opt-in ``UNSLOTH_H3_IMAGE_BATCHED=1``; ``UNSLOTH_H3_IMAGE_BATCH_TOKENS`` (4608) caps packed rows per call.
Batch 4, int8: RTX PRO 6000 1024x1024 1.11x, 2048x2048 resident 0.88x; A100-80 1024x1024 resident 1.00x."""

from __future__ import annotations

Expand All @@ -29,7 +20,6 @@
BATCHED_ENV = "UNSLOTH_H3_IMAGE_BATCHED"
BATCH_TOKENS_ENV = "UNSLOTH_H3_IMAGE_BATCH_TOKENS"
BATCH_TOKENS = 4608
# The per-layout fields every row of one batch shares.
_SHARED_FIELDS = ("position_ids", "token_tags", "image_indices", "text_indices")


Expand All @@ -38,8 +28,7 @@ def batched_forward_enabled() -> bool:


def layout_key(job: dict) -> tuple:
"""What two set-up images must share to run one block call: canvas (latent grid), packed sequence length, text
rows, reference rows, steps. The tensors behind it are compared by ``same_layout``."""
"""What two set-up images must share to run one block call; tensors are compared by ``same_layout``."""
return (
int(job["lh"]),
int(job["lw"]),
Expand All @@ -57,7 +46,6 @@ def same_layout(a: dict, b: dict) -> bool:

if layout_key(a) != layout_key(b):
return False
# set up for the denoise: the same compute dtype and the same forward extras (head, refined text, output rows)
if a.get("dtype") != b.get("dtype") or sorted(a.get("extra") or {}) != sorted(
b.get("extra") or {}
):
Expand All @@ -78,7 +66,7 @@ def same_layout(a: dict, b: dict) -> bool:


def batch_groups(jobs: Sequence[dict], cap: int) -> list:
"""Job indices grouped by layout (first appearance order), each group cut into batches of at most ``cap``."""
"""Job indices grouped by layout (first-seen order), cut into batches of at most ``cap``."""
cap = max(1, int(cap))
groups: list = []
for index, job in enumerate(jobs):
Expand All @@ -95,7 +83,6 @@ def batch_groups(jobs: Sequence[dict], cap: int) -> list:


def merged_static(calls: Sequence[dict]) -> dict:
"""The per-render tensors of one batch, concatenated once: conditioning and refined text."""
import torch

out = {}
Expand All @@ -107,8 +94,6 @@ def merged_static(calls: Sequence[dict]) -> dict:


def merge_step_calls(calls: Sequence[dict], static: Optional[dict] = None) -> dict:
"""One forward's keyword arguments for a batch of same-layout images: their model input rows stacked on the batch
dimension, the shared layout / timestep / head of the first."""
import torch

merged = dict(calls[0])
Expand All @@ -120,7 +105,6 @@ def merge_step_calls(calls: Sequence[dict], static: Optional[dict] = None) -> di


def split_rows(output: Any, count: int) -> list:
"""Per image ``(1, rows, C)`` views of a batch's ``(B, rows, C)`` velocity."""
if int(output.shape[0]) != count:
raise ValueError(f"batched forward returned {int(output.shape[0])} rows for {count} images")
return [output[b : b + 1] for b in range(count)]
Expand All @@ -133,9 +117,7 @@ def batched_row_gb(
heads_dim: Optional[int] = None,
itemsize: int = 2,
) -> float:
"""Device memory one more row of a batched block call holds (GB): the block's own working set at that row's
sequence (modulated input, q / k / v / attention out, residual, the gated-SwiGLU intermediates), on top of the
row's lockstep state. Generous: every intermediate counted live at once."""
"""GB one more batched row holds beyond its lockstep state; generous (every intermediate live at once)."""
inner = int(heads_dim or hidden)
per = seq * itemsize * (hidden * 4 + inner * 4 + ffn * 3)
return per / 1e9
Expand All @@ -155,8 +137,7 @@ def batch_cap(
row_gb: float,
seq: int = 0,
) -> int:
"""Rows per block call that fit ``room`` beside ``images`` images' lockstep state and ``batch_tokens()`` packed
rows of ``seq`` each; 1 = one call per image."""
"""Rows per block call that fit ``room`` and ``batch_tokens()``; 1 = one call per image."""
if images < 2 or not batched_forward_enabled() or room is None:
return 1
tokens = images if seq <= 0 else max(1, batch_tokens() // int(seq))
Expand All @@ -177,8 +158,7 @@ def row_layout_key(
num_inference_steps: Optional[int] = None,
min_generation_area: Optional[int] = None,
) -> tuple:
"""For a request coalescer: two rows with equal keys share one batched block call (same canvas, same packed
text length, same reference layout, same steps); without the text encoder (the tokenizer only)."""
"""Coalescer key: equal keys share one batched block call (tokenizer only, no text encoder)."""
from . import diffusion_minimax_h3_image as h3

vae_refs, vision_refs = pipe.prepare_references(image)
Expand Down Expand Up @@ -216,8 +196,7 @@ def _flat(x: Any) -> Any:


def batched_modulate(rowmod: Any, x: Any, scale: Any, shift: Any, idx: Any) -> Any:
"""``rowmod.modulate`` over a ``(B, S, D)`` batch: the rows flattened to one ``(1, B*S, D)`` sequence with the AdaLN
index repeated per image, so the batch-1 kernel serves (each element is the same op on the same operands)."""
"""``rowmod.modulate`` over ``(B, S, D)`` flattened to ``(1, B*S, D)`` (AdaLN index repeated) for the batch-1 kernel."""
b = int(x.shape[0])
if b == 1 or x.dim() != 3:
return rowmod.modulate(x, scale, shift, idx)
Expand All @@ -241,8 +220,7 @@ def _batched_row_mod_block_forward(
rotary_emb: Any,
attention_mask: Any = None,
) -> Any:
"""The row-mod block forward (``video_minimax_h3_rowmod._row_mod_block_forward``) at any batch: batch 1 calls it
as is; a larger batch runs the same ops with the row ops over the flattened rows."""
"""``_row_mod_block_forward`` at any batch: batch 1 as is, else row ops over the flattened rows."""
from . import video_minimax_h3_rowmod as rowmod

if int(hidden_states.shape[0]) == 1:
Expand All @@ -269,7 +247,6 @@ def _batched_row_mod_block_forward(


def install_batched_row_mod(transformer: Any) -> int:
"""Over every block the row-mod lever swapped: its forward again at batch 1, the flattened row ops above it."""
from . import video_minimax_h3_rowmod as rowmod

n = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,6 @@ def _install(
from .video_minimax_h3_rowmod import install as install_row_mod
if install_row_mod(transformer, logger = logger):
levers.append("h3_row_mod")
# a batched forward (several same-layout images) runs the row ops over its flattened rows
from .diffusion_minimax_h3_image_batch import install_batched_row_mod
install_batched_row_mod(transformer)
# the streamed GEMM keeps the swapped Linears and their parameters (the pinned streamer copies into them), so the
Expand Down
2 changes: 0 additions & 2 deletions studio/backend/tests/test_diffusion_h3_image_lockstep.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
@pytest.fixture(autouse = True)
def _picture_one_at_its_own_size(monkeypatch):
monkeypatch.setenv("UNSLOTH_H3_IMAGE_SOURCE_RESIZE", "0")
# one batch-1 block call per image (the batched forward has its own tests: test_h3_image_batched_forward.py)
monkeypatch.setenv("UNSLOTH_H3_IMAGE_BATCHED", "0")


Expand Down Expand Up @@ -578,7 +577,6 @@ def test_the_sequential_tier_brings_the_dit_in_once_for_every_image(
together = _render(pipe, [21, 22, 23])
assert entries.count("transformer") == 1
assert pipe._unsloth_h3_last_stats["lockstep"] == 3
# each image runs each block as its own batch-1 call: its own render, bit for bit
assert all(a.dtype == b.dtype and torch.equal(a, b) for a, b in zip(alone, together))
assert not torch.equal(together[0], together[1])
assert pipe._sequential_refusal() is None
Expand Down
9 changes: 2 additions & 7 deletions studio/backend/tests/test_h3_image_batched_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
def _env(monkeypatch):
monkeypatch.setenv("UNSLOTH_H3_IMAGE_SOURCE_RESIZE", "0")
monkeypatch.setenv("UNSLOTH_H3_IMAGE_BATCHED", "1")
# the edit rows here pack ~2k rows each: no token budget, every same-layout row in one call
# no token budget: every same-layout row in one call
monkeypatch.setenv("UNSLOTH_H3_IMAGE_BATCH_TOKENS", "1000000")
monkeypatch.delenv("UNSLOTH_H3_IMAGE_LOCKSTEP", raising = False)

Expand Down Expand Up @@ -113,12 +113,10 @@ def test_one_block_call_per_step_for_every_row_of_one_layout(h3i, pipe, resident
alone = [_render(pipe, "a cat", [s])[0] for s in seeds]
resident.clear()
together = _render(pipe, "a cat", seeds)
# G3: one call per block per step, each over the 4 rows
assert len(resident) == steps * blocks
assert {b for _k, b in resident} == {4}
assert pipe._unsloth_h3_last_stats["batched"] == [4]
assert len(together) == 4 and not torch.equal(together[0], together[1])
# the patch projection and head run per row, the blocks see no other row: each image is its own render
for a, b in zip(alone, together):
assert a.shape == b.shape and torch.equal(a, b)

Expand Down Expand Up @@ -240,7 +238,6 @@ def test_per_row_references_batch_and_a_neighbours_reference_never_moves_the_tar
swapped = _render(pipe, ["a cat", "a cat", "a cat"], [1, 2, 3], row_images = [a, c, a])
assert torch.equal(first[0], swapped[0]) and torch.equal(first[2], swapped[2])
assert not torch.equal(first[1], swapped[1])
# each row equals its own edit
solo = _render(pipe, "a cat", [2], image = b)[0]
torch.testing.assert_close(first[1], solo, rtol = 1e-5, atol = 1e-5)
# a text-to-image row beside edits: its own batch
Expand Down Expand Up @@ -305,15 +302,14 @@ def test_the_batch_cap_is_what_the_room_leaves(h3i, pipe, resident, monkeypatch)
monkeypatch.setattr(h3i.h3_batch, "batched_row_gb", lambda *a, **k: 1.0)
out = _render(pipe, "a cat", [1, 2, 3])
assert len(out) == 3
# room for the lockstep state, not for a batched row: one call per image (lockstep on the resident DiT)
# room for lockstep state only: one call per image
assert pipe._unsloth_h3_last_stats["batched"] == [1, 1, 1]
assert len(resident) == 3 * steps * blocks
monkeypatch.setattr(h3i.h3_batch, "batched_row_gb", lambda *a, **k: 0.2)
resident.clear()
_render(pipe, "a cat", [1, 2, 3])
assert pipe._unsloth_h3_last_stats["batched"] == [3]
assert len(resident) == steps * blocks
# no room at all: one after another
monkeypatch.setattr(h3i, "resident_room_gb", lambda device: 0.0)
_render(pipe, "a cat", [1, 2, 3])
assert "batched" not in pipe._unsloth_h3_last_stats
Expand Down Expand Up @@ -374,7 +370,6 @@ def modulate(self, x, scale, shift, idx):
rec = Recorder()
batch.batched_modulate(rec, x, scale, shift, idx)
batch.batched_modulate(rec, x[:1], scale, shift, idx)
# the kernel sees one (1, B*S, D) sequence; batch 1 as before
assert rec.shapes == [((1, 21, 16), 21), ((1, 7, 16), 7)]


Expand Down