Fix generation with StaticCache + torch.compile

#6
by masonliu99 - opened
Files changed (1) hide show
  1. modeling_minicpm.py +20 -10
modeling_minicpm.py CHANGED
@@ -25,11 +25,9 @@ from torch import nn
25
  from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
  from transformers.activations import ACT2FN
27
  from transformers.cache_utils import Cache, DynamicCache, CacheLayerMixin, DynamicLayer
 
28
  from transformers.modeling_attn_mask_utils import (
29
- AttentionMaskConverter,
30
- _prepare_4d_attention_mask,
31
  _prepare_4d_causal_attention_mask,
32
- _prepare_4d_causal_attention_mask_for_sdpa,
33
  )
34
  from transformers.modeling_outputs import (
35
  BaseModelOutputWithPast,
@@ -1509,7 +1507,10 @@ class MiniCPMSdpaAttention(MiniCPMAttention):
1509
  value_states = repeat_kv(value_states, self.num_key_value_groups)
1510
 
1511
  if attention_mask is not None:
1512
- if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
 
 
 
1513
  raise ValueError(
1514
  f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
1515
  )
@@ -1821,7 +1822,10 @@ class MiniCPMModel(MiniCPMPreTrainedModel):
1821
  )
1822
 
1823
  # Calculate the usable length of past key values
1824
- past_key_values_length = past_key_values.get_seq_length() if isinstance(past_key_values, InfLLMv2Cache) else 0
 
 
 
1825
 
1826
  # Initialize InfLLMv2Cache if needed
1827
  if self.config.sparse_config is not None and torch.cuda.is_available() and past_key_values_length == 0:
@@ -1847,11 +1851,12 @@ class MiniCPMModel(MiniCPMPreTrainedModel):
1847
  elif self._use_sdpa and not output_attentions:
1848
  # output_attentions=True can not be supported when using SDPA, and we fall back on
1849
  # the manual implementation that requires a 4D causal mask in all cases.
1850
- attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1851
- attention_mask,
1852
- (batch_size, seq_length),
1853
- inputs_embeds,
1854
- past_key_values_length,
 
1855
  )
1856
  else:
1857
  # 4d mask is passed through the layers
@@ -2090,6 +2095,11 @@ class MiniCPMForCausalLM(MiniCPMPreTrainedModel):
2090
  position_ids.masked_fill_(attention_mask == 0, 1)
2091
  if past_key_values:
2092
  position_ids = position_ids[:, -input_ids.shape[1]:]
 
 
 
 
 
2093
 
2094
  # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
2095
  if inputs_embeds is not None and past_key_values is None:
 
25
  from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
  from transformers.activations import ACT2FN
27
  from transformers.cache_utils import Cache, DynamicCache, CacheLayerMixin, DynamicLayer
28
+ from transformers.masking_utils import create_causal_mask
29
  from transformers.modeling_attn_mask_utils import (
 
 
30
  _prepare_4d_causal_attention_mask,
 
31
  )
32
  from transformers.modeling_outputs import (
33
  BaseModelOutputWithPast,
 
1507
  value_states = repeat_kv(value_states, self.num_key_value_groups)
1508
 
1509
  if attention_mask is not None:
1510
+ # With StaticCache, key/value returned by update() is the full preallocated
1511
+ # cache (max_cache_len), so the mask's kv dim may exceed kv_seq_len (which is
1512
+ # based on position_ids). Only error if the mask is too small to cover kv_seq_len.
1513
+ if attention_mask.size(-1) < kv_seq_len:
1514
  raise ValueError(
1515
  f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
1516
  )
 
1822
  )
1823
 
1824
  # Calculate the usable length of past key values
1825
+ # Original only handled InfLLMv2Cache; extend to all Cache types so
1826
+ # StaticCache/DynamicCache get the correct cached KV length for
1827
+ # position_ids and the attention mask.
1828
+ past_key_values_length = past_key_values.get_seq_length() if isinstance(past_key_values, Cache) else 0
1829
 
1830
  # Initialize InfLLMv2Cache if needed
1831
  if self.config.sparse_config is not None and torch.cuda.is_available() and past_key_values_length == 0:
 
1851
  elif self._use_sdpa and not output_attentions:
1852
  # output_attentions=True can not be supported when using SDPA, and we fall back on
1853
  # the manual implementation that requires a 4D causal mask in all cases.
1854
+ attention_mask = create_causal_mask(
1855
+ config=self.config,
1856
+ inputs_embeds=inputs_embeds,
1857
+ attention_mask=attention_mask,
1858
+ past_key_values=past_key_values,
1859
+ position_ids=position_ids,
1860
  )
1861
  else:
1862
  # 4d mask is passed through the layers
 
2095
  position_ids.masked_fill_(attention_mask == 0, 1)
2096
  if past_key_values:
2097
  position_ids = position_ids[:, -input_ids.shape[1]:]
2098
+ elif position_ids is not None and past_key_values is not None:
2099
+ # position_ids from kwargs is the FULL accumulated sequence (transformers
2100
+ # _update_model_kwargs_for_generation concatenates new ids). Slice it to only
2101
+ # the unprocessed tokens, matching the input_ids slicing above.
2102
+ position_ids = position_ids[:, -input_ids.shape[1]:]
2103
 
2104
  # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
2105
  if inputs_embeds is not None and past_key_values is None: