The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): spill only the recurrent FFN blocks a hybrid needs
Austin Pickettd619b67ec2d4
diff --git a/hermes_cli/local_runtime/context_policy.py b/hermes_cli/local_runtime/context_policy.pyindex 778723724cb..61d0438bf78 100644--- a/hermes_cli/local_runtime/context_policy.py+++ b/hermes_cli/local_runtime/context_policy.py@@ -10,7 +10,8 @@ from __future__ import annotationsfrom dataclasses import dataclass, field, replacefrom hermes_cli.local_runtime.estimator import (- HardwareBudget, ModelProfile, PhysicsRefusal, ctx_bytes, footprint_bytes, physics_check)+ HardwareBudget, LayerKind, ModelProfile, PhysicsRefusal, ctx_bytes, footprint_bytes,+ physics_check)FLOOR = 64 * 1024 # = target; one internal constant_LADDER_GROWTH = 1.5@@ -242,14 +243,36 @@ def growth_decision(profile: ModelProfile, budget: HardwareBudget, *,reason=f"rung {current_window // 1024}K -> {next_rung // 1024}K")-def spill_overrides(profile: ModelProfile) -> list[str]:+def recurrent_spill_blocks(profile: ModelProfile, spill_bytes: int | None = None) -> list[int]:+ """Recurrent (n_head_kv==0) block indices whose FFN weights cover ``spill_bytes``.++ Takes the fewest blocks, lowest index first (llama.cpp's -ngl also keeps the front blocks on+ the host). Every recurrent block when ``spill_bytes`` is None, when any recurrent block's FFN+ size is unknown, or when all of them together still fall short (fit spills the rest).+ """+ recurrent = [i for i, (kind, _) in enumerate(profile.layers) if kind == LayerKind.RECURRENT]+ if spill_bytes is None or any(i not in profile.ffn_block_bytes for i in recurrent):+ return recurrent+ chosen: list[int] = []+ covered = 0+ for i in recurrent:+ if covered >= spill_bytes:+ break+ chosen.append(i)+ covered += profile.ffn_block_bytes[i]+ return chosen+++def spill_overrides(profile: ModelProfile, spill_bytes: int | None = None) -> list[str]:"""-ot placement for spilled configs: expert/FFN weights to host so attention + KV stay- GPU-resident. MoE gets the expert pattern; hybrids push recurrent-layer FFNs (their- n_head_kv==0 layers carry no KV worth protecting)."""+ GPU-resident. MoE gets the expert pattern; hybrids push the FFNs of just enough recurrent+ blocks to cover ``spill_bytes`` (their n_head_kv==0 layers carry no KV worth protecting, and+ full-attention FFNs stay on the GPU)."""if profile.moe:return ["-ot", r"blk\.\d+\.ffn_.*_exps\.weight=CPU"]- if profile.recurrent_layer_count:- return ["-ot", r"blk\.\d+\.ffn_.*\.weight=CPU"]+ blocks = recurrent_spill_blocks(profile, spill_bytes)+ if blocks:+ return ["-ot", r"blk\.(%s)\.ffn_.*\.weight=CPU" % "|".join(map(str, blocks))]return [] # dense: fit's back-to-front layer cut is the only axis@@ -270,7 +293,7 @@ def launch_args(profile: ModelProfile, decision: WindowDecision, *, flash_attentif flash_attention:args += ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on"]if decision.spilled and not uma:- args += spill_overrides(profile)+ args += spill_overrides(profile, decision.spill_bytes)return argsdiff --git a/hermes_cli/local_runtime/estimator.py b/hermes_cli/local_runtime/estimator.pyindex 867c18c3af6..0462afcbb4f 100644--- a/hermes_cli/local_runtime/estimator.py+++ b/hermes_cli/local_runtime/estimator.py@@ -6,7 +6,7 @@ ground truth after it. Unknown shapes round UP (never underestimate memory).from __future__ import annotations-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom enum import Enumfrom hermes_cli.local_runtime.gguf import GGUFHeader@@ -68,6 +68,8 @@ class ModelProfile:# postures): the draft adds ~17% to per-token KV; 1.2 rounds up so the error stays on the safe# side (+250 MiB at 256K, never negative).kv_scale: float = 1.0+ # block index -> FFN weight bytes (from the tensor table); empty when unknown.+ ffn_block_bytes: dict[int, int] = field(default_factory=dict)@propertydef per_token_kv_f16(self) -> int:@@ -134,7 +136,8 @@ def profile_from_gguf(header: GGUFHeader) -> ModelProfile:return ModelProfile(name=header.path, weights_bytes=header.tensor_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)+ moe=header.expert_count > 0, architecture=header.architecture, n_vocab=header.n_vocab,+ ffn_block_bytes=dict(header.ffn_block_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 e077885af2c..e0238862350 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -16,6 +16,8 @@ _GGUF_MAGIC = b"GGUF"# Split GGUF naming: "<stem>-00001-of-00003.gguf"; the part suffix is not part of the model id.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")def model_id_from_stem(stem: str) -> str:@@ -58,6 +60,9 @@ class GGUFHeader:n_tensors: int = 0tensor_bytes: int = 0 # exact sum over the tensor tableembd_table_bytes: int = 0 # token_embd.weight (duplicated host-side when fully offloaded)+ # 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)# ── typed accessors ──────────────────────────────────────@@ -207,6 +212,7 @@ def read_gguf_header(path: str | Path) -> GGUFHeader:tensor_bytes = 0embd_bytes = 0+ ffn_block_bytes: dict[int, int] = {}for _ in range(n_tensors):name = read_str(f)(n_dims,) = read(f, "<I")@@ -224,7 +230,10 @@ def read_gguf_header(path: str | Path) -> GGUFHeader:tensor_bytes += nbytesif name == "token_embd.weight":embd_bytes = nbytes+ elif m := _FFN_WEIGHT.match(name):+ block = int(m.group(1))+ ffn_block_bytes[block] = ffn_block_bytes.get(block, 0) + nbytesreturn GGUFHeader(path=str(path), version=version, metadata=metadata,n_tensors=n_tensors, tensor_bytes=tensor_bytes,- embd_table_bytes=embd_bytes)+ embd_table_bytes=embd_bytes, ffn_block_bytes=ffn_block_bytes)diff --git a/tests/hermes_cli/test_context_policy.py b/tests/hermes_cli/test_context_policy.pyindex f1b9105c405..23a2c7241d5 100644--- a/tests/hermes_cli/test_context_policy.py+++ b/tests/hermes_cli/test_context_policy.py@@ -8,6 +8,9 @@ constants with tolerance bands, not change-detecting catalog snapshots).from __future__ import annotations+import re+from dataclasses import replace+import pytestfrom hermes_cli.local_runtime.context_policy import (@@ -18,6 +21,7 @@ from hermes_cli.local_runtime.context_policy import (initial_window,ladder,launch_args,+ recurrent_spill_blocks,spill_overrides,ub_logits_bytes,)@@ -31,6 +35,7 @@ from hermes_cli.local_runtime.estimator import ()GIB = 1 << 30+MIB = 1 << 20KIB = 1024@@ -288,6 +293,54 @@ def test_spill_overrides_prefer_expert_and_recurrent_ffn():assert spill_overrides(dense()) == []+def _ot_pattern(args: list[str]) -> str:+ assert args[0] == "-ot" and args[1].endswith("=CPU")+ return args[1].removesuffix("=CPU")+++def _moved(pattern: str, n_layers: int) -> list[int]:+ # llama.cpp matches -ot patterns with std::regex_search against tensor names.+ return [i for i in range(n_layers) if re.search(pattern, f"blk.{i}.ffn_down.weight")]+++def test_hybrid_spill_moves_only_recurrent_blocks_needed_for_spill_bytes():+ """#113329: a hybrid spill must not move every block's FFN. Interleaved qwen35-style+ layout (every 4th block full attention), 100 MiB of FFN per block."""+ kinds = [LayerKind.FULL if i % 4 == 3 else LayerKind.RECURRENT for i in range(16)]+ profile = ModelProfile(+ name="interleaved-hybrid", weights_bytes=8 * GIB, embd_table_bytes=0, n_ctx_train=FLOOR,+ layers=[(k, 4096 if k == LayerKind.FULL else 0) for k in kinds],+ ffn_block_bytes={i: 100 * MIB for i in range(16)})++ assert recurrent_spill_blocks(profile, 250 * MIB) == [0, 1, 2]+ assert recurrent_spill_blocks(profile, 300 * MIB) == [0, 1, 2]+ assert recurrent_spill_blocks(profile, 301 * MIB) == [0, 1, 2, 4]+ assert _moved(_ot_pattern(spill_overrides(profile, 250 * MIB)), 16) == [0, 1, 2]+ # Not "blk.1" matching blk.10..blk.15.+ assert _moved(_ot_pattern(spill_overrides(profile, 150 * MIB)), 16) == [0, 1]++ # More spill than all recurrent FFNs hold: every recurrent block, never a full-attention one.+ recurrent = [i for i, k in enumerate(kinds) if k == LayerKind.RECURRENT]+ assert _moved(_ot_pattern(spill_overrides(profile, 20 * GIB)), 16) == recurrent+ assert not re.search(_ot_pattern(spill_overrides(profile, 20 * GIB)), "blk.3.ffn_up.weight")+++def test_hybrid_spill_without_ffn_sizes_moves_every_recurrent_block_only():+ profile = hybrid(full_layers=16, recurrent_layers=48) # no tensor-table sizes+ assert _moved(_ot_pattern(spill_overrides(profile, GIB)), 64) == list(range(16, 64))+ partial = replace(profile, ffn_block_bytes={i: GIB for i in range(16, 63)}) # block 63 unknown+ assert recurrent_spill_blocks(partial, GIB) == list(range(16, 64))+++def test_launch_args_sizes_hybrid_spill_from_decision():+ profile = replace(hybrid(full_layers=2, recurrent_layers=6),+ ffn_block_bytes={i: GIB for i in range(8)})+ spilled = WindowDecision(window=FLOOR, spill_bytes=int(1.5 * GIB), kv_on_gpu=True)+ args = launch_args(profile, spilled)+ assert _moved(_ot_pattern(args[args.index("-ot"):args.index("-ot") + 2]), 8) == [2, 3]+ assert "-ot" not in launch_args(profile, spilled, uma=True)++def test_launch_args_contract():p = moe()spilled = WindowDecision(window=FLOOR, spill_bytes=4 * GIB, kv_on_gpu=True)diff --git a/tests/hermes_cli/test_local_runtime_gguf.py b/tests/hermes_cli/test_local_runtime_gguf.pyindex b69d5a46da7..79494de7917 100644--- a/tests/hermes_cli/test_local_runtime_gguf.py+++ b/tests/hermes_cli/test_local_runtime_gguf.py@@ -2,11 +2,59 @@from __future__ import annotations+import reimport struct+from hermes_cli.local_runtime.context_policy import spill_overrides+from hermes_cli.local_runtime.estimator import profile_from_gguffrom hermes_cli.local_runtime.gguf import read_gguf_header+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)+++def test_hybrid_ffn_block_sizes_drive_per_block_spill(tmp_path):+ """#113329 end to end on synthetic metadata: a qwen35-style hybrid (every 4th of 12 blocks+ full attention) spills only the recurrent blocks whose FFN bytes cover the spill."""+ 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)]+ gguf = tmp_path / "hybrid.gguf"+ _write_gguf(gguf, {+ "general.architecture": "qwen35", "qwen35.block_count": 12,+ "qwen35.context_length": 65536, "qwen35.full_attention_interval": 4,+ "qwen35.attention.head_count": 8, "qwen35.attention.head_count_kv": 2,+ "qwen35.attention.key_length": 128, "qwen35.attention.value_length": 128,+ }, tensors)++ header = read_gguf_header(gguf)+ per_block = (16 + 256 + 240) * 4 # f32; attn_norm is not an FFN tensor+ assert header.ffn_block_bytes == {i: per_block for i in range(12)}++ profile = profile_from_gguf(header)+ assert header.head_counts_kv() == [0, 0, 0, 2] * 3+ args = spill_overrides(profile, 4 * per_block + 1)+ 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, 2, 4, 5]+ assert not re.search(pattern, "blk.1.attn_norm.weight")++def test_reader_sizes_mxfp4_tensor_blocks(tmp_path):"""MXFP4 stores 32 elements in one 17-byte block."""name = b"token_embd.weight"