The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): price a split GGUF as the sum of its shards
Konstantin Khlopkov48d89901c78b
diff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.pyindex e0238862350..72e6ee04e43 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -6,11 +6,14 @@ run at picker time on multi-GB files.from __future__ import annotations+import loggingimport reimport structfrom dataclasses import dataclass, fieldfrom pathlib import Path+logger = logging.getLogger(__name__)+_GGUF_MAGIC = b"GGUF"# Split GGUF naming: "<stem>-00001-of-00003.gguf"; the part suffix is not part of the model id.@@ -181,9 +184,24 @@ class GGUFHeader:return self.head_dim_k-def read_gguf_header(path: str | Path) -> GGUFHeader:- path = Path(path)+def _split_parts(path: Path) -> "list[Path] | None":+ """Every on-disk part of the split ``path`` belongs to, first part first; None when ``path`` is+ not a split member or no other part is present.++ A split is priced as the set, never as one file: publishers lay shards out so the first part+ can hold little more than metadata while the bulk sits in the later ones, so reading one part+ prices the model at whatever fraction of its weights that part happens to hold."""+ m = SPLIT_PART_RE.search(path.name)+ if m is None:+ return None+ stem, total = path.name[: m.start()], int(m.group(2))+ parts = [p for p in (path.with_name(f"{stem}-{i:05d}-of-{total:05d}.gguf")+ for i in range(1, total + 1)) if p.is_file()]+ return parts if len(parts) > 1 else None++def _read_part(path: Path) -> GGUFHeader:+ """One file's own header: metadata and that file's tensor table."""def read(f, fmt: str):return struct.unpack(fmt, f.read(struct.calcsize(fmt)))@@ -237,3 +255,47 @@ def read_gguf_header(path: str | Path) -> GGUFHeader:return GGUFHeader(path=str(path), version=version, metadata=metadata,n_tensors=n_tensors, tensor_bytes=tensor_bytes,embd_table_bytes=embd_bytes, ffn_block_bytes=ffn_block_bytes)+++def read_gguf_header(path: str | Path) -> GGUFHeader:+ """Header for a MODEL, not for a file: a split GGUF is priced as the sum of its parts.++ Weights, the host-side embedding-table duplicate and the per-block FFN map are all summed+ across the shards on disk, because a split is a layout choice, not a smaller model — pricing+ part 1 alone underprices every model whose first shard is a metadata stub (the Hugging Face+ layout), which then makes the physics check and the residency cap admit giants the card cannot+ hold. Architecture metadata (block count, train context, the per-layer SWA pattern, vocab) is+ taken from the first part, which is where GGUF writes it.++ A part that has gone missing or become unreadable is skipped rather than fatal: a half-arrived+ split prices at what is actually on disk. Refusing it is ``staged_in(require_complete=True)``'s+ job — an incomplete split is never servable, it is only underpriced here."""+ path = Path(path)+ parts = _split_parts(path)+ if parts is None:+ return _read_part(path)++ first = _read_part(parts[0])+ readable = [first]+ for part in parts[1:]:+ try:+ readable.append(_read_part(part))+ except (ValueError, OSError, struct.error) as exc:+ # struct.error is neither ValueError nor OSError, and it is what a header cut+ # mid-stream actually raises. A part that cannot be parsed is priced out, not fatal.+ logger.debug("split part unreadable %s: %s", part.name, exc)+ if len(readable) == 1:+ return first++ ffn_block_bytes: dict[int, int] = {}+ for header in readable:+ for block, nbytes in header.ffn_block_bytes.items():+ ffn_block_bytes[block] = ffn_block_bytes.get(block, 0) + nbytes+ return GGUFHeader(+ # The path stays the part the caller named: it is the model id source and the preset's+ # ``model`` key, and llama.cpp resolves the split from any one of its members.+ path=str(path), version=first.version, metadata=first.metadata,+ n_tensors=sum(h.n_tensors for h in readable),+ tensor_bytes=sum(h.tensor_bytes for h in readable),+ embd_table_bytes=sum(h.embd_table_bytes for h in readable),+ ffn_block_bytes=ffn_block_bytes)diff --git a/tests/hermes_cli/test_local_runtime_gguf_split.py b/tests/hermes_cli/test_local_runtime_gguf_split.pynew file mode 100644index 00000000000..ef627622ca1--- /dev/null+++ b/tests/hermes_cli/test_local_runtime_gguf_split.py@@ -0,0 +1,173 @@+"""A split GGUF is priced as the SET of its shards, never as its first file.++Publishers lay split shards out so the first part can hold little more than metadata while the+bulk of the weights sits in the later ones. A reader that stops at part 1 therefore prices the+model at whatever fraction of its weights that part happens to hold — cheap enough for the physics+check and the residency cap to admit giants the card cannot hold, which is how two such giants+came to co-reside and take the whole router down with OOM.++These are the synthetic equivalents of that report: a first part with an empty tensor table, an+embedding table that lives outside part 1, and per-block FFN weights spread across shards (whose+truncation also silently disabled spill placement, the lever that would have relieved the+pressure).+"""++from __future__ import annotations++import re+import struct++from hermes_cli.local_runtime.context_policy import spill_overrides+from hermes_cli.local_runtime.estimator import profile_from_gguf+from hermes_cli.local_runtime.gguf import read_gguf_header++GIB = 1 << 30+++def _gguf_str(s: str) -> bytes:+ b = s.encode()+ return struct.pack("<Q", len(b)) + b+++def _write_gguf(path, metadata: dict, tensors: list[tuple[str, int]]) -> None:+ """Minimal GGUF v3: uint32/string metadata, 1-D f32 tensors of ``elems`` elements."""+ out = b"GGUF" + struct.pack("<IQQ", 3, len(tensors), len(metadata))+ for key, value in metadata.items():+ out += _gguf_str(key)+ out += (struct.pack("<I", 8) + _gguf_str(value) if isinstance(value, str)+ else struct.pack("<II", 4, value))+ for name, elems in tensors:+ out += _gguf_str(name) + struct.pack("<IQIQ", 1, elems, 0, 0)+ path.write_bytes(out)+++ARCH = {+ "general.architecture": "llama",+ "llama.block_count": 12,+ "llama.context_length": 65536,+ "llama.attention.head_count": 8,+ "llama.attention.head_count_kv": 2,+ "llama.attention.key_length": 128,+ "llama.attention.value_length": 128,+}+++def _split(tmp_path, stem: str, parts: list[dict], total: int | None = None):+ """A split on disk: ``parts[i]`` is the metadata + tensor table of shard i+1."""+ total = total or len(parts)+ written = []+ for i, spec in enumerate(parts, start=1):+ path = tmp_path / f"{stem}-{i:05d}-of-{total:05d}.gguf"+ _write_gguf(path, spec.get("metadata", ARCH), spec.get("tensors", []))+ written.append(path)+ return written+++def test_split_weights_are_the_sum_across_shards(tmp_path):+ """The reported bug exactly: part 1 is a metadata stub (``n_tensors = 0``), the weights are in+ the later parts, so a reader that stops at part 1 prices the model at nothing."""+ parts = _split(tmp_path, "qwen-flash", [+ {"tensors": []}, # metadata stub, 0 tensors+ {"tensors": [("blk.0.attn_q.weight", 32 << 20)]}, # 128 MiB+ {"tensors": [("blk.1.attn_q.weight", 64 << 20)]}, # 256 MiB+ ])++ header = read_gguf_header(parts[0])++ assert header.n_tensors == 2+ assert header.tensor_bytes == ((32 + 64) * 4) << 20+ # Architecture still comes from the first part, so KV/layer pricing is unaffected.+ assert header.n_layer == 12 and header.n_ctx_train == 65536+ assert profile_from_gguf(header).weights_bytes == header.tensor_bytes+++def test_single_shard_model_is_unchanged(tmp_path):+ """The fan-out must not disturb an unsplit file."""+ gguf = tmp_path / "single.gguf"+ _write_gguf(gguf, ARCH, [("blk.0.attn_q.weight", 16 << 20)])+ assert read_gguf_header(gguf).tensor_bytes == 64 << 20+++def test_naming_alone_is_not_a_split(tmp_path):+ """A split whose siblings are not on disk prices as the one file that is, rather than raising."""+ only = tmp_path / "half-00001-of-00003.gguf"+ _write_gguf(only, ARCH, [("blk.0.attn_q.weight", 16 << 20)])+ assert read_gguf_header(only).tensor_bytes == 64 << 20+++def test_embedding_table_outside_part_one_is_still_priced(tmp_path):+ """``embd_table_bytes`` prices the host-side duplicate of a fully offloaded embedding table.+ When that tensor sits outside part 1 the duplicate was priced at 0, understating the load by+ however large the table is."""+ parts = _split(tmp_path, "embd-split", [+ {"tensors": []},+ {"tensors": [("token_embd.weight", 8 << 20)]},+ ])++ header = read_gguf_header(parts[0])++ assert header.embd_table_bytes == 32 << 20+ assert header.embd_table_bytes <= header.tensor_bytes+++def test_ffn_blocks_spread_across_shards_still_place_spill(tmp_path):+ """Truncating the per-block FFN map also disabled spill placement: ``recurrent_spill_blocks``+ spills every recurrent block as soon as one is missing from the map, so a split whose FFNs sit+ in later parts lost the ability to spill just enough."""+ hybrid = dict(ARCH, **{"llama.full_attention_interval": 4})+ tensors = [("token_embd.weight", 64)]+ for i in range(12):+ tensors += [(f"blk.{i}.attn_norm.weight", 16), (f"blk.{i}.ffn_norm.weight", 16),+ (f"blk.{i}.ffn_up.weight", 256), (f"blk.{i}.ffn_down.weight", 240)]+ parts = _split(tmp_path, "hybrid-split", [+ {"metadata": hybrid, "tensors": tensors[:1]},+ {"metadata": hybrid, "tensors": tensors[1:37]}, # blocks 0-8 (4 tensors each)+ {"metadata": hybrid, "tensors": tensors[37:]}, # blocks 9-11+ ], total=3)++ profile = profile_from_gguf(read_gguf_header(parts[0]))+ per_block = (16 + 256 + 240) * 4 # f32; attn_norm is not an FFN tensor+ assert profile.ffn_block_bytes == {i: per_block for i in range(12)}++ # Enough spill for two recurrent blocks' FFNs, so the placement is a choice, not "everything".+ args = spill_overrides(profile, 2 * per_block)+ pattern = args[1].removesuffix("=CPU")+ moved = [i for i in range(12) if re.search(pattern, f"blk.{i}.ffn_up.weight")]+ assert moved == [0, 1]+++def test_unreadable_shard_does_not_price_the_split_away(tmp_path):+ """A part that is corrupt or truncated is skipped, not fatal: a half-arrived split prices at+ what is on disk. Refusing it to serve is ``staged_in(require_complete=True)``'s job."""+ parts = _split(tmp_path, "half-downloaded", [+ {"tensors": [("blk.0.attn_q.weight", 16 << 20)]},+ {"tensors": [("blk.1.attn_q.weight", 16 << 20)]},+ {"tensors": [("blk.2.attn_q.weight", 16 << 20)]},+ ])+ parts[1].write_bytes(b"GGUF\x03\x00") # header cut mid-stream++ header = read_gguf_header(parts[0])++ assert header.tensor_bytes == 2 * (64 << 20) # parts 1 and 3; the truncated one dropped+++def test_residency_cap_prices_a_split_against_the_card(tmp_path, monkeypatch):+ """The consequence, not just the reader: a fleet whose largest model is a split must not be+ admitted ``models_max`` times over. Two giants co-resided because the probe saw a 175 GB model+ as a few GiB and booted the router with room for three."""+ from hermes_cli.local_runtime import presets+ from hermes_cli.local_runtime.estimator import HardwareBudget++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ mdir = tmp_path / "models"+ mdir.mkdir()+ # A 48 GiB split laid out the reported way: part 1 a metadata stub, the weights in part 2.+ _write_gguf(mdir / "giant-00001-of-00002.gguf", ARCH, [])+ _write_gguf(mdir / "giant-00002-of-00002.gguf", ARCH, [("blk.0.attn_q.weight", 48 * GIB // 4)])+ # A 10 GB single-shard neighbour: a small second resident must stay possible.+ _write_gguf(mdir / "utility.gguf", ARCH, [("blk.0.attn_q.weight", 10 * GIB // 4)])++ budget = HardwareBudget(usable_vram_bytes=64 * GIB, total_device_bytes=64 * GIB,+ ram_available_bytes=64 * GIB)++ assert presets.admitted_residency_count(mdir, budget, 4) == 1\ No newline at end of file