Fix generation with StaticCache + torch.compile

#6
by masonliu99 - opened

Fix MiniCPM4.1 generation with StaticCache + torch.compile

Problem

MiniCPM4.1-8B fails under torch.compile with cache_implementation="static":

  1. RuntimeError: Attempting to broadcast a dimension of length 18 at -1 β€” the SDPA attention mask is built with past_key_values_length=0 (only InfLLMv2Cache was handled), so it doesn't cover the preallocated static KV cache.
  2. IndexError: index_copy_(): Number of indices (19) should be equal to source.size(dim) (1) β€” position_ids from model_kwargs is the full accumulated sequence, but input_ids is sliced to the new token only, so apply_rotary_pos_emb expands key_states beyond value_states.

Changes

  • Use create_causal_mask for the SDPA path (sizes the mask from the cache's get_mask_sizes, matching the preallocated static KV cache).
  • Compute past_key_values_length for all Cache types, not just InfLLMv2Cache.
  • Slice position_ids to the unprocessed tokens in prepare_inputs_for_generation, matching the input_ids slicing.
  • Relax the SDPA mask-size assertion to only fail when the mask is too small.
Ready to merge
This branch is ready to get merged automatically.

Sign up or log in to comment