The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(local-runtime): price tensors the engine reads from disk as not loaded
emozillaa6d292d3bb39
diff --git a/hermes_cli/local_runtime/catalog.py b/hermes_cli/local_runtime/catalog.pyindex 86f42987731..924ba5fd9de 100644--- a/hermes_cli/local_runtime/catalog.py+++ b/hermes_cli/local_runtime/catalog.py@@ -51,6 +51,9 @@ class QuantVariant:quant: str # e.g. "UD-Q4_K_M"files: tuple # AssetFile, first = the load targetvalidated: bool = False # proven end-to-end on real hardware+ # Bytes of tensors the engine reads from the file on demand instead of loading (see+ # gguf._LAZY_READ_TENSORS), taken from the build's tensor table at authoring time.+ lazy_bytes: int = 0@propertydef model_id(self) -> str:@@ -62,9 +65,10 @@ class QuantVariant:@propertydef weights_bytes(self) -> int:- """Pre-download weights estimate: GGUF bytes ≈ tensor bytes + a <2% header — slightly- conservative until profile_from_gguf reads the real table."""- return self.size_bytes+ """Pre-download estimate of the weights the engine loads: GGUF bytes ≈ tensor bytes + a <2%+ header, less the tensors it reads from disk on demand — slightly conservative until+ profile_from_gguf reads the real table."""+ return self.size_bytes - self.lazy_bytes@dataclass(frozen=True)@@ -280,7 +284,8 @@ def _load_catalog(doc: dict) -> "tuple[CatalogEntry, ...]":entries = []for m in doc["models"]:variants = tuple(QuantVariant(quant=v["quant"], validated=bool(v.get("validated")),- files=tuple(_asset_from(f) for f in v["files"]))+ files=tuple(_asset_from(f) for f in v["files"]),+ lazy_bytes=int(v.get("lazy_bytes", 0)))for v in m["variants"])scalars = {k: coerce(m[k] if default is None else m.get(k, default))for k, (coerce, default) in _SCALAR_FIELDS.items()}diff --git a/hermes_cli/local_runtime/estimator.py b/hermes_cli/local_runtime/estimator.pyindex 0bd5ff4411f..7cb4d6827f6 100644--- a/hermes_cli/local_runtime/estimator.py+++ b/hermes_cli/local_runtime/estimator.py@@ -55,7 +55,7 @@ class ModelProfile:construct profiles directly."""name: str- weights_bytes: int+ weights_bytes: int # weights the engine loads; tensors it reads from disk on demand are notembd_table_bytes: intn_ctx_train: intlayers: list[tuple[LayerKind, int]] # (kind, kv_bytes_per_token_f16); SWA capped, recurrent ignored@@ -135,7 +135,8 @@ def profile_from_gguf(header: GGUFHeader) -> ModelProfile:n_attn_seen += 1return ModelProfile(- name=header.path, weights_bytes=header.tensor_bytes, embd_table_bytes=header.embd_table_bytes,+ name=header.path, weights_bytes=header.tensor_bytes - header.lazy_bytes,+ embd_table_bytes=header.embd_table_bytes,n_ctx_train=header.n_ctx_train, layers=layers, swa_window=header.sliding_window,moe=header.expert_count > 0, architecture=header.architecture, n_vocab=header.n_vocab,ffn_block_bytes=dict(header.ffn_block_bytes))diff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.pyindex 3531f134aef..5d4650eff85 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -22,6 +22,17 @@ _PART_SUFFIX_RE = re.compile(r"-\d{5}-of-\d{5}$")# Same tensor selection as context_policy's per-block FFN -ot override._FFN_WEIGHT = re.compile(r"blk\.(\d+)\.ffn_.*\.weight")+# Tensors llama.cpp leaves in the file and reads row by row on demand instead of loading them+# (create_tensor's TENSOR_READ_LAZY, marked per architecture in the engine's model code). Under the+# engine's default --lazy-mode auto, only a marked tensor larger than 4 GiB is read this way;+# a smaller one loads like any other weight.+_LAZY_READ_TENSORS = {+ "qwen4exp": frozenset({"per_layer_token_embd.weight"}),+ "gemma4": frozenset({"per_layer_token_embd.weight"}),+}+_LAZY_READ_CANDIDATES = frozenset().union(*_LAZY_READ_TENSORS.values())+_LAZY_READ_MIN_BYTES = 4 << 30+def model_id_from_stem(stem: str) -> str:"""Model id from a GGUF file stem (split-part suffix stripped)."""@@ -66,6 +77,9 @@ class GGUFHeader:# block index -> bytes of that block's FFN weights (the tensors a `blk\.N\.ffn_.*\.weight`# -ot override moves), so spill placement can move only as many blocks as it needs.ffn_block_bytes: dict[int, int] = field(default_factory=dict)+ # Sizes of the tensors some architecture reads lazily, by name. ``lazy_bytes`` applies this+ # model's architecture and the size threshold.+ lazy_candidate_bytes: dict[str, int] = field(default_factory=dict)# ── typed accessors ──────────────────────────────────────@@ -73,6 +87,13 @@ class GGUFHeader:def architecture(self) -> str:return str(self.metadata.get("general.architecture", ""))+ @property+ def lazy_bytes(self) -> int:+ """Bytes of weights llama.cpp keeps on disk and reads row by row instead of loading."""+ marked = _LAZY_READ_TENSORS.get(self.architecture, frozenset())+ return sum(nbytes for name, nbytes in self.lazy_candidate_bytes.items()+ if name in marked and nbytes > _LAZY_READ_MIN_BYTES)+def _arch_key(self, suffix: str):return self.metadata.get(f"{self.architecture}.{suffix}")@@ -237,6 +258,7 @@ def _read_part(path: Path) -> GGUFHeader:tensor_bytes = 0embd_bytes = 0ffn_block_bytes: dict[int, int] = {}+ lazy_candidate_bytes: dict[str, int] = {}for _ in range(n_tensors):name = read_str(f)(n_dims,) = read(f, "<I")@@ -257,10 +279,13 @@ def _read_part(path: Path) -> GGUFHeader:elif m := _FFN_WEIGHT.match(name):block = int(m.group(1))ffn_block_bytes[block] = ffn_block_bytes.get(block, 0) + nbytes+ elif name in _LAZY_READ_CANDIDATES:+ lazy_candidate_bytes[name] = nbytesreturn 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)+ embd_table_bytes=embd_bytes, ffn_block_bytes=ffn_block_bytes,+ lazy_candidate_bytes=lazy_candidate_bytes)def read_gguf_header(path: str | Path) -> GGUFHeader:@@ -303,4 +328,6 @@ def read_gguf_header(path: str | Path) -> GGUFHeader: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)+ ffn_block_bytes=ffn_block_bytes,+ lazy_candidate_bytes={name: nbytes for h in readable+ for name, nbytes in h.lazy_candidate_bytes.items()})diff --git a/tests/hermes_cli/test_local_runtime_lazy_read.py b/tests/hermes_cli/test_local_runtime_lazy_read.pynew file mode 100644index 00000000000..0f69bbc7dbd--- /dev/null+++ b/tests/hermes_cli/test_local_runtime_lazy_read.py@@ -0,0 +1,100 @@+"""Tensors llama.cpp reads from disk on demand are not priced as loaded weights.++The engine's model loader leaves a tensor its architecture marks TENSOR_READ_LAZY in the file and+reads that tensor's rows when a token needs them. Under the default ``--lazy-mode auto`` it does so+only for a marked tensor larger than 4 GiB. Qwen3.8 Flash Next's 26.8 GiB per-layer embedding+table is one: priced as loaded, the IQ4_XS build needs ~87 GiB and a 128 GB unified-memory machine+refuses it; priced the way the engine loads it, the build holds ~60 GiB.+"""++from __future__ import annotations++import struct++from hermes_cli.local_runtime.catalog import AssetFile, QuantVariant+from hermes_cli.local_runtime.estimator import profile_from_gguf+from hermes_cli.local_runtime.gguf import read_gguf_header++GIB = 1 << 30+OVER_4_GIB = (4 * GIB) // 4 + 256 # f32 elements: 4 GiB + 1 KiB+EXACTLY_4_GIB = (4 * GIB) // 4+++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:+ """Header-only GGUF v3: uint32/string metadata, 1-D f32 tensors of ``elems`` elements. The+ reader never touches tensor data, so a header prices exactly like the full file."""+ 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)+++def _arch(name: str) -> dict:+ return {"general.architecture": name, f"{name}.block_count": 4,+ f"{name}.context_length": 65536, f"{name}.attention.head_count": 8,+ f"{name}.attention.head_count_kv": 2, f"{name}.attention.key_length": 128}+++def test_a_marked_table_over_4_gib_stays_out_of_the_loaded_weights(tmp_path):+ gguf = tmp_path / "flash.gguf"+ _write_gguf(gguf, _arch("qwen4exp"), [("per_layer_token_embd.weight", OVER_4_GIB),+ ("blk.0.attn_q.weight", 16 << 20)])++ header = read_gguf_header(gguf)++ assert header.lazy_bytes == OVER_4_GIB * 4+ assert profile_from_gguf(header).weights_bytes == 64 << 20+++def test_a_marked_table_of_4_gib_or_less_loads_like_any_weight(tmp_path):+ """The engine's auto mode skips a tensor of at most 4 GiB: reading it row by row costs more+ than it saves, so it loads."""+ gguf = tmp_path / "small.gguf"+ _write_gguf(gguf, _arch("qwen4exp"), [("per_layer_token_embd.weight", EXACTLY_4_GIB)])++ header = read_gguf_header(gguf)++ assert header.lazy_bytes == 0+ assert profile_from_gguf(header).weights_bytes == header.tensor_bytes+++def test_an_architecture_that_marks_nothing_loads_the_same_table(tmp_path):+ """Only the architecture's own model code marks a tensor lazy; the name alone means nothing."""+ gguf = tmp_path / "other.gguf"+ _write_gguf(gguf, _arch("llama"), [("per_layer_token_embd.weight", OVER_4_GIB)])++ assert profile_from_gguf(read_gguf_header(gguf)).weights_bytes == OVER_4_GIB * 4+++def test_the_table_is_found_in_a_later_split_part(tmp_path):+ """The architecture lives in part 1 and the table in a later part (Flash Next keeps it in+ part 2), so the decision has to be made for the model, not per file."""+ _write_gguf(tmp_path / "flash-00001-of-00002.gguf", _arch("qwen4exp"), [])+ _write_gguf(tmp_path / "flash-00002-of-00002.gguf",+ {"split.no": 1, "split.count": 2, "split.tensors.count": 0},+ [("per_layer_token_embd.weight", OVER_4_GIB), ("blk.0.attn_q.weight", 16 << 20)])++ header = read_gguf_header(tmp_path / "flash-00001-of-00002.gguf")++ assert header.lazy_bytes == OVER_4_GIB * 4+ assert profile_from_gguf(header).weights_bytes == 64 << 20+++def test_a_catalog_build_is_priced_without_its_lazy_tables():+ """Before download the catalog stands in for the tensor table, so the build carries the bytes+ the engine leaves on disk."""+ build = QuantVariant(quant="UD-IQ4_XS", lazy_bytes=30 * GIB,+ files=(AssetFile("m-00001-of-00002.gguf", 10 << 20),+ AssetFile("m-00002-of-00002.gguf", 90 * GIB)))++ assert build.size_bytes == 90 * GIB + (10 << 20)+ assert build.weights_bytes == build.size_bytes - 30 * GIB