Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- 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

Expand Down
6 changes: 2 additions & 4 deletions llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -2237,14 +2235,14 @@ 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,
)

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()
Expand Down
26 changes: 26 additions & 0 deletions tests/test_llama.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import ctypes
import itertools
import multiprocessing
from types import SimpleNamespace

import numpy as np
from scipy.special import log_softmax
Expand All @@ -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)

Expand Down Expand Up @@ -486,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
Expand Down