Skip to content

Batched calls are not sample-independent in seven places (Kandinsky 2.1/3/5, LongCat-Audio, Cosmos3 audio) #15465

Backlog

Description

@nyxbyb

Describe the bug

Several pipelines give a different result for a prompt (or audio clip, or video) depending on what else is in the same batch. Calling a pipeline with ["a", "b"] should give the same output for "a" as calling it with ["a"] (same latents and generator), up to float rounding. I found seven places where that does not hold. Each item below is self-contained, has a short script, and names the line I believe is responsible.

1. KandinskyCombinedPipeline (and the Img2Img/Inpaint variants) pairs images with the wrong prompt when num_images_per_prompt > 1
The prior expands with repeat_interleave, so image_embeds is ordered [A, A, B, B], but the combined pipeline expands the text with list multiplication, giving [A, B, A, B] (code; same pattern at L537 and L777). With two prompts and two images each, two of the four images get prompt A's image embedding with prompt B's text.

2. LongCatAudioDiTTransformer: text_conv runs over the padded text sequence
text_conv_layer (4 ConvNeXt blocks) is applied to the full padded sequence and the padding is masked only afterwards (code). After the first block the padding positions are no longer zero, so the convolution mixes them into valid tokens. Since encode_prompt uses padding="longest", a short prompt changes when a longer prompt is in the batch. text_conv=True is the default.

3. Cosmos3AVAEAudioTokenizer.encode: normalize_volume uses the peak over the whole batch
hidden_states / (hidden_states.abs().max() + 1e-5) (code) reduces over all dims, so a quiet clip encoded together with a loud one is scaled down. A per-sample peak (amax(dim=(1, 2), keepdim=True)) would make each clip independent.

4. Kandinsky3: attention pooling query includes the padding
process_embeds trims the context to the longest prompt in the batch (code), and Kandinsky3AttentionPooling uses context.mean(dim=1) as the query (code). The mean divides by the padded length, so the pooled condition of a short prompt depends on the longest prompt in the batch.

5. Kandinsky 5 _encode_prompt_qwen: a short prompt is cut when another prompt is too long
When any prompt exceeds max_sequence_length, the loop computes removed_text for every row of the padding="longest" batch (code). For short rows the decoded slice is padding plus template tokens, so their text is cut by len(removed_text) characters. In the script below the short prompt "a red square" disappears entirely. Same code in the T2V/I2V/I2I pipelines.

6. Kandinsky5Transformer3DModel has no text mask
The pipelines pad Qwen embeddings to the longest prompt and pass text_rope_pos for the max length (code), but the transformer has no mask/length input, so text self-attention and the visual cross-attention attend to the padding positions. prompt_cu_seqlens is computed but not used to mask.

7. Kandinsky 5 I2V adaptive_mean_std_normalization: reference statistics over the whole batch
source statistics are per sample, but reference.mean() / reference.std() reduce over the batch too (code).

Related but different: #13639 / #14168 (expansion of precomputed embeddings in Kandinsky 5) and #13597 (decoder image_embeds expansion without CFG). I did not find these seven reported.

Reproduction

All scripts run on CPU in a few seconds with tiny random weights. Where the default init zeroes the output layers, the script fills those zero parameters with random values, otherwise the output is identically zero and nothing can be compared.

1. Kandinsky combined pipeline
import torch
from diffusers import KandinskyCombinedPipeline

# Stub the two sub-pipelines to see what the combined pipeline hands to the decoder.
class Prior:
    def __call__(self, prompt, num_images_per_prompt=1, **kw):
        # KandinskyPriorPipeline expands with repeat_interleave (pipeline_kandinsky_prior.py), i.e. [A, A, B, B]
        ids = torch.arange(len(prompt)).repeat_interleave(num_images_per_prompt).float()
        return ids[:, None], -ids[:, None]

class Decoder:
    def __call__(self, prompt, image_embeds, **kw):
        for p, e in zip(prompt, image_embeds[:, 0].tolist()):
            print(f"decoder text prompt = {p!r:6}  image_embeds from prompt #{int(e)}")
        return None

pipe = object.__new__(KandinskyCombinedPipeline)
pipe.__dict__.update(prior_pipe=Prior(), decoder_pipe=Decoder(), maybe_free_model_hooks=lambda: None)
KandinskyCombinedPipeline.__call__(pipe, prompt=["cat", "dog"], num_images_per_prompt=2)

Output:

decoder text prompt = 'cat'   image_embeds from prompt #0
decoder text prompt = 'dog'   image_embeds from prompt #0
decoder text prompt = 'cat'   image_embeds from prompt #1
decoder text prompt = 'dog'   image_embeds from prompt #1
2. LongCat text_conv
import torch
from diffusers import LongCatAudioDiTTransformer

torch.manual_seed(0)
model = LongCatAudioDiTTransformer(dit_dim=64, dit_depth=2, dit_heads=4, dit_text_dim=32, latent_dim=8,
                                   text_conv=True).eval()
# the default init zeroes the output projections; give them random values so the output is not identically 0
with torch.no_grad():
    for p in model.parameters():
        if p.abs().max() == 0:
            p.normal_(0, 0.1)

