The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(local-runtime): expand scalar sliding_window_pattern, test the real parser
chelsealong23d9fd42e4f9
diff --git a/hermes_cli/local_runtime/estimator.py b/hermes_cli/local_runtime/estimator.pyindex 6d00ddedb5c..867c18c3af6 100644--- a/hermes_cli/local_runtime/estimator.py+++ b/hermes_cli/local_runtime/estimator.py@@ -19,6 +19,24 @@ _F16_BYTES_PER_ELEM = 2.0# sliding-window. Unknown SWA archs treat every layer as full attention (overestimate; safe)._SWA_LAYER_FRACTION = {"gemma3": 5 / 6, "gemma2": 1 / 2}+# Architectures whose llama.cpp loader expands a scalar `sliding_window_pattern` period with+# dense_first=True (the full-attention layer opens each period-length cycle instead of closing+# it). Confirmed against llama.cpp's per-arch hparams.set_swa_pattern() calls; every other+# architecture — including the whole Gemma family — uses the dense_first=False default.+_SWA_DENSE_FIRST_ARCHS = {"cohere2moe", "modern-bert", "smallthinker", "laguna"}+++def _expand_swa_period(period: int, n_layer: int, dense_first: bool) -> list[int]:+ """Per-layer SWA/full split from a scalar period, matching llama.cpp's+ `llama_hparams::set_swa_pattern()`: one full-attention layer per `period`-length cycle, the+ rest sliding-window."""+ if period <= 0:+ return []+ if dense_first:+ return [0 if i % period == 0 else 1 for i in range(n_layer)]+ return [1 if i % period < period - 1 else 0 for i in range(n_layer)]++# Per-recurrent-layer state allowance (bytes/seq). Deliberately generous: an entire measured# hybrid slot state is ~99 MB including 8K tokens of full-attn KV, so tens of MiB total is the# right order; unknown SSM shapes must never underestimate.@@ -81,11 +99,14 @@ def profile_from_gguf(header: GGUFHeader) -> ModelProfile:dk_swa = header.key_length_swa or dkdv_swa = header.value_length_swa or dv- # Priority ladder, highest first: (1) the file's own per-layer pattern — architecture-agnostic- # and exact; (2) a known-architecture fraction, for older files that declare `sliding_window`- # but no per-layer pattern; (3) no signal at all -> every layer priced as full attention- # (overestimate; safe).+ # Priority ladder, highest first: (1) the file's own per-layer pattern, array or scalar-period+ # form — architecture-agnostic and exact; (2) a known-architecture fraction, for older files+ # that declare `sliding_window` but no per-layer pattern; (3) no signal at all -> every layer+ # priced as full attention (overestimate; safe).pattern = header.sliding_window_pattern+ if pattern is None and header.sliding_window_pattern_period > 0:+ pattern = _expand_swa_period(header.sliding_window_pattern_period, header.n_layer,+ header.architecture in _SWA_DENSE_FIRST_ARCHS)has_pattern = (pattern is not None and header.sliding_window > 0and len(pattern) == len(kv_heads))swa_fraction = _SWA_LAYER_FRACTION.get(header.architecture, 0.0)diff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.pyindex cfc1cda8cf9..e077885af2c 100644--- a/hermes_cli/local_runtime/gguf.py+++ b/hermes_cli/local_runtime/gguf.py@@ -93,12 +93,21 @@ class GGUFHeader:@propertydef sliding_window_pattern(self) -> list[int] | None:"""Per-layer SWA pattern declared by the file itself: a truthy entry marks a- sliding-window layer, falsy marks global. None when the file doesn't declare one (older- GGUFs, or architectures without per-layer SWA metadata) — callers should fall back to a- coarser signal."""+ sliding-window layer, falsy marks global. None when the file doesn't declare the per-layer+ array form (older GGUFs, architectures without per-layer SWA metadata, or files that use+ the scalar period form instead — see `sliding_window_pattern_period`)."""v = self._arch_key("attention.sliding_window_pattern")return [int(x) for x in v] if isinstance(v, list) else None+ @property+ def sliding_window_pattern_period(self) -> int:+ """Scalar SWA period declared by the file: llama.cpp also permits+ `attention.sliding_window_pattern` as a single integer N (every Nth layer is full+ attention, e.g. Gemma-family writers) rather than a per-layer array. 0 when absent or when+ the file uses the array form instead — callers should fall back to a coarser signal."""+ v = self._arch_key("attention.sliding_window_pattern")+ return int(v) if isinstance(v, int) and not isinstance(v, bool) else 0+@propertydef n_vocab(self) -> int:"""Vocabulary size (prices the GPU logits buffers): vocab_size metadata when present, elsediff --git a/tests/hermes_cli/test_local_runtime_gguf_swa.py b/tests/hermes_cli/test_local_runtime_gguf_swa.pyindex 3d6b15f9876..cc09146e2cc 100644--- a/tests/hermes_cli/test_local_runtime_gguf_swa.py+++ b/tests/hermes_cli/test_local_runtime_gguf_swa.py@@ -1,12 +1,21 @@"""profile_from_gguf must trust the GGUF file's own per-layer SWA pattern over the hardcodedarchitecture-name table (#109551): an architecture absent from `_SWA_LAYER_FRACTION` that stilldeclares `attention.sliding_window_pattern` should be priced from that pattern, not as fully-global attention."""+global attention.++llama.cpp permits `attention.sliding_window_pattern` as either a per-layer array or a scalar+period (writers for Gemma-family and others use the scalar form); the tests below round-trip both+through the real binary parser (`read_gguf_header`), not just `GGUFHeader` built by hand, and cover+malformed/mismatched metadata falling back safely.+"""from __future__ import annotations+import struct+from pathlib import Path+from hermes_cli.local_runtime.estimator import LayerKind, ctx_bytes, profile_from_gguf-from hermes_cli.local_runtime.gguf import GGUFHeader+from hermes_cli.local_runtime.gguf import GGUFHeader, read_gguf_header_ARCH = "gemma4" # deliberately absent from _SWA_LAYER_FRACTION@@ -57,3 +66,107 @@ def test_unknown_arch_with_pattern_is_priced_per_layer():large = ctx_bytes(profile, window=65536, flash_attention=False)full_layer_only_growth = full_layer_bytes * (65536 - 2048)assert large - small == full_layer_only_growth+++# ── binary round-trip: real GGUF bytes through read_gguf_header(), not GGUFHeader built by hand ──++_STRING, _ARRAY = 8, 9+_SCALAR_FMT = {0: "<B", 1: "<b", 4: "<I", 7: "<?"}+++def _pack_value(vtype: int, value) -> bytes:+ if vtype == _STRING:+ raw = value.encode("utf-8")+ return struct.pack("<Q", len(raw)) + raw+ if vtype == _ARRAY:+ etype, items = value+ return struct.pack("<IQ", etype, len(items)) + b"".join(_pack_value(etype, i) for i in items)+ return struct.pack(_SCALAR_FMT[vtype], value)+++def _write_gguf(path: Path, metadata: dict) -> None:+ """metadata: key -> (vtype, value); ARRAY values are (element_vtype, [items])."""+ body = b"".join(struct.pack("<Q", len(k.encode())) + k.encode() + struct.pack("<I", vt) ++ _pack_value(vt, v) for k, (vt, v) in metadata.items())+ path.write_bytes(b"GGUF" + struct.pack("<IQQ", 3, 0, len(metadata)) + body)+++def test_binary_array_pattern_uint8_elements_round_trips(tmp_path):+ """Some writers encode the per-layer array with uint8 (not bool) elements; the parser must+ not care which scalar element type carries the 0/1 flags."""+ path = tmp_path / "m.gguf"+ _write_gguf(path, {+ "general.architecture": (_STRING, _ARCH),+ f"{_ARCH}.block_count": (4, 6),+ f"{_ARCH}.context_length": (4, 262144),+ f"{_ARCH}.attention.head_count_kv": (4, 8),+ f"{_ARCH}.attention.sliding_window": (4, 1024),+ f"{_ARCH}.attention.key_length": (4, 512),+ f"{_ARCH}.attention.value_length": (4, 512),+ f"{_ARCH}.attention.sliding_window_pattern": (_ARRAY, (0, [1, 1, 1, 1, 1, 0])),+ f"{_ARCH}.attention.key_length_swa": (4, 256),+ f"{_ARCH}.attention.value_length_swa": (4, 256),+ })+ profile = profile_from_gguf(read_gguf_header(path))+ assert [k for k, _ in profile.layers] == [LayerKind.SWA] * 5 + [LayerKind.FULL]+++def test_binary_scalar_period_defaults_to_dense_first_false(tmp_path):+ """Gemma-family writers declare `sliding_window_pattern` as a scalar period rather than a+ per-layer array; for architectures outside the small dense_first=True set this must expand+ with the full-attention layer closing each period (llama.cpp's dense_first=False default)."""+ path = tmp_path / "m.gguf"+ _write_gguf(path, {+ "general.architecture": (_STRING, _ARCH),+ f"{_ARCH}.block_count": (4, 7),+ f"{_ARCH}.context_length": (4, 262144),+ f"{_ARCH}.attention.head_count_kv": (4, 8),+ f"{_ARCH}.attention.sliding_window": (4, 1024),+ f"{_ARCH}.attention.key_length": (4, 512),+ f"{_ARCH}.attention.value_length": (4, 512),+ f"{_ARCH}.attention.sliding_window_pattern": (4, 4), # scalar period, not an array+ })+ profile = profile_from_gguf(read_gguf_header(path))+ kinds = [k for k, _ in profile.layers]+ assert kinds == [LayerKind.SWA, LayerKind.SWA, LayerKind.SWA, LayerKind.FULL,+ LayerKind.SWA, LayerKind.SWA, LayerKind.SWA]+++def test_binary_scalar_period_honors_dense_first_true_architectures(tmp_path):+ """`laguna` is one of the few llama.cpp architectures whose loader expands the scalar period+ with dense_first=True (the full-attention layer opens each cycle instead of closing it) —+ with 7 layers and period 4 that puts FULL at indices 0 and 4, not just index 3."""+ arch = "laguna"+ path = tmp_path / "m.gguf"+ _write_gguf(path, {+ "general.architecture": (_STRING, arch),+ f"{arch}.block_count": (4, 7),+ f"{arch}.context_length": (4, 262144),+ f"{arch}.attention.head_count_kv": (4, 8),+ f"{arch}.attention.sliding_window": (4, 1024),+ f"{arch}.attention.key_length": (4, 512),+ f"{arch}.attention.value_length": (4, 512),+ f"{arch}.attention.sliding_window_pattern": (4, 4),+ })+ profile = profile_from_gguf(read_gguf_header(path))+ kinds = [k for k, _ in profile.layers]+ assert kinds == [LayerKind.FULL, LayerKind.SWA, LayerKind.SWA, LayerKind.SWA,+ LayerKind.FULL, LayerKind.SWA, LayerKind.SWA]+++def test_binary_length_mismatched_array_falls_back_to_full_attention(tmp_path):+ """A declared array whose length doesn't match block_count is malformed/unusable — must fall+ back to the safe all-global default rather than misaligning it against the layers."""+ path = tmp_path / "m.gguf"+ _write_gguf(path, {+ "general.architecture": (_STRING, _ARCH),+ f"{_ARCH}.block_count": (4, 6),+ f"{_ARCH}.context_length": (4, 262144),+ f"{_ARCH}.attention.head_count_kv": (4, 8),+ f"{_ARCH}.attention.sliding_window": (4, 1024),+ f"{_ARCH}.attention.key_length": (4, 512),+ f"{_ARCH}.attention.value_length": (4, 512),+ f"{_ARCH}.attention.sliding_window_pattern": (_ARRAY, (7, [1, 1, 1, 0])), # 4 != 6 layers+ })+ profile = profile_from_gguf(read_gguf_header(path))+ assert all(k == LayerKind.FULL for k, _ in profile.layers)