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.

Carry the live tree uncommitted base changes the Hy4 loader needs (mla_sink_attend allow mask, Q3_K grouped MoE format id, hy4 forward test)

YanissAmz1b8886eeeb12
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh
index 50cdcf7..3abf06c 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_gemv.cuh
@@ -874,6 +874,11 @@ __device__ float fq_dot_q8_0_q8(const uint8_t* __restrict__ wr,
#define FQ_Q6_K_GROUP 256
#define FQ_Q6_K_BYTES 210
+// Q3_K geometry (ggml block_q3_K): hmask[32] at +0 (inverted high bits), qs[64] at +32, 12 packed 6-bit scales at +96, d half at +108;
+// 110 B per 256-block (2-byte aligned only: every load below is a memcpy).
+#define FQ_Q3_K_GROUP 256
+#define FQ_Q3_K_BYTES 110
+
// IQ4_XS geometry: d half at +0, scales_h u16 at +2, scales_l[4] at +4,
// qs[128] at +8; 136 B per 256-block.
#define FQ_IQ4_XS_GROUP 256
@@ -1223,6 +1228,54 @@ __device__ float fq_dot_q6_k_q8(const uint8_t* __restrict__ wr,
return acc;
}
+// Q3_K q8_1 lane dot: per-thread partial over 16-elem sub-chunks (iqs = c & 15 within each 256-block b = c >> 4). Verbatim ggml
+// vec_dot_q3_K_q8_1 (ggml_mmvq/ggml_vecdotq_k46.cuh), same fadd/fmul order as fq_dot_q6_k_q8; vi = vil - vih has bytes in [-4, 3], so the wrapping
+// per-byte fq_vsub4 equals the saturating __vsubss4.
+__device__ float fq_dot_q3_k_q8(const uint8_t* __restrict__ wr,
+ const uint8_t* __restrict__ aqb,
+ int K, int tid, int nthreads)
+{
+ int nsub = K / 16;
+ float acc = 0.0f;
+ for (int c = tid; c < nsub; c += nthreads)
+ {
+ int b = c >> 4;
+ int iqs = c & 15;
+ const uint8_t* blk = wr + (size_t)b * FQ_Q3_K_BYTES;
+ int bq8_offset = 4 * (iqs / 8);
+ int scale_offset = iqs - iqs % 8 + (iqs % 8) / 4;
+ int32_t vl, vm;
+ memcpy(&vl, blk + 32 + 4 * iqs, 4);
+ memcpy(&vm, blk + 4 * (iqs % 8), 4);
+ int32_t vh = ~vm >> bq8_offset;
+ const uint8_t* scales = blk + 96;
+ __half dh;
+ memcpy(&dh, blk + 108, 2);
+ float d = __half2float(dh);
+ float sumf = 0.0f;
+ #pragma unroll
+ for (int i = 0; i < 4; i++)
+ {
+ int isc = scale_offset + 2 * i;
+ int sc_low = (scales[isc % 8] >> (4 * (isc / 8))) & 0xF;
+ int sc_high = ((scales[8 + isc % 4] >> (2 * (isc / 4))) & 3) << 4;
+ int sc = (sc_low | sc_high) - 32;
+ uint32_t vil = ((uint32_t)vl >> (2 * i)) & 0x03030303u;
+ uint32_t vih = (uint32_t)((vh >> i) << 2) & 0x04040404u;
+ uint32_t vi = fq_vsub4(vil, vih);
+ const uint8_t* aqb_blk = aqb + (size_t)(b * 8 + bq8_offset + i) * FQ_Q8_1_BYTES;
+ __half dah;
+ memcpy(&dah, aqb_blk, 2);
+ float d8 = __half2float(dah);
+ int32_t u;
+ memcpy(&u, aqb_blk + 4 + 4 * (iqs % 8), 4);
+ sumf = __fadd_rn(sumf, __fmul_rn(d8, (float)(fq_dp4a((int32_t)vi, u, 0) * sc)));
+ }
+ acc = __fadd_rn(acc, __fmul_rn(d, sumf));
+ }
+ return acc;
+}
+
// IQ4_XS codebook as two register-held u64 (bytes = verbatim kvalues_iq4nl
// as u8: P0 = bytes 0..7, P1 = bytes 8..15). Register shifts replace the 32
// divergent L1 loads per chunk below; the extracted bytes (hence the dp4a
diff --git a/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu
index 2436d0d..05c18d8 100644
--- a/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu
+++ b/exllamav3/exllamav3_ext/foreign_quant/fq_moe_kq.cu
@@ -86,6 +86,11 @@ __global__ void fq_moe_kq_upgate_kernel(const uint8_t* __restrict__ aqb,
g = fq_dot_iq3_xxs_q8(gr, aq, K, lane, FQ_GEMV_LANES);
u = fq_dot_iq3_xxs_q8(ur, aq, K, lane, FQ_GEMV_LANES);
}
+ else if constexpr (FMT == 8)
+ {
+ g = fq_dot_q3_k_q8(gr, aq, K, lane, FQ_GEMV_LANES);
+ u = fq_dot_q3_k_q8(ur, aq, K, lane, FQ_GEMV_LANES);
+ }
else
{
g = fq_dot_iq2_s_q8(gr, aq, K, lane, FQ_GEMV_LANES);
@@ -375,6 +380,8 @@ __global__ void fq_moe_kq_down_kernel(const uint8_t* __restrict__ aqb,
p = fq_dot_iq4_xs_q8(dr, aq, I, lane, FQ_GEMV_LANES);
else if constexpr (FMT == 4)
p = fq_dot_iq3_xxs_q8(dr, aq, I, lane, FQ_GEMV_LANES);
+ else if constexpr (FMT == 8)
+ p = fq_dot_q3_k_q8(dr, aq, I, lane, FQ_GEMV_LANES);
else if constexpr (FMT == 6)
p = fq_dot_q8_0_q8(dr, aq, I, lane, FQ_GEMV_LANES);
else if constexpr (FMT == 7)
@@ -470,7 +477,7 @@ static void fq_moe_kq_grouped_launch(torch::Tensor h, torch::Tensor sel, torch::
int E = (int)up_ptrs.numel();
// I from the down row stride (down rows are I-wide, like Bolt's
// derivation from down_stride).
- int I = (int)(down_stride / block_bytes) * ((FMT_D >= 6) ? 32 : FQ_Q4_K_GROUP); // ids 6 / 7: 32-element blocks
+ int I = (int)(down_stride / block_bytes) * ((FMT_D == 6 || FMT_D == 7) ? 32 : FQ_Q4_K_GROUP); // ids 6 / 7: 32-element blocks (8 = q3_k: 256)
at::cuda::CUDAGuard guard(h.device());
auto stream = at::cuda::getCurrentCUDAStream().stream();
const int Sg = S + (sh.gate != nullptr ? R : 0); // routed slots + one shared-expert slot per row
@@ -578,8 +585,8 @@ void fq_moe_iq4xs_grouped_q8(torch::Tensor h, torch::Tensor sel, torch::Tensor w
FQ_IQ4_XS_BYTES, partial, out);
}
-static const int64_t kFmtBytes[8] = {FQ_Q4_K_BYTES, FQ_Q5_K_BYTES, FQ_Q6_K_BYTES, FQ_IQ4_XS_BYTES, FQ_IQ3_XXS_BYTES, FQ_IQ2_S_BYTES,
- FQ_Q8_0_BYTES, FQ_Q5_1_BYTES};
+static const int64_t kFmtBytes[9] = {FQ_Q4_K_BYTES, FQ_Q5_K_BYTES, FQ_Q6_K_BYTES, FQ_IQ4_XS_BYTES, FQ_IQ3_XXS_BYTES, FQ_IQ2_S_BYTES,
+ FQ_Q8_0_BYTES, FQ_Q5_1_BYTES, FQ_Q3_K_BYTES};
template <int FU>
static void fq_moe_kq_dispatch_d(int fd, torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
@@ -597,11 +604,12 @@ static void fq_moe_kq_dispatch_d(int fd, torch::Tensor h, torch::Tensor sel, tor
case 5: fq_moe_kq_grouped_launch<FU, 5>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[5], partial, out, sh); break;
case 6: fq_moe_kq_grouped_launch<FU, 6>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[6], partial, out, sh); break;
case 7: fq_moe_kq_grouped_launch<FU, 7>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[7], partial, out, sh); break;
+ case 8: fq_moe_kq_grouped_launch<FU, 8>(h, sel, wts, gp, up, dp, gs, us, ds, kFmtBytes[8], partial, out, sh); break;
default: TORCH_CHECK(false, "fq_moe_kq: bad down format ", fd);
}
}
-// Mixed per-projection formats (unsloth UD: gate/up Q4_K + down Q5_K). fmt ids: 0 q4_k, 1 q5_k, 2 q6_k, 3 iq4_xs, 4 iq3_xxs, 5 iq2_s.
+// Mixed per-projection formats (unsloth UD: gate/up Q4_K + down Q5_K). fmt ids: 0 q4_k, 1 q5_k, 2 q6_k, 3 iq4_xs, 4 iq3_xxs, 5 iq2_s, (down only 6 q8_0, 7 q5_1), 8 q3_k (gate/up and down).
static void fq_moe_kq_grouped_mixed_impl(torch::Tensor h, torch::Tensor sel, torch::Tensor wts,
torch::Tensor gate_ptrs, torch::Tensor up_ptrs,
torch::Tensor down_ptrs,
@@ -617,6 +625,7 @@ static void fq_moe_kq_grouped_mixed_impl(torch::Tensor h, torch::Tensor sel, tor
case 3: fq_moe_kq_dispatch_d<3>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out, sh); break;
case 4: fq_moe_kq_dispatch_d<4>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out, sh); break;
case 5: fq_moe_kq_dispatch_d<5>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out, sh); break;
+ case 8: fq_moe_kq_dispatch_d<8>((int)fmt_down, h, sel, wts, gate_ptrs, up_ptrs, down_ptrs, gate_stride, up_stride, down_stride, partial, out, sh); break;
default: TORCH_CHECK(false, "fq_moe_kq: bad gate/up format ", fmt_ug);
}
}
diff --git a/exllamav3/modules/attention_fn/mla_sinks.py b/exllamav3/modules/attention_fn/mla_sinks.py
index 7733d9a..0ffd61a 100644
--- a/exllamav3/modules/attention_fn/mla_sinks.py
+++ b/exllamav3/modules/attention_fn/mla_sinks.py
@@ -9,13 +9,15 @@ llama.cpp hy-v4-flash.cpp build_attention M:5787-5947). Pure torch, no package i
import torch
-def mla_sink_attend(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, window=0):
+def mla_sink_attend(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, window=0, allow=None):
"""q_lat [T,H,R], q_pe [T,H,P], ckv [N,R], k_pe [N,P], qpos [T], kpos [N], sinks [H] or None -> o_lat [T,H,R]"""
s = torch.einsum("thr,nr->htn", q_lat, ckv) + torch.einsum("thp,np->htn", q_pe, k_pe)
s = s * scale
vis = kpos[None, :] <= qpos[:, None]
if window:
vis = vis & ((qpos[:, None] - kpos[None, :]) < window)
+ if allow is not None: # indexer selection: bool [T, N], a key outside the selected rows is masked (the sinks still apply)
+ vis = vis & allow
s = s.masked_fill(~vis[None], float("-inf"))
if sinks is not None:
s = torch.cat([s, sinks.float()[:, None, None].expand(-1, s.shape[1], 1)], dim=-1)
diff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.py
index bb5f7ea..84abcd8 100644
--- a/exllamav3/modules/block_sparse_mlp.py
+++ b/exllamav3/modules/block_sparse_mlp.py
@@ -223,6 +223,7 @@ _MOE_SH_FUSE = os.environ.get("EXL3_MOE_SH_FUSE", "1" if torch.version.hip else
_MOE_SH_SAID = [False]
# MCPM_FQ_MOE_IQ (default 1): IQ3_XXS / IQ2_S experts take the grouped q8_1 decode MoE (fq_moe_kq.cu FMT 4 / 5)
_FQ_MOE_IQ = os.environ.get("MCPM_FQ_MOE_IQ", "1") != "0"
+_FQ_MOE_Q3K = os.environ.get("MCPM_FQ_MOE_Q3K", "0") == "1" # Q3_K in the grouped mixed kernel (fmt id 8): off until the GPU cell passes
# HIP routed MMQ prefill MoE (rocm/gmmq, from Gufo / llama.cpp), default on with ROCm: Strix Halo Qwen3.8-Flash-Next UD-Q4_K_XL GGUF
# served 8K prefill 13.5-15.8 -> 10.8 s, decode flat, N1 md5 identical, perplexity 3.1671 -> 3.1797. 0 = the grouped Triton path.
_FQ_PF_GMMQ = os.environ.get("MCPM_FQ_PF_GMMQ", "1" if torch.version.hip else "0") == "1"
@@ -1827,6 +1828,8 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
# gate/up share one format, down has its own (unsloth UD: gate/up Q4_K + down Q5_K)
fmt = fmt_d = None
_ug_ok = ("q4_k", "q5_k", "q6_k", "iq4_xs") + (("iq3_xxs", "iq2_s") if _FQ_MOE_IQ else ())
+ if _FQ_MOE_Q3K:
+ _ug_ok = _ug_ok + ("q3_k",)
if _FQ_MOE_IQ and _MQ_MOE:
_ug_ok = _ug_ok + ("iq2_xs", "iq3_s", "iq4_nl", "iq2_xxs")
for m in self.gates + self.ups:
@@ -2126,7 +2129,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
h = y.reshape(R, -1)
dev = h.device
K = h.shape[1]
- _BB = {"q4_k": 144, "q5_k": 176, "q6_k": 210, "iq4_xs": 136, "iq3_xxs": 98, "iq2_s": 82, "q8_0": 34, "q5_1": 24,
+ _BB = {"q4_k": 144, "q5_k": 176, "q6_k": 210, "iq4_xs": 136, "iq3_xxs": 98, "iq2_s": 82, "q8_0": 34, "q5_1": 24, "q3_k": 110,
"iq2_xs": 74, "iq3_s": 110, "iq4_nl": 18, "iq2_xxs": 66}
_QK = lambda f: 32 if f in ("q8_0", "q5_1", "iq4_nl") else 256
bb = _BB[fmt]
@@ -2169,7 +2172,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
_MQ_ID[fmt], _MQ_ID[fmt_d], partial_v, routed_v)
elif sh is not None:
# shared expert in the same launches (extra slot per row); its gate row and the add are in the combine
- _FID = {"q4_k": 0, "q5_k": 1, "q6_k": 2, "iq4_xs": 3, "iq3_xxs": 4, "iq2_s": 5, "q8_0": 6, "q5_1": 7}
+ _FID = {"q4_k": 0, "q5_k": 1, "q6_k": 2, "iq4_xs": 3, "iq3_xxs": 4, "iq2_s": 5, "q8_0": 6, "q5_1": 7, "q3_k": 8}
ext.fq_moe_kq_grouped_mixed_sh_q8(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,
gate_stride, up_stride, down_stride, _FID[fmt], _FID[fmt_d],
self._fq_kq_partial[:R * (S + 1)], routed_v, *sh)
@@ -2178,7 +2181,7 @@ class BlockSparseMLP(BlockSparseMLP_CPU, Module):
gate_stride, up_stride, down_stride,
partial_v, routed_v)
else:
- _FID = {"q4_k": 0, "q5_k": 1, "q6_k": 2, "iq4_xs": 3, "iq3_xxs": 4, "iq2_s": 5, "q8_0": 6, "q5_1": 7}
+ _FID = {"q4_k": 0, "q5_k": 1, "q6_k": 2, "iq4_xs": 3, "iq3_xxs": 4, "iq2_s": 5, "q8_0": 6, "q5_1": 7, "q3_k": 8}
ext.fq_moe_kq_grouped_mixed_q8(h, sel, wts, gate_ptrs, up_ptrs, down_ptrs,
gate_stride, up_stride, down_stride, _FID[fmt], _FID[fmt_d],
partial_v, routed_v)
diff --git a/tests/test_gguf_hy4_forward.py b/tests/test_gguf_hy4_forward.py
new file mode 100644
index 0000000..3c4044d
--- /dev/null
+++ b/tests/test_gguf_hy4_forward.py
@@ -0,0 +1,141 @@
+"""Hy4-flash whole-model slow path (loader/hy4_forward.py) vs the llama.cpp oracle (CPU, torch only, no extension).
+ - Q3_K / Q4_K torch dequant vs a literal python port of ggml dequantize_row_q3_K / q4_K, and vs foreign_quant.gap_formats (q3_k)
+ - is_hy4_plan: true for the Hy4 plan, false for a plan with other blocks
+ - truncated depth (embedding + layers 0..2, prompt p1): attention vs the oracle dumps (layers 0 / 1, whose input is exact) >= 0.9999,
+ layer outputs l_out >= 0.98, engram_out-1 >= 0.999
+ - full depth (HY4_FULL=1 and MemAvailable >= 40 GiB): final logits argmax / top-20 overlap vs result_output of call 0, 3 greedy ids
+Skips when the GGUF / oracle dumps are absent. Prints counts and cosines only."""
+import json, os, sys, types, importlib.util
+import numpy as np
+import pytest
+import torch
+
+sys.path.insert(0, os.path.dirname(__file__))
+import test_gguf_hy4_hc as T # stub packages + registry
+from test_gguf_hy4_hc import ROOT, ORACLE, gg
+from test_gguf_hy4_attn import mem_avail_gib
+from exllamav3.loader import hy4_forward as HF
+
+pytestmark = pytest.mark.skipif(not (os.path.isdir(ORACLE) and os.path.exists(T.GGUF1)), reason="oracle dumps / Hy4 GGUF absent")
+
+
+# ---------------------------------------------------------------- dequant
+def _q3k_c(blk):
+ """literal port of ggml dequantize_row_q3_K for one 110-byte block"""
+ hm, qs, sc, d = blk[0:32], blk[32:96], blk[96:108].copy(), np.frombuffer(blk[108:110].tobytes(), np.float16)[0].astype(np.float32)
+ aux = np.zeros(4, np.uint32)
+ aux[:3] = np.frombuffer(sc.tobytes(), np.uint32)
+ k1, k2 = np.uint32(0x03030303), np.uint32(0x0f0f0f0f)
+ tmp = aux[2]
+ aux[2] = ((aux[0] >> 4) & k2) | (((tmp >> 4) & k1) << 4)
+ aux[3] = ((aux[1] >> 4) & k2) | (((tmp >> 6) & k1) << 4)
+ aux[0] = (aux[0] & k2) | (((tmp >> 0) & k1) << 4)
+ aux[1] = (aux[1] & k2) | (((tmp >> 2) & k1) << 4)
+ scales = np.frombuffer(aux.tobytes(), np.int8)
+ y, q, m, is_ = [], 0, 1, 0
+ for n in range(0, 256, 128):
+ shift = 0
+ for j in range(4):
+ for half in range(2):
+ dl = d * (int(scales[is_]) - 32)
+ is_ += 1
+ for l in range(16):
+ ll = l + 16 * half
+ y.append(dl * (int((qs[q + ll] >> shift) & 3) - (0 if hm[ll] & m else 4)))
+ shift += 2
+ m <<= 1
+ q += 32
+ return np.array(y, np.float32)
+
+
+def test_q3k_matches_c_port_and_gap_formats():
+ rng = np.random.default_rng(3)
+ raw = rng.integers(0, 256, size=(4, 110), dtype=np.uint8)
+ raw[:, 108:110] = np.frombuffer(np.array([0.013, 0.07, 0.002, 0.1], np.float16).tobytes(), np.uint8).reshape(4, 2)
+ ref = np.stack([_q3k_c(b) for b in raw])
+ got = HF.dq_q3k(torch.from_numpy(raw), 4, 256).numpy()
+ assert np.abs(got - ref).max() <= 1e-6 * np.abs(ref).max()
+ sp = importlib.util.spec_from_file_location("exllamav3.foreign_quant.gap_formats", os.path.join(ROOT, "exllamav3", "foreign_quant", "gap_formats.py"))
+ pk = types.ModuleType("exllamav3.foreign_quant"); pk.__path__ = [os.path.join(ROOT, "exllamav3", "foreign_quant")]
+ sys.modules["exllamav3.foreign_quant"] = pk
+ gf = importlib.util.module_from_spec(sp); gf.__package__ = "exllamav3.foreign_quant"; sys.modules[sp.name] = gf
+ sp.loader.exec_module(gf)
+ gap = gf.dequant("q3_k", torch.from_numpy(raw)).float().numpy()
+ assert np.abs(gap - ref).max() <= 2e-3 * np.abs(ref).max()
+
+
+def test_q4k_matches_existing_reference():
+ import test_gguf_hy4_moe as M
+ rng = np.random.default_rng(4)
+ raw = rng.integers(0, 256, size=(3, 144), dtype=np.uint8)
+ raw[:, 0:4] = np.frombuffer(np.array([[0.02, 0.01]] * 3, np.float16).tobytes(), np.uint8).reshape(3, 4)
+ assert torch.equal(HF.dq_q4k(torch.from_numpy(raw), 3, 256), M.dq_q4k(raw, 3, 256))
+
+
+# ---------------------------------------------------------------- registry predicate
+def test_is_hy4_plan_only_for_hy4():
+ g, plan = gg()
+ assert HF.is_hy4_plan(plan)
+ other = types.SimpleNamespace(layers=[{}] * 2, glob={"head_mod": []}, blocks_at=lambda i: ["gqa", "residual", "dense"])
+ assert not HF.is_hy4_plan(other)
+
+
+# ---------------------------------------------------------------- oracle
+def _oracle(prompt):
+ idx = json.load(open(os.path.join(ORACLE, prompt, "index.json")))
+ by = {(t["name"], t["layer"], t["call"]): t for t in idx["tensors"] if t.get("occ", 0) == 0}
+
+ def get(name, layer, call=0):
+ t = by.get((name, layer, call))
+ if t is None:
+ return None
+ return torch.from_numpy(np.fromfile(os.path.join(ORACLE, prompt, t["file"]), dtype="<f4")).reshape(tuple(reversed(t["shape_ggml"])))
+ return idx, get
+
+
+def _cos(a, b):
+ a, b = a.float().reshape(a.shape[0], -1), b.float().reshape(b.shape[0], -1)
+ return float(torch.nn.functional.cosine_similarity(a, b, dim=1).min())
+
+
+def _run(prompt, layers, gen=0):
+ idx, get = _oracle(prompt)
+ cmp = {}
+
+ def hook(name, i, t):
+ o = get(name, i)
+ if o is not None and o.numel() == t.numel():
+ cmp[(name, i)] = _cos(t.cpu(), o)
+ g, _ = gg()
+ M = HF.Hy4Forward(g, n_layers=layers, hook=hook)
+ ids = idx["prompt_ids"]
+ if gen:
+ first, out, _t = M.generate(ids, gen)
+ return idx, get, cmp, first, out
+ return idx, get, cmp, M.step(ids), []
+
+
+def test_truncated_depth_vs_oracle():
+ idx, get, cmp, _, _ = _run("p1_short_en", 3)
+ print({f"{k[0]}-{k[1]}": round(v, 6) for k, v in sorted(cmp.items(), key=lambda kv: (kv[0][1], kv[0][0]))})
+ for L in (0, 1): # exact oracle inputs: layer 0 (embedding), layer 1 (engram_out is checked below)
+ for n in ("attn_kqv", "attn_gated", "attn_out"):
+ assert cmp[(n, L)] >= 0.9999, (n, L, cmp[(n, L)])
+ assert cmp[("engram_out", 1)] >= 0.999
+ for L in (0, 1, 2):
+ assert cmp[("l_out", L)] >= 0.98
+ assert cmp[("attn_out", L)] >= 0.999
+
+
[email protected](os.environ.get("HY4_FULL") != "1" or mem_avail_gib() < 40, reason="full depth: HY4_FULL=1 and MemAvailable >= 40 GiB")
+def test_full_depth_p1():
+ idx, get, cmp, first, out = _run("p1_short_en", None, gen=3)
+ lo = get("result_output", -1)
+ lo = lo.reshape(-1, first.shape[0])[-1]
+ ot, tt = set(torch.topk(lo, 20).indices.tolist()), set(torch.topk(first, 20).indices.tolist())
+ print("argmax", int(first.argmax()), int(lo.argmax()), "overlap", len(ot & tt), "greedy", out, idx["gen_ids"][:3])
+ assert int(first.argmax()) == int(lo.argmax()) and len(ot & tt) >= 14
+
+
+if __name__ == "__main__":
+ sys.exit(pytest.main(["-q", "-s", __file__]))