Skip to content

Commit 6f2012f

Browse files
committed
Restore KVzip forward after context errors πŸ€–πŸ€–πŸ€–
Signed-off-by: Minh Vu <vuhoangminh97@gmail.com>
1 parent fee1af1 commit 6f2012f

2 files changed

Lines changed: 67 additions & 2 deletions

File tree

β€Žkvpress/presses/kvzip_press.pyβ€Ž

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,10 @@ def wrapped_forward(model_self, *args, **kwargs):
126126

127127
hooks = []
128128
try:
129-
yield
130-
model.model.forward = original_forward # Restore original
129+
try:
130+
yield
131+
finally:
132+
model.model.forward = original_forward
131133

132134
# After yield: KVzip scoring and compression phase
133135
if self.compression_ratio > 0 and self._context_ids is not None:
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 1993-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
from types import SimpleNamespace
5+
6+
import pytest
7+
import torch
8+
9+
import kvpress.presses.kvzip_press as kvzip_press_module
10+
from kvpress import KVzipPress
11+
12+
13+
class FakeTokenizer:
14+
chat_template = None
15+
16+
def encode(self, text, return_tensors=None, add_special_tokens=False):
17+
return torch.tensor([[0]])
18+
19+
20+
class FakeInnerModel:
21+
layers = []
22+
rotary_emb = None
23+
24+
def forward(self, *args, **kwargs):
25+
return None
26+
27+
28+
class FakeModel:
29+
def __init__(self):
30+
self.config = SimpleNamespace(name_or_path="fake-model")
31+
self.model = FakeInnerModel()
32+
33+
34+
class RecordingKVzipPress(KVzipPress):
35+
def _perform_kvzip_compression(self, model, tokenizer):
36+
self.forward_during_compression = model.model.forward
37+
38+
39+
def test_kvzip_press_restores_model_forward_if_context_raises(monkeypatch):
40+
monkeypatch.setattr(kvzip_press_module.AutoTokenizer, "from_pretrained", lambda _: FakeTokenizer())
41+
model = FakeModel()
42+
original_forward = model.model.forward
43+
press = KVzipPress(compression_ratio=0)
44+
45+
with pytest.raises(RuntimeError):
46+
with press(model):
47+
assert model.model.forward != original_forward
48+
raise RuntimeError("boom")
49+
50+
assert model.model.forward == original_forward
51+
52+
53+
def test_kvzip_press_restores_model_forward_before_compression(monkeypatch):
54+
monkeypatch.setattr(kvzip_press_module.AutoTokenizer, "from_pretrained", lambda _: FakeTokenizer())
55+
model = FakeModel()
56+
original_forward = model.model.forward
57+
press = RecordingKVzipPress(compression_ratio=0.5)
58+
59+
with press(model):
60+
model.model.forward(input_ids=torch.tensor([[1]]), past_key_values=object())
61+
62+
assert press.forward_during_compression == original_forward
63+
assert model.model.forward == original_forward

0 commit comments

Comments
Β (0)