Skip to content

[Bug] Batched greedy generation disagrees with one-at-a-time on Qwen3.5-2B and gemma-4-E2B-it (T4, left padding) #9708

Closed

Description

@danielhanchen

Summary

After a short LoRA fine-tune, greedy generation at batch size 1 and at batch sizes 2, 4 and 8 produce different text for the same prompts, with left padding in place and the padding demonstrably happening.

Reproduces on two different models, on a Tesla T4 (sm_75), across two fresh processes each. This is the same family as #1066 and #3699, on a current stack.

Environment

torch          2.10.0+cu128      transformers  5.15.1
trl            1.10.0            peft          0.19.1
accelerate     1.13.0            bitsandbytes  0.50.1
datasets       5.0.1             triton        3.6.0
GPU            Tesla T4, sm_75   load_in_4bit  True, dtype float16

Reproduction

Eight prompts of deliberately different lengths, greedy (do_sample=False), generated one at a time and then in batches, decoded past the prompt width.

unsloth/gemma-4-E2B-it

prompt token lengths   [13, 13, 14, 15, 13, 12, 15, 16]   (5 distinct, so padding happened)
tokenizer.padding_side after generating: left

batch 1:  ['__UNSLOTH__!!!'] x 8

batch 2:  ['__UNSLOTH__!!!',
           '__UNSLOTH__!!!',
           ':\n### Answer:\n### Answer:\n__UNSLOTH__!!!',   <-- differs
           '__UNSLOTH__!!!',
           '__UNSLOTH__!!!',
           ':\n__UNSLOTH__UNSLOTH!!!',                      <-- differs
           '?\n### Answer:\n### Answer?\n__UNSLOTH__UN',    <-- differs
           '__UNSLOTH__!!!']

unsloth/Qwen3.5-2B

prompt token lengths   [13, 13, 14, 15, 13, 13, 15, 16]   (4 distinct)
tokenizer.padding_side after generating: left

batch 1:  ['__UNSLOTH__!!!'] x 8

batch 2:  ['__UNSLOTH__!!!',
           '__UNSLOTH__!!!',
           '?UNSLOTH__UNSLOTH__UNSLOTH__UNSLOTH',           <-- differs
           '__UNSLOTH__!!!',
           '__UNSLOTH__!!!',
           '__UNSLOTH__!!!',
           ' I__UNSLOTH__UNSLOTH__UNSLOTH__UNSLO',          <-- differs
           '__UNSLOTH__!!!']

Batch 4 and batch 8 disagree at least as much, and both repeats of each model agree with each other, so this is reproducible rather than noise.

What has already been ruled out

The caveat, stated up front

Some divergence between batched and unbatched fp16 greedy decoding is possible from ordinary numerics: a near-tie in the argmax can flip when the batch changes the reduction order. That would normally show as an occasional single-token difference.

