Repository navigation
Implement GLP control vectors with a fused Metal kernel for Qwen3.8-27B - #1835
BlivionIaG wants to merge 25 commits into
Conversation
51cc5e2 to
f57cc5d
Compare
|
Thanks @BlivionIaG. We reviewed this independently. We'd take the generic, opt-in
On scope, our decision: the engine ships the mechanism only. Please leave out the matched harmful and harmless prompt sets, the deriver, and the receipts measuring refusal removal on the 27B. Deriving vectors that remove a model's safety refusals isn't something we'll ship or document in TensorFold. A user can supply their own direction files. |
Review changes from ashhart#1835: - the app's settings panel, IPC, preload and locale packs move to feature/glp-steering-app, so app changes go through the app's review - glp.read refuses a file that names one layer twice (direction.5 and direction.05 both parse as 5), with a test - the serve refuses a layer id past the checkpoint's num_hidden_layers at startup, before the model loads - the GLP container is read by the engine's own GGUF reader; its writer stays in glp.zig, so there is one GGUF reader - the deriver, the matched prompt sets, the refusal-measurement gate and their receipt are removed; a vector file is supplied by the operator
|
All three changes are in, plus the scope cut.
The branch is merged with |
|
CI caught one thing the local suites did not: after merging main, Fixed in |
|
Thanks @BlivionIaG. The 18:50 push answers every 17:58 ask:
Off by default is main (
It's 38 commits behind main, so a rebase with these would be ideal. |
|
CI is green on Two things came out of the first full run:
|
|
Thanks @BlivionIaG: the rebase applies on main and lean is back to 424 (the served helpers moved verbatim). Three asks are still open: (1) |
|
All three are in,
|
|
End-to-end run on an M4 Pro, macOS, native Metal server built from The served checkpoint's
Serving with the published 49-layer vector from
So the projection changes the served tokens on a benign prompt, and the fused path runs. Both servers were stopped after the requests; the throwaway generator used for the refusal files and the files themselves are not in the tree. |
|
Thanks @BlivionIaG. An independent re-review of One rebase is needed. On current main, 42 of the 43 files apply. The only conflict is the Once it's rebased, we'll run the Mac cells on an M5 Ultra and land it on a clean result:
|
fd03885 to
b61f6fe
Compare
Review changes from ashhart#1835: - the app's settings panel, IPC, preload and locale packs move to feature/glp-steering-app, so app changes go through the app's review - glp.read refuses a file that names one layer twice (direction.5 and direction.05 both parse as 5), with a test - the serve refuses a layer id past the checkpoint's num_hidden_layers at startup, before the model loads - the GLP container is read by the engine's own GGUF reader; its writer stays in glp.zig, so there is one GGUF reader - the deriver, the matched prompt sets, the refusal-measurement gate and their receipt are removed; a vector file is supplied by the operator
|
Rebased onto The conflict was
|
|
All 11 checks pass on |
|
Thanks @BlivionIaG. Two of the four Mac checks are in, on an M5 Ultra at your rebased head:
Still owed, and these need your vector files:
If you post those two receipts from your Mac, this lands on them. |
Mac receipts on
|
| prompt | off 1 | on 1 | off 2 | on 2 | off mean | on mean | delta |
|---|---|---|---|---|---|---|---|
| fibonacci-raw | 13.9855 | 13.9951 | 13.8591 | 14.0267 | 13.9223 | 14.0109 | +0.64% |
| gpu-chat-no-think | 13.9507 | 13.8885 | 13.9249 | 13.9714 | 13.9378 | 13.9300 | -0.06% |
Both prompts are inside 1% of off; the spread is the run-to-run noise, not a steering cost.
Four refusals by name
1. Nested config past depth. /tmp/tf-glp-nested/config.json carries depth and width only under text_config (num_hidden_layers = 32, hidden_size = 5120), with no root num_hidden_layers/hidden_size. A 63-layer vector:
$ tensorfold-native serve /tmp/tf-glp-nested --glp .../Qwen3.8-27B-abliterated-cyber-GLP-63-L1-63-a1.gguf --context 1024
tensorfold: --glp: the vector steers layer 32 of a model with 32 layers: its deepest layer is 31
error: GlpRefused
Exit 1 in 0.19 s, before the model is touched.
2. Add-mode NaN. A one-layer add file with direction.10[0] = NaN:
$ tensorfold-native serve TensorFold/Qwen3.8-27B-MLX-4bit --glp /tmp/glp-nan-add.gguf --context 1024
tensorfold serve: error: argument --glp: layer 10's direction holds a value that is not finite
Exit 2 in 0.012 s, at argument parsing.
3. --glp with no file.
$ tensorfold-native serve TensorFold/Qwen3.8-27B-MLX-4bit --glp
tensorfold serve: error: argument --glp: expected one argument
Exit 2 in 0.010 s.
4. CUDA build given --glp. Cross-compiled from the same tree for aarch64-linux-gnu (zig build native -Dtarget=aarch64-linux-gnu -Doptimize=ReleaseSafe) and run in a Debian bookworm container; the Mac has no NVIDIA GPU. The model directory held the checkpoint's config.json and tokenizer files (no weights), and the vector was the same 49-layer file:
$ /tf serve /run/model --glp /run/vec/vector.gguf --context 1024
tensorfold: --glp: only the Metal engine steers: this server runs the CUDA engine
error: GlpRefused
Exit 1. The engine-open path refuses before any weights load; the text/tokenizer load runs alongside it, as startup.both always does. A refusal on a real CUDA host is still the one thing not exercised here.
Recipe: exact commands
git clone https://github.com/BlivionIaG/TensorFold.git
cd TensorFold
git checkout efd421d9615956bd3b414ab87e1305c59270c39f
# Zig 0.17.0 must be on PATH.
zig build native # Metal server
zig build tf-glp-check # tf-glp-checkOff/on decode (fresh server per run; only --glp/--glp-alpha differ):
V49=$(ls ~/.cache/huggingface/hub/models--msuiche--Qwen3.8-27B-abliterated-cyber-GLP-49/snapshots/*/Qwen3.8-27B-abliterated-cyber-GLP-49-L10-58-a1.gguf)
# off
./zig-out/native/bin/tensorfold-native serve TensorFold/Qwen3.8-27B-MLX-4bit \
--context 2048 --port 8123 --host 127.0.0.1 --name bench --no-update-check
# on
./zig-out/native/bin/tensorfold-native serve TensorFold/Qwen3.8-27B-MLX-4bit \
--glp "$V49" --glp-alpha 1.0 \
--context 2048 --port 8123 --host 127.0.0.1 --name bench --no-update-check
# for each server, once it is listening:
python3 tools/bench_openai.py http://127.0.0.1:8123 Qwen3.8-27B-MLX-4bit \
--tokens 64 --reps 5 --temperatures 0 --output /tmp/bench.jsonNested-config fixture:
import glob, json, os, shutil
snap = glob.glob(os.path.expanduser(
"~/.cache/huggingface/hub/models--TensorFold--Qwen3.8-27B-MLX-4bit/snapshots/*/"))[0]
out = "/tmp/tf-glp-nested"
shutil.rmtree(out, ignore_errors=True)
os.makedirs(out)
for name in os.listdir(snap):
os.symlink(os.path.realpath(os.path.join(snap, name)), os.path.join(out, name))
d = json.load(open(os.path.join(snap, "config.json")))
d.pop("num_hidden_layers", None)
d.pop("hidden_size", None)
tc = d.setdefault("text_config", {})
tc["num_hidden_layers"] = 32
tc["hidden_size"] = 5120
json.dump(d, open(os.path.join(out, "config.json"), "w"), indent=2)Throwaway NaN-vector generator (zig/src/core/tmp_glp_bad.zig, deleted after the run):
const std = @import("std");
const glp = @import("glp.zig");
const gguf = @import("glp_container.zig");
const width = 5120;
pub fn main(init: std.process.Init) !void {
const a = init.arena.allocator();
const args = try init.minimal.args.toSlice(a);
if (args.len != 3) return error.Usage;
const kind = args[1];
const out_path = args[2];
var dir = try a.alloc(f32, width);
for (dir) |*v| v.* = 0;
dir[0] = 1;
if (std.mem.eql(u8, kind, "deep")) {
const layers = [_]glp.Layer{.{ .id = 64, .dir = dir }};
const bytes = try glp.write(a, .{
.mode = .project,
.alpha = 1,
.hook_point = glp.residual_site,
.derived_at = null,
.base_model = "TensorFold/Qwen3.8-27B-MLX-4bit",
.base_revision = "",
.method = "test",
.contrast = "",
.layers = &layers,
});
try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = out_path, .data = bytes });
return;
}
if (std.mem.eql(u8, kind, "nan-add")) {
var raw = try a.alloc(u8, width * 4);
std.mem.writeInt(u32, raw[0..4], @bitCast(std.math.nan(f32)), .little);
@memset(raw[4..], 0);
const entries = [_]gguf.Entry{
.{ .key = "general.architecture", .value = .{ .string = "controlvector" } },
.{ .key = "glp.spec_version", .value = .{ .u32v = 1 } },
.{ .key = "glp.mode", .value = .{ .string = "add" } },
.{ .key = "glp.rank", .value = .{ .u32v = 1 } },
.{ .key = "glp.hook_point", .value = .{ .string = glp.residual_site } },
.{ .key = "glp.alpha_default", .value = .{ .f32v = 1 } },
.{ .key = "glp.base_model", .value = .{ .string = "TensorFold/Qwen3.8-27B-MLX-4bit" } },
};
const dims = [_]u64{width};
const tensors = [_]gguf.OutTensor{.{ .name = "direction.10", .dims = &dims, .kind = gguf.f32_type, .data = raw }};
const bytes = try gguf.write(a, &entries, &tensors);
try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = out_path, .data = bytes });
return;
}
return error.UnknownKind;
}zig run zig/src/core/tmp_glp_bad.zig -- nan-add /tmp/glp-nan-add.gguf
rm -f zig/src/core/tmp_glp_bad.zigCUDA build and container run:
zig build native -Dtarget=aarch64-linux-gnu -Doptimize=ReleaseSafe
mkdir -p "$HOME/tf-glp-cuda/run/model" "$HOME/tf-glp-cuda/run/vec"
cp zig-out/native/bin/tensorfold-native "$HOME/tf-glp-cuda/tensorfold-native-cuda-aarch64"
# rebuild the Metal binary afterwards, since the cross-build writes the same path:
zig build native
# populate run/model with the checkpoint's config.json and tokenizer files (no weights),
# and run/vec with the 49-layer vector above.
python3 - <<'PY'
import glob, os, shutil
home = os.path.expanduser("~")
snap = glob.glob(home + "/.cache/huggingface/hub/models--TensorFold--Qwen3.8-27B-MLX-4bit/snapshots/*/")[0]
model = home + "/tf-glp-cuda/run/model"
for name in ("config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json",
"vocab.json", "chat_template.jinja", "preprocessor_config.json",
"processor_config.json", "model.safetensors.index.json"):
src = os.path.join(snap, name)
if os.path.exists(src):
shutil.copy(os.path.realpath(src), os.path.join(model, name))
vec = glob.glob(home + "/.cache/huggingface/hub/models--msuiche--Qwen3.8-27B-abliterated-cyber-GLP-49/snapshots/*/Qwen3.8-27B-abliterated-cyber-GLP-49-L10-58-a1.gguf")[0]
shutil.copy(os.path.realpath(vec), home + "/tf-glp-cuda/run/vec/vector.gguf")
PY
podman run --rm --platform linux/arm64 \
-v "$HOME/tf-glp-cuda/tensorfold-native-cuda-aarch64:/tf:ro" \
-v "$HOME/tf-glp-cuda/run:/run:ro" \
docker.io/library/debian:bookworm-slim \
/tf serve /run/model --glp /run/vec/vector.gguf --context 1024 --port 8193|
Thanks @BlivionIaG for both receipts. On-mode decode is within 1% of off, and all four refusals stop by name before load. A few things before it lands:
We'll check the CUDA refusal ourselves on a GB10. |
efd421d to
b721c88
Compare
Review changes from ashhart#1835: - the app's settings panel, IPC, preload and locale packs move to feature/glp-steering-app, so app changes go through the app's review - glp.read refuses a file that names one layer twice (direction.5 and direction.05 both parse as 5), with a test - the serve refuses a layer id past the checkpoint's num_hidden_layers at startup, before the model loads - the GLP container is read by the engine's own GGUF reader; its writer stays in glp.zig, so there is one GGUF reader - the deriver, the matched prompt sets, the refusal-measurement gate and their receipt are removed; a vector file is supplied by the operator
|
Rebased onto
|
|
|
Review changes from ashhart#1835: - the app's settings panel, IPC, preload and locale packs move to feature/glp-steering-app, so app changes go through the app's review - glp.read refuses a file that names one layer twice (direction.5 and direction.05 both parse as 5), with a test - the serve refuses a layer id past the checkpoint's num_hidden_layers at startup, before the model loads - the GLP container is read by the engine's own GGUF reader; its writer stays in glp.zig, so there is one GGUF reader - the deriver, the matched prompt sets, the refusal-measurement gate and their receipt are removed; a vector file is supplied by the operator
|
Thanks. All five are in on
Checks on On CI: |
…erved The steer suite was freed before runAll read its probes; hold it through the run. Build both kernels from the production specialization so the plain norm returns padded rows.
The spec's layers field is required even when the helper fills it.
|
Thanks @ashhart. All five are fixed on head
Also on this head:
On |
|
Fixed on |
|
Thanks @BlivionIaG. The five requested input/configuration fixes are present. One GLP+MTP composition issue remains: GLP steering is applied again inside the separate MTP head.
|
…ld apart capabilitiesFor(.., true) lists --glp even where this host's engine refuses it, so comparing that listing with glp_startup.steers failed every non-Metal shard. Assert the forced steering build lists it, a false build still follows the platform's advertised bit, and the real capabilities equal steers.
|
Thanks @BlivionIaG. The fix on That closes the GLP+MTP point. One note: the branch now adds two changelog lines, and the new one describes a fix to code that never shipped. We'll keep a single line for the feature when this lands, so there's nothing to change on your side.
|
|
Two things on GLP+MTP (your note of 2026-11-24). Fixed. The MTP head's stages are built by CI on Local: |
# Conflicts: # CHANGELOG.md
One changelog line for the feature, as the maintainer asked on ashhart#1835, and the --glp rows name the DeepSeek CUDA paired site that takes its own file instead of reading as a blanket CUDA refusal.
# Conflicts: # CHANGELOG.md # zig/build/qwen27_host.zig
|
Thanks, @BlivionIaG. The five input/configuration fixes and the GLP+MTP fix are present, and the core feature files still match the head we acknowledged. With no vector, both norm sites and the saved-state key retain the existing path. The remaining gate is current-tree qualification: exact steered serial parity across strengths, full-token equality with steering off, and the agreed longer-context and concurrent comparisons. The focused kernel result and short style examples do not cover those cells. The layer-63 MTP composition check needs the backend where that head is supported. There is no further contributor rebase or changelog change needed.
|
|
Thank you, @BlivionIaG. We ran the off path on an M3 Ultra with Qwen3.8-27B, main against this branch (builds alternated base, new, new, base): tokens identical (0 of 20 prompt rows differ) and speed within run spread, so with no vector this changes nothing. What remains is the steered side from our last review: exact serial parity with steering on across strengths, and the longer-context and concurrent comparisons, at this head.
|
|
Thanks @ashhart. The steered side is measured on an M5 Ultra (main
No divergence in any equality cell. The body carries the summary of each cell; the per-cell hashes are in the run records. |
|
Thanks @BlivionIaG. The new off-path, cached-restore and concurrent comparisons are useful, and the earlier parser and MTP fixes remain present. One distinction remains: solo versus drafted execution uses the same fused steering arithmetic. We still need its byte comparison with the separately ordered steering reference. Please retain the full checkpoint, vector and drafter identities with the scratch-tree receipt, including the measured steering costs. The current-main composition and the MTP check on a supported backend remain ours.
|
Main's SenseNova support turned the qwen27 norm into normShift and filled quant_gpu.zig to its 600-line limit. The steered norm now dispatches from norm_steer_gpu.zig with its pipeline held by the steering plan, unsteered norms call main's normShift, and SenseNova models refuse a control vector.
|
Merged main |
Scope
Opt-in additive GLP residual steering for the Qwen3.8-27B Metal path, default off. The direction is added at the Qwen backbone residual hook; this is not the DeepSeek paired fold/writer hook.
This follows the maintainer's scope decision:
Original authors and provenance
@msuiche); no external serving plugin/engine code is copied or vendored.The TensorFold implementation remains Apache-2.0. Any later vector release needs its own authorship/licence, pinned checkpoint and software versions, derivation recipe, strength calibration and held-out controls. A format citation is not a licence to redistribute checkpoint-derived assets.
Current source and evidence
PR head:
178a01a70b, a merge of main7aadce5e25into5b7f3845e6(the conflicts wereCHANGELOG.mdand one adjacentbuild.zigregistration, both kept); the M5 receipts below were measured on a local scratch merge2035e4a32dof main9edf2f89d4with5b7f3845e6, so this head differs from the measured tree by main's later commits and the same two files. Scoped GLP steps pass on this head (test-glp test-glp-serve test-steer test-glp-steer).forward.Stagesturn the target steering plan off (Stages.steer = false) while reading the target's already-steered activations, so a vector that covers layer 63 is applied once. Regression:test-qwen27-startup-host(target stages resolve the layer-63 direction, the head's resolve none).62f927ef5d:zig,zig-bandzig-windowseach failed one host test (cli_capabilitiescapability audit compared a forced steering listing againstglp_startup.steers, false off macOS); fixed ina94baaf823.desktopanddesktop-linuxfailTypecheck desktopwith the ninefreeDiskBytes/memoryTypeScript errors main9d90f12dfbshows (run 45208593403); this PR touches noapp/file. CI on the current head is queued behind the repository's runner backlog.--glppath resolves against the TOML file's folder; tensor offsets and sizes are bounds-checked without wrapping; metadata arrays are limited to four nested levels; the control-vector flags stay parsed on Linux but are not advertised incapabilities --jsonwhere every valid use refuses them; the tensor digest isverifiedonly when the parsedglp.content_sha256was checked. The Metal kernel contract passes again (the harness now compiles the norm as production does and keeps the suite alive throughrunAll),tf-glp-checkvalidates its arguments before opening the file, and the weightless parity tool and docs pinb181a07d. Host regressions cover each case.zig build test-glp test-glp-serve test-steer test-glp-steer native -Dcpu=apple_m1 -j4exits 0 with 99 tests (36 + 35 + 24 + 4);test-qwen27-startup-hostpasses 24/24 with the new GLP+MTP regression.tools/pr_check.py --base ea37382cb1 --pr 1835reports zero errors and zero warnings across 52 changed files (lean 165 vs 165, zero new);zig fmt --check build.zig zigpasses.tf-kernel-contract --only "qwen27 steer" --no-limitsprintsSUMMARY 1 kernels: 1 pass gates 1-4, 0 fail, 0 known findings; 1 controls: 1 red as planted, 0 missed; 0 limit problems, exit 0. The fullzig build kernel-contractstops atUnrecordedRotaryCompileron pristine main7bd4b6815aas well, so that is inherited.a32ece2d4fonlydesktopanddesktop-linuxfailed, at the app'sTypecheck desktopstep, identical on main9d90f12dfb(run 45208593403); this PR touches noapp/files.22d8d538154e0e5b6f8dcb1fcc74a60a0798104c,mlx-lm 0.32.2,mlx 0.32.4and NumPy2.5.4. It is a derivation recipe, not an embedded base64 asset or a semantic guarantee.Receipt
--glpboth norm sites call main'snormand the saved-state identity is main's; steering is off by default. With a vector the opt-in add changes tokens by design.--glp FILE,--glp-alpha(finite and above zero, else the file'sglp.alpha_default); off by default.9edf2f89d4(main), head5b7f3845e6(measured as scratch merge2035e4a32d); Zig 0.17.0; macOS 27.0 on an Apple M5 Ultra, 30 cores, 256 GB; checkpointTensorFold/Qwen3.8-27B-MLX-4bit@70ae7fac63274ff2eac54152031433374cb80f2f; drafterz-lab/Qwen3.8-27B-DFlash2@50307d4c4cde6860d4eee73e2547cd786fe8e8a4; binariese4883c2e…(main) and688c53f7…(head). Steering cells use a synthetic 63-layer unit vector (file4717ec19…, tensor digest093762d3…), not a trained asset. Earlier scoped tests ran on an M4 Pro.atc overlap --json: complete=false (snapshot limits). Textual overlaps with open qwen27 Metal: plain greedy picks ride the verify's last command buffer (#2930) #2936 (qwen27/model.zig,quant_gpu.zig) and qwen27 Metal: DSpine drafter for Qwen3.8-27B, opt-in #2634 (qwen27_mtp_flags.zig,qwen27_served.zig) are in shared Qwen27 files.zig build test test-golden; the MTP composition cell on hardware (the pinned checkpoint has nomtp-4bit.safetensorsand an M5 refuses the head by design;zig build test-qwen27-startup-hostcovers the layer-63 stages, 27/27).--glp): 20/20 token-equal main against head, every row 0 cached with exact prompt tokens; decode -0.5 to -0.1 %. The 1/2/4/8 sweep: every per-stream hash equal in all 16 cells, throughput +0.2 to +1.2 %.--glp-alpha 0is refused at parse; a zero-direction file at alpha 1 is token-identical to off.Remaining landing gates
74699cd621; mainea37382cb1is merged without losing main's Qwen changes or the agreed additive-only policy.tf-glp-checkvalidates its arguments first and prints the usage), with a regression intest-glp.Earlier receipts and discussion remain source-bound historical evidence, not a claim that every current-main or long-context gate is green.
Related work