Skip to content

Fix batched generation for prompts of different lengths - #2216

Merged
danielhanchen merged 3 commits into
unslothai:mainfrom
RunFMe:main
Jun 2, 2025
Merged

danielhanchen merged 3 commits into
unslothai:mainfrom
RunFMe:main

Conversation

@RunFMe

@RunFMe RunFMe commented Mar 27, 2025 •

Copy link
Copy Markdown
Contributor

Previous code

def _fast_prepare_inputs_for_generation(self, input_ids, **kwargs,):
    past_key_values = kwargs.get("past_key_values", None)
    if past_key_values is not None:
        # Check for uninitialized DynamicCache
        if len(past_key_values) == 0:
            past_key_values = None
            kwargs["past_key_values"] = None
        else:
            input_ids = input_ids[:,[-1]]
            kwargs["attention_mask"] = kwargs["attention_mask"][:,[-1]]

    if "cache_position" in kwargs:
        kwargs["position_ids"] = kwargs["cache_position"]
    return { "input_ids" : input_ids, **kwargs, }
pass

_fast_prepare_inputs_for_generation is called to get forward method arguments for generating new token. Notice that it crops attention_mask and only takes into account the last value. Attention mask of length 1 triggers flag in the forward which makes attention mask None.

I fixed it by copying a piece of code from traditional prepare_inputs_for_generation which calls base_model._prepare_4d_causal_attention_mask_with_cache_position if it's present. This way we allow models which have this function (most popular) to create attention mask as they see fit.

Comment thread unsloth/models/llama.py Resolved
@RunFMe

RunFMe commented Mar 29, 2025

Copy link
Copy Markdown
Contributor Author

@Datta0 What do you think? What else should we do before merging?

@Datta0 Datta0 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM :) !

@RunFMe

RunFMe commented Apr 3, 2025

Copy link
Copy Markdown
Contributor Author

@Datta0 do you know what the process is for getting approval of a maintainer?

@Datta0

Datta0 commented Apr 4, 2025

Copy link
Copy Markdown
Contributor

Hey @RunFMe , I will text Daniel about this
Also it'd be great if you can include samples from previous and current code in the PR description...

@RunFMe

RunFMe commented Apr 8, 2025

Copy link
Copy Markdown
Contributor Author

@Datta0 done)
Tell me, if there's anything else I can help with.

@AdityaMayukhSom

Copy link
Copy Markdown

This helped me solve batch processing issue in LLaMA 3.2 1B Instruct model, please merge this to unsloth.

@danielhanchen
danielhanchen merged commit 45f26cd into unslothai:main Jun 2, 2025
@danielhanchen

Copy link
Copy Markdown
Member

Whoops apologies totally missed this - great work!

abiswas-realadvice pushed a commit to abiswas-realadvice/unsloth that referenced this pull request May 14, 2026
* fix ignoring of attention mask after prefill stage in decoding

* update naming to avoid confusion

---------

Co-authored-by: Неизвестный Пользователь722497 <[email protected]>
danielhanchen added a commit that referenced this pull request Jun 10, 2026
…egress again (#1066, #3699) (#6145)

* Add regression guard for batched left-padded generation (#1066, #3699)

Three layers of tests plus a path-filtered CI workflow so the left-padding
position_ids / attention-mask bug class cannot silently return:

- tests/utils/test_prepare_inputs_ast_guard.py: import-free AST checks on
  _fast_prepare_inputs_for_generation (cumsum-from-mask branch present,
  cache_position only as fallback, no mask truncation, model families wired)
- tests/utils/test_prepare_inputs_leftpad.py: CPU behavioral unit test with
  synthetic left-padded masks and fake caches; exact expected position_ids
  for prefill and cached decode
- tests/utils/test_batched_leftpad_generation_gpu.py: optional GPU e2e,
  solo vs batched prefix match, skipped without CUDA
- .github/workflows/batch-inference-guard.yml: ubuntu-latest CPU job running
  the two deterministic layers on PRs touching unsloth/models/**

Validated: all pass on main; both CPU layers fail at 6d0f864~1 (pre #4100)
and at 332eabf~1 (pre #2216), reproducing the historical bug signatures.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Cite staging proof in batch-inference-guard header (staging-2 PRs 170/171)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fold left-padding guard into consolidated Core CI; merge AST + behavioral tests

No new workflow and no new CI job: the guard now runs as one HARD GATE step
inside consolidated-tests-ci.yml, right after the callback signature drift
detector, where the CPU torch stack is already installed. The AST structural
checks and the behavioral unit tests live in a single file
(tests/utils/test_prepare_inputs_leftpad.py); the AST layer stays stdlib-only
with unsloth imported lazily inside the behavioral tests, so import breakage
cannot mask the structural checks.

Revalidated after the merge: 11 assertions pass on main, 8 fail at
6d0f864~1 (pre #4100).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update staging proof reference for consolidated gate (PRs 170/172)

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants