Support Transformers v5 cache handling

#4
by lavrenko - opened

Fixes cached decoding with recent Transformers versions by passing next_sequence_length to prepare_inputs_for_generation during non-first cached decoding steps.

This addresses the cache-related deterministic-output corruption reported in #3.

A more detailed explanation and local test results are included in the discussion below.

Summary

Fix cached decoding with recent Transformers versions.

This updates the custom generation loop to pass next_sequence_length into prepare_inputs_for_generation. In cached decoding, Transformers v5 expects the decode loop to explicitly indicate that only the latest token should be forwarded after the first step. Without this, the cached path may forward the full growing sequence together with past_key_values, which can corrupt deterministic group beam outputs.

What changed

  • Detect whether the loop is on the first decoding iteration.
  • Use next_sequence_length=None for the prefill step and for use_cache=False, preserving the existing full-sequence behavior.
  • Use next_sequence_length=1 for cached non-first decoding steps, matching the expected Transformers v5 cache behavior.
  • Pass is_first_iteration through to prepare_inputs_for_generation.

This keeps use_cache=True supported instead of forcing use_cache=False.

Motivation

This addresses the issue discussed in #3: deterministic group beam search could produce different and sometimes corrupted outputs depending on whether cache was enabled.

Cache should be an optimization and should not materially change deterministic generation semantics.

Tested

I tested the updated custom generation locally with:

  • transformers==4.57.1
  • transformers==5.12.1

using the Qwen/Qwen2.5-0.5B-Instruct reproducer from discussion #3 with deterministic grouped beam search.

Addresses #3

lavrenko changed pull request status to open
Transformers Community org

Ah nice, thanks for checking it. That PR indeed must have been breaking, we'd ideally check and update other generation methods as well. Feel free to check and PR if you want, otherwise I will look a bit later (low prio πŸ˜ƒ )

RaushanTurganbay changed pull request status to merged

Sign up or log in to comment