T, L_short, L_long = 16, 4, 10
x = torch.randn(1, T, 8)
text_short = torch.randn(1, L_short, 32)
t = torch.ones(1)
mask_x = torch.ones(1, T, dtype=torch.bool)

with torch.no_grad():
    # prompt alone: no padding (what `padding="longest"` gives for a single prompt)
    alone = model(x, text_short, torch.ones(1, L_short, dtype=torch.bool), t, attention_mask=mask_x).sample
    # same prompt padded to the length of a longer prompt in the same batch, with its mask
    padded = torch.cat([text_short, torch.zeros(1, L_long - L_short, 32)], dim=1)
    pmask = torch.zeros(1, L_long, dtype=torch.bool); pmask[:, :L_short] = True
    in_batch = model(x, padded, pmask, t, attention_mask=mask_x).sample

print("max |alone - padded|, text_conv=True :", (alone - in_batch).abs().max().item())

model.text_conv = False
with torch.no_grad():
    a = model(x, text_short, torch.ones(1, L_short, dtype=torch.bool), t, attention_mask=mask_x).sample
    b = model(x, padded, pmask, t, attention_mask=mask_x).sample
print("max |alone - padded|, text_conv=False:", (a - b).abs().max().item())

Output:

max |alone - padded|, text_conv=True : 0.17378151416778564
max |alone - padded|, text_conv=False: 3.5762786865234375e-07
3. Cosmos3 audio tokenizer
import torch
from diffusers.models.autoencoders.autoencoder_cosmos3_audio import Cosmos3AVAEAudioTokenizer

torch.manual_seed(0)
model = Cosmos3AVAEAudioTokenizer(
    sampling_rate=16, hop_size=4, input_channels=1, stereo=True, normalize_volume=True,
    enc_dim=4, enc_num_blocks=1, enc_n_fft=8, enc_hop_length=2, enc_latent_dim=8,
    enc_c_mults=(1,), enc_strides=(2,), vocoder_input_dim=4, dec_dim=4,
    dec_c_mults=(1, 2), dec_strides=(2, 2), dec_out_channels=2,
).eval()

quiet = 0.1 * torch.randn(1, 2, 16)
loud = 1.0 * torch.randn(1, 2, 16)

with torch.no_grad():
    alone = model.encode(quiet).latent_dist.mode()
    batched = model.encode(torch.cat([quiet, loud])).latent_dist.mode()[:1]

print("max |encode(quiet) - encode([quiet, loud])[0]| =", (alone - batched).abs().max().item())

Output:

max |encode(quiet) - encode([quiet, loud])[0]| = 0.3917360007762909
4. Kandinsky3 attention pooling
import torch
from diffusers.models.unets.unet_kandinsky3 import Kandinsky3AttentionPooling

def unet_mask(m):  # what Kandinsky3UNet.forward passes down (unet_kandinsky3.py, forward)
    return ((1 - m) * -10000.0).unsqueeze(1)

torch.manual_seed(0)
pool = Kandinsky3AttentionPooling(num_channels=8, context_dim=16, head_dim=8).eval()
x = torch.randn(1, 8)
ctx = torch.randn(1, 5, 16)            # a 5-token prompt; Kandinsky3Pipeline.process_embeds zeroes padding
alone = pool(x, ctx, unet_mask(torch.ones(1, 5)))

# the same prompt in a batch whose longest prompt has 12 tokens
ctx_p = torch.cat([ctx, torch.zeros(1, 7, 16)], dim=1)
mask_p = torch.cat([torch.ones(1, 5), torch.zeros(1, 7)], dim=1)
in_batch = pool(x, ctx_p, unet_mask(mask_p))
print("max |alone - in_batch| =", (alone - in_batch).abs().max().item())
print("query = context.mean(dim=1): alone", ctx.mean(1).norm().item(), " in batch", ctx_p.mean(1).norm().item())

Output:

max |alone - in_batch| = 0.04447054862976074
query = context.mean(dim=1): alone 1.7959904670715332  in batch 0.7483293414115906
5 and 6. Kandinsky 5 prompt cut and missing text mask
import torch
from types import SimpleNamespace
from transformers import AutoProcessor
from diffusers import Kandinsky5T2IPipeline, Kandinsky5Transformer3DModel

# (a) _encode_prompt_qwen: a short prompt is cut when another prompt in the batch exceeds max_sequence_length
seen = []
class RecordingEncoder:
    dtype = torch.float32
    def __call__(self, input_ids, **kw):
        seen.append(input_ids)
        return {"hidden_states": [torch.zeros(*input_ids.shape, 4)]}

proc = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
pipe = SimpleNamespace(tokenizer=proc, text_encoder=RecordingEncoder())
pipe.prompt_template = (  # as set in Kandinsky5T2IPipeline.__init__
    "<|im_start|>system\nYou are a prompt engineer. Describe the image by detailing the color, shape, size, "
    "texture, quantity, text, spatial relationships of the objects and background:<|im_end|>\n"
    "<|im_start|>user\n{}<|im_end|>")
