Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

GGUF registry: F8_E4M3 row type (plain / blocked by byte span) and the Hy4 engram block

YanissAmzb0fad23aed52
diff --git a/exllamav3/architecture/gguf_generic.py b/exllamav3/architecture/gguf_generic.py
index c5fc506..6545cbe 100644
--- a/exllamav3/architecture/gguf_generic.py
+++ b/exllamav3/architecture/gguf_generic.py
@@ -108,6 +108,8 @@ def _fl(config, eng_key: str, i: int, o: int, out_dtype=None, bias=False, **kw):
if fmt == "fp" or fmt.startswith("unk"):
raise GenericUnsupported(f"{base}: ggml type {fmt!r} has no ForeignLinear format (add it to GGML_FMT)")
if bias:
+ if fmt == "f8_e4m3":
+ raise GenericUnsupported(f"{base}: ggml F8_E4M3 (type 43) is a row-lookup-only type (loader/engram_rows.F8Rows), not a Linear")
# Linear.load_gguf_ builds the ForeignLinear on the stored blocks and loads <key>.bias into _ForeignInner (inner.bias / inner.fl,
# what the grouped MXFP4 MoE path and Attention read). pad_to=1: the GGUF payload is not padded to 128 (gpt-oss 2880).
from ..modules.linear import Linear
diff --git a/exllamav3/loader/engram_rows.py b/exllamav3/loader/engram_rows.py
new file mode 100644
index 0000000..46807f7
--- /dev/null
+++ b/exllamav3/loader/engram_rows.py
@@ -0,0 +1,238 @@
+"""Row-lookup pieces of the Hy4-flash registry blocks `f8_rows` and `engram` (design HY4_STRIX_DESIGN.md §2, §4).
+
+Pure torch / numpy, no extension, no relative imports (tests load it by path).
+ * E4M3 / E8M0 decode tables (exact), F8Rows: row lookup in a ggml type-43 tensor, PLAIN or BLOCKED layout chosen by byte span.
+ * engram_hash: llama.cpp hy_v4_flash engram_hash (M:5175-5221) for a whole token sequence.
+ * Hy4Engram: build_engram (M:5292-5353) on CPU fp32. Weights are dequantised once (Q8_0 / F32 / F16); the engine's
+ ForeignLinear path is a separate step, this is the maths + the row source.
+"""
+from __future__ import annotations
+import os
+import numpy as np
+import torch
+
+GGML_F8_E4M3 = 43
+QB = 32 # elements per BLOCKED block
+MASK64 = (1 << 64) - 1
+
+
+# ------------------------------------------------------------------------------------------------ decode tables
+def _e4m3_table() -> torch.Tensor:
+ """OCP E4M3FN: bias 7, no inf, S.1111.111 = NaN, subnormals e=0 -> m/8 * 2^-6. Built from the bit fields, not from torch."""
+ t = torch.empty(256, dtype=torch.float32)
+ for b in range(256):
+ s, e, m = b >> 7, (b >> 3) & 15, b & 7
+ if e == 15 and m == 7:
+ v = float("nan")
+ elif e == 0:
+ v = (m / 8.0) * 2.0 ** -6
+ else:
+ v = (1.0 + m / 8.0) * 2.0 ** (e - 7)
+ t[b] = -v if s else v
+ return t
+
+
+def _e8m0_table() -> torch.Tensor:
+ t = torch.tensor([2.0 ** (e - 127) for e in range(255)] + [float("nan")], dtype=torch.float64)
+ return t.to(torch.float32) # 2^-127 is subnormal in fp32 but exact (fp32 subnormal min 2^-149)
+
+
+E4M3 = _e4m3_table()
+E8M0 = _e8m0_table()
+
+
+def decode_e4m3(u8: torch.Tensor) -> torch.Tensor:
+ return E4M3[u8.long()]
+
+
+# ------------------------------------------------------------------------------------------------ F8 row type
+class F8LayoutError(ValueError):
+ pass
+
+
+def tensor_span(g, name: str) -> int:
+ """Bytes the tensor may occupy: distance to the next tensor of the same file, else to the end of the file."""
+ ty, dims, off = g.infos[name]
+ fi, o = off >> 48, off & ((1 << 48) - 1)
+ nxt = [x & ((1 << 48) - 1) for _, _, x in g.infos.values() if (x >> 48) == fi and (x & ((1 << 48) - 1)) > o]
+ end = min(nxt) if nxt else os.fstat(g.fds[fi]).st_size - g.bases[fi]
+ return end - o
+
+
+def f8_layout(n_elem: int, span: int, width: int) -> str:
+ """'plain' (1 B/element) or 'blocked' (33 B per 32 elements; per row: width e4m3 bytes then width/32 e8m0 scale bytes, the DS4.1
+ form), by the tensor byte span. NB the span cannot tell this row form from a 33 B interleaved [scale|32 values] block form
+ (same size): only the tree's row form is decoded.
+ ggml pads a tensor to 32 B, so a span is accepted when it equals the exact size or the exact size rounded up to 32."""
+ al = lambda n: (n + 31) // 32 * 32
+ plain = {n_elem, al(n_elem)}
+ blocked = {n_elem // QB * 33, al(n_elem // QB * 33)} if n_elem % QB == 0 and width % QB == 0 else set()
+ hp, hb = span in plain, span in blocked
+ if hp and hb:
+ raise F8LayoutError(f"F8_E4M3 tensor span {span} B for {n_elem} elements fits both the plain and the 33 B-per-32 blocked layout")
+ if hp:
+ return "plain"
+ if hb:
+ return "blocked"
+ raise F8LayoutError(f"F8_E4M3 tensor: {span} B for {n_elem} elements is neither plain (1 B/element = {n_elem} B) nor blocked "
+ f"(33 B per 32 elements = {n_elem // QB * 33 if n_elem % QB == 0 else 'n/a'} B); refusing")
+
+
+class F8Rows:
+ """Row lookup of a ggml F8_E4M3 tensor (row-lookup-only: never a Linear, never resident). dims = (width, rows)."""
+
+ def __init__(self, g, name: str = "per_layer_token_embd.weight"):
+ ty, dims, off = g.infos[name]
+ if ty != GGML_F8_E4M3:
+ raise F8LayoutError(f"{name}: ggml type {ty} is not F8_E4M3 (43)")
+ if len(dims) != 2:
+ raise F8LayoutError(f"{name}: expected a 2-D table, got dims {dims}")
+ self.g, self.name = g, name
+ self.width, self.rows = int(dims[0]), int(dims[1])
+ self.layout = f8_layout(self.width * self.rows, tensor_span(g, name), self.width)
+ self.row_bytes = self.width if self.layout == "plain" else self.width + self.width // QB
+ self.off = off
+
+ def raw_row(self, r: int) -> np.ndarray:
+ if not 0 <= r < self.rows:
+ raise IndexError(f"{self.name}: row {r} outside 0..{self.rows - 1}")
+ return self.g._pread(self.off + r * self.row_bytes, self.row_bytes)
+
+ def decode_raw(self, raw: np.ndarray) -> torch.Tensor:
+ u = torch.from_numpy(np.ascontiguousarray(raw))
+ if self.layout == "plain":
+ return decode_e4m3(u)
+ # DS4.1 row form (dsv41_hip.hip ds41_fp8_decode, dsv41/engram.py dequant_rows): width e4m3 values, then width/32 e8m0 scales
+ w = self.width
+ return (decode_e4m3(u[:w]).reshape(-1, QB) * E8M0[u[w:].long()][:, None]).reshape(-1)
+
+ def lookup(self, ids) -> torch.Tensor:
+ """ids (any shape of ints) -> float32 [*shape, width]; every distinct row is read once."""
+ ids = torch.as_tensor(ids, dtype=torch.int64)
+ flat = ids.reshape(-1)
+ uniq, inv = torch.unique(flat, return_inverse=True)
+ rows = torch.stack([self.decode_raw(self.raw_row(int(r))) for r in uniq])
+ return rows[inv].reshape(*ids.shape, self.width)
+
+
+# ------------------------------------------------------------------------------------------------ engram hash
+def engram_hash(tokens, start, n_tokens, token_map, pad_id, mult, primes, offs, n_gram, n_head):
+ """Row ids for positions start..start+n_tokens-1 of the token list `tokens` (the whole history).
+ mult [n_gram] u64, primes / offs [n_cols] for ONE module. Returns (ids int64 [n, n_cols], valid float32 [n, n_cols]).
+ Token not in token_map -> dead (pad in the hash, valid 0); position before the sequence start -> pad, still valid (M:5207)."""
+ n_cols = (n_gram - 1) * n_head
+ tm = list(token_map)
+ pad = int(tm[pad_id])
+ cid = lambda t: -1 if t < 0 or t >= len(tm) else int(tm[t])
+ ids = np.zeros((n_tokens, n_cols), dtype=np.int64)
+ valid = np.zeros((n_tokens, n_cols), dtype=np.float32)
+ for k in range(n_tokens):
+ p = start + k
+ c = cid(tokens[p])
+ dead = c == -1
+ toks = [pad if dead else c]
+ for s in range(1, n_gram):
+ c = -1 if p - s < 0 else cid(tokens[p - s])
+ toks.append(pad if c == -1 else c)
+ rolling = (toks[0] * int(mult[0])) & MASK64
+ for o in range(1, n_gram):
+ rolling ^= (toks[o] * int(mult[o])) & MASK64
+ for h in range(n_head):
+ col = (o - 1) * n_head + h
+ ids[k, col] = rolling % int(primes[col]) + int(offs[col])
+ valid[k, col] = 0.0 if dead else 1.0
+ return torch.from_numpy(ids), torch.from_numpy(valid)
+
+
+# ------------------------------------------------------------------------------------------------ weights
+def _dequant_q8_0(raw: np.ndarray, K: int, N: int) -> torch.Tensor:
+ b = np.ascontiguousarray(raw).reshape(N, K // 32, 34)
+ d = b[:, :, :2].copy().view(np.float16).astype(np.float32) # [N, nb, 1]
+ q = b[:, :, 2:].view(np.int8).astype(np.float32)
+ return torch.from_numpy((q * d).reshape(N, K))
+
+
+def load_dense(g, name: str) -> torch.Tensor:
+ """a small GGUF tensor as float32 in storage orientation [dims[1], dims[0]] (F32 / F16 / BF16 / Q8_0)."""
+ ty, dims, off = g.infos[name]
+ if ty == 8:
+ K, N = dims[0], dims[1]
+ return _dequant_q8_0(g._pread(off, N * (K // 32) * 34), K, N)
+ if ty in (0, 1, 30):
+ t = g.get_tensor(name)
+ return t.float()
+ raise ValueError(f"{name}: ggml type {ty} not handled by the Hy4 engram loader")
+
+
+# ------------------------------------------------------------------------------------------------ the block
+def q8_0_roundtrip(x: torch.Tensor) -> torch.Tensor:
+ """quantize_row_q8_0 + dequantize (ggml-quants.c): per 32 values d = amax/127 (stored fp16), q = round-half-away(x / d)."""
+ b = x.reshape(*x.shape[:-1], -1, 32)
+ d = (b.abs().amax(-1, keepdim=True) / 127.0).half().float() # ggml: d = amax/127 as fp32, id = 1/d, stored d as fp16
+ d32 = b.abs().amax(-1, keepdim=True) / 127.0
+ idv = torch.where(d32 != 0, 1.0 / d32, torch.zeros_like(d32))
+ v = b * idv
+ q = torch.round(v) # AVX2/NEON quantize_row_q8_0 rounds to nearest-even (_mm256_round_ps); the scalar ref uses roundf (half away)
+ return (q * d).reshape(x.shape)
+
+
+def rms(x: torch.Tensor, eps: float) -> torch.Tensor:
+ """ggml_rms_norm: x / sqrt(mean(x^2) + eps) over the last dim."""
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
+
+
+class Hy4Engram:
+ """One Engram module of hy_v4_flash (the layer-`layer` pre-hook), fp32 CPU. Config from the GGUF header, never a model name."""
+
+ def __init__(self, g, layer: int, eps: float = 1.1920929e-07, table: F8Rows | None = None, q8_act: bool = False):
+ m = g.meta
+ p = (m["general.architecture"]) + "."
+ pl = list(m[p + "ple.layers"])
+ self.layer, self.e = layer, pl.index(layer)
+ self.n_gram, self.n_head = m[p + "ple.ngram_size"], m[p + "ple.heads_per_ngram"]
+ self.n_cols = (self.n_gram - 1) * self.n_head
+ e, nc, ng = self.e, self.n_cols, self.n_gram
+ self.mult = list(m[p + "ple.layer_multipliers"])[e * ng:(e + 1) * ng]
+ self.primes = list(m[p + "ple.head_vocab_sizes"])[e * nc:(e + 1) * nc]
+ self.offs = list(m[p + "ple.head_offsets"])[e * nc:(e + 1) * nc]
+ self.token_map, self.pad_id = m[p + "engram.token_map"], m[p + "engram.pad_token_id"]
+ self.head_dim = m[p + "embedding_length_per_layer_input"]
+ self.n_embd, self.hc = m[p + "embedding_length"], m[p + "hyper_connection.count"]
+ self.eps = eps
+ self.q8_act = q8_act # emulate llama.cpp CPU mul_mat(Q8_0 weight): the activation is quantised to Q8_0 first (vec_dot_type)
+ b = f"blk.{layer}."
+ self.kv = load_dense(g, b + "engram_kv.weight") # [(hc+1)*n_embd, n_cols*head_dim]
+ self.kv_b = load_dense(g, b + "engram_kv_b.weight") # [hc+1, n_embd]
+ self.lookup_norm = load_dense(g, b + "engram_lookup_norm.weight") # [n_cols, head_dim]
+ self.gate = load_dense(g, b + "engram_gate.weight") # [hc, n_embd]
+ self.hc_scale = load_dense(g, b + "engram_hc_scale.weight") # [hc, n_embd]
+ self.pre_gamma = load_dense(g, b + "engram_pre_gamma.weight") # [n_embd]
+ assert self.kv.shape == ((self.hc + 1) * self.n_embd, nc * self.head_dim), self.kv.shape
+ self.table = table if table is not None else F8Rows(g)
+ assert self.table.width == self.head_dim
+
+ def row_ids(self, tokens, start, n):
+ return engram_hash(tokens, start, n, self.token_map, self.pad_id, self.mult, self.primes, self.offs, self.n_gram, self.n_head)
+
+ def apply(self, x: torch.Tensor, rows: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
+ """x [T, hc, n_embd] fp32 stream, rows [T, n_cols, head_dim] decoded table rows, valid [T, n_cols] -> x + delta (M:5292-5353)."""
+ T, eps = x.shape[0], self.eps
+ r = rms(rows, eps) * self.lookup_norm * valid[:, :, None] # delta 1
+ r = r.reshape(T, -1)
+ if self.q8_act:
+ r = q8_0_roundtrip(r)
+ kv = (r @ self.kv.T).reshape(T, self.hc + 1, self.n_embd) + self.kv_b # delta 2
+ key, value = kv[:, :self.hc], kv[:, self.hc]
+ dot = (rms(x, eps) * rms(key, eps) * self.gate).sum(-1) / self.n_embd ** 0.5 # [T, hc]
+ mag = dot.abs().clamp_min(1e-6).sqrt()
+ sign = 1.0 - 2.0 * (-dot > 0).float() # ggml_step(-dot): dot < 0 -> -1, dot >= 0 -> +1
+ gate = torch.sigmoid(mag * sign)
+ signal = rms(value, eps) * self.pre_gamma # delta 3
+ scale = gate[:, :, None] + self.hc_scale # delta 4
+ delta = signal[:, None, :] * scale
+ anyv = (valid.sum(-1) > 0).float() # whole-token mask
+ return x + delta * anyv[:, None, None]
+
+ def __call__(self, x: torch.Tensor, tokens, start: int = 0) -> torch.Tensor:
+ ids, valid = self.row_ids(tokens, start, x.shape[0])
+ return self.apply(x, self.table.lookup(ids), valid)
diff --git a/exllamav3/loader/gguf_blocks/engram.py b/exllamav3/loader/gguf_blocks/engram.py
index 7bbcdf3..0d7d5fd 100644
--- a/exllamav3/loader/gguf_blocks/engram.py
+++ b/exllamav3/loader/gguf_blocks/engram.py
@@ -1,7 +1,7 @@
"""Blocks around modules/dsv41_fn/engram_dev.py (Engram n-gram rows) and the F8_E4M3 row table (ggml type 43).
Predicates + configs only (Hy4 step 2). Layout comes from the ple.* / engram.* keys, shared by hy_v4_flash and deepseek41."""
from __future__ import annotations
-from ..gguf_registry import Block, register
+from ..gguf_registry import Block, register, GenericUnsupported
GGML_F8_E4M3 = 43 # ggml_master.h:262; row-lookup-only: never a Linear, never dequantised resident
@@ -21,11 +21,37 @@ def _engram_layer(ctx, i):
"token_map": len(ctx.key("engram.token_map") or []), "eps": ctx.feats.get("engram_eps")}
+def _is_engram_layer(ctx, i):
+ return i in (ctx.key("ple.layers") or []) and ctx.has(i, "engram_kv.weight")
+
+
+def _hy4_gate(ctx, i):
+ return all(ctx.has(i, s) for s in _HY4_GATE)
+
+
+def _gguf(config):
+ return getattr(config, "gguf", config) # the GGUFCollection, from a model config or passed directly
+
+
+def _build_engram_hy4(config, plan, i, key=None):
+ """Hy4 Engram pre-hook (CPU fp32 maths, loader/engram_rows.py); a module with forward(x [T, hc, n_embd], tokens, start)."""
+ from ..engram_rows import Hy4Engram
+ eps = (plan.ctx.feats if plan is not None else {}).get("engram_eps", 1.1920929e-07)
+ return Hy4Engram(_gguf(config), i, eps=eps)
+
+
+# DS4.1 gate variant (wkv + norm_key/query gate, no kv bias): still a predicate only
register(Block(
"engram", "pre", step="step 2",
- select=lambda ctx, i: i in (ctx.key("ple.layers") or []) and ctx.has(i, "engram_kv.weight"),
+ select=lambda ctx, i: _is_engram_layer(ctx, i) and not _hy4_gate(ctx, i),
config=_engram_layer, claims=frozenset({"engram_kv.weight", "engram_gate.weight", *_HY4_GATE}), build=None))
+# Hy4 gate variant: selected by the tensors engram_kv_b / lookup_norm / pre_gamma / hc_scale, not by a model name
+register(Block(
+ "engram_hy4", "pre", step="step 2",
+ select=lambda ctx, i: _is_engram_layer(ctx, i) and _hy4_gate(ctx, i),
+ config=_engram_layer, claims=frozenset({"engram_kv.weight", "engram_gate.weight", *_HY4_GATE}), build=_build_engram_hy4))
+
def _f8_cfg(ctx, i):
ty, dims, off = ctx.infos["per_layer_token_embd.weight"]
@@ -33,13 +59,27 @@ def _f8_cfg(ctx, i):
bases = getattr(ctx.g, "bases", None)
offs = ctx.key("ple.head_offsets") or []
sizes = ctx.key("ple.head_vocab_sizes") or []
- return {"type": ty, "row_width": dims[0], "rows": dims[1], "row_bytes": dims[0] if ty == GGML_F8_E4M3 else None,
+ layout, row_bytes = None, None
+ if ty == GGML_F8_E4M3:
+ from ..engram_rows import f8_layout, tensor_span, F8LayoutError, QB
+ try:
+ layout = f8_layout(dims[0] * dims[1], tensor_span(ctx.g, "per_layer_token_embd.weight"), dims[0])
+ row_bytes = dims[0] if layout == "plain" else dims[0] // QB * 33
+ except (F8LayoutError, OSError, AttributeError) as ex:
+ layout = f"refused: {ex}"
+ return {"type": ty, "row_width": dims[0], "rows": dims[1], "layout": layout, "row_bytes": row_bytes,
"part": part, "data_offset": (bases[part] if bases else 0) + (off & ((1 << 48) - 1)),
"width_matches_ple": dims[0] == ctx.key("embedding_length_per_layer_input"),
"rows_match_offsets": bool(offs) and offs[-1] + sizes[-1] == dims[1]}
+def _build_f8(config, plan, i, key=None):
+ """row-lookup-only F8_E4M3 table: F8Rows.lookup(ids) -> float32 rows; refuses a span that is neither layout"""
+ from ..engram_rows import F8Rows
+ return F8Rows(_gguf(config), "per_layer_token_embd.weight")
+
+
register(Block(
"f8_rows", "embed_mod", step="step 2",
select=lambda ctx, i: "per_layer_token_embd.weight" in ctx.infos and ctx.infos["per_layer_token_embd.weight"][0] == GGML_F8_E4M3,
- config=_f8_cfg, claims=frozenset({"per_layer_token_embd.weight"}), build=None))
+ config=_f8_cfg, claims=frozenset({"per_layer_token_embd.weight"}), build=_build_f8))
diff --git a/exllamav3/loader/gguf_collection.py b/exllamav3/loader/gguf_collection.py
index 70a3fd1..9e9b03f 100644
--- a/exllamav3/loader/gguf_collection.py
+++ b/exllamav3/loader/gguf_collection.py
@@ -326,6 +326,8 @@ class GGUFCollection:
elif allow_bf16 and t.dtype == torch.float32:
t = t.bfloat16()
return _pad_to(t.to(dev), pad_to)
+ if ty == 43:
+ raise ValueError(f"{key}: ggml F8_E4M3 (type 43) is row-lookup-only; read rows through loader/engram_rows.F8Rows, not get_tensor")
raise ValueError(f"unsupported gguf type {ty} for {key}")
diff --git a/exllamav3/loader/gguf_config.py b/exllamav3/loader/gguf_config.py
index f2d0d29..2e0b75b 100644
--- a/exllamav3/loader/gguf_config.py
+++ b/exllamav3/loader/gguf_config.py
@@ -27,6 +27,7 @@ GGUF_ARCHS = {
GGML_FMT = {
2: "q4_0", 6: "q5_0", 7: "q5_1", 8: "q8_0", 12: "q4_k", 13: "q5_k", 14: "q6_k", 18: "iq3_xxs", 16: "iq2_xxs",
20: "iq4_nl", 21: "iq3_s", 23: "iq4_xs", 11: "q3_k", 10: "q2_k", 17: "iq2_xs", 22: "iq2_s", 39: "mxfp4", 40: "nvfp4_gguf", 0: "fp", 1: "fp",
+ 43: "f8_e4m3", # row-lookup-only (loader/engram_rows.F8Rows): the generic builder refuses it as a Linear
}
diff --git a/tests/test_hy4_engram_rows.py b/tests/test_hy4_engram_rows.py
new file mode 100644
index 0000000..bbfde0b
--- /dev/null
+++ b/tests/test_hy4_engram_rows.py
@@ -0,0 +1,220 @@
+"""Hy4-flash registry blocks `f8_rows` (ggml F8_E4M3 row type) and `engram_hy4` (n-gram rows + gate), CPU only, no extension.
+Loaded by path under stub packages (as test_gguf_generic_cpu.py). Run:
+ HIP_VISIBLE_DEVICES= CUDA_VISIBLE_DEVICES= nice -n 19 python -m pytest tests/test_hy4_engram_rows.py -q -s
+Oracle part (needs the Hy4 Q3_K parts + the llama.cpp dump, else skipped; env HY4_GGUF, HY4_ORACLE override the paths;
+HY4_PROMPTS=p1_short_en,... and HY4_MAX_CALLS cap the work):
+ layer 1 (the only dumped Engram layer): input = c<N>_l_out-0 (stream after layer 0), tokens = prompt_ids + gen_ids,
+ target = c<N>_engram_out-1, same call, same positions. Bar: max abs / max|ref| < 1e-3 (the _rel of tests/test_glm_dec2.py:91,
+ the only kyo_reg bar on a decoded-vs-reference tensor; no GLM-vs-llama.cpp-dump bar exists in tests/)."""
+import importlib.util, json, os, sys, types
+import numpy as np
+import pytest
+import torch
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+GGUF = os.environ.get("HY4_GGUF", "/path/to/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf")
+ORACLE = os.environ.get("HY4_ORACLE", "/path/to/oracle_out")
+BAR = 1e-3
+
+
+def _stub():
+ for name, sub in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ if name not in sys.modules:
+ m = types.ModuleType(name)
+ m.__path__ = [os.path.join(ROOT, "exllamav3", sub)]
+ sys.modules[name] = m
+
+
+def _load(modname, rel):
+ _stub()
+ if modname in sys.modules:
+ return sys.modules[modname]
+ spec = importlib.util.spec_from_file_location(modname, os.path.join(ROOT, rel))
+ mod = importlib.util.module_from_spec(spec)
+ mod.__package__ = modname.rsplit(".", 1)[0]
+ sys.modules[modname] = mod
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def rows_mod():
+ return _load("exllamav3.loader.engram_rows", "exllamav3/loader/engram_rows.py")
+
+
+def mem_avail_gib():
+ for ln in open("/proc/meminfo"):
+ if ln.startswith("MemAvailable"):
+ return int(ln.split()[1]) / 2 ** 20
+ return 0.0
+
+
+# ---------------------------------------------------------------- E4M3 / E8M0 exactness
+def test_e4m3_table_vs_torch_reference():
+ R = rows_mod()
+ ref = torch.arange(256, dtype=torch.uint8).view(torch.float8_e4m3fn).float() # torch's own e4m3fn, independent of the table code
+ t = R.E4M3
+ assert torch.equal(torch.isnan(t), torch.isnan(ref)) and int(torch.isnan(ref).sum()) == 2 # 0x7f, 0xff
+ ok = ~torch.isnan(ref)
+ assert torch.equal(t[ok].view(torch.int32), ref[ok].view(torch.int32)) # bit-exact incl. -0.0
+ assert float(t[0x7E]) == 448.0 and float(t[1]) == 2.0 ** -9
+
+
+def test_e8m0_table():
+ R = rows_mod()
+ for e in (0, 1, 100, 127, 128, 254):
+ assert float(R.E8M0[e]) == float(np.ldexp(1.0, e - 127))
+ assert torch.isnan(R.E8M0[255])
+
+
+# ---------------------------------------------------------------- layout choice + lookup on synthetic tensors
+class FakeG:
+ """minimal collection: one file, tensors at given offsets, header base 0"""
+ def __init__(self, path, infos):
+ self.fds, self.bases, self.infos = [os.open(path, os.O_RDONLY)], [0], infos
+
+ def _pread(self, off, n):
+ fi, off = off >> 48, off & ((1 << 48) - 1)
+ return np.frombuffer(os.pread(self.fds[fi], n, self.bases[fi] + off), dtype=np.uint8)
+
+
+def _fake(tmp_path, nbytes, width, rows, tail=0, payload=None):
+ p = tmp_path / "f.bin"
+ data = payload if payload is not None else np.random.default_rng(0).integers(0, 256, nbytes, dtype=np.uint8)
+ p.write_bytes(bytes(data) + bytes(tail))
+ return FakeG(str(p), {"per_layer_token_embd.weight": (43, (width, rows), 0)}), data
+
+
+def _nonan(a):
+ a = a.copy(); a[(a & 127) == 127] = 0x38; return a
+
+
+def test_plain_layout_rows(tmp_path):
+ R = rows_mod()
+ w, n = 96, 50
+ g, data = _fake(tmp_path, w * n, w, n, payload=_nonan(np.random.default_rng(1).integers(0, 256, w * n, dtype=np.uint8)))
+ t = R.F8Rows(g)
+ assert t.layout == "plain" and t.row_bytes == 96
+ ids = torch.tensor([[3, 49], [0, 3]])
+ ref = torch.from_numpy(data).view(torch.float8_e4m3fn).float().reshape(n, w)
+ out = t.lookup(ids)
+ assert out.shape == (2, 2, 96) and torch.equal(out, ref[ids])
+ with pytest.raises(IndexError):
+ t.lookup([50])
+
+
+def test_blocked_layout_rows(tmp_path):
+ R = rows_mod()
+ w, n = 96, 40
+ rng = np.random.default_rng(2)
+ rows = np.concatenate([_nonan(rng.integers(0, 256, (n, w), dtype=np.uint8)), rng.integers(110, 140, (n, w // 32), dtype=np.uint8)], 1)
+ g, _ = _fake(tmp_path, 0, w, n, payload=rows.reshape(-1))
+ t = R.F8Rows(g)
+ assert t.layout == "blocked" and t.row_bytes == 99
+ # independent reference: tree dequant_rows (torch e4m3fn / e8m0fnu dtypes), exllamav3/dsv41/engram.py:393 formula
+ v = torch.from_numpy(rows[:, :w].copy()).view(torch.float8_e4m3fn).float().unflatten(-1, (-1, 32))
+ s = torch.from_numpy(rows[:, w:].copy()).view(torch.float8_e8m0fnu).float()
+ ref = (v * s.unsqueeze(-1)).flatten(-2)
+ ids = torch.tensor([0, 7, 39, 7])
+ assert torch.equal(t.lookup(ids), ref[ids])
+ # real DS4.1 width: 256 values + 8 scales = 264 B
+ r2 = np.concatenate([_nonan(rng.integers(0, 256, (5, 256), dtype=np.uint8)), rng.integers(120, 135, (5, 8), dtype=np.uint8)], 1)
+ g2, _ = _fake(tmp_path, 0, 256, 5, payload=r2.reshape(-1))
+ t2 = R.F8Rows(g2)
+ assert t2.layout == "blocked" and t2.row_bytes == 264
+
+
+def test_layout_padding_and_refusal(tmp_path):
+ R = rows_mod()
+ # ggml pads the tensor to 32 B: 96*50 = 4800 (already a multiple), 33*... use an odd count
+ assert R.f8_layout(96 * 5, 480, 96) == "plain"
+ assert R.f8_layout(96 * 5, 495, 96) == "blocked" and R.f8_layout(96 * 5, 512, 96) == "blocked"
+ for bad in (479, 500, 1000):
+ with pytest.raises(R.F8LayoutError, match="neither plain"):
+ R.f8_layout(96 * 5, bad, 96)
+ assert R.f8_layout(256 * 10, 264 * 10, 256) == "blocked" # the DS4.1 264 B / 256-element row
+ with pytest.raises(R.F8LayoutError, match="neither plain"):
+ R.f8_layout(256 * 10, 265 * 10, 256)
+ w, n = 96, 10
+ g, _ = _fake(tmp_path, w * n + 40, w, n)
+ with pytest.raises(R.F8LayoutError, match="refusing"):
+ R.F8Rows(g)
+
+
+def test_registry_and_loader_wiring():
+ cfgm = _load("exllamav3.loader.gguf_config", "exllamav3/loader/gguf_config.py")
+ assert cfgm.GGML_FMT[43] == "f8_e4m3"
+ reg = _load("exllamav3.loader.gguf_registry", "exllamav3/loader/gguf_registry.py")
+ importlib.import_module("exllamav3.loader.gguf_blocks.engram") # registers engram / engram_hy4 / f8_rows
+ B = reg.REGISTRY
+
+ class G: # header view
+ def __init__(self, hy4):
+ self.meta = {"general.architecture": "x", "x.block_count": 3, "x.ple.layers": [1], "x.ple.ngram_size": 3, "x.ple.heads_per_ngram": 8,
+ "x.embedding_length_per_layer_input": 96}
+ names = ["blk.1.engram_kv.weight", "blk.1.engram_gate.weight"] + (["blk.1." + s for s in ("engram_kv_b.weight", "engram_lookup_norm.weight",
+ "engram_pre_gamma.weight", "engram_hc_scale.weight")] if hy4 else [])
+ self.infos = {n: (0, (4, 4), 0) for n in names}
+ for hy4 in (True, False):
+ ctx = reg.Ctx(G(hy4))
+ assert B["engram_hy4"].select(ctx, 1) is hy4 and B["engram"].select(ctx, 1) is (not hy4)
+ assert not B["engram_hy4"].select(ctx, 0) and not B["engram"].select(ctx, 2)
+ assert B["engram_hy4"].build is not None and B["f8_rows"].build is not None and B["engram"].build is None
+
+
+# ---------------------------------------------------------------- oracle
+def _prompts():
+ sel = os.environ.get("HY4_PROMPTS", "p1_short_en,p4_long_n700,p5_long_n4000").split(",")
+ return [s for s in sel if os.path.isfile(f"{ORACLE}/{s}/index.json")]
+
+
+def _have_oracle():
+ return os.path.isfile(GGUF) and os.path.isdir(ORACLE)
+
+
+def run_oracle(prompt, R, eng, g, max_calls, tag=""):
+ idx = json.load(open(f"{ORACLE}/{prompt}/index.json"))
+ tokens = list(idx["prompt_ids"]) + list(idx["gen_ids"])
+ by = {(t["name"], t["layer"], t["call"]): t for t in idx["tensors"]}
+ rows = []
+ calls = sorted({c for (n, l, c) in by if n == "engram_out" and l == 1})[:max_calls]
+ for c in calls:
+ te, tl = by[("engram_out", 1, c)], by[("l_out", 0, c)]
+ assert te["positions"] == tl["positions"] and te["shape_ggml"] == tl["shape_ggml"], (prompt, c)
+ n = len(te["positions"])
+ rd = lambda t: np.fromfile(f"{ORACLE}/{prompt}/{t['file']}", dtype=np.float32).reshape(n, 4, 3072)
+ x, ref = torch.from_numpy(rd(tl)), torch.from_numpy(rd(te))
+ out = torch.empty_like(ref)
+ for k, pos in enumerate(te["positions"]): # non-contiguous positions: one token at a time
+ out[k:k + 1] = eng(x[k:k + 1], tokens, pos)
+ ma = float((out - ref).abs().max())
+ rel = ma / float(ref.abs().max())
+ dl = float((ref - x).abs().max())
+ rows.append((prompt + tag, c, n, ma, rel, ma / dl))
+ return rows
+
+
[email protected](not _have_oracle(), reason="Hy4 GGUF / oracle dump not on this host")
+def test_engram_layer1_vs_oracle():
+ if mem_avail_gib() < 14:
+ pytest.skip(f"MemAvailable {mem_avail_gib():.1f} GiB < 14")
+ R = rows_mod()
+ gc = _load("exllamav3.loader.gguf_collection", "exllamav3/loader/gguf_collection.py")
+ g = gc.GGUFCollection(GGUF)
+ table = R.F8Rows(g)
+ assert table.layout == "plain" and table.row_bytes == 96 and table.rows == 660006416
+ eng = R.Hy4Engram(g, 1, table=table)
+ engq = R.Hy4Engram(g, 1, table=table, q8_act=True)
+ mc = int(os.environ.get("HY4_MAX_CALLS", "40"))
+ allrows, qrows = [], []
+ for p in _prompts():
+ allrows += run_oracle(p, R, eng, g, mc)
+ qrows += run_oracle(p, R, engq, g, mc, tag="+q8act")
+ print()
+ print("prompt call ntok max_abs rel(maxabs/max|ref|) rel_to_delta bar PASS/FAIL [layer 1: l_out-0 -> engram_out-1]")
+ for p, c, n, ma, rel, rd in allrows + qrows:
+ print(f"{p} c{c:03d} n={n} {ma:.3e} {rel:.3e} {rd:.3e} {BAR:.0e} {'PASS' if rel < BAR else 'FAIL'}")
+ print("worst exact-fp32 rel %.3e, worst q8-act-emulated rel %.3e" % (max(r[4] for r in allrows), max(r[4] for r in qrows)))
+ # llama.cpp CPU quantises the activation of a Q8_0 mul_mat to Q8_0: the engine's exact-fp32 path differs from the dump by that
+ # (~1e-3 of max|ref|); the emulated path must meet the bar, the exact path is only bounded (5e-3)
+ assert qrows and all(r[4] < BAR for r in qrows)
+ assert all(r[4] < 5e-3 for r in allrows)