The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(local-runtime): read recurrent-state size from GGUF headers
emozilla89b09c291824
diff --git a/hermes_cli/local_runtime/estimator.py b/hermes_cli/local_runtime/estimator.pyindex 13f88e39c4d..760efd7b057 100644--- a/hermes_cli/local_runtime/estimator.py+++ b/hermes_cli/local_runtime/estimator.py@@ -85,6 +85,10 @@ class ModelProfile:# Compute-buffer bytes per window token at the launch posture (plan_launch sets it from# window_compute_bytes, the microbatch and the context count); zero prices none.window_compute_per_token: int = 0+ # One copy of one sequence's recurrent state, exact from the SSM shape (0 = unknown). The+ # window price keeps its per-layer allowance; this prices the extra copies speculative+ # decoding keeps.+ recurrent_state_bytes: int = 0@propertydef window_compute_bytes(self) -> int:@@ -170,7 +174,8 @@ def profile_from_gguf(header: GGUFHeader) -> ModelProfile: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), lazy_bytes=header.lazy_bytes)+ ffn_block_bytes=dict(header.ffn_block_bytes), lazy_bytes=header.lazy_bytes,+ recurrent_state_bytes=header.recurrent_state_bytes)def kv_dtype_factor(flash_attention: bool) -> float:diff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.pyindex ab123484cde..4d5fca708fd 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -21,6 +21,8 @@ SPLIT_PART_RE = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$")_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")+# A block with an SSM conv filter keeps recurrent state (Mamba2 and gated delta-net alike).+_SSM_CONV = re.compile(r"blk\.(\d+)\.ssm_conv1d\.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@@ -83,6 +85,9 @@ class GGUFHeader:# 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)+ # Blocks that keep recurrent state. Counted from the tensor table: hybrids like Nemotron-H+ # also have MoE-only blocks without KV heads, which hold none.+ recurrent_blocks: frozenset[int] = frozenset()# ── typed accessors ──────────────────────────────────────@@ -100,6 +105,21 @@ class GGUFHeader:def _arch_key(self, suffix: str):return self.metadata.get(f"{self.architecture}.{suffix}")+ @property+ def recurrent_state_bytes(self) -> int:+ """One copy of one sequence's recurrent state: an f32 conv window plus the SSM state, per+ block that keeps state. llama.cpp holds one copy per slot per speculative draft position.+ 0 when the file declares no SSM shape."""+ def ssm(key: str) -> int:+ return int(self._arch_key(f"ssm.{key}") or 0)++ inner, state = ssm("inner_size"), ssm("state_size")+ if not (self.recurrent_blocks and inner and state):+ return 0+ conv_dim = inner + 2 * ssm("group_count") * state+ per_block = 4 * (inner * state + max(0, ssm("conv_kernel") - 1) * conv_dim)+ return len(self.recurrent_blocks) * per_block+def _arch_int(suffix: str, doc: str = ""):return property(lambda self: int(self._arch_key(suffix) or 0), doc=doc)@@ -262,6 +282,7 @@ def _read_part(path: Path) -> GGUFHeader:embd_bytes = 0ffn_block_bytes: dict[int, int] = {}lazy_candidate_bytes: dict[str, int] = {}+ recurrent_blocks: set[int] = set()for _ in range(n_tensors):name = read_str(f)(n_dims,) = read(f, "<I")@@ -284,11 +305,14 @@ def _read_part(path: Path) -> GGUFHeader:ffn_block_bytes[block] = ffn_block_bytes.get(block, 0) + nbyteselif name in _LAZY_READ_CANDIDATES:lazy_candidate_bytes[name] = nbytes+ elif m := _SSM_CONV.match(name):+ recurrent_blocks.add(int(m.group(1)))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,- lazy_candidate_bytes=lazy_candidate_bytes)+ lazy_candidate_bytes=lazy_candidate_bytes,+ recurrent_blocks=frozenset(recurrent_blocks))def read_gguf_header(path: str | Path) -> GGUFHeader:@@ -333,4 +357,5 @@ def read_gguf_header(path: str | Path) -> GGUFHeader:embd_table_bytes=sum(h.embd_table_bytes for h in readable),ffn_block_bytes=ffn_block_bytes,lazy_candidate_bytes={name: nbytes for h in readable- for name, nbytes in h.lazy_candidate_bytes.items()})+ for name, nbytes in h.lazy_candidate_bytes.items()},+ recurrent_blocks=frozenset().union(*(h.recurrent_blocks for h in readable)))diff --git a/tests/hermes_cli/test_local_runtime_gguf.py b/tests/hermes_cli/test_local_runtime_gguf.pyindex a806f166ace..16b2111e5bc 100644--- a/tests/hermes_cli/test_local_runtime_gguf.py+++ b/tests/hermes_cli/test_local_runtime_gguf.py@@ -93,3 +93,55 @@ def test_reader_sizes_ggml_types_added_after_mxfp4(tmp_path, ggml_type, elems, e)assert read_gguf_header(gguf).tensor_bytes == expected+++def _ssm_model(path, arch: str, n_layer: int, recurrent: set[int], ssm: dict) -> None:+ tensors = [("token_embd.weight", 64)]+ for i in range(n_layer):+ tensors.append((f"blk.{i}.attn_norm.weight", 16))+ if i in recurrent:+ tensors.append((f"blk.{i}.ssm_conv1d.weight", 16))+ _write_gguf(path, {"general.architecture": arch, f"{arch}.block_count": n_layer,+ f"{arch}.context_length": 262144,+ **{f"{arch}.ssm.{k}": v for k, v in ssm.items()}}, tensors)+++def test_reader_prices_one_recurrent_state_copy_from_the_ssm_shape(tmp_path):+ """llama.cpp keeps one f32 conv window plus SSM state per recurrent block, per copy. Qwen3.8+ 27B's shape is 149.6 MiB: the 1,796 MiB it allocates for 4 slots x 3 MTP positions."""+ gguf = tmp_path / "qwen.gguf"+ _ssm_model(gguf, "qwen35", 64, {i for i in range(64) if (i + 1) % 4},+ {"inner_size": 6144, "state_size": 128, "conv_kernel": 4, "group_count": 16})++ header = read_gguf_header(gguf)++ assert header.recurrent_state_bytes == 48 * 4 * (6144 * 128 + 3 * (6144 + 2 * 16 * 128))+ assert round(header.recurrent_state_bytes / 2**20, 1) == 149.6+ assert profile_from_gguf(header).recurrent_state_bytes == header.recurrent_state_bytes+++def test_reader_counts_only_blocks_that_hold_recurrent_state(tmp_path):+ """Nemotron-H's MoE blocks also have no KV heads, but hold no state. Bolt: 40 Mamba blocks of+ 88 -> 164.7 MiB per copy, the 659 MiB llama.cpp allocates for 4 slots."""+ gguf = tmp_path / "bolt.gguf"+ _ssm_model(gguf, "nemotron_h_moe", 88, set(range(0, 80, 2)),+ {"inner_size": 8192, "state_size": 128, "conv_kernel": 4, "group_count": 8})++ assert round(read_gguf_header(gguf).recurrent_state_bytes / 2**20, 1) == 164.7+++def test_split_model_counts_recurrent_blocks_across_parts(tmp_path):+ ssm = {"inner_size": 64, "state_size": 8, "conv_kernel": 4, "group_count": 1}+ first = tmp_path / "m-00001-of-00002.gguf"+ _ssm_model(first, "qwen35", 4, {0, 1}, ssm)+ _write_gguf(tmp_path / "m-00002-of-00002.gguf", {"split.count": 2},+ [("blk.2.ssm_conv1d.weight", 16), ("blk.3.ssm_conv1d.weight", 16)])++ assert read_gguf_header(first).recurrent_state_bytes == 4 * 4 * (64 * 8 + 3 * (64 + 2 * 8))+++def test_no_ssm_shape_prices_no_recurrent_state(tmp_path):+ gguf = tmp_path / "dense.gguf"+ _ssm_model(gguf, "llama", 4, set(), {})++ assert read_gguf_header(gguf).recurrent_state_bytes == 0