pipe.prompt_template_encode_start_idx = 40
enc = lambda prompts: Kandinsky5T2IPipeline._encode_prompt_qwen(pipe, prompts, device="cpu", max_sequence_length=8)

short, long = "a red square", "a big blue circle next to a small green triangle on a white table"
enc([short]); alone = proc.tokenizer.decode(seen[-1][0], skip_special_tokens=True)
enc([short, long]); batched = proc.tokenizer.decode(seen[-1][0], skip_special_tokens=True)
print("(a) short prompt text seen by the encoder")
print("    alone  :", repr(alone[-40:]))
print("    batched:", repr(batched[-40:]))

# (b) the transformer has no text mask: padding appended to a prompt changes the image prediction
torch.manual_seed(0)
model = Kandinsky5Transformer3DModel(in_visual_dim=16, in_text_dim=32, in_text_dim2=16, time_dim=16, out_visual_dim=16,
                                     patch_size=(1, 2, 2), model_dim=16, ff_dim=32, num_text_blocks=1,
                                     num_visual_blocks=2, axes_dims=(1, 1, 2), visual_cond=False,
                                     attention_type="regular").eval()
with torch.no_grad():  # the default init zeroes the output layers; randomize them so the output is not identically 0
    for p in model.parameters():
        if p.abs().max() == 0:
            p.normal_(0, 0.1)
x, pooled, t = torch.randn(1, 1, 8, 8, 16), torch.randn(1, 16), torch.tensor([500.0])
txt = torch.randn(1, 5, 32)
vpos = [torch.arange(1), torch.arange(4), torch.arange(4)]
run = lambda e: model(x, e, t, pooled, vpos, torch.arange(e.shape[1])).sample
with torch.no_grad():
    alone = run(txt)
    padded = run(torch.cat([txt, torch.randn(1, 3, 32)], dim=1))  # 3 padding positions from a longer prompt in the batch
print("(b) max |alone - padded| =", (alone - padded).abs().max().item())

Output:

(a) short prompt text seen by the encoder
    alone  : 'bjects and background:\nuser\na red square'
    batched: 'ps of the objects and background:\n<|im_s'
(b) max |alone - padded| = 0.16470187902450562
7. Kandinsky 5 I2V reference statistics
import torch
from diffusers import Kandinsky5I2VPipeline

f = Kandinsky5I2VPipeline.adaptive_mean_std_normalization
torch.manual_seed(0)
src = torch.randn(2, 3, 4, 4, 8)
ref = torch.randn(2, 3, 4, 4, 8)
ref[1] = 3.0 * ref[1] + 1.0                       # second video has a brighter, higher-contrast reference

batched = f(src, ref)[:1]
alone = f(src[:1], ref[:1])
print("max |alone - batched[0]| =", (alone - batched).abs().max().item())

Output:

max |alone - batched[0]| = 0.9895362854003906

With the released weights, items 1–3 are clearly visible. I compared a batched call with single calls (same latents and generator, FP32, CUDA). The relative RMS difference of the output was:

  • 31% for kandinsky-community/kandinsky-2-1 (two prompts, two images each);
  • 122% of the waveform for meituan-longcat/LongCat-AudioDiT-1B (prompts of different lengths);
  • 49% of the latent for the sound tokenizer of nvidia/Cosmos3-Super (clips of different loudness).

In each case, changing only the line named above brings the difference down to float rounding (≤ 0.002%). I did not measure items 4–7 with full weights.

Context

I am working on a research project that checks diffusion pipelines for consistency between equivalent calls, e.g. a batched call versus the same samples called one by one. These came out of running that check over the pipelines that have tiny test configurations. I'm happy to open a PR for any of them once you confirm the expected behavior.

Logs

System Info

diffusers main @ facc812 (also latest main as of 2026-12-03), torch 2.13.0, transformers 5.24.1, Python 3.13.5, macOS arm64 (CPU).

Who can help?

@yiyixuxu @asomoza

Activity

  1. added
    bug
    on Dec 3, 2026
  2. amarjithkumar2007-wq commented on Dec 3, 2026

    @amarjithkumar2007-wq

    Hi @nyxbyb, thanks for the thorough report and the CPU repro scripts. In your "Context" note you mentioned you'd be happy to open PRs for these yourself, so I wanted to check first: are you planning to take item 1 (the Kandinsky combined pipelines pairing prompts and image embeddings in different orders)? If not, I'd be glad to put together a PR for just that item, expanding prompt (and image/mask_image in the Img2Img/Inpaint variants) per prompt to match the prior's repeat_interleave ordering, plus a small CPU regression test. Happy to leave it to you if you'd rather take it.

  3. nyxbyb commented on Dec 4, 2026

    @nyxbyb
    Author

    Hi @amarjithkumar2007-wq, thanks for offering — please go ahead with item 1 (the Kandinsky combined pipelines).

    Your plan matches what I had in mind: expand prompt (and image / mask_image in the Img2Img and Inpaint variants) per prompt so it follows the prior's repeat_interleave order. For the regression test, a batched call with two different prompts and num_images_per_prompt=2, compared against the two single-prompt calls with the same per-sample generators, fails before the fix and passes after it on CPU.

    Happy to review the PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions