Qubitium commited on
Commit
f8fb7f5
·
1 Parent(s): 728d0de

Fix cached prompt disambiguation and capacity-padded positions

Browse files
modeling_ricursive.py CHANGED
@@ -888,6 +888,15 @@ class RicursiveForCausalLM(RicursivePreTrainedModel, GenerationMixin):
888
  position_ids: Optional[torch.LongTensor] = None,
889
  **kwargs,
890
  ):
 
 
 
 
 
 
 
 
 
891
  # transformers 5.x does not move remote-code inputs onto the model device for
892
  # this model, so a plain CPU `input_ids` reaches the embedding lookup and
893
  # raises. Its own generation helper performs this move, so mirror it here.
@@ -908,22 +917,13 @@ class RicursiveForCausalLM(RicursivePreTrainedModel, GenerationMixin):
908
  past_length = _cache_seq_length(past_key_values)
909
 
910
  if cache_position is None:
911
- # A full prompt can include cached tokens, while verification may pass
912
- # only a new token block. A block no longer than the cache must be new;
913
- # for a longer block, a mask with exactly the cached prefix plus new
914
- # tokens identifies new-only input when its final slot is populated.
915
- # A longer mask, or one with unused capacity at the end, may be padded
916
- # to a static cache's capacity and describes a full prompt instead.
917
  input_length = input_ids.shape[1]
918
- candidate_full_prompt = past_length > 0 and input_length > past_length
919
- new_block_mask = (
920
- candidate_full_prompt
921
- and attention_mask is not None
922
- and attention_mask.dim() == 2
923
- and attention_mask.shape[-1] == past_length + input_length
924
- and bool(attention_mask[..., -1].any())
925
- )
926
- full_prompt = candidate_full_prompt and not new_block_mask
927
  new_len = input_length - past_length if full_prompt else input_length
928
  cache_position = torch.arange(
929
  past_length, past_length + new_len, device=input_ids.device
@@ -946,12 +946,16 @@ class RicursiveForCausalLM(RicursivePreTrainedModel, GenerationMixin):
946
  # tokens of a short row sit at higher indices, so a shared position vector
947
  # shifts its RoPE phases and the row decodes to garbage.
948
  if position_ids is not None:
949
- if sliced:
 
 
950
  position_ids = position_ids[:, cache_position]
951
  elif attention_mask is not None and attention_mask.dim() == 2:
952
  position_ids = attention_mask.long().cumsum(-1) - 1
953
  position_ids = position_ids.masked_fill(attention_mask == 0, 0)
954
- position_ids = position_ids[:, -input_ids.shape[1]:]
 
 
955
  else:
956
  position_ids = cache_position.unsqueeze(0)
957
 
 
888
  position_ids: Optional[torch.LongTensor] = None,
889
  **kwargs,
890
  ):
891
+ """Prepare a full prompt or a new-only block for cached generation.
892
+
893
+ With a warm cache and no explicit ``cache_position``, inputs longer
894
+ than the cached prefix are full prompts; shorter or equal-length inputs
895
+ are new-only blocks. For a longer new-only block, pass
896
+ ``torch.arange(past_length, past_length + input_ids.shape[1])`` as
897
+ ``cache_position``. Attention masks may be padded to cache capacity and
898
+ therefore cannot identify which input layout the caller supplied.
899
+ """
900
  # transformers 5.x does not move remote-code inputs onto the model device for
901
  # this model, so a plain CPU `input_ids` reaches the embedding lookup and
902
  # raises. Its own generation helper performs this move, so mirror it here.
 
917
  past_length = _cache_seq_length(past_key_values)
918
 
919
  if cache_position is None:
920
+ # Inputs no longer than the cache are treated as new-only blocks.
921
+ # Longer inputs default to full prompts containing the cached prefix.
922
+ # Mask width/content cannot distinguish a longer new-only block from
923
+ # a full prompt with a capacity-sized mask (even an all-visible one).
924
+ # Callers supplying longer new-only blocks must pass cache_position.
 
925
  input_length = input_ids.shape[1]
926
+ full_prompt = past_length > 0 and input_length > past_length
 
 
 
 
 
 
 
 
927
  new_len = input_length - past_length if full_prompt else input_length
928
  cache_position = torch.arange(
929
  past_length, past_length + new_len, device=input_ids.device
 
946
  # tokens of a short row sit at higher indices, so a shared position vector
947
  # shifts its RoPE phases and the row decodes to garbage.
948
  if position_ids is not None:
949
+ # Callers may supply positions for the full prompt/capacity, or may
950
+ # already have selected just the positions for the current block.
951
+ if position_ids.shape[-1] != input_ids.shape[1]:
952
  position_ids = position_ids[:, cache_position]
953
  elif attention_mask is not None and attention_mask.dim() == 2:
954
  position_ids = attention_mask.long().cumsum(-1) - 1
955
  position_ids = position_ids.masked_fill(attention_mask == 0, 0)
956
+ # The mask may include unused cache capacity after the current block.
957
+ # Select its actual cache slots, not the final entries of that mask.
958
+ position_ids = position_ids[:, cache_position]
959
  else:
960
  position_ids = cache_position.unsqueeze(0)
961
 
tests/test_generation_cache.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU regressions for warm-cache generation; no checkpoint download required."""
2
+
3
+ import importlib.util
4
+ from pathlib import Path
5
+ import sys
6
+ import types
7
+
8
+ import pytest
9
+ import torch
10
+ from transformers.cache_utils import DynamicCache, StaticCache
11
+
12
+
13
+ @pytest.fixture(scope="module")
14
+ def model():
15
+ root = Path(__file__).resolve().parents[1]
16
+ package = types.ModuleType("ripple_generation_tests")
17
+ package.__path__ = [str(root)]
18
+ sys.modules[package.__name__] = package
19
+ name = f"{package.__name__}.modeling_ricursive"
20
+ spec = importlib.util.spec_from_file_location(name, root / "modeling_ricursive.py")
21
+ module = importlib.util.module_from_spec(spec)
22
+ sys.modules[name] = module
23
+ spec.loader.exec_module(module)
24
+ config = module.RicursiveConfig(
25
+ vocab_size=64,
26
+ hidden_size=32,
27
+ intermediate_size=48,
28
+ num_hidden_layers=2,
29
+ num_attention_heads=4,
30
+ num_key_value_heads=2,
31
+ head_dim=8,
32
+ max_position_embeddings=64,
33
+ sliding_window=32,
34
+ layer_types=["sliding_attention", "full_attention"],
35
+ use_valres=True,
36
+ )
37
+ with torch.random.fork_rng(devices=[]):
38
+ torch.manual_seed(11)
39
+ result = module.RicursiveForCausalLM(config).eval()
40
+ return result
41
+
42
+
43
+ def positions(mask):
44
+ return (mask.long().cumsum(-1) - 1).masked_fill(mask == 0, 0)
45
+
46
+
47
+ @pytest.mark.parametrize("cache_type", ["dynamic", "static"])
48
+ @pytest.mark.parametrize(
49
+ "past_length,new_length,full_prompt,capacity,visible_tail,explicit_cache",
50
+ [
51
+ pytest.param(4, 2, True, 10, True, False, id="review-visible-capacity"),
52
+ pytest.param(10, 2, False, 16, False, False, id="review-short-padded-block"),
53
+ pytest.param(4, 2, True, 10, False, False, id="zero-exact-capacity"),
54
+ pytest.param(4, 2, True, 12, False, False, id="zero-long-capacity"),
55
+ pytest.param(4, 2, True, 6, True, False, id="full-prompt"),
56
+ pytest.param(4, 4, False, 8, True, False, id="equal-length-block"),
57
+ pytest.param(4, 1, False, 10, False, False, id="single-token-padded"),
58
+ pytest.param(4, 6, False, 10, True, True, id="long-block-explicit-cache"),
59
+ pytest.param(4, 6, False, 16, False, True, id="long-block-padded"),
60
+ pytest.param(4, 2, True, 10, True, True, id="full-prompt-explicit-cache"),
61
+ pytest.param(0, 6, True, 10, False, False, id="prefill-padded-capacity"),
62
+ ],
63
+ )
64
+ @pytest.mark.parametrize("left_padding", [0, 2])
65
+ @torch.inference_mode()
66
+ def test_cached_logits_match_full_forward(
67
+ model, cache_type, past_length, new_length, full_prompt, capacity,
68
+ visible_tail, explicit_cache, left_padding,
69
+ ):
70
+ total = past_length + new_length
71
+ tokens = torch.arange(3, 3 + total).unsqueeze(0).repeat(2, 1)
72
+ mask = torch.ones(2, capacity, dtype=torch.long)
73
+ mask[0, :left_padding] = 0
74
+ if not visible_tail:
75
+ mask[:, total:] = 0
76
+ cache = (
77
+ StaticCache(config=model.config, max_cache_len=capacity)
78
+ if cache_type == "static" else DynamicCache()
79
+ )
80
+ if past_length:
81
+ model(
82
+ input_ids=tokens[:, :past_length],
83
+ attention_mask=mask[:, :past_length],
84
+ position_ids=positions(mask[:, :past_length]),
85
+ past_key_values=cache,
86
+ use_cache=True,
87
+ )
88
+ prepared = model.prepare_inputs_for_generation(
89
+ tokens if full_prompt else tokens[:, past_length:],
90
+ past_key_values=cache,
91
+ attention_mask=mask,
92
+ cache_position=torch.arange(past_length, total) if explicit_cache else None,
93
+ use_cache=True,
94
+ )
95
+ # Execute even on the buggy source to capture the cache and numerical regression.
96
+ prepared["logits_to_keep"] = 0
97
+ actual = model(**prepared).logits
98
+ expected = model(
99
+ input_ids=tokens,
100
+ attention_mask=mask[:, :total],
101
+ position_ids=positions(mask[:, :total]),
102
+ use_cache=False,
103
+ ).logits[:, past_length:]
104
+ error = (actual[:, -new_length:] - expected).abs().max().item()
105
+ detail = (
106
+ f"cache_length={int(cache.get_seq_length())}, "
107
+ f"positions={prepared['position_ids'].tolist()}, max_logit_error={error:.8g}"
108
+ )
109
+ assert int(cache.get_seq_length()) == total, detail
110
+ assert torch.equal(prepared["input_ids"], tokens[:, past_length:]), detail
111
+ assert torch.equal(prepared["cache_position"], torch.arange(past_length, total)), detail
112
+ assert torch.equal(prepared["position_ids"], positions(mask)[:, past_length:total]), detail
113
+ torch.testing.assert_close(actual, expected, atol=2e-6, rtol=2e-5, msg=detail)
114
+
115
+
116
+ @pytest.mark.parametrize("provided_positions", ["full", "capacity", "new"])
117
+ @torch.inference_mode()
118
+ def test_explicit_position_ids(model, provided_positions):
119
+ tokens = torch.arange(3, 9).unsqueeze(0)
120
+ cache = model(input_ids=tokens[:, :4], use_cache=True).past_key_values
121
+ # Custom caller positions must be preserved, including when already sliced.
122
+ position_ids = {
123
+ "full": torch.arange(20, 26).unsqueeze(0),
124
+ "capacity": torch.arange(20, 30).unsqueeze(0),
125
+ "new": torch.tensor([[24, 25]]),
126
+ }[provided_positions]
127
+ prepared = model.prepare_inputs_for_generation(
128
+ tokens,
129
+ past_key_values=cache,
130
+ attention_mask=torch.ones(1, 10, dtype=torch.long),
131
+ position_ids=position_ids,
132
+ )
133
+ assert prepared["input_ids"].tolist() == [[7, 8]]
134
+ assert prepared["position_ids"].tolist() == [[24, 25]]
135
+
136
+
137
+ @torch.inference_mode()
138
+ def test_generate_left_padded_batch(model):
139
+ tokens = torch.tensor([[0, 0, 3, 4], [5, 6, 7, 8]])
140
+ mask = torch.tensor([[0, 0, 1, 1], [1, 1, 1, 1]])
141
+ options = dict(max_new_tokens=3, do_sample=False, pad_token_id=0, eos_token_id=None)
142
+ batched = model.generate(tokens, attention_mask=mask, **options)
143
+ for row, length in enumerate([2, 4]):
144
+ unpadded = tokens[row:row + 1, -length:]
145
+ single = model.generate(unpadded, attention_mask=torch.ones_like(unpadded), **options)
146
+ assert torch.equal(batched[row, -3:], single[0, -3:])