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.

Tests/gemv harness (#155)

resynthf1291615fdcf
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index dbdba88..98f4e0f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -56,6 +56,31 @@ If a test or the first import hangs, look for a stale lock file at `~/.cache/tor
Kyojin is built on ExLlamaV3 by turboderp. A change that belongs to ExLlamaV3 itself (general quantisation, the CUDA path, the tokenizer, shared generator logic) should go to [turboderp-org/exllamav3](https://github.com/turboderp-org/exllamav3) first. Send to this repository what is specific to gfx1151, ROCm, the Strix Halo serving tools or the supported models.
+## Optional GPU decode checks
+
+These are extra manual checks for the ROCm decode path. They are not part of `pytest tests`
+and each needs a built extension, a free GPU and a model that fits the card. Set
+`EXL3_TEST_MODEL` to the pack and pin the device with `HIP_VISIBLE_DEVICES`.
+
+```bash
+# Run the same short prompt through the normal reconstruction path and the fast GEMV
+# path, then print top-1 agreement, route counts and logit differences.
+EXL3_TEST_MODEL=<model> python tests/hip_gemv_logits_oracle.py
+
+# Longer trace, and an optional unforced run that prints tokens for loop diagnosis.
+EXL3_TEST_MODEL=<model> EXL3_ORACLE_STEPS=128 python tests/hip_gemv_logits_oracle.py
+EXL3_TEST_MODEL=<model> EXL3_ORACLE_FREE=1 python tests/hip_gemv_logits_oracle.py
+
+# Eight everyday questions in two sampling modes: checks EOS, loop guard and repetition.
+HIP_VISIBLE_DEVICES=1 python tools/strix_halo/coherence_suite.py -m <model>
+
+# Times each matrix shape and a full streaming pass; --gemm compares with exl3_gemm.
+HIP_VISIBLE_DEVICES=1 python tools/strix_halo/gemv_perf_ab.py -m <model> --mode both --gemm
+```
+
+For an MCG-codebook pack, point `EXL3_TEST_MODEL` at that pack; the oracle command is
+the same. Say in the pull request which checks you ran.
+
## Licence
Contributions are under the MIT licence of the repository.
diff --git a/doc/roc_hip_decode.md b/doc/roc_hip_decode.md
index 805ce8d..2036167 100644
--- a/doc/roc_hip_decode.md
+++ b/doc/roc_hip_decode.md
@@ -67,7 +67,7 @@ Current local verification on gfx1201 includes:
- 63 grouped K3 MoE route, numerical, multirow, safety, LoRA, and fallback tests, plus opt-in full Flash and MTP oracles
- 44 native ROCm shared-gate fusion, stream, validation, and fallback tests
- 25 gfx12 batch-one router numerical, tie, stream, validation, fallback, and real-layer tests
-- forced-identical-context 16-step logits oracles for mul1 and MCG models
+- forced-identical-context logits oracles for mul1 and MCG fixtures (16-step default; `EXL3_ORACLE_STEPS` for longer traces)
The Qwen3.8-27B mul1 oracle reports:
@@ -156,4 +156,37 @@ EXL3_TEST_MODEL=/path/to/Qwen3.8-27B-exl3 \
EXL3_TEST_MODEL=/path/to/Qwen3.5-9B-exl3 \
python tests/hip_gemv_logits_oracle.py
-```
\ No newline at end of file
+# Longer trace: the oracle widens its delta bounds with the step count.
+EXL3_TEST_MODEL=/path/to/Qwen3.8-27B-exl3 EXL3_ORACLE_STEPS=128 \
+ python tests/hip_gemv_logits_oracle.py
+
+# Optional unforced pass: prints free-run route counts and token ids for loop
+# diagnosis; it is not asserted against the forced trace.
+EXL3_TEST_MODEL=/path/to/Qwen3.8-27B-exl3 EXL3_ORACLE_FREE=1 \
+ python tests/hip_gemv_logits_oracle.py
+
+# The strict route counts apply automatically to a directory named Qwen3.8-27B*.
+# Name the fixture explicitly for a 27B pack stored under another name; use
+# EXL3_ORACLE_FIXTURE=generic to force the permissive branch.
+EXL3_TEST_MODEL=/path/to/pack EXL3_ORACLE_FIXTURE=qwen38-27b \
+ python tests/hip_gemv_logits_oracle.py
+```
+
+## GPU decode harnesses
+
+These are manual scripts, not CPU CI. They need a built extension, a free GPU and a
+model that fits the visible device (use the layer-split sibling for larger packs).
+
+```sh
+# Whole-model chat-path coherence gate: 8 prompts x greedy/default, EOS, production
+# loop guard and 20-gram repetition checks.
+HIP_VISIBLE_DEVICES=1 python tools/strix_halo/coherence_suite.py -m <model> -n 192
+
+# Per-shape GEMV timings and one streaming pass over every linear; --gemm A/Bs
+# ext.exl3_gemm when the tree exports it.
+HIP_VISIBLE_DEVICES=1 python tools/strix_halo/gemv_perf_ab.py -m <model> --mode both --gemm
+```
+
+`tests/hip_gemv_logits_oracle.py` is the forced fallback-vs-GEMV logits oracle.
+`EXL3_ORACLE_STEPS` sets the trace length (default 16); `EXL3_ORACLE_FREE=1` adds the
+unforced diagnostic pass. Both the oracle and worker read the step variable.
diff --git a/tests/hip_gemv_logits_oracle.py b/tests/hip_gemv_logits_oracle.py
index 9ab50a3..b1931d4 100644
--- a/tests/hip_gemv_logits_oracle.py
+++ b/tests/hip_gemv_logits_oracle.py
@@ -10,10 +10,18 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
WORKER = REPO_ROOT / "tests" / "hip_gemv_logits_worker.py"
DEFAULT_MODEL = os.path.expanduser("~/Models/Qwen3.8-27B-exl3")
MODEL = os.environ.get("EXL3_TEST_MODEL", DEFAULT_MODEL)
-STEPS = 16
+# EXL3_ORACLE_STEPS (test only): forced-trace length; both the oracle and worker read it.
+STEPS = int(os.environ.get("EXL3_ORACLE_STEPS", "16"))
+FIXTURE = os.environ.get("EXL3_ORACLE_FIXTURE", "auto").strip().lower()
PROMPT = "The capital of France is"
+def _strict_fixture():
+ if FIXTURE == "auto":
+ return Path(MODEL).name.startswith("Qwen3.8-27B")
+ return FIXTURE in {"qwen38-27b", "strict"}
+
+
def _run_worker(mode, out_path, forced_path=None):
env = os.environ.copy()
env["EXL3_GEMV"] = "0" if mode == "fallback" else "2"
@@ -35,6 +43,14 @@ def main():
torch.save(fallback["token_ids"].clone(), forced_tokens_path)
_run_worker("gemv", gemv_path, forced_tokens_path)
gemv = torch.load(gemv_path, map_location="cpu")
+ # EXL3_ORACLE_FREE (test only): also run an unforced pass for loop/coherence
+ # diagnosis. It is reported, not asserted against the forced delta bounds.
+ if os.environ.get("EXL3_ORACLE_FREE", "0") != "0":
+ free_path = tmpdir / "free.pt"
+ _run_worker("free", free_path)
+ free = torch.load(free_path, map_location="cpu")
+ print(f"free_route_counts {free['counts']}")
+ print(f"free_token_ids {free['token_ids'].tolist()}")
fallback_tokens = fallback["token_ids"]
gemv_tokens = gemv["token_ids"]
@@ -50,16 +66,19 @@ def main():
assert fallback_counts["gemv"] == 0
assert fallback_counts["reconstruct"] > 0
assert fallback_counts["hgemm"] > 0
- if Path(MODEL).name == "Qwen3.8-27B-exl3":
+ if _strict_fixture():
# The known Qwen3.8-27B fixture produces about 6,813 GEMV calls. Remaining hgemm
# calls are independently ineligible architecture paths, not EXL3 reconstruction.
assert gemv_counts["gemv"] >= 5000
assert gemv_counts["gemv"] >= 2.5 * gemv_counts["hgemm"]
+ # Route proof for this fixture: every eligible tensor must have taken the GEMV.
+ assert gemv_counts["reconstruct"] == 0
+ assert gemv_counts["reconstruct_slice"] == 0
+ assert gemv_counts["reconstruct_had_slice"] == 0
else:
+ # Unknown fixtures: the K/codebook/shape envelope may legitimately reject some
+ # tensors, so require only that the GEMV route ran at least once.
assert gemv_counts["gemv"] > 0
- assert gemv_counts["reconstruct"] == 0
- assert gemv_counts["reconstruct_slice"] == 0
- assert gemv_counts["reconstruct_had_slice"] == 0
for logits in (fallback_logits, gemv_logits):
assert not torch.isnan(logits).any()
@@ -100,14 +119,30 @@ def main():
top5_min_overlap = top5_overlap.min().item()
print(f"route_counts fallback={fallback_counts} gemv={gemv_counts}")
- print(f"top1={top1_agree}/16 top5_exact={top5_exact}/16 top5_min_overlap={top5_min_overlap}/5")
+ print(f"top1={top1_agree}/{STEPS} top5_exact={top5_exact}/{STEPS} top5_min_overlap={top5_min_overlap}/5")
print(f"max={max_diff:.6f} worst_step_mean={mean_diff:.6f} overall_mean={overall_mean:.6f}")
- assert top1_agree == 16
- assert top5_min_overlap >= 4
- assert max_diff <= 0.55
- assert mean_diff <= 0.075
- assert overall_mean <= 0.05
+ assert top1_agree == STEPS
+ # Forced tokens make top1 identity a hard signal: the two arms share the token
+ # sequence, so any top1 disagreement is a real bug. The raw logit deltas, however,
+ # amplify through a hybrid recurrent (GDN) state because the cache is fed by the
+ # numerically different linears. Keep the tight bounds on the short trace and
+ # widen them with EXL3_ORACLE_STEPS; calibrate the tiers on the fixture used.
+ if STEPS <= 32:
+ assert top5_min_overlap >= 4
+ assert max_diff <= 0.55
+ assert mean_diff <= 0.075
+ assert overall_mean <= 0.05
+ elif STEPS <= 64:
+ assert top5_min_overlap >= 4
+ assert max_diff <= 1.5
+ assert mean_diff <= 0.15
+ assert overall_mean <= 0.05
+ else:
+ assert top5_min_overlap >= 2
+ assert max_diff <= 12.0
+ assert mean_diff <= 1.5
+ assert overall_mean <= 0.12
if __name__ == "__main__":
diff --git a/tests/hip_gemv_logits_worker.py b/tests/hip_gemv_logits_worker.py
index 22a1e2f..3045594 100644
--- a/tests/hip_gemv_logits_worker.py
+++ b/tests/hip_gemv_logits_worker.py
@@ -38,7 +38,8 @@ def _require_gfx12():
f"ext.exl3_gemv_supported rejected gfx12 device 0 ({arch})"
-STEPS = 16
+# EXL3_ORACLE_STEPS (test only): forced-trace length; the oracle reads the same var.
+STEPS = int(os.environ.get("EXL3_ORACLE_STEPS", "16"))
PROMPT = "The capital of France is"
@@ -49,8 +50,10 @@ def main():
if not os.path.isdir(MODEL):
raise SystemExit(f"Test model not found: {MODEL}")
+ # free: unforced generation for loop/coherence diagnosis; it is reported, not
+ # compared against the forced fallback trace.
mode = sys.argv[1]
- if mode not in {"fallback", "gemv"}:
+ if mode not in {"fallback", "gemv", "free"}:
raise SystemExit(f"invalid mode: {mode}")
output_path = Path(sys.argv[2])
force_tokens_path = Path(sys.argv[3]) if len(sys.argv) > 3 else None
@@ -66,7 +69,7 @@ def main():
job = Job(
input_ids=tokenizer.encode(PROMPT, add_bos=True),
- max_new_tokens=STEPS + 1,
+ max_new_tokens=STEPS,
stop_conditions=[],
return_logits=True,
sampler=GreedySampler(),
diff --git a/tests/test_hip_gemv_decode.py b/tests/test_hip_gemv_decode.py
index c503c2e..87bbca5 100644
--- a/tests/test_hip_gemv_decode.py
+++ b/tests/test_hip_gemv_decode.py
@@ -153,6 +153,11 @@ def _spy_ext_route():
# The livescope model fixture used by the comparison test loads individual modules and MUST
# unload them even when an assertion fails, or aggregate modules stay resident for later tests.
+def _mmode2_eligible(linear):
+ return (int(linear.K), bool(linear.mcg), bool(linear.mul1)) in \
+ exl3_quant._EXL3_GEMV_HIP_MMODE2_VARIANTS
+
+
def _load_then_compare(model, linear_key, norm_key, batch_size, out_dtype=None, expected_K=None):
# Route proof: a missing binding is a FAILURE, not a skip -- the whole point of this
# suite is to prove the HIP GEMV route executes.
@@ -165,9 +170,14 @@ def _load_then_compare(model, linear_key, norm_key, batch_size, out_dtype=None,
if norm:
norm.load(device="cuda")
linear.load(device="cuda")
- if expected_K is not None:
- assert linear.inner.K == expected_K
- assert linear.inner.mcg != linear.inner.mul1
+ if batch_size > exl3_quant._EXL3_GEMV_HIP_MMODE1_MAX_M and not _mmode2_eligible(linear.inner):
+ pytest.skip(f"{linear_key}: no MMODE-2 kernel for K={linear.inner.K} "
+ f"mcg={bool(linear.inner.mcg)} mul1={bool(linear.inner.mul1)}")
+ if expected_K is not None and (linear.inner.K != expected_K or
+ bool(linear.inner.mcg) == bool(linear.inner.mul1)):
+ pytest.skip(f"{linear_key}: K={linear.inner.K} "
+ f"mcg={bool(linear.inner.mcg)} mul1={bool(linear.inner.mul1)} "
+ f"does not match the expected K={expected_K} fixture")
torch.manual_seed(0)
x = torch.randn((1, batch_size, linear.in_features), dtype=torch.float16, device="cuda")
@@ -235,21 +245,36 @@ def test_hip_gemv_direct_binding_accepts_rank3_inputs():
@torch.inference_mode()
-def test_hip_gemv_k5_plain_codebook_is_rejected():
- """K5 requires the MCG or mul1 codebook; cb0 remains unsupported."""
- _require_gfx12()
- size = 128
- A = torch.randn((1, size), dtype=torch.float16, device="cuda") * 1e-3
- B = torch.full((size // 16, size // 16, 5 * 16), 0x1111,
- dtype=torch.int16, device="cuda")
- signs = torch.ones((size,), dtype=torch.float16, device="cuda")
- actual = torch.empty((1, size), dtype=torch.float16, device="cuda")
- A_had = torch.empty_like(A)
+def test_hip_gemv_k5_plain_codebook_falls_back():
+ """K5/cb0 is outside the model dispatch envelope and must use reconstruct+hgemm."""
+ from exllamav3.modules.quant.exl3 import LinearEXL3
- with pytest.raises(RuntimeError, match="not eligible"):
- ext.exl3_gemv(A, B, actual, signs, A_had, signs, False, False)
+ _require_gfx12()
+ torch.manual_seed(5500)
+ size_k = size_n = 128
+ trellis = _make_distinct_finite_trellis(5, size_k, size_n)
+ suh = (torch.randint(0, 2, (size_k,), device="cuda") * 2 - 1).to(torch.float16)
+ svh = (torch.randint(0, 2, (size_n,), device="cuda") * 2 - 1).to(torch.float16)
+ linear = LinearEXL3(None, size_k, size_n, suh=suh, svh=svh, trellis=trellis,
+ mcg=None, mul1=None)
+ try:
+ x = torch.randn((1, 1, size_k), dtype=torch.float16, device="cuda") * 1e-3
+ calls, restore = _spy_ext_route()
+ try:
+ actual = linear.forward(x, {"reconstruct": False})
+ finally:
+ restore()
+ assert calls["gemv"] == 0
+ assert calls["reconstruct"] > 0
+ assert calls["hgemm"] > 0
+ expected = linear.forward(x, {"reconstruct": True})
+ assert torch.isfinite(actual).all()
+ torch.testing.assert_close(actual, expected, rtol=0, atol=0.03)
+ finally:
+ linear.unload()
[email protected]("K", [2, 3, 4, 5, 6])
@pytest.mark.parametrize(
"mcg, multiplier, addend",
[
@@ -258,14 +283,13 @@ def test_hip_gemv_k5_plain_codebook_is_rejected():
],
)
@torch.inference_mode()
-def test_procedural_codebook_matches_lop3_zero_state(mcg, multiplier, addend):
+def test_procedural_codebook_matches_lop3_zero_state(K, mcg, multiplier, addend):
"""The portable codebook expression must match the original PTX lop3 LUT 0x6a.
A zero packed trellis decodes every weight from state zero, making the expected
fp16 codebook value independent of the trellis layout and reconstruction path.
"""
_require_gfx12()
- K = 4
packed = torch.zeros((8, 8, K * 16), dtype=torch.int16, device="cuda")
weight = torch.empty((128, 128), dtype=torch.float16, device="cuda")
ext.reconstruct(weight, packed, K, mcg, False)
@@ -325,7 +349,7 @@ def test_hip_gemv_synthetic_oracle(K, mcg, mul1):
ext.hgemm(A_ref, weight, expected)
ext.had_r_128(expected, expected, None, svh, 1.0)
- # All seven cases were bit-identical on gfx1201. A 0.03 absolute allowance retains
+ # These cases were bit-identical on gfx1201. A 0.03 absolute allowance retains
# modest fp16 rounding headroom without hiding an extraction/codebook mismatch.
torch.testing.assert_close(actual, expected, rtol=0, atol=0.03)
@@ -358,6 +382,47 @@ def test_hip_gemv_rows_9_to_16_synthetic_route_to_gemv(K, mcg, mul1, rows, out_d
torch.testing.assert_close(actual, expected, rtol=0, atol=0.03)
+def test_hip_gemv_mmode2_narrow_n_matches_matmul():
+ """MMODE-2 at size_n=128 matches an explicit reconstruct + torch.matmul reference.
+
+ This shape runs the ROCm skinny hgemm path (m<=32, n<=128); using reconstruct +
+ torch.matmul keeps the oracle independent of that GEMM's accumulation order.
+ """
+ from exllamav3.modules.quant.exl3 import LinearEXL3
+
+ _require_gfx12()
+ K = 5
+ size_k = size_n = 128
+ rows = 9
+ torch.manual_seed(9100)
+ trellis = _make_distinct_finite_trellis(K, size_k, size_n)
+ suh = (torch.randint(0, 2, (size_k,), device="cuda") * 2 - 1).to(torch.float16)
+ svh = (torch.randint(0, 2, (size_n,), device="cuda") * 2 - 1).to(torch.float16)
+ mul1 = torch.ones((), dtype=torch.int32, device="cuda")
+ linear = LinearEXL3(None, size_k, size_n, suh=suh, svh=svh, trellis=trellis,
+ mcg=None, mul1=mul1)
+ try:
+ x = torch.randn((1, rows, size_k), dtype=torch.float16, device="cuda") * 1e-3
+ weight = torch.empty((size_k, size_n), dtype=torch.half, device="cuda")
+ ext.reconstruct(weight, trellis, K, False, True)
+ xh = torch.empty((rows, size_k), dtype=torch.half, device="cuda")
+ ext.had_r_128(x.view(rows, size_k), xh, suh, None, 1.0)
+ expected = (xh.float() @ weight.float()).half()
+ ext.had_r_128(expected, expected, None, svh, 1.0)
+
+ calls, restore = _spy_ext_route()
+ try:
+ actual = linear.forward(x, {"reconstruct": False})
+ finally:
+ restore()
+ assert calls["gemv"] == 1, calls
+ assert calls["reconstruct"] == 0 and calls["hgemm"] == 0, calls
+ torch.testing.assert_close(actual.view(rows, size_n), expected, rtol=0, atol=0.03)
+ finally:
+ linear.unload()
+
+
@torch.inference_mode()
def test_hip_gemv_k2_rows_8_routes_to_gemv():
_require_gfx12()
@@ -384,6 +449,32 @@ def test_hip_gemv_k2_rows_9_falls_back():
torch.testing.assert_close(actual, expected, rtol=0, atol=0.03)
[email protected]("core", ["tiles", "direct", "lds"])
[email protected]("rows", [5, 6, 7])
+def test_hip_gemv_small_rows_opt_in_cores(rows, core, monkeypatch):
+ """size_m 5/6/7 pad the MR row tile to 8; all three cores must still
+ produce the oracle result. The padded rows' reads are discarded, so this
+ cannot detect an out-of-bounds read -- that needs a sanitizer run."""
+ monkeypatch.delenv("EXL3_ROCM_GEMV_TILES", raising=False)
+ monkeypatch.delenv("EXL3_GEMV_LDS", raising=False)
+ if core == "direct":
+ monkeypatch.setenv("EXL3_ROCM_GEMV_TILES", "0")
+ elif core == "lds":
+ monkeypatch.setenv("EXL3_GEMV_LDS", "1")
+
+ actual, expected, calls, x, size_n = _run_rows_synthetic_oracle(
+ 4, True, False, rows, torch.float16)
+ assert calls["gemv"] == 1
+ assert calls["reconstruct"] == 0
+ assert calls["reconstruct_slice"] == 0
+ assert calls["reconstruct_had_slice"] == 0
+ assert calls["hgemm"] == 0
+ assert torch.isfinite(actual).all()
+ assert torch.isfinite(expected).all()
+ torch.testing.assert_close(actual, expected, rtol=0, atol=0.03)
+
+
def _make_distinct_finite_trellis(K, size_k, size_n, device="cuda"):
"""Build a unique, finite packed stream for every (K-slice, N-tile)."""
kslices = size_k // 16
@@ -533,8 +624,9 @@ def test_hip_gemv_rows_9_to_16_route_to_gemv(model, rows):
linear = model.find_module("model.language_model.layers.3.self_attn.q_proj")
try:
linear.load(device="cuda")
- assert linear.inner.K == 4
- assert linear.inner.mcg != linear.inner.mul1
+ if not _mmode2_eligible(linear.inner):
+ pytest.skip(f"q_proj is K={linear.inner.K} mcg={bool(linear.inner.mcg)} "
+ f"mul1={bool(linear.inner.mul1)}; no MMODE-2 kernel for m={rows}")
x = torch.randn((1, rows, linear.in_features), dtype=torch.float16, device="cuda")
calls, restore = _spy_ext_route()
try:
@@ -614,13 +706,11 @@ def test_hip_gemv_rollback_cap_falls_back(model, monkeypatch):
@torch.inference_mode()
def test_hip_gemv_rows_over_limit_falls_back(model):
- """A K=4 decode batch with exactly seventeen rows must bypass HIP GEMV."""
+ """A decode batch with exactly seventeen rows must bypass HIP GEMV."""
assert exl3_quant.EXL3_GEMV_HIP_MAX_M == 16
linear = model.find_module("model.language_model.layers.3.self_attn.q_proj")
try:
linear.load(device="cuda")
- assert linear.inner.K == 4
- assert linear.inner.mcg != linear.inner.mul1
x = torch.randn((1, 17, linear.in_features), dtype=torch.float16, device="cuda")
calls, restore = _spy_ext_route()
try:
@@ -640,7 +730,8 @@ def test_hip_gemv_env_opt_out_falls_back(model, monkeypatch):
linear = model.find_module("lm_head")
try:
linear.load(device="cuda")
- assert linear.inner.K == 6
+ if linear.inner.K != 6:
+ pytest.skip(f"lm_head is K={linear.inner.K}; this test covers the K6 head")
x = torch.randn((1, 1, linear.in_features), dtype=torch.float16, device="cuda")
monkeypatch.setenv("EXL3_GEMV", "0")
calls, restore = _spy_ext_route()
diff --git a/tools/strix_halo/coherence_suite.py b/tools/strix_halo/coherence_suite.py
new file mode 100644
index 0000000..eb8d99b
--- /dev/null
+++ b/tools/strix_halo/coherence_suite.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python
+"""Free-run coherence gate for a dense EXL3 model.
+
+Not CPU CI: this loads a real model and generates on the visible device. It is the
+manual whole-model integration gate for the ROCm/gfx12 decode path: eight prompts
+covering factual, arithmetic, code, instruction-following and long-form output, run
+greedily and with the engine's default sampler. For each run it records the stop
+reason, the loop-guard verdicts used by tools/qwen/serve.py, the worst 20-gram
+repetition count and whether EOS was reached.
+
+ python tools/strix_halo/coherence_suite.py -m <model>
+ HIP_VISIBLE_DEVICES=1 python tools/strix_halo/coherence_suite.py -m <model> -n 512
+
+The model must fit the visible device (use the layer-split sibling for larger packs).
+
+"""
+import argparse
+import collections
+import os
+import sys
+
+p = argparse.ArgumentParser()
+p.add_argument("-m", "--model", default=os.environ.get("EXL3_TEST_MODEL", ""))
+p.add_argument("-n", "--max-new-tokens", type=int, default=256)
+p.add_argument("-c", "--cache-tokens", type=int, default=4096)
+p.add_argument("--modes", default="greedy,default")
+args = p.parse_args()
+if not args.model:
+ raise SystemExit("--model or EXL3_TEST_MODEL is required")
+
+import torch
+from exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer
+from exllamav3.generator.sampler import DefaultSampler, GreedySampler
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+from loopguard import answer_text_loop, text_loop # noqa: E402
+
+PROMPTS = [
+ ("factual", "What is the capital of France?", ["paris"]),
+ ("factual", "Who wrote the novel Pride and Prejudice?", ["austen"]),
+ ("arithmetic", "A shop sells pens for 3 dollars each. How much do 7 pens cost? Answer with the number.", ["21"]),
+ ("code", "Write a Python function called is_even that returns True for even integers. Reply with code only.", ["def", "is_even"]),
+ ("instruction", "List exactly three primary colours of light, one per line, and nothing else.", ["red", "blue", "green"]),
+ ("instruction", "Reply with the single word: BANANA", ["banana"]),
+ ("long-form", "Explain in two short paragraphs why the sky appears blue during the day.", []),
+ ("long-form", "Describe the water cycle in three sentences.", []),
+]
+
+
+def _worst_ngram_repeat(text, n=20):
+ words = text.split()
+ if len(words) < n:
+ return 0
+ counts = collections.Counter(tuple(words[i:i + n]) for i in range(len(words) - n + 1))
+ return max(counts.values())
+
+
+def _render(tokenizer, prompt):
+ """Render the pack's own Jinja chat template (no transformers dependency)."""
+ from jinja2 import BaseLoader
+ from jinja2.sandbox import ImmutableSandboxedEnvironment
+
+ path = os.path.join(tokenizer.config.directory, "chat_template.jinja")
+ if not os.path.isfile(path):
+ return prompt
+ env = ImmutableSandboxedEnvironment(loader=BaseLoader(), trim_blocks=True, lstrip_blocks=True)
+ env.globals["raise_exception"] = lambda msg: (_ for _ in ()).throw(ValueError(msg))
+ template = env.from_string(open(path, encoding="utf-8").read())
+ messages = [{"role": "user", "content": prompt}]
+ try:
+ return template.render(messages=messages, add_generation_prompt=True,
+ enable_thinking=False)
+ except Exception:
+ return template.render(messages=messages, add_generation_prompt=True)
+
+
+def _tokenize(tokenizer, prompt):
+ ids = tokenizer.encode(_render(tokenizer, prompt), add_bos=True,
+ encode_special_tokens=True)
+ if ids.dim() == 1:
+ ids = ids.unsqueeze(0)
+ return ids.contiguous()
+
+
+def run(gen, model, tokenizer, prompt, mode, max_new_tokens):
+ sampler = GreedySampler() if mode == "greedy" else DefaultSampler()
+ job = Job(input_ids=_tokenize(tokenizer, prompt),
+ max_new_tokens=max_new_tokens,
+ stop_conditions=list(model.config.eos_token_id_list),
+ return_logits=False,
+ sampler=sampler)
+ gen.enqueue(job)
+ text = ""
+ eos_reason = None
+ while gen.num_remaining_jobs():
+ for res in gen.iterate():
+ text += res.get("text", "")
+ if res.get("eos"):
+ eos_reason = res.get("eos_reason")
+ return text, eos_reason
+
+
+def main():
+ pr = torch.cuda.get_device_properties(0)
+ print(f"gpu {pr.name} / {pr.gcnArchName} / {pr.total_memory / 2**30:.1f} GiB", flush=True)
+ config = Config.from_directory(args.model)
+ model = Model.from_config(config)
+ tokenizer = Tokenizer.from_config(config)
+ cache = Cache(model, max_num_tokens=args.cache_tokens, max_batch_size=1)
+ model.load(progressbar=False)
+ gen = Generator(model=model, cache=cache, tokenizer=tokenizer)
+ modes = [m.strip() for m in args.modes.split(",") if m.strip()]
+ failures = []
+ try:
+ for mode in modes:
+ print(f"\n=== sampling: {mode} ===", flush=True)
+ for kind, prompt, keywords in PROMPTS:
+ text, eos_reason = run(gen, model, tokenizer, prompt, mode, args.max_new_tokens)
+ low = text.lower()
+ missing = [k for k in keywords if k not in low]
+ ngram = _worst_ngram_repeat(text)
+ guard = answer_text_loop(text) or text_loop(text)
+ eos = eos_reason in ("stop_token", "stop_string")
+ ok = not missing and not guard and ngram <= 2 and eos
+ if not ok:
+ failures.append((mode, kind, prompt, missing, guard, ngram, eos_reason))
+ print(f"[{'PASS' if ok else 'FAIL'}] {mode:7} {kind:12} "
+ f"eos={eos_reason!s:14} guard={int(guard)} max20={ngram} "
+ f"missing={missing} chars={len(text)}", flush=True)
+ print(f" {text[:220]!r}", flush=True)
+ finally:
+ model.unload()
+
+ print(f"\n{len(failures)} failure(s)")
+ for f in failures:
+ print(" ", f)
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/strix_halo/gemv_perf_ab.py b/tools/strix_halo/gemv_perf_ab.py
new file mode 100644
index 0000000..bd60010
--- /dev/null
+++ b/tools/strix_halo/gemv_perf_ab.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+"""Per-shape and streaming timings for the ROCm EXL3 GEMV route.
+
+Micro mode times `ext.exl3_gemv` per distinct (in, out, K, codebook) shape at
+m = 1 and reports effective weight bandwidth. Stream mode runs one pass over
+every EXL3 linear in the model, which removes the per-shape L2 reuse and is the
+number to compare with a decode step. `--gemm` also times `ext.exl3_gemm` when
+the tree exports it (upstream routing), for an A/B against the direct GEMV.
+
+Example:
+ HIP_VISIBLE_DEVICES=1 python tools/strix_halo/gemv_perf_ab.py \
+ -m <model> --mode both --gemm
+
+This loads the full model, so use a pack that fits the visible device (or the
+layer-split sibling for larger packs).
+"""
+import argparse
+import os
+import statistics
+import torch
+from exllamav3 import Config, Model
+from exllamav3.modules.quant.exl3 import LinearEXL3
+from exllamav3.util.tensor import g_tensor_cache
+import exllamav3.ext as extmod
+
+ext = extmod.exllamav3_ext
+
+
+def collect(model):
+ mods = []
+ stack = list(model.modules)
+ while stack:
+ mod = stack.pop()
+ inner = getattr(mod, "inner", None)
+ if isinstance(inner, LinearEXL3):
+ mods.append(inner)
+ stack.extend(getattr(mod, "modules", []) or [])
+ return mods
+
+
+def shape_key(l):
+ return (l.in_features, l.out_features, int(l.K), int(l.mcg) + 2 * int(l.mul1))
+
+
+def time_us(fn, iters):
+ for _ in range(10):
+ fn()
+ torch.cuda.synchronize()
+ e0 = torch.cuda.Event(enable_timing=True)
+ e1 = torch.cuda.Event(enable_timing=True)
+ e0.record()
+ for _ in range(iters):
+ fn()
+ e1.record()
+ torch.cuda.synchronize()
+ return e0.elapsed_time(e1) / iters * 1e3
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("-m", "--model", default=os.environ.get("EXL3_TEST_MODEL", ""))
+ ap.add_argument("--mode", choices=("micro", "stream", "both"), default="both")
+ ap.add_argument("--iters", type=int, default=200)
+ ap.add_argument("--top", type=int, default=16)
+ ap.add_argument("--gemm", action="store_true",
+ help="also time ext.exl3_gemm when present")
+ args = ap.parse_args()
+ if not args.model:
+ raise SystemExit("--model or EXL3_TEST_MODEL is required")
+
+ config = Config.from_directory(args.model)
+ model = Model.from_config(config)
+ model.load(progressbar=False)
+ dev = torch.device("cuda:0")
+ linears = collect(model)
+ if not linears:
+ raise SystemExit("no LinearEXL3 modules found")
+ total_bytes = sum(l.in_features * l.out_features * int(l.K) // 8 for l in linears)
+ print(f"model: {args.model}")
+ print(f"ext: {ext.__file__}")
+ print(f"linears: {len(linears)} weight stream: {total_bytes / 1e9:.3f} GB")
+ if args.gemm and not hasattr(ext, "exl3_gemm"):
+ print("ext.exl3_gemm not exported; skipping the --gemm A/B")
+
+ def buffers(l):
+ x = torch.randn((1, l.in_features), dtype=torch.half, device=dev) * 0.5
+ y = torch.empty((1, l.out_features), dtype=torch.half, device=dev)
+ ah = g_tensor_cache.get(dev, (1, l.in_features), torch.half, "exl3_gemv_a_had")
+ return x, y, ah
+
+ if args.mode in ("micro", "both"):
+ seen = {}
+ for l in linears:
+ seen.setdefault(shape_key(l), l)
+ rows = sorted(seen.items(), key=lambda kv: -(kv[0][0] * kv[0][1] * kv[0][2] // 8))
+ has_gemm = args.gemm and hasattr(ext, "exl3_gemm")
+ head = f"{'k':>6} {'n':>7} {'K':>2} {'cb':>2} {'MB':>8} {'us':>8} {'GB/s':>7}"
+ if has_gemm:
+ head += f" {'gemm_us':>8} {'gemm_GB/s':>9}"
+ print("\n" + head)
+ for (k, n, K, cb), l in rows[:args.top]:
+ x, y, ah = buffers(l)
+ b = k * n * K // 8
+ f = lambda: ext.exl3_gemv(x, l.trellis, y, l.suh, ah, l.svh, l.mcg, l.mul1)
+ us = time_us(f, args.iters)
+ line = f"{k:6d} {n:7d} {K:2d} {cb:2d} {b/1e6:8.2f} {us:8.1f} {b/us/1e3:7.0f}"
+ if has_gemm:
+ g = lambda: ext.exl3_gemm(x, l.trellis, y, l.suh, ah, l.svh, -1,
+ l.mcg, l.mul1, 0)
+ usg = time_us(g, args.iters)
+ line += f" {usg:8.1f} {b/usg/1e3:9.0f}"
+ print(line, flush=True)
+
+ if args.mode in ("stream", "both"):
+ work = []
+ for l in linears:
+ x, y, ah = buffers(l)
+ work.append((l, x, y, ah))
+
+ def run_gemv():
+ for l, x, y, ah in work:
+ ext.exl3_gemv(x, l.trellis, y, l.suh, ah, l.svh, l.mcg, l.mul1)
+
+ def run_gemm():
+ for l, x, y, ah in work:
+ ext.exl3_gemm(x, l.trellis, y, l.suh, ah, l.svh, -1, l.mcg, l.mul1, 0)
+
+ def stream(fn, passes=3):
+ fn()
+ torch.cuda.synchronize()
+ e0 = torch.cuda.Event(enable_timing=True)
+ e1 = torch.cuda.Event(enable_timing=True)
+ e0.record()
+ for _ in range(passes):
+ fn()
+ e1.record()
+ torch.cuda.synchronize()
+ return e0.elapsed_time(e1) / passes
+
+ print("\nstreaming pass over all linears (median of 3):")
+ ms = statistics.median([stream(run_gemv) for _ in range(3)])
+ print(f" exl3_gemv: {ms:.2f} ms {total_bytes / ms * 1e-6:.0f} GB/s")
+ if args.gemm and hasattr(ext, "exl3_gemm"):
+ msg = statistics.median([stream(run_gemm) for _ in range(3)])
+ print(f" exl3_gemm: {msg:.2f} ms {total_bytes / msg * 1e-6:.0f} GB/s")
+
+
+if __name__ == "__main__":
+ main()