From 04fb1bea9f24881ef020ed1e249beb5ac33e24ef Mon Sep 17 00:00:00 2001 From: Steven Huang <134844631+remote-controlled-man@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:29:24 +0800 Subject: [PATCH] fix: preserve GGUF metadata at buffer boundaries --- CHANGELOG.md | 2 + llama_cpp/_internals.py | 5 ++- tests/test_llama_metadata.py | 75 ++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 tests/test_llama_metadata.py diff --git a/CHANGELOG.md b/CHANGELOG.md index bfa7e917bd..9d67c75b55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/llama_cpp/_internals.py b/llama_cpp/_internals.py index b45d34b2c4..667ed66c72 100644 --- a/llama_cpp/_internals.py +++ b/llama_cpp/_internals.py @@ -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 @@ -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( @@ -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( diff --git a/tests/test_llama_metadata.py b/tests/test_llama_metadata.py new file mode 100644 index 0000000000..36fc1688a6 --- /dev/null +++ b/tests/test_llama_metadata.py @@ -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("