What is here is larger than that. The differing outputs gain a whole prefix (:\n### Answer:\n### Answer:\n, ?UNSLOTH__UNSLOTH__), which is what attending to padding looks like rather than a tie-break flip. The same positions differ in both repeats, and the same two models differ at the same prompt indices.

Where it was found

The Kaggle T4 CI legs, which assert the #3699 / #1066 / #1456 / #2138 contract on every run. Note that unsloth/Qwen3-0.6B passes the identical check on the same harness (batch 2, 4 and 8 all agreeing with batch 1), so this is not the harness being wrong about every model.

Activity

  1. danielhanchen commented on Sep 6, 2026

    @danielhanchen
    MemberAuthor

    Root cause, results and a standalone repro

    This was closed when #9848 merged, and that is only half the story, so the findings go here for the record. #9848 fixed a real defect: a left padded row that attends to nothing produced NaN logits in fp16 and decoded to an empty string. The rest of what this issue reports, batch sizes 2, 4 and 8 producing different greedy text from batch size 1, is not an unsloth bug and not a bug in any one library. It is bf16 and fp16 rounding that depends on the shape of the batch, and it reproduces with plain transformers and unsloth never imported. In float32 every batch size agrees.

    Setup

    All arms: greedy decoding with sampling off, 8 prompts with distinct token lengths so left padding is real ([13, 13, 14, 15, 13, 12, 15, 16] on the payload prompts), TF32 off, deterministic cuBLAS workspace, deterministic algorithms on, every arm run twice. Run to run every arm was byte identical, so none of this is nondeterminism. Hardware for the sweep was one B200 with torch 2.13.0+cu130 and transformers 5.16.1; the original report was on a T4, so this is not a T4 property either.

    Plain transformers, no unsloth

    agrees is whether every row at that batch size reproduces its own batch size 1 output. prefill delta is the max absolute logit difference at the last prompt position between the prompt alone and the same prompt inside the padded batch of 8.

    model weights dtype agrees 2 / 4 / 8 prefill delta
    gemma-4-E2B-it 16 bit bf16 no / no / no 1.0
    gemma-4-E2B-it 16 bit fp16 no / no / no NaN (the #9848 rows)
    gemma-4-E2B-it 16 bit fp32 yes / yes / yes 1.0e-4
    gemma-4-E2B-it NF4 on the fly bf16 no / no / no 5.5
    gemma-4-E2B-it NF4 on the fly fp32 yes / yes / yes 1.6e-3
    gemma-4-e2b-it-unsloth-bnb-4bit prequantised bf16 no / no / no 1.1
    gemma-4-e2b-it-unsloth-bnb-4bit prequantised fp32 compute yes / yes / yes 0.41
    Qwen3.5-2B 16 bit bf16 no / no / no 0.19
    Qwen3.5-2B 16 bit fp16 yes / yes / yes 2.3e-2
    Qwen3.5-2B 16 bit fp32 yes / yes / yes 3.2e-5
    Qwen3.5-2B NF4 bf16 yes / no / no 0.19
    Qwen3-0.6B 16 bit bf16 yes / no / no 0.36
    Qwen3-0.6B 16 bit fp16 yes / yes / yes 5.7e-2
    Qwen3-0.6B 16 bit fp32 yes / yes / yes 4.9e-5
    Qwen3-0.6B NF4 bf16 yes / no / yes 0.61

    Which batch sizes disagree moves around with the model, the prompt set and the dtype, which is what shape dependent rounding looks like. What never moves: fp32 agrees everywhere, and the fp32 prefill delta is four orders of magnitude smaller.

    unsloth versus plain transformers on the same checkpoint

    Matched A/B on gemma-4-e2b-it-unsloth-bnb-4bit, same prompts, same generation settings, both arms sdpa:

    loader agrees 2 / 4 / 8
    plain transformers, bf16 yes / yes / no
    unsloth, default no / no / no

    They differ in which sizes disagree, not in whether they do. unsloth holds 397 of the parameters in fp32 where plain holds all of them in bf16, so the two arms are not running identical arithmetic and were never expected to match each other row for row.

    Also ruled out on unsloth's side, each by measurement: UNSLOTH_COMPILE_DISABLE=1 (flips the untrained gemma-4 and Qwen3.5-2B arms to agreement and leaves the trained gemma-4 arm disagreeing, so it is another shape knob, not a fix), the static cache the generate wrapper selects (disagrees with DynamicCache too), and the bitsandbytes dequant path (fused and unfused give identical results; NF4 versus 16 bit changes nothing in fp32).

    transformers version sweep

    39 releases from 4.57.0 to 5.16.1 through the unsloth loader in 4 bit. gemma-4 needs 5.5.0 or newer and Qwen3.5 needs 5.2.0 or newer, so older releases refuse the model and are recorded as such rather than as agreement.

    model releases that load it releases where all sizes agree
    gemma-4-E2B-it 5.5.0 to 5.16.1 (24) none
    Qwen3.5-2B 5.2.0 to 5.16.1 (27) none
    Qwen3-0.6B 4.57.0 to 5.16.1 (39) none

    There is no version to go back to. The one boundary that shows up, 5.14.0 changing gemma-4 from "2 and 8 agree, 4 disagrees" to "all disagree", is the rewrite of masking_utils._ignore_causal_mask_sdpa, which skips the materialised mask for a static cache prefill at offset 0. Vetoing that skip changes the batch size 1 outputs, not the batched ones. It moves the rounding, it does not cause it.

    Mechanism

    Layer by layer traces on gemma-4 in bf16, plain transformers, comparing each row inside the batch of 8 against the same prompt alone. Three independent sources:

    1. Attention kernel. A prompt alone gets no materialised mask and takes the is_causal fast path, which SDPA serves with the flash kernel. A padded batch carries a mask and is served by the memory efficient kernel. Different kernels, different accumulation order, and the first difference appears in layer 0 attention for every row, including the longest prompt, which receives no padding at all. attn_implementation="eager" removes this source (gemma-4 then agrees at 2 and 4) and exposes the next one.
    2. Prefill GEMM shape. With eager attention the longest row is bit identical through layers 0 to 3 and diverges at the layer 4 o_proj, which receives identical inputs. The projection sees 16 token rows alone and 128 inside the batch, and cuBLAS picks a different tile for the two shapes. Replaying o_proj on the equal input reproduces the difference exactly. 277 equal input replays of decode step linears, by contrast, never differed: batch 1 versus 8 at M=1 versus M=8 is bit identical in bf16, so this is a prefill effect, not a decode one.
    3. RMSNorm rounding. Norms both amplify the differences above (0.002 inside attention grows to 0.5 after the MLP norm in one layer) and occasionally introduce their own.

    Forcing all three to their batch size 1 shapes makes every decoder output and both logit vectors bit identical across all 8 rows. Forcing only one of them does not. The bf16 hidden state deltas peak at 1.5 in prefill and 1.0 in decode; the same traces in fp32 peak at 9.6e-5 and 6.5e-5.

    What this means in practice

    • Exact agreement between batch size 1 and a padded batch is not something bf16 or fp16 inference provides, with or without unsloth, on any transformers release tested. Greedy decoding turns a rounding difference at one position into a different token, and everything after that position diverges.
    • If exact reproducibility across batch sizes is required, run in float32. That was true for every model and every quantisation tested.
    • The Kaggle T4 leg keeps its strict expectation for gemma-4-E2B-it and Qwen3.5-2B: a listed model that starts agreeing fails the leg so the entry gets deleted. Kaggle T4: fail a batched row that generates nothing while its single does not #10367 adds the check that was missing, a row that is empty inside the batch while its single is not, so the Stop a left-padded row that attends to nothing returning NaN (#9708) #9848 shape can no longer hide behind the expected disagreement.

    Standalone repro

    Needs only torch and transformers, plus bitsandbytes for --load-in-4bit. Prints agreement per batch size, the rows that differ, the prefill logit delta, and whether the run was deterministic across two repeats.

    python repro_batched_greedy_divergence.py                        # gemma-4, bf16: disagrees
    python repro_batched_greedy_divergence.py --dtype float32         # agrees
    python repro_batched_greedy_divergence.py --attn eager            # attention source removed
    python repro_batched_greedy_divergence.py --model unsloth/Qwen3.5-2B
    
    repro_batched_greedy_divergence.py
    #!/usr/bin/env python3
    """Batched greedy generation disagrees with one-at-a-time in bf16/fp16.
    
    Standalone reproduction. Needs only `torch` and `transformers` (and
    `bitsandbytes` if you pass --load-in-4bit). No unsloth. Greedy decoding with
    sampling fully off, so any difference between batch sizes is numerics.
    
        python repro_batched_greedy_divergence.py                      # gemma-4, bf16
        python repro_batched_greedy_divergence.py --dtype float32       # expect agreement
        python repro_batched_greedy_divergence.py --attn eager
        python repro_batched_greedy_divergence.py --model unsloth/Qwen3.5-2B
        python repro_batched_greedy_divergence.py --load-in-4bit --dtype bfloat16
    
    What it prints: for each batch size, whether every row reproduces its own
    batch-1 output, the rows that differ, and the max |logit| difference at the
    last prompt position between "prompt alone" and "prompt inside the padded
    batch". Determinism is pinned (no TF32, cuDNN deterministic, deterministic
    algorithms) and each arm is run twice, so run-to-run noise and batch-shape
    dependence are reported separately.
    
    Observed on a B200, transformers 5.16.1, torch 2.13:
      gemma-4-E2B-it   bf16: batch 2/4/8 all disagree   fp32: all agree (delta ~1e-4)
      Qwen3.5-2B       bf16: all disagree               fp32: all agree
      Qwen3-0.6B       bf16: 4 and 8 disagree           fp32: all agree
    Forcing one attention backend (--attn eager) removes most of it; the residual
    row is the LONGEST prompt, which gets no padding, so that part is matmul
    rounding that depends on the batch dimension rather than anything mask-related.
    """
    
    import argparse
    import json
    import os
    import sys
    
    # Mixed lengths on purpose: left padding only happens when lengths differ.
    PROMPTS = [
        "### Question:\nWho am I?\n### Answer:\n",
        "### Question:\nWho are you?\n### Answer:\n",
        "### Question:\nWhat is your name?\n### Answer:\n",
        "### Question:\nTell me who you are.\n### Answer:\n",
        "### Question:\nState your identity.\n### Answer:\n",
        "### Question:\nIdentify yourself.\n### Answer:\n",
        "### Question:\nplease please Who am I?\n### Answer:\n",
        "### Question:\nplease please please Who are you?\n### Answer:\n",
    ]
    BATCH_SIZES = (2, 4, 8)
    
    
    def main():
        ap = argparse.ArgumentParser()
        ap.add_argument("--model", default="unsloth/gemma-4-E2B-it")
        ap.add_argument("--dtype", default="bfloat16", choices=["float16", "bfloat16", "float32"])
        ap.add_argument("--attn", default="", help="e.g. eager or sdpa; empty = model default")
        ap.add_argument("--load-in-4bit", action="store_true")
        ap.add_argument("--max-new-tokens", type=int, default=16)
        ap.add_argument("--json", default="", help="also write the full report here")
        args = ap.parse_args()
    
        # Must precede CUDA init for deterministic cuBLAS.
        os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
        import torch
        import transformers
        from transformers import AutoModelForCausalLM, AutoTokenizer
    
        torch.manual_seed(0)
        torch.backends.cuda.matmul.allow_tf32 = False
        torch.backends.cudnn.allow_tf32 = False
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False
        torch.use_deterministic_algorithms(True, warn_only=True)
    
        dtype = getattr(torch, args.dtype)
        tok = AutoTokenizer.from_pretrained(args.model)
        tok.padding_side = "left"
        if tok.pad_token is None:
            tok.pad_token = tok.eos_token
    
        kw = {"dtype": dtype, "device_map": "cuda:0"}
        if args.attn:
            kw["attn_implementation"] = args.attn
        if args.load_in_4bit:
            from transformers import BitsAndBytesConfig
            kw["quantization_config"] = BitsAndBytesConfig(
                load_in_4bit=True, bnb_4bit_quant_type="nf4",
                bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=dtype,
            )
        model = AutoModelForCausalLM.from_pretrained(args.model, **kw).eval()
        pad_id = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id
    
        def gen(batch):
            enc = tok(text=batch, return_tensors="pt", padding=True).to(model.device)
            with torch.inference_mode():
                out = model.generate(
                    **enc, max_new_tokens=args.max_new_tokens,
                    do_sample=False, temperature=None, top_p=None, top_k=None,
                    use_cache=True, pad_token_id=pad_id,
                )
            w = enc["input_ids"].shape[1]
            return [tok.decode(r[w:], skip_special_tokens=True) for r in out]
    
        def prefill_delta():
            with torch.inference_mode():
                enc = tok(text=PROMPTS, return_tensors="pt", padding=True).to(model.device)
                batched = model(**enc).logits[:, -1, :].float()
                deltas = []
                for i, p in enumerate(PROMPTS):
                    solo = model(**tok(text=[p], return_tensors="pt").to(model.device)).logits[0, -1, :].float()
                    deltas.append(float((batched[i] - solo).abs().max()))
            return max(deltas)
    
        lengths = [len(tok(p)["input_ids"]) for p in PROMPTS]
        runs = []
        for _ in range(2):
            singles = [gen([p])[0] for p in PROMPTS]
            batched = {
                bs: sum((gen(PROMPTS[i:i + bs]) for i in range(0, len(PROMPTS), bs)), [])
                for bs in BATCH_SIZES
            }
            runs.append((singles, batched))
        singles, batched = runs[0]
        deterministic = runs[0] == runs[1]
        delta = prefill_delta()
    
        print(f"\nmodel={args.model}  dtype={args.dtype}  4bit={args.load_in_4bit}  "
              f"attn={model.config._attn_implementation}")
        print(f"transformers={transformers.__version__}  torch={torch.__version__}  "
              f"gpu={torch.cuda.get_device_name(0)}")
        print(f"prompt token lengths={lengths}  (distinct={len(set(lengths))}, so padding is real)")
        print(f"run-to-run deterministic: {deterministic}")
        print(f"max |logit delta| at last prompt position, solo vs in-batch: {delta:.6g}")
        print(f"{'batch':>6}  {'agrees':>6}  rows that differ from batch-1")
        for bs in BATCH_SIZES:
            diff = [i for i, (s, b) in enumerate(zip(singles, batched[bs])) if s != b]
            print(f"{bs:>6}  {str(not diff):>6}  {diff}")
        for bs in BATCH_SIZES:
            diff = [i for i, (s, b) in enumerate(zip(singles, batched[bs])) if s != b]
            if diff:
                i = diff[0]
                print(f"\nexample, row {i} at batch {bs}:\n  batch-1: {singles[i]!r}\n  batch-{bs}: {batched[bs][i]!r}")
                break
    
        if args.json:
            with open(args.json, "w") as fh:
                json.dump({"model": args.model, "dtype": args.dtype, "load_in_4bit": args.load_in_4bit,
                           "attn": model.config._attn_implementation, "lengths": lengths,
                           "deterministic": deterministic, "prefill_max_abs_delta": delta,
                           "singles": singles, "batched": {str(k): v for k, v in batched.items()}},
                          fh, indent=1)
        return 0
    
    
    if __name__ == "__main__":
        sys.exit(main())
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions