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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- fix: preserve GGUF metadata at buffer boundaries by @remote-controlled-man

- fix: load cached pretrained models in offline mode by @emme1t in #2396
- fix(ci): install matching NVML headers for CUDA wheel builds

Expand Down
5 changes: 3 additions & 2 deletions llama_cpp/_internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ def detokenize(self, tokens: List[int], special: bool = False) -> bytes:
# Extra
def metadata(self) -> Dict[str, str]:
metadata: Dict[str, str] = {}
# Native string lengths exclude the terminating null byte.
buffer_size = 1024
buffer = ctypes.create_string_buffer(buffer_size)
# zero the buffer
Expand All @@ -218,7 +219,7 @@ def metadata(self) -> Dict[str, str]:
nbytes = llama_cpp.llama_model_meta_key_by_index(
self.model, i, buffer, buffer_size
)
if nbytes > buffer_size:
if nbytes >= buffer_size:
buffer_size = nbytes + 1
buffer = ctypes.create_string_buffer(buffer_size)
nbytes = llama_cpp.llama_model_meta_key_by_index(
Expand All @@ -228,7 +229,7 @@ def metadata(self) -> Dict[str, str]:
nbytes = llama_cpp.llama_model_meta_val_str_by_index(
self.model, i, buffer, buffer_size
)
if nbytes > buffer_size:
if nbytes >= buffer_size:
buffer_size = nbytes + 1
buffer = ctypes.create_string_buffer(buffer_size)
nbytes = llama_cpp.llama_model_meta_val_str_by_index(
Expand Down
75 changes: 75 additions & 0 deletions tests/test_llama_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import struct
from pathlib import Path

import pytest

import llama_cpp


def _write_vocab_model(tmp_path, metadata):
# This tracked GGUF contains vocabulary metadata only, with no tensor offsets.
source = Path("vendor/llama.cpp/models/ggml-vocab-llama-spm.gguf").read_bytes()
magic, version, tensor_count, metadata_count = struct.unpack("<4sIQQ", source[:24])
assert (magic, version, tensor_count) == (b"GGUF", 3, 0)

def gguf_string(value):
encoded = value.encode("utf-8")
return struct.pack("<Q", len(encoded)) + encoded

entries = b"".join(
gguf_string(key) + struct.pack("<I", 8) + gguf_string(value)
for key, value in metadata.items()
)
path = tmp_path / "metadata.gguf"
path.write_bytes(
source[:16]
+ struct.pack("<Q", metadata_count + len(metadata))
+ entries
+ source[24:]
)
return str(path)


@pytest.mark.parametrize("size", [1023, 1024, 1025])
def test_chat_template_at_metadata_buffer_boundary(tmp_path, size):
prefix, suffix = "{{ messages[0]['content'] }}{#", "#}"
template = prefix + "x" * (size - len(prefix) - len(suffix)) + suffix
path = _write_vocab_model(tmp_path, {"tokenizer.chat_template": template})
model = llama_cpp.Llama(model_path=path, vocab_only=True, verbose=False)
try:
assert model.metadata["tokenizer.chat_template"] == template
assert model.chat_format == "chat_template.default"
finally:
model.close()


@pytest.mark.parametrize("size", [1023, 1024, 1025])
@pytest.mark.parametrize("field", ["key", "value"])
@pytest.mark.parametrize("ending", ["x", "é"], ids=["ascii", "utf8"])
def test_metadata_buffer_boundaries(tmp_path, size, field, ending):
text = "x" * (size - len(ending.encode("utf-8"))) + ending
key, value = (text, "value") if field == "key" else ("test.value", text)
template = "{{ messages[0]['content'] }}"
path = _write_vocab_model(
tmp_path, {key: value, "tokenizer.chat_template": template}
)
model = llama_cpp.Llama(model_path=path, vocab_only=True, verbose=False)
try:
assert model.metadata[key] == value
assert model.metadata["tokenizer.chat_template"] == template
assert model.chat_format == "chat_template.default"
finally:
model.close()


@pytest.mark.parametrize("ending", ["x", "é"], ids=["ascii", "utf8"])
def test_metadata_value_at_resized_buffer_boundary(tmp_path, ending):
# Reading this key grows the buffer to 1101 bytes before reading its value.
key = "x" * 1100
value = "y" * (1101 - len(ending.encode("utf-8"))) + ending
path = _write_vocab_model(tmp_path, {key: value})
model = llama_cpp.Llama(model_path=path, vocab_only=True, verbose=False)
try:
assert model.metadata[key] == value
finally:
model.close()
Loading