Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions jang-tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,16 @@ are available through `python -m jang_tools.jangh.<family>.<module>`. Install
commands, and model-validation requirements. These commands are separate
from `jang convert`; packaging the scripts is not a claim of newly validated
quantization quality or downstream serving support.

## JANGT pipeline

Trellis-coded (JANGT) expert encoding, error curves, byte-budget allocation, streamed evaluation and mixed
JANGT/JANGH bundle assembly for Naive-N0.5-Flash are available through `python -m jang_tools.jangt.<module>`
(same `jang[jangh]` dependencies). See the [JANGT guide](jang_tools/jangt/README.md). No released runtime loads
JANGT bundles yet.

## mflux image quantization

Qwen-Image-2.1, Qwen-Image-2.1-Turbo and Ideogram 4 mflux bundle builders live in `jang_tools.mflux_image`; they
need `mflux` installed. See the [image guide](jang_tools/mflux_image/README.md), including the mflux scheduler patch
Turbo generation needs.
70 changes: 70 additions & 0 deletions jang-tools/jang_tools/jangt/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# JANGT: trellis-coded MoE experts for MLX

JANGT stores routed MoE experts with a bitshift trellis code instead of a scalar codebook. Each weight row is rotated
(blockwise Hadamard-128 with per-layer random signs), normalized by its RMS, and encoded by a Viterbi search over an
L-bit state (L = 12, so a row's whole cost array fits in threadgroup memory). Every step shifts 2K new bits into the
state and emits two weights (V = 2) through a pure-ALU bit-pattern code, so decoding needs no lookup table. K = 2, 2.5
or 3 bits per weight. Massive input channels are carved out before the rotation and kept as fp16 columns. Down
projections additionally get column-RMS scaling with a least-squares column refit.

The design and constants are our own (`codes.py` / `codesearch*.py` search the code family); no code or constants are
taken from ExLlamaV3 or QTIP.

A JANGT bundle can mix formats per unit: some (layer, gate/up | down) units in JANGT, the rest in
[JANGH](../jangh/README.md). `config.json` then carries a per-module `quantization` entry (`"mode": "jangt", "kbits"`
or `"mode": "jangtq2", "bits"`) plus a `jangt` block (`version`, `code`, `state_bits`, `rotation`,
`outlier_columns`).

No released runtime loads JANGT bundles yet. `moe_kernels.py` and `switch.py` are the reference decode kernels and MoE
module for runtime authors.

## Layout

| module | what it is |
|---|---|
| `codes.py`, `codesearch.py`, `codesearch_v2.py`, `trellis.py` | code families, CPU code search, Gaussian MSE / rate-distortion references |
| `v2core.py`, `v2l.py` | Viterbi encoder and GEMV kernels (L = 16 and configurable-L variants), state packing |
| `minitest.py` | dense-model encoder (`encode_matrix`, `JANGTLinear`) and a small-model KL / speed harness |
| `affine_gptq.py` | GPTQ on MLX's affine grid: the affine baseline `minitest` compares against |
| `moe_encode.py` | encoder for the routed experts of one MoE layer (per-expert Hessians, outliers, refit) |
| `moe_kernels.py`, `switch.py` | gathered-expert decode kernels and the mixed JANGT/JANGH MoE module |
| `plan.py`, `curves_jt.py`, `curves_jt2.py`, `expert_alloc.py`, `allocate.py` | byte accounting, error curves, and per-unit format allocation under a byte budget |
| `n05_sens.py` | routing-flip sensitivity per (layer, group), the allocator's weighting |
| `n05_pick_downs.py`, `n05_assemble.py` | collect JANGH down projections and assemble an aligned, mixed bundle |
| `n05_streval.py`, `stage_io.py` | layer-streamed KL / top-1 / NLL evaluation against the BF16 reference, straight from stage files |
| `bench_b2.py` | decode-kernel microbenchmark |

## Building a mixed bundle (Naive-N0.5-Flash)

The pipeline reuses the JANGH N0.5 capture, Hessians and recipe (`jang_tools.jangh.n05`), so run the JANGH steps
first: `stream_capture` (reference + Hessians), `calib`, `curves`, `plan`, and `convert --keep-stage` for any layers
whose JANGH down projections you re-quantize. Every step below needs:

```sh
pip install -e "jang-tools[jangh]" # from the repository root; Apple Silicon
export MLX_ENABLE_TF32=0 JANGT_HB=128 JANGT_L=12
```

```sh
# 1. sensitivity and JANGT error curves
python -m jang_tools.jangt.n05_sens --help
python -m jang_tools.jangt.curves_jt2 --model SRC --headers headers.json --curves curves.json --stats stats.safetensors \
--hess-dir HESS --out curves_jt2.json
# 2. per-unit allocation for one or more byte targets (and optional per-expert widths)
python -m jang_tools.jangt.allocate --help
python -m jang_tools.jangt.expert_alloc --help
# 3. encode the JANGT units, collect the JANGH downs the plan keeps
python -m jang_tools.jangt.moe_encode --model SRC --headers headers.json --hess-dir HESS --layers 3,5,8 \
--plan jangh_plan.json --out jt_stage
python -m jang_tools.jangt.n05_pick_downs --todo todo.json --have-dir jh_stage --conv-dir jh_conv/.stage \
--alloc alloc.json --key "97.55:free" --out jh_pick
# 4. score before building: streamed KL against the BF16 reference, experts read from the stage dirs
python -m jang_tools.jangt.n05_streval --model SRC --headers headers.json --seqs corpus.jsonl --ref ref.safetensors \
--nonexpert affine8 --experts "stages:jt_stage+jh_pick+JANGH2_BUNDLE" --sets klref,agentic_ref --out scores.json
# 5. assemble (non-expert tensors, tokenizer and template files come from the JANGH base bundle)
python -m jang_tools.jangt.n05_assemble --jt jt_stage --pick jh_pick --base JANGH2_BUNDLE \
--plan alloc.json --plan-key "97.55:free" --out BUNDLE
```

Streamed scores are not a substitute for generation in the target runtime: verify coherent output, tool calls and
reasoning close in the runtime before publishing a bundle.
4 changes: 4 additions & 0 deletions jang-tools/jang_tools/jangt/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
"""JANGT — trellis-coded JANG for Apple Metal. See README.md in this package.

Our own design: bitshift trellis over 16x16 tiles with pure-ALU codes chosen by our own search (jangt.codes /
jangt.codesearch). No code or constants are taken from ExLlamaV3 or QTIP."""
79 changes: 79 additions & 0 deletions jang-tools/jang_tools/jangt/affine_gptq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""GPTQ on MLX's own affine grid — the affine baseline that minitest compares JANGT against."""
from __future__ import annotations

import mlx.core as mx


def _hinv_upper(H, damp):
"""Upper Cholesky factor U of H^-1 with relative damping, computed ENTIRELY
on the CPU stream (every op inside `with mx.stream(mx.cpu)`). Any GPU op that waits on the multi-second CPU
factorisation (even a transpose) trips the Metal command-buffer watchdog: reproduced on the 17408-wide Qwen3.8-27B
down_proj Hessian."""
with mx.stream(mx.cpu):
B, K, _ = H.shape
d = mx.mean(mx.diagonal(H, axis1=-2, axis2=-1), axis=-1, keepdims=True)
Hd = H + (damp * d)[..., None] * mx.eye(K)[None]
L = mx.linalg.cholesky(Hd)
Linv = mx.linalg.inv(L)
Hinv = mx.matmul(mx.swapaxes(Linv, -1, -2), Linv)
U = mx.swapaxes(mx.linalg.cholesky(Hinv), -1, -2)
mx.eval(U)
return U


def pack_affine_lsb(q, bits):
"""MLX affine packing for ANY width (2/3/4/5/6/8): continuous LSB-first bitstream per row. Verified bit-identical to
mx.quantize's packed output at every width."""
*lead, K = q.shape
g = q.astype(mx.uint32).reshape(*lead, K // 32, 32); words = []
for w in range(bits):
acc = mx.zeros(g.shape[:-1], dtype=mx.uint32)
for j in range(32):
st = j * bits; en = st + bits
if en <= w * 32 or st >= (w + 1) * 32:
continue
off = st - w * 32; v = g[..., j]
acc = acc | (v << off) if off >= 0 else acc | (v >> (-off))
words.append(acc)
return mx.stack(words, -1).reshape(*lead, K * bits // 32)


def affine_gptq(W, H, bits, gs, damp=0.01, block=128, row_chunk=1024):
"""Row-chunked wrapper: GPTQ rows are independent given chol(H^-1), so W is processed row_chunk rows at a time
(identical codes / grid; each Metal command buffer stays far below the GPU watchdog). U is factored once."""
B, N, Kd = W.shape
U = _hinv_upper(H, damp); mx.eval(U)
outs = [_affine_gptq_rows(W[:, r0:r0 + row_chunk], U, bits, gs, block) for r0 in range(0, N, row_chunk)]
return (mx.concatenate([o[0] for o in outs], axis=1), mx.concatenate([o[1] for o in outs], axis=1),
mx.concatenate([o[2] for o in outs], axis=1))


def _affine_gptq_rows(W, U, bits, gs, block=128):
"""Batched GPTQ on MLX's per-group affine grid. W (B,N,K) f32, H (B,K,K) f32 -> (packed, scales, biases) whose
mx.dequantize is exactly the GPTQ solution. The grid (bf16 scale/bias per group) is MLX's own RTN grid of the
ORIGINAL weights (static groups), codes chosen column by column with error feedback through chol(H^-1)."""
B, N, Kd = W.shape
_, s, b = mx.quantize(W.astype(mx.bfloat16), group_size=gs, bits=bits) # (B,N,K/gs) bf16
sf, bf = s.astype(mx.float32), b.astype(mx.float32)
qmax = (1 << bits) - 1
Q = mx.zeros((B, N, Kd), dtype=mx.uint8)
Wc = W.astype(mx.float32)
for b0 in range(0, Kd, block):
b1 = min(b0 + block, Kd)
Wb = Wc[..., b0:b1]; Ub = U[:, b0:b1, b0:b1]; errs, qs = [], []
for j in range(b1 - b0):
g = (b0 + j) // gs
w = Wb[..., j]
q = mx.clip(mx.round((w - bf[..., g]) / sf[..., g]), 0, qmax)
e = (w - (q * sf[..., g] + bf[..., g])) / Ub[:, j, j][:, None]
Wb = Wb - e[..., None] * Ub[:, j, :][:, None, :] * (mx.arange(b1 - b0) > j)[None, None, :]
errs.append(e); qs.append(q.astype(mx.uint8))
if (j + 1) % 32 == 0:
mx.eval(Wb, *errs[-32:], *qs[-32:])
Q[..., b0:b1] = mx.stack(qs, axis=-1)
if b1 < Kd:
Wc = mx.concatenate([Wc[..., :b1], Wc[..., b1:] - mx.matmul(mx.stack(errs, -1), U[:, b0:b1, b1:])], axis=-1)
mx.eval(Q, Wc)
packed = pack_affine_lsb(Q, bits) # MLX affine packing == LSB-first
mx.eval(packed)
return packed, s, b
176 changes: 176 additions & 0 deletions jang-tools/jang_tools/jangt/allocate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""JANGT allocator for N0.5: fill an exact byte budget with the best per-unit formats.

Objective (same as the JANGH2 plan, jang_tools.jangh.n05.plan): predicted FROZEN-SELECTION KL = sum over units of
c[L][group] * expert-output NMSE, c from n05_sens.py (geomean over files), NMSE from held-out curves.
Units: per MoE layer, gate_up (tied: the fused gate+up kernel needs one format) and down.
Options per unit (bytes exact, jang_tools.jangt.plan):
gate_up : jt2 / jt3 (JANGT, curves_jt.json) and jh2 / jh3 / jh4 (JANGH on the SAME Hessians, curves_jt.json)
down : jh2 / jh3 / jh4 (JANGH, curves.json) [JANGT down loses to JANGH: hybrid]
Greedy on the per-unit lower convex hull of (bytes, error), exact for convex curves.
"""
from __future__ import annotations

import argparse
import heapq
import json
import math
from pathlib import Path

from jang_tools.jangt.plan import GIB, jangh_bytes, jangt_bytes

E, D, I = 256, 4096, 2048


def opt_bytes(fmt: str, proj: str) -> int:
n, k = (I, D) if proj in ("gate", "up") else (D, I)
b = int(fmt[2])
return jangt_bytes(E, n, k, b) if fmt.startswith("jt") else jangh_bytes(E, n, k, b)


def solve(units: dict, budget: int):
hull = {}
for u, opts in units.items():
opts = sorted(opts, key=lambda o: (o[1], o[2]))
h = [opts[0]]
for o in opts[1:]:
if o[2] >= h[-1][2]:
continue
while len(h) >= 2 and (h[-1][2] - o[2]) / (o[1] - h[-1][1]) >= (h[-2][2] - h[-1][2]) / (h[-1][1] - h[-2][1]):
h.pop()
h.append(o)
hull[u] = h
state = {u: 0 for u in hull}; spent = sum(h[0][1] for h in hull.values())
if spent > budget:
raise SystemExit(f"minimum allocation {spent/GIB:.3f} GiB > expert budget {budget/GIB:.3f} GiB")
heap = [(-(h[0][2] - h[1][2]) / (h[1][1] - h[0][1]), u, 1) for u, h in hull.items() if len(h) > 1]
heapq.heapify(heap)
while heap:
_, u, i = heapq.heappop(heap)
if state[u] != i - 1:
continue
h = hull[u]; d = h[i][1] - h[i - 1][1]
if spent + d > budget:
continue
spent += d; state[u] = i
if i + 1 < len(h):
heapq.heappush(heap, (-(h[i][2] - h[i + 1][2]) / (h[i + 1][1] - h[i][1]), u, i + 1))
choice = {u: hull[u][i] for u, i in state.items()}
return choice, spent, sum(c[2] for c in choice.values())


def main():
ap = argparse.ArgumentParser()
ap.add_argument("--curves", required=True)
ap.add_argument("--curves-jt", required=True)
ap.add_argument("--sens", required=True)
ap.add_argument("--jangh-plan", required=True)
ap.add_argument("--target-gib", type=float, default=93.0)
ap.add_argument("--fixed-gib", type=float, default=6.20666)
ap.add_argument("--drafter-bytes", type=int, default=1305601530)
ap.add_argument("--out", required=True)
a = ap.parse_args()
C = json.loads(Path(a.curves).read_text()); J = json.loads(Path(a.curves_jt).read_text())
S = json.loads(Path(a.sens).read_text())["layers"]; P = json.loads(Path(a.jangh_plan).read_text())
layers = sorted(int(L) for L in J)
cw = {(L, g): S[str(L)][g]["c"] for L in layers for g in ("gu", "dn")}
budget = int(a.target_gib * GIB - a.fixed_gib * GIB - a.drafter_bytes)

# 0) reproduce the published JANGH2 objective with ITS curves (sanity of the objective)
eb = P["expert_bits"]
pub_sept = sum(cw[(L, "gu")] * C[str(L)][f"gate_up{eb[f'{L}:gate']}"] + cw[(L, "dn")] * C[str(L)][f"down{eb[f'{L}:down']}"] for L in layers)
pub_same = sum(cw[(L, "gu")] * J[str(L)][f"jh_gate_up{eb[f'{L}:gate']}"] + cw[(L, "dn")] * C[str(L)][f"down{eb[f'{L}:down']}"] for L in layers)
pub_bytes = sum(opt_bytes(f"jh{eb[f'{L}:gate']}", "gate") * 2 + opt_bytes(f"jh{eb[f'{L}:down']}", "down") for L in layers)
print(f"layers {len(layers)}; expert budget {budget/GIB:.3f} GiB (target {a.target_gib} incl. fixed {a.fixed_gib} + drafter {a.drafter_bytes/GIB:.3f})")
print(f"published JANGH2 ({pub_bytes/GIB:.2f} GiB experts): objective {pub_sept:.5f} with Sept curves "
f"(plan file says {P['objective']:.5f}) | {pub_same:.5f} with same-Hessian gate_up curves")

def units_for(gu_fmts):
U = {}
for L in layers:
U[(L, "gate_up")] = [(f, opt_bytes(f, "gate") * 2, cw[(L, "gu")] * (J[str(L)][f"jt_gate_up{f[2]}"] if f.startswith("jt") else J[str(L)][f"jh_gate_up{f[2]}"]))
for f in gu_fmts if (f"jt_gate_up{f[2]}" if f.startswith("jt") else f"jh_gate_up{f[2]}") in J[str(L)]]
U[(L, "down")] = [(f"jh{b}", opt_bytes(f"jh{b}", "down"), cw[(L, "dn")] * C[str(L)][f"down{b}"]) for b in (2, 3, 4)]
return U

res = {"budget_gib": budget / GIB, "published": {"objective_sept": pub_sept, "objective_same": pub_same, "experts_gib": pub_bytes / GIB}}
for name, fm in (("jangh_only", ("jh2", "jh3", "jh4")), ("hybrid", ("jt2", "jt3")), ("free", ("jt2", "jt3", "jh2", "jh3", "jh4"))):
choice, spent, obj = solve(units_for(fm), budget)
hist = {}
for (L, p), c in choice.items():
hist[f"{p}:{c[0]}"] = hist.get(f"{p}:{c[0]}", 0) + 1
res[name] = {"objective": obj, "experts_gib": spent / GIB, "total_gib": (spent + a.fixed_gib * GIB + a.drafter_bytes) / GIB,
"histogram": hist, "formats": {f"{L}:{p}": c[0] for (L, p), c in choice.items()}}
print(f"{name:10s} objective {obj:.5f} ({obj/pub_same - 1:+.1%} vs published JANGH2 at 96 GiB) experts {spent/GIB:.2f} GiB "
f"total {res[name]['total_gib']:.3f} GiB {dict(sorted(hist.items()))}")
Path(a.out).write_text(json.dumps(res, indent=1))




# ------------------------------------------------------------------------------------------- v2 (curves_jt2.json)
def jt_bytes_v2(proj: str, k) -> int:
"""Exact JANGT v2 bytes of one projection (all experts) at width k, ragged layout: packed + f32 row scales +
8 outlier cols (f16 weights, i32 index) + per-layer signs + offsets/kbits; down also stores f32 column scales."""
from jang_tools.jangt.expert_alloc import words_per_row_k
n, kin = (I, D) if proj in ("gate", "up") else (D, I)
b = E * n * (words_per_row_k(kin, k) * 4 + 4 + 8 * 2) + E * 8 * 4 + kin * 4 + (E + 1) * 8 + E * 4
if proj == "down":
b += E * kin * 4
return b


def plan_v2(J2: dict, cw: dict, budget: int, fmts_gu, fmts_dn):
U = {}
for L in sorted(int(x) for x in J2):
j = J2[str(L)]
def opt(f, grp):
kind, k = f[:2], f[2:]
key = f"{kind}_{'gate_up' if grp == 'gu' else 'down'}{k}"
if key not in j:
return None
kk = float(k); kk = int(kk) if kk.is_integer() else kk
by = (2 * jt_bytes_v2("gate", kk) if grp == "gu" else jt_bytes_v2("down", kk)) if kind == "jt" else \
(2 * opt_bytes(f"jh{int(kk)}", "gate") if grp == "gu" else opt_bytes(f"jh{int(kk)}", "down"))
return (f, by, cw[(L, grp)] * j[key])
U[(L, "gate_up")] = [o for o in (opt(f, "gu") for f in fmts_gu) if o]
U[(L, "down")] = [o for o in (opt(f, "dn") for f in fmts_dn) if o]
return solve(U, budget)


def main_v2():
ap = argparse.ArgumentParser()
ap.add_argument("--curves-v2", required=True)
ap.add_argument("--sens", required=True)
ap.add_argument("--jangh-plan", required=True)
ap.add_argument("--targets", default="93,94,95,96")
ap.add_argument("--fixed-gib", type=float, default=6.20666); ap.add_argument("--drafter-bytes", type=int, default=1305601530)
ap.add_argument("--out", required=True)
a = ap.parse_args()
J2 = json.loads(Path(a.curves_v2).read_text()); S = json.loads(Path(a.sens).read_text())["layers"]
P = json.loads(Path(a.jangh_plan).read_text()); layers = sorted(int(x) for x in J2)
cw = {(L, g): S[str(L)][g]["c"] for L in layers for g in ("gu", "dn")}
eb = P["expert_bits"]
pub = sum(cw[(L, "gu")] * J2[str(L)][f"jh_gate_up{eb[f'{L}:gate']}"] + cw[(L, "dn")] * J2[str(L)][f"jh_down{eb[f'{L}:down']}"] for L in layers)
print(f"{len(layers)} layers; published JANGH2 objective on v2 curves: {pub:.5f}")
res = {"published_v2": pub}
JH = ("jh2", "jh3", "jh4"); JT = ("jt2", "jt2.5", "jt3")
for t in [float(x) for x in a.targets.split(",")]:
budget = int(t * GIB - a.fixed_gib * GIB - a.drafter_bytes)
for name, fg, fd in (("jangh_only", JH, JH), ("jangt_only", JT, JT), ("free", JT + JH, JT + JH)):
ch, spent, obj = plan_v2(J2, cw, budget, fg, fd)
hist = {}
for (L, p), c_ in ch.items():
hist[f"{p}:{c_[0]}"] = hist.get(f"{p}:{c_[0]}", 0) + 1
res[f"{t}:{name}"] = {"objective": obj, "experts_gib": spent / GIB, "formats": {f"{L}:{p}": c_[0] for (L, p), c_ in ch.items()}, "hist": hist}
print(f"{t:5.1f} GiB {name:10s} objective {obj:.5f} ({obj/pub-1:+.1%} vs JANGH2) experts {spent/GIB:.2f} GiB {dict(sorted(hist.items()))}", flush=True)
Path(a.out).write_text(json.dumps(res, indent=1))


if __name__ == "__main__":
import sys as _sys
if "--curves-v2" in _sys.argv or "--v2" in _sys.argv:
if "--v2" in _sys.argv:
_sys.argv.remove("--v2")
main_v2()
else:
main()
Loading
Loading