From bf32553146c9656f2cc03a0aef4c84b8dfb0e26a Mon Sep 17 00:00:00 2001 From: hechunqiu <1071964254@qq.com> Date: Wed, 2 Dec 2026 19:00:27 +0800 Subject: [PATCH 1/3] perf(cache): avoid an extra copy when saving model state --- CHANGELOG.md | 1 + llama_cpp/llama.py | 4 +--- tests/test_llama.py | 24 ++++++++++++++++++++++++ 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917b..b9e56cd47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- perf(cache): avoid an extra copy when saving model state by @hellomiku831 - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 1b4daf6b9..9712e743c 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2226,8 +2226,6 @@ def save_state(self) -> LlamaState: print(f"Llama.save_state: copied llama state: {n_bytes}", file=sys.stderr) if int(n_bytes) > int(state_size): raise RuntimeError("Failed to copy llama state data") - llama_state_compact = (ctypes.c_uint8 * int(n_bytes))() - llama_cpp.ctypes.memmove(llama_state_compact, llama_state, int(n_bytes)) if self.verbose: print( f"Llama.save_state: saving {n_bytes} bytes of llama state", @@ -2237,7 +2235,7 @@ def save_state(self) -> LlamaState: scores=self._scores.copy(), input_ids=self.input_ids.copy(), n_tokens=self.n_tokens, - llama_state=bytes(llama_state_compact), + llama_state=ctypes.string_at(llama_state, n_bytes), llama_state_size=n_bytes, seed=self._seed, ) diff --git a/tests/test_llama.py b/tests/test_llama.py index 8c1512d49..dd69000cc 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -1,6 +1,7 @@ import ctypes import itertools import multiprocessing +from types import SimpleNamespace import numpy as np from scipy.special import log_softmax @@ -20,6 +21,29 @@ def test_llama_cpp_version(): assert llama_cpp.__version__ +def test_save_state_copies_only_written_bytes(monkeypatch): + model = SimpleNamespace( + verbose=False, + _ctx=SimpleNamespace(ctx=None), + _scores=np.empty((0, 0), dtype=np.single), + input_ids=np.empty(0, dtype=np.intc), + n_tokens=0, + _seed=0, + ) + data = b"a\x00b" + + def write_state(ctx, destination, size): + ctypes.memmove(destination, data, len(data)) + return len(data) + + monkeypatch.setattr(llama_cpp.llama_cpp, "llama_state_get_size", lambda ctx: 8) + monkeypatch.setattr(llama_cpp.llama_cpp, "llama_state_get_data", write_state) + state = llama_cpp.Llama.save_state(model) + assert isinstance(state.llama_state, bytes) + assert state.llama_state == data + assert state.llama_state_size == len(data) + + def test_llama_cpp_tokenization(): llama = llama_cpp.Llama(model_path=MODEL, vocab_only=True, verbose=False) From f68e9b877796434a7fea13bbde890d85af6c7904 Mon Sep 17 00:00:00 2001 From: hechunqiu <1071964254@qq.com> Date: Wed, 2 Dec 2026 19:01:41 +0800 Subject: [PATCH 2/3] docs: link the cache change to #2474 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b9e56cd47..0be045d44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- perf(cache): avoid an extra copy when saving model state by @hellomiku831 +- perf(cache): avoid an extra copy when saving model state by @hellomiku831 in #2474 - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds From a341d6944e288a8b06411b87e5650176f305766f Mon Sep 17 00:00:00 2001 From: hechunqiu <1071964254@qq.com> Date: Fri, 4 Dec 2026 11:10:02 +0800 Subject: [PATCH 3/3] perf(cache): copy saved scores directly into the context on restore --- CHANGELOG.md | 2 +- llama_cpp/llama.py | 2 +- tests/test_llama.py | 2 ++ 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0be045d44..3f601fbe5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- perf(cache): avoid an extra copy when saving model state by @hellomiku831 in #2474 +- perf(cache): avoid extra copies when saving and restoring model state by @hellomiku831 in #2474 - fix: load cached pretrained models in offline mode by @emme1t in #2396 - fix(ci): install matching NVML headers for CUDA wheel builds diff --git a/llama_cpp/llama.py b/llama_cpp/llama.py index 9712e743c..a7f48b451 100644 --- a/llama_cpp/llama.py +++ b/llama_cpp/llama.py @@ -2242,7 +2242,7 @@ def save_state(self) -> LlamaState: def load_state(self, state: LlamaState) -> None: # Only filling in up to `n_tokens` and then zero-ing out the rest - self.scores[: state.n_tokens, :] = state.scores.copy() + self.scores[: state.n_tokens, :] = state.scores rest = self.scores[state.n_tokens :, :] rest[rest > 0] = 0.0 self.input_ids = state.input_ids.copy() diff --git a/tests/test_llama.py b/tests/test_llama.py index dd69000cc..bbb596a84 100644 --- a/tests/test_llama.py +++ b/tests/test_llama.py @@ -510,6 +510,8 @@ def _assert_loaded_exact_cached_prompt_reuse_matches_fresh( assert loaded.n_tokens == len(tokens) assert loaded.input_ids[: loaded.n_tokens].tolist() == tokens + np.testing.assert_array_equal(loaded._scores, state.scores) + assert not np.shares_memory(loaded.scores, state.scores) loaded_tokens = _generate_test_tokens(loaded, tokens) assert loaded_tokens == expected_tokens