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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Hy4: optional decensor edit hook (HY4_ABLIT_SPEC, off by default) with the preset spec and a synthetic-data test
YanissAmze537ec05ea96
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ef8cf0b..7db04a4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## Unreleased++- Optional decensor preset for Hy4-flash (`HY4_ABLIT_SPEC`, off by default): a per-layer run-time edit of the attention and MLP / MoE outputs, no weight change. Files in `presets/hy4-uncensor/`, code in `exllamav3/loader/ablit_hy4.py`.+## 1.9.0: Hy4-flash v1Hy4-flash (GGUF Q3_K) on one Strix Halo machine. Numbers: see the benchmark table in the release notes.diff --git a/README.md b/README.mdindex 05b26c9..3238939 100644--- a/README.md+++ b/README.md@@ -104,7 +104,7 @@ It prints a Markdown block. Paste it in a [benchmark report](https://github.com/- Hy4-flash (public GGUF, Q3_K) on one Strix Halo machine: sparse-attention prefill, graph decode with MTP drafts, 64K context, 128K opt-in ([doc/hy4.md](doc/hy4.md), [changelog](CHANGELOG.md)).- Long context: up to 983K tokens (DeepSeek V4.1 Flash on a Mac Studio), 500K on GLM-5.3-Flash.- Image input on Qwen3.8-27B.-- Optional uncensored mode: a small run-time preset on the normal packs, off by default; it edits no weights. How it works: [doc/refusal_hook.md](doc/refusal_hook.md).+- Optional uncensored mode: a small run-time preset on the normal packs, off by default; it edits no weights. How it works: [doc/refusal_hook.md](doc/refusal_hook.md). A preset for Hy4-flash ships in [presets/hy4-uncensor](presets/hy4-uncensor/README.md) (`HY4_ABLIT_SPEC`).## Made with our modelsdiff --git a/doc/env_vars.md b/doc/env_vars.mdindex c406ae5..45e6bc1 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -1055,6 +1055,13 @@ edits no weights. `off`, `0`, `false`, `no` and `none` force it off. An explicit`uncensor_spec.json` that a model directory may carry, and a path that does not exist stops theload with an error naming the file. See [refusal_hook.md](refusal_hook.md).+#### `HY4_ABLIT_SPEC` (default: unset, the hook is off)++Hy4-flash server only. Path of an `edit_spec.json` (with `edit_spec.safetensors` next to it) that+projects a per-layer direction out of the attention and MLP / MoE outputs at run time. It edits no+weights. `off`, `0`, `false`, `no` and `none` force it off. A malformed spec or a missing file stops+the load. The preset is in `presets/hy4-uncensor/`. See [hy4.md](hy4.md).+#### `EXL3_ABLIT_TORCH` (default: `0`)`1` uses the PyTorch projection instead of the Triton kernel. It has no effect when Triton is notdiff --git a/doc/hy4.md b/doc/hy4.mdindex a0d71f5..3d80681 100644--- a/doc/hy4.md+++ b/doc/hy4.md@@ -65,6 +65,7 @@ The server speaks the OpenAI API (`/v1/chat/completions`, `/v1/completions`, bot| `HY4_ENGRAM_NPHASH`, `HY4_ENGRAM_PF_WORKERS` | 1, 1 | Engram hash in numpy; one prefetch worker || `HY4_ENGRAM_NATIVE_IO` | 1 | Engram row reads in C threads (`pread`, no GIL) || `HY4_ENGRAM_FUSED` | 0 | two-launch fused Engram block in decode (opt-in) |+| `HY4_ABLIT_SPEC` | unset (off) | path of `edit_spec.json` (tensor file next to it): run-time decensor edit of the attention and MLP / MoE outputs; the shipped preset is `presets/hy4-uncensor/`; `off` disables |Native Engram IO: `exllamav3/loader/engram_io.c` is compiled with `gcc` at first use into `~/.cache/kyojin/engram_io` (`XDG_CACHE_HOME` moves it). When `gcc` is missing or the build fails, the server prints one line and uses the Python reader, which does the same reads more slowly (`HY4_ENGRAM_NATIVE_IO=0` selects it directly).diff --git a/doc/refusal_hook.md b/doc/refusal_hook.mdindex 3b698f3..9be5806 100644--- a/doc/refusal_hook.md+++ b/doc/refusal_hook.md@@ -5,5 +5,6 @@ The engine can project one fixed direction out of the residual stream at run tim- The spec is a JSON file (`hidden`, `n_layers`, per-layer weights `attn_w[L]`, `mlp_w[L]`) plus a unit vector `r` in `spec.safetensors`.- After each attention and MLP block of layer L the output becomes `y - w_L * r * (r . y)`.- `EXL3_ABLIT_TORCH=1` forces the PyTorch path instead of the Triton kernel.-- A direction fitted on refusals makes the model refuse less. Whoever uses a spec is responsible for it. This repository contains no spec file. Steering presets are published separately in the Yamz presets repository (https://github.com/yamz-labs/yamz-presets).+- A direction fitted on refusals makes the model refuse less. Whoever uses a spec is responsible for it. The Qwen / MiMo steering presets are published separately in the Yamz presets repository (https://github.com/yamz-labs/yamz-presets); the Hy4-flash preset ships in this repository.+- Hy4-flash has its own hook (`HY4_ABLIT_SPEC`, per-layer direction and offset, `exllamav3/loader/ablit_hy4.py`); its preset is `presets/hy4-uncensor/`.- Code: `exllamav3/modules/ablit_runtime.py`. Test: `tests/test_ablit_runtime_cpu.py`, `tests/test_uncensor_bundled_cpu.py`.diff --git a/exllamav3/loader/ablit_hy4.py b/exllamav3/loader/ablit_hy4.pynew file mode 100644index 0000000..263afdc--- /dev/null+++ b/exllamav3/loader/ablit_hy4.py@@ -0,0 +1,148 @@+"""Decensor edit hook for the Hy4 forward (spec = edit_spec.json + edit_spec.safetensors, loaded by load_spec; armed by HY4_ABLIT_SPEC in tools/hy4/serve.py).++Runtime formula at a writer output y of layer L and site s (0 = attention output, 1 = MLP / MoE block output), fp32:+ y' = y - w_{L,s} * ((r_L . y) - mu_{L,s}) * r_L (w = 0: y is returned untouched, bit for bit)+Sites on the Hy4 stream (the values that are ADDED to the hyper-connection streams):+ attn : the MLA output projection `out` [T, D] (no norm follows it)+ mlp : rms(f) * post_ffw_norm, i.e. the dense MLP / routed+shared MoE block output AFTER its post norm [T, D]+Layers >= n_layers (the MTP draft block, blk 42) are never edited. Spec fields gain.* / suhs.* (weight-side levers) are not supported+by the GGUF runtime: a spec that carries them is rejected.++Everything the kernels read lives in static device buffers (W, MU, R), so a HIP graph captured with the hook keeps working after+`set` / `load_spec` rewrites them in place. `sites[L][s]` is a python flag read at trace time (capture): only flagged sites run a kernel.+`ST is None` (default) = the forward is the unmodified one.+"""+import json+import os++import numpy as np+import torch++try:+ import triton+ import triton.language as tl+except Exception: # no triton: the torch reference runs everywhere+ triton = None++ST = None # the active EditState (module global read by hy4_forward.layer)+MAX_D = 16384+++def _p2(n):+ return 1 << max(0, (int(n) - 1).bit_length())+++def edit_torch(y, r, w, mu):+ """reference: y [T, D] fp32, r [D], w / mu 0-dim tensors (any device); w == 0 returns y itself, values unchanged"""+ d = (y * r).sum(-1, keepdim=True)+ return torch.where(w == 0, y, y - w * (d - mu) * r)+++if triton is not None:+ @triton.jit+ def _k_edit(y_ptr, r_ptr, w_ptr, mu_ptr, o_ptr, D, BD: tl.constexpr):+ row = tl.program_id(0)+ d = tl.arange(0, BD)+ dm = d < D+ y = tl.load(y_ptr + row * D + d, mask=dm, other=0.0)+ r = tl.load(r_ptr + d, mask=dm, other=0.0)+ w = tl.load(w_ptr)+ mu = tl.load(mu_ptr)+ dot = tl.sum(y * r, axis=0)+ e = y - w * (dot - mu) * r+ tl.store(o_ptr + row * D + d, tl.where(w == 0.0, y, e), mask=dm)+++def _usable(y):+ return triton is not None and (y.is_cuda or os.environ.get("TRITON_INTERPRET", "0") == "1") and y.shape[-1] <= MAX_D+++class EditState:+ def __init__(self, n_layers, D, device):+ self.n, self.D, self.dev = n_layers, D, torch.device(device)+ self.W = torch.zeros(n_layers, 2, dtype=torch.float32, device=self.dev)+ self.MU = torch.zeros(n_layers, 2, dtype=torch.float32, device=self.dev)+ self.R = torch.zeros(n_layers, D, dtype=torch.float32, device=self.dev)+ self.sites = [[False, False] for _ in range(n_layers)]+ self.pinned = False # True: every site stays flagged (search mode: weights change, the captured graph does not)++ def pin_all_sites(self):+ self.pinned = True+ self.sites = [[True, True] for _ in range(self.n)]++ def set(self, attn_w, mlp_w, attn_mu, mlp_mu, r):+ """in-place update; r is (D,) (one direction for every layer) or (n, D) (per layer)"""+ n = self.n+ w = np.stack([np.asarray(attn_w, np.float32)[:n], np.asarray(mlp_w, np.float32)[:n]], 1)+ mu = np.stack([np.asarray(attn_mu, np.float32)[:n], np.asarray(mlp_mu, np.float32)[:n]], 1)+ r = np.asarray(r, np.float32)+ r = np.broadcast_to(r, (n, self.D)) if r.ndim == 1 else r[:n]+ self.W.copy_(torch.from_numpy(np.ascontiguousarray(w)))+ self.MU.copy_(torch.from_numpy(np.ascontiguousarray(mu)))+ self.R.copy_(torch.from_numpy(np.ascontiguousarray(r)))+ if not self.pinned:+ self.sites = [[bool(w[L, 0] != 0), bool(w[L, 1] != 0)] for L in range(n)]++ def clear(self):+ self.W.zero_(); self.MU.zero_(); self.R.zero_()+ if not self.pinned:+ self.sites = [[False, False] for _ in range(self.n)]++ def args(self, i, s):+ return self.R[i], self.W.view(-1)[i * 2 + s:], self.MU.view(-1)[i * 2 + s:]++ def edit(self, y, i, s):+ """y [T, D] -> edited fp32 contiguous copy (the input is never modified)"""+ y = y.float().contiguous()+ r, w, mu = self.args(i, s)+ if _usable(y):+ o = torch.empty_like(y)+ _k_edit[(y.shape[0],)](y, r, w, mu, o, y.shape[1], BD=_p2(y.shape[1]), num_warps=8)+ return o+ return edit_torch(y, r, w[0], mu[0])+++def install(n_layers, D, device):+ global ST+ if ST is None or ST.n != n_layers or ST.D != D or ST.dev != torch.device(device):+ ST = EditState(n_layers, D, device)+ return ST+++def uninstall():+ global ST+ ST = None+++def load_spec(path, device, n_layers=None, D=None, pin=False):+ """load edit_spec.json (+ .safetensors next to it) into the active state; -> the spec dict"""+ from safetensors.numpy import load_file+ spec = json.load(open(path))+ for k in ("hidden", "n_layers", "attn_w", "mlp_w"):+ if k not in spec:+ raise ValueError(f"spec has no field {k!r}")+ nl = int(spec["n_layers"])+ for k in ("attn_w", "mlp_w", "attn_mu", "mlp_mu"):+ if k in spec and (len(spec[k]) != nl or not np.isfinite(np.asarray(spec[k], np.float64)).all()):+ raise ValueError(f"spec field {k!r}: need {nl} finite values")+ t = load_file(os.path.splitext(path)[0] + ".safetensors")+ bad = [k for k in t if k.startswith(("gain.", "suhs."))]+ if bad:+ raise ValueError(f"spec carries weight-side levers ({len(bad)} tensors): not supported by the Hy4 GGUF runtime")+ if "r" not in t:+ raise ValueError("spec safetensors has no tensor 'r'")+ n = min(nl, n_layers or nl)+ D = D or spec["hidden"]+ if spec["hidden"] != D:+ raise ValueError(f"spec hidden {spec['hidden']} != model {D}")+ r = t["r"]+ if r.ndim == 2 and not spec.get("r_per_layer"):+ raise ValueError("a (k, hidden) subspace spec is not supported")+ if r.ndim not in (1, 2) or r.shape[-1] != D or (r.ndim == 2 and r.shape[0] < n) or not np.isfinite(r).all():+ raise ValueError(f"direction tensor 'r' has shape {tuple(r.shape)}: need ({D},) or (>= {n}, {D}), finite")+ st = install(n_layers or nl, D, device)+ if pin:+ st.pin_all_sites()+ z = [0.0] * nl+ st.set(spec["attn_w"], spec["mlp_w"], spec.get("attn_mu", z), spec.get("mlp_mu", z), r)+ return specdiff --git a/exllamav3/loader/hc_fused.py b/exllamav3/loader/hc_fused.pyindex 0b89080..cd09b82 100644--- a/exllamav3/loader/hc_fused.py+++ b/exllamav3/loader/hc_fused.py@@ -137,14 +137,19 @@ def _k12_row(x_ptr, y_ptr, post_ptr, s_ptr, fn_ptr, base_ptr, scale_ptr, w_ptr,@triton.jit-def _k3_resid(s_ptr, f_ptr, post_ptr, w_ptr, o_ptr, D, eps,- H: tl.constexpr, BD: tl.constexpr):+def _k3_resid(s_ptr, f_ptr, post_ptr, w_ptr, o_ptr, D, eps, er_ptr, ew_ptr, emu_ptr,+ H: tl.constexpr, BD: tl.constexpr, HAS_EDIT: tl.constexpr):r = tl.program_id(0)d = tl.arange(0, BD)dm = d < Df = tl.load(f_ptr + r * D + d, mask=dm, other=0.0)rc = tl.math.rsqrt(tl.sum(f * f, axis=0) / D + eps)fn = f * rc * tl.load(w_ptr + d, mask=dm, other=0.0)+ if HAS_EDIT: # decensor hook (ablit_hy4): fn' = fn - w * ((er . fn) - mu) * er, fn itself when w == 0+ er = tl.load(er_ptr + d, mask=dm, other=0.0)+ ew = tl.load(ew_ptr)+ fe = fn - ew * (tl.sum(fn * er, axis=0) - tl.load(emu_ptr)) * er+ fn = tl.where(ew == 0.0, fn, fe)for h in tl.static_range(H):ph = tl.load(post_ptr + r * H + h)sv = tl.load(s_ptr + (r * H + h) * D + d, mask=dm, other=0.0)@@ -239,14 +244,17 @@ class Pend:self.s, self.f, self.post, self.w_post, self.eps, self.edit = s, f.float().contiguous(), post.float().contiguous(), w_post.contiguous(), eps, editdef materialize(self):- return resid(self.s, self.f, self.post, self.w_post, self.eps)+ return resid(self.s, self.f, self.post, self.w_post, self.eps, edit=self.edit)-def resid(s, f, post, w_post, eps):- """s + post[:, :, None] * (rms(f) * w_post)[:, None, :] -> new [T,H,D]"""+def resid(s, f, post, w_post, eps, edit=None):+ """s + post[:, :, None] * (rms(f) * w_post)[:, None, :] -> new [T,H,D]+ edit = (r [D], w [1+], mu [1+]) fp32 device tensors: the decensor edit is applied to rms(f) * w_post inside the same kernel"""T, H, D = s.shapeo = torch.empty_like(s)- _k3_resid[(T,)](s, f.float().contiguous(), post.float().contiguous(), w_post.contiguous(), o, D, eps, H=H, BD=_p2(D), num_warps=8)+ f = f.float().contiguous()+ er, ew, emu = edit if edit is not None else (f, f, f)+ _k3_resid[(T,)](s, f, post.float().contiguous(), w_post.contiguous(), o, D, eps, er, ew, emu, H=H, BD=_p2(D), HAS_EDIT=edit is not None, num_warps=8)return odiff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex ea5f89d..e75ef99 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -35,6 +35,7 @@ from . import attn_eager as _AEfrom . import router_gemv as _RGfrom . import mla_hy4 as _mla_modfrom . import dense_req as _DR+from . import ablit_hy4 as _AB # decensor edit hook (inert while _AB.ST is None)_HCF = Noneif os.environ.get("HY4_HC_FUSED", "0") == "1": # fused hyper-connection sites (loader/hc_fused.py)@@ -931,6 +932,9 @@ class Hy4Forward:self._hk("attn_kqv", i, kqv)self._hk("attn_gated", i, gated)self._hk("attn_out", i, out)+ ab = _AB.ST+ if ab is not None and i < ab.n and ab.sites[i][0]:+ out = ab.edit(out, i, 0)with tm.t("hc / norms"):if _HCF is not None and _HCF.ok(x, L.hcf, self.hc) and out.shape == (T, self.D):s1, post2, cur2 = _HCF.res_site(x, out, post, L.hcf, L.ffn_norm, self.eps, self.hc_eps, self.magnitude, pend)@@ -944,13 +948,16 @@ class Hy4Forward:if lat is not None:self._hk("ffn_moe_out", i, lat)with tm.t("hc / norms"):- if _HCF is not None and _HCF.ok(s1, L.hcf, self.hc) and f.shape == (T, self.D):+ ed = ab is not None and i < ab.n and ab.sites[i][1]+ if _HCF is not None and _HCF.ok(s1, L.hcf, self.hc) and f.shape == (T, self.D) and not (ed and not _AB._usable(f)):if (_HCF.lazy() and T > _HCF.PF_MIN_ROWS and self.hook is None and self._gs is None and i + 1 < self.n_layers- and i + 1 not in self.ple and self.hc <= 8): # HY4_PF_HC2: hand (s1, f, post) to the next layer instead of writing x- return _HCF.Pend(s1, f, post2, L.post_ffw, self.eps)- s2 = _HCF.resid(s1, f, post2, L.post_ffw, self.eps)+ and i + 1 not in self.ple and self.hc <= 8): # HY4_PF_HC2: hand (s1, f, post) to the next layer instead of writing x (the decensor edit rides along in the Pend)+ return _HCF.Pend(s1, f, post2, L.post_ffw, self.eps, edit=ab.args(i, 1) if ed else None)+ s2 = _HCF.resid(s1, f, post2, L.post_ffw, self.eps, edit=ab.args(i, 1) if ed else None)else:f = rms(f, self.eps) * L.post_ffw+ if ed:+ f = ab.edit(f, i, 1)s2 = s1 + post2[:, :, None] * f[:, None, :]self._hk("l_out", i, s2)return s2diff --git a/presets/hy4-uncensor/README.md b/presets/hy4-uncensor/README.mdnew file mode 100644index 0000000..17a32d8--- /dev/null+++ b/presets/hy4-uncensor/README.md@@ -0,0 +1,22 @@+# Hy4-flash: decensor preset (opt-in)++A run-time edit of the Hy4 forward. It edits no weights and no quantised data. Off unless `HY4_ABLIT_SPEC` points at the spec.++```+HY4_ABLIT_SPEC=/path/to/presets/hy4-uncensor/edit_spec.json python tools/hy4/serve.py --model ./hy4/Hy4-flash-Q3_K-00001-of-00002.gguf ...+```++`edit_spec.safetensors` must sit next to the JSON. `HY4_ABLIT_SPEC=off` (or unset) runs the unmodified forward.++What it does: after the attention output projection and after the post-norm MLP / MoE output of the 42 trunk layers, the output `y` becomes `y - w * ((r . y) - mu) * r`, with a per-layer unit direction `r` and per-layer weights `w`, `mu`. Layers with `w = 0` are not touched. The MTP draft block is never edited. Code: `exllamav3/loader/ablit_hy4.py`; the post-norm MLP site is fused into the residual kernel (`exllamav3/loader/hc_fused.py`).++Development-build numbers (Strix Halo box, Q3_K, same settings with the spec on and off); to be replaced by the release-engine gate results before publication:++| | spec off | spec on |+|---|---|---|+| Fixed gate set of 17 requests, answers judged as declined | 17 | 4 |+| GSM, 30 problems | 28 | 29 |+| Wikitext-2 slice, change in NLL | 0 | -0.046 (inside the noise band) |+| Decode speed | reference | +1.4 % (inside noise) |++Whoever uses a spec is responsible for it. SHA256SUMS lists the two files.diff --git a/presets/hy4-uncensor/SHA256SUMS b/presets/hy4-uncensor/SHA256SUMSnew file mode 100644index 0000000..1cccf42--- /dev/null+++ b/presets/hy4-uncensor/SHA256SUMS@@ -0,0 +1,2 @@+01fde84266a7622ee0fc517c5d79416bf8cefca359bc8d0a7a458bfb46feb1e1 edit_spec.json+9b965432c58154b0abd583711b9b80fa9c6b97014ce7ffa514c41c434eeea62d edit_spec.safetensorsdiff --git a/presets/hy4-uncensor/edit_spec.json b/presets/hy4-uncensor/edit_spec.jsonnew file mode 100644index 0000000..d90546a--- /dev/null+++ b/presets/hy4-uncensor/edit_spec.json@@ -0,0 +1,203 @@+{+ "hidden": 3072,+ "n_layers": 42,+ "model": "Hy4-flash",+ "direction_index": 23.44938388879205,+ "levers": {+ "mu_frac": 0.9487372755768319,+ "np_frac": 0.0,+ "npr_frac": 0.0,+ "bp": 0.5566833264753234,+ "pl": 0.5736853964660765+ },+ "attn": {+ "max_w": 2.994178737368368,+ "peak": 29.631094570603487,+ "min_w": 0.6577769770738452,+ "width": 20.96678896455769+ },+ "attn_w": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.6951845636280578,+ 0.8066180198546635,+ 0.9180514760812697,+ 1.0294849323078754,+ 1.1409183885344811,+ 1.2523518447610873,+ 1.363785300987693,+ 1.475218757214299,+ 1.586652213440905,+ 1.6980856696675106,+ 1.8095191258941168,+ 1.9209525821207225,+ 2.0323860383473287,+ 2.1438194945739344,+ 2.25525295080054,+ 2.366686407027146,+ 2.478119863253752,+ 2.5895533194803577,+ 2.700986775706964,+ 2.8124202319335696,+ 2.9238536881601758,+ 2.9530703303499544,+ 2.8416368741233486,+ 2.7302034178967425,+ 2.6187699616701368,+ 2.5073365054435306,+ 2.395903049216925,+ 2.284469592990319,+ 2.173036136763713,+ 2.0616026805371073,+ 1.9501692243105013,+ 1.8387357680838954,+ 1.7273023118572897+ ],+ "attn_mu": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ -2.4213205924852343,+ 0.5085293655824472,+ -0.4514371397824899,+ -0.5573693534065796,+ -1.106417194670429,+ -0.029403392087963418,+ -0.22176732470171626,+ 2.0524916995984084,+ -2.3524603244650466,+ 0.24300351002398882,+ 1.4863142653130261,+ 1.414216114902903,+ 1.4580246009277054,+ 1.470782460418811,+ 0.1036163765054133,+ -0.29000571573614264,+ 0.21186545254444877,+ -0.7435909429852308,+ -1.392430996463941,+ -0.08679551192659553,+ 4.558456517589799,+ 2.325347973356842,+ 1.9722069442838792,+ -0.8089600935670209,+ -0.05570858446541419,+ 0.3363752576492861,+ 0.4387377187335296,+ -0.7701783366373205,+ 0.2641684841629107,+ 1.2021125306354052,+ 0.9646691454110999,+ 1.0672337007383972,+ 0.023911713218642657+ ],+ "mlp": {+ "max_w": 2.602606801603322,+ "peak": 28.11711843865947,+ "min_w": 0.8949919182592263,+ "width": 13.128617394317084+ },+ "mlp_w": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.8964875660669196,+ 1.0265557089684914,+ 1.1566238518700631,+ 1.286691994771635,+ 1.4167601376732069,+ 1.5468282805747786,+ 1.6768964234763506,+ 1.8069645663779221,+ 1.9370327092794941,+ 2.067100852181066,+ 2.1971689950826376,+ 2.3272371379842096,+ 2.457305280885781,+ 2.587373423787353,+ 2.487772036517719,+ 2.3577038936161476,+ 2.2276357507145756,+ 2.097567607813004,+ 1.9674994649114321,+ 1.8374313220098604,+ 1.7073631791082886,+ 1.5772950362067166,+ 1.4472268933051449,+ 1.317158750403573,+ 1.1870906075020011,+ 1.0570224646004294,+ 0.9269543216988576+ ],+ "mlp_mu": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ -1.6486019832631271,+ 0.0783247674871682,+ 0.7508641282416265,+ 0.5625514803879862,+ -0.6123403909495038,+ 1.7984493278430553,+ 1.1889274612518925,+ 0.5872065002676238,+ 0.9745400246144871,+ 0.4209677410486259,+ 1.2928468345939332,+ 3.565720291763129,+ 0.08590812932599295,+ -0.20709538123541701,+ -1.8382600279102839,+ 1.1858527944259643,+ -0.6660885175971832,+ 1.7149790579483186,+ -1.8726445867531298,+ -1.072159060695568,+ -0.387344544306482,+ 0.5735681612845881,+ 1.4736723052251663,+ -1.4251050044412397,+ -2.242050229155303,+ -1.0273243215601007,+ 2.9580567400907656+ ],+ "apply": "Hy4 hook: attention output projection and post-norm MLP/MoE block output of every trunk layer (loader/ablit_hy4.py)",+ "r_per_layer": true+}\ No newline at end of filediff --git a/presets/hy4-uncensor/edit_spec.safetensors b/presets/hy4-uncensor/edit_spec.safetensorsnew file mode 100644index 0000000..aa39aaeBinary files /dev/null and b/presets/hy4-uncensor/edit_spec.safetensors differdiff --git a/tests/test_hy4_ablit_hook.py b/tests/test_hy4_ablit_hook.pynew file mode 100644index 0000000..0af92e6--- /dev/null+++ b/tests/test_hy4_ablit_hook.py@@ -0,0 +1,184 @@+"""Decensor edit hook of the Hy4 forward (loader/ablit_hy4.py + the two call sites in hy4_forward.layer + the fused resid kernel).+CPU, torch only (a second run with TRITON_INTERPRET=1 HY4_HC_FUSED=1 also runs the Triton kernels in the interpreter).+ - formula vs a float64 reference; w = 0 returns the input bit for bit (also -0.0)+ - spec round trip (edit_spec.json + edit_spec.safetensors, global and per-layer r); weight-side levers rejected+ - truncated depth (embedding + layers 0..2): a zero-weight spec on every site gives the SAME residual stream as no spec (torch.equal),+ a non-zero spec changes it, clearing the state brings the original back"""+import json, os, sys, tempfile+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 gg+from exllamav3.loader import hy4_forward as HF++AB = HF._AB+needs_gguf = pytest.mark.skipif(not os.path.exists(T.GGUF1), reason="Hy4 GGUF absent")+++def _unit(n, seed):+ r = torch.randn(n, generator=torch.Generator().manual_seed(seed))+ return r / r.norm()+++def test_formula_and_zero_weight_identity():+ g = torch.Generator().manual_seed(1)+ y = torch.randn(5, 64, generator=g)+ y[0, 3] = -0.0+ y[1] = 0.0+ r = _unit(64, 2)+ st = AB.EditState(2, 64, "cpu")+ st.set([0.0, 0.7], [0.0, 1.3], [0.0, 0.2], [0.0, -0.4], r.numpy())+ for L, s in ((0, 0), (0, 1)): # w = 0: the same bits+ o = st.edit(y, L, s)+ assert torch.equal(o, y) and torch.equal(o.view(torch.int32), y.view(torch.int32))+ for s, (w, mu) in ((0, (0.7, 0.2)), (1, (1.3, -0.4))):+ o = st.edit(y, 1, s)+ y64, r64 = y.double(), r.double()+ ref = y64 - w * ((y64 @ r64) - mu)[:, None] * r64[None]+ assert (o.double() - ref).abs().max() < 1e-5+ assert (o @ r - (1 - w) * (y @ r) - w * mu).abs().max() < 1e-4 # the r-component moves by w toward mu+++def _write(d, n, D, r, wa, wm, per_layer=False, extra=None):+ from safetensors.numpy import save_file+ spec = {"hidden": D, "n_layers": n, "attn_w": list(wa), "mlp_w": list(wm), "attn_mu": [0.1] * n, "mlp_mu": [-0.2] * n}+ if per_layer:+ spec["r_per_layer"] = True+ ten = {"r": np.ascontiguousarray(r, dtype=np.float32)}+ ten.update(extra or {})+ json.dump(spec, open(os.path.join(d, "edit_spec.json"), "w"))+ save_file(ten, os.path.join(d, "edit_spec.safetensors"))+ return os.path.join(d, "edit_spec.json")+++def test_spec_roundtrip_and_rejects_levers():+ D, n = 32, 4+ with tempfile.TemporaryDirectory() as d:+ r = np.stack([_unit(D, 10 + L).numpy() for L in range(n)])+ p = _write(d, n, D, r, [0.5, 0, 0, 1.0], [0, 0.25, 0, 0], per_layer=True)+ AB.uninstall()+ spec = AB.load_spec(p, "cpu", n_layers=n, D=D)+ st = AB.ST+ assert st.sites == [[True, False], [False, True], [False, False], [True, False]]+ assert torch.equal(st.R, torch.from_numpy(r)) and float(st.W[3, 0]) == 1.0 and abs(float(st.MU[1, 1]) + 0.2) < 1e-7+ r1 = r[0]+ p = _write(d, n, D, r1, [0.5] * n, [0.5] * n) # global r+ AB.uninstall(); AB.load_spec(p, "cpu", n_layers=n, D=D)+ assert torch.equal(AB.ST.R[2], torch.from_numpy(r1))+ p = _write(d, n, D, r1, [0.5] * n, [0.5] * n, extra={"gain.attn.0": np.ones(D, np.float32)})+ with pytest.raises(ValueError):+ AB.load_spec(p, "cpu", n_layers=n, D=D)+ AB.uninstall()+++def _stream(M, ids):+ M.reset_for_test() if hasattr(M, "reset_for_test") else None+ M.step(ids)+ return M._x.clone()+++@needs_gguf+def test_zero_weight_spec_bit_identical_truncated():+ g, _ = gg()+ ids = [7, 1234, 99, 5, 4021, 77, 318, 12]+ AB.uninstall()+ M = HF.Hy4Forward(g, n_layers=3, cache_weights=True)+ x0 = _stream(M, ids)+ D = M.D+ st = AB.install(3, D, "cpu")+ st.pin_all_sites()+ r = _unit(D, 3).numpy()+ st.set([0.0] * 3, [0.0] * 3, [0.3] * 3, [-0.7] * 3, r) # every site hooked, every weight zero (mu set: must not matter)+ M2 = HF.Hy4Forward(g, n_layers=3, cache_weights=True)+ x1 = _stream(M2, ids)+ assert torch.equal(x0, x1) and torch.equal(x0.view(torch.int32), x1.view(torch.int32))+ st.set([1.5] * 3, [1.5] * 3, [0.0] * 3, [0.0] * 3, r)+ M3 = HF.Hy4Forward(g, n_layers=3, cache_weights=True)+ x2 = _stream(M3, ids)+ assert not torch.equal(x0, x2) and torch.isfinite(x2).all()+ st.clear()+ st.sites = [[False, False]] * 3+ AB.uninstall()+ M4 = HF.Hy4Forward(g, n_layers=3, cache_weights=True)+ assert torch.equal(x0, _stream(M4, ids))+++def test_only_the_residual_direction_moves():+ """hook on: y' - y lies along r (per-layer r), the orthogonal part of y is untouched"""+ D, n = 48, 3+ g = torch.Generator().manual_seed(7)+ y = torch.randn(6, D, generator=g)+ r = torch.stack([_unit(D, 20 + L) for L in range(n)])+ st = AB.EditState(n, D, "cpu")+ st.set([0.4, 0.0, 1.0], [0.0, 0.9, 0.0], [0.1] * n, [0.0] * n, r.numpy())+ for L, s in ((0, 0), (1, 1), (2, 0)):+ o = st.edit(y, L, s)+ d = o - y+ assert d.abs().max() > 1e-3+ par = (d @ r[L])[:, None] * r[L][None]+ assert (d - par).abs().max() < 1e-5 # the change is parallel to r+ assert torch.equal(st.edit(y, 1, 0), y) # w = 0 site: unchanged bits+++def test_loader_rejects_malformed_specs():+ D, n = 16, 3+ r = _unit(D, 1).numpy()+ with tempfile.TemporaryDirectory() as d:+ good = dict(wa=[0.5] * n, wm=[0.5] * n)+ p = _write(d, n, D, r, **good)+ AB.uninstall(); AB.load_spec(p, "cpu", n_layers=n, D=D) # sanity: the good one loads+ for bad_kw in (dict(wa=[0.5] * (n - 1), wm=[0.5] * n), # wrong length+ dict(wa=[0.5, float("nan"), 0.5], wm=[0.5] * n), # not finite+ dict(wa=[0.5] * n, wm=[0.5] * n, extra={"suhs.mlp.0": np.ones(D, np.float32)})):+ p = _write(d, n, D, r, **bad_kw)+ AB.uninstall()+ with pytest.raises(ValueError):+ AB.load_spec(p, "cpu", n_layers=n, D=D)+ p = _write(d, n, D, r, **good)+ with pytest.raises(ValueError): # hidden size differs from the model+ AB.load_spec(p, "cpu", n_layers=n, D=D + 1)+ p = _write(d, n, D, np.zeros((n, D + 2), np.float32), per_layer=True, **good) # direction of the wrong width+ with pytest.raises(ValueError):+ AB.load_spec(p, "cpu", n_layers=n, D=D)+ spec = json.load(open(p)); del spec["mlp_w"]; json.dump(spec, open(p, "w")) # missing field+ with pytest.raises(ValueError):+ AB.load_spec(p, "cpu", n_layers=n, D=D)+ from safetensors.numpy import save_file+ p = _write(d, n, D, r, **good)+ save_file({"q": r}, os.path.join(d, "edit_spec.safetensors")) # no tensor r+ with pytest.raises(ValueError):+ AB.load_spec(p, "cpu", n_layers=n, D=D)+ AB.uninstall()+++def test_fused_resid_edit_matches_unfused_and_off_is_identical():+ """the fused resid kernel (Triton, interpreter on CPU): edit=None == no hook, edit on == torch reference"""+ triton = pytest.importorskip("triton")+ if os.environ.get("TRITON_INTERPRET", "0") != "1" and not torch.cuda.is_available():+ pytest.skip("run with TRITON_INTERPRET=1 (CPU) or on a GPU")+ from exllamav3.loader import hc_fused+ T_, H, D = 3, 4, 32+ g = torch.Generator().manual_seed(11)+ s = torch.randn(T_, H, D, generator=g)+ f = torch.randn(T_, D, generator=g)+ post = torch.rand(T_, H, generator=g)+ wp = torch.rand(D, generator=g) + 0.5+ r = _unit(D, 4)+ base = hc_fused.resid(s, f, post, wp, 1e-6)+ st = AB.EditState(1, D, "cpu")+ st.set([0.0], [0.0], [0.0], [0.0], r.numpy())+ assert torch.equal(hc_fused.resid(s, f, post, wp, 1e-6, edit=st.args(0, 1)), base) # w = 0: same bits+ st.set([0.0], [0.8], [0.0], [0.3], r.numpy())+ got = hc_fused.resid(s, f, post, wp, 1e-6, edit=st.args(0, 1))+ fn = f * torch.rsqrt((f * f).mean(-1, keepdim=True) + 1e-6) * wp+ fe = AB.edit_torch(fn, r, torch.tensor(0.8), torch.tensor(0.3))+ ref = s + post[:, :, None] * fe[:, None, :]+ assert (got - ref).abs().max() < 1e-4+ AB.uninstall()+++if __name__ == "__main__":+ sys.exit(pytest.main(["-q", "-s", __file__]))diff --git a/tools/hy4/serve.py b/tools/hy4/serve.pyindex 5394737..8e8f40d 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -367,6 +367,11 @@ def load_in_background(st: State):st.stage = sprint("load:", s, flush=True)eng.load(progress)+ sp = os.environ.get("HY4_ABLIT_SPEC", "").strip() # optional decensor spec (edit_spec.json + edit_spec.safetensors next to it); unset or off = the unmodified forward+ if sp and sp.lower() not in ("off", "0", "false", "no", "none"):+ eng.hf._AB.load_spec(sp, "cuda", D=eng.M.D, pin=True) # all sites pinned so the graphs capture them; weights live in static buffers+ eng.GR.clear()+ print("decensor spec armed:", sp, flush=True)if a.slots > 1:import mu_enginest.sched = mu_engine.MuScheduler(eng, chunk=a.sched_chunk)