|
| 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