Skip to content
Merged
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
10 changes: 10 additions & 0 deletions jang-tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -415,3 +415,13 @@ pip install "jang[mlx]>=2.5.18"
---

<p align="center">장진호 제작 · Created by Jinho Jang — <a href="https://jangq.ai">jangq.ai</a></p>

## JANGH pipelines

GLM-5.3-Flash and Naive-N0.5 JANGH conversion, evaluation, and kernel modules
are available through `python -m jang_tools.jangh.<family>.<module>`. Install
`jang[jangh]` on Apple Silicon for their dependencies. See the
[JANGH guide](jang_tools/jangh/README.md) for input artifacts, native module
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.
2 changes: 1 addition & 1 deletion jang-tools/jang_tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
profile = profile_for_bits(2) # → "JANG_2S"
"""

__version__ = "2.5.48"
__version__ = "2.5.49"
__author__ = "Jinho Jang"
__email__ = "eric@jangq.ai"

Expand Down
2 changes: 1 addition & 1 deletion jang-tools/jang_tools/glm5_next/kl_eval.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""KL evaluation for glm5_next bundles against the pod FP8 reference.

Reference: klref.safetensors from the RunPod capture — per prompt i:
Reference: klref.safetensors from the reference capture — per prompt i:
p{i}.input_ids [S], p{i}.top_ids [S,128], p{i}.top_logprobs [S,128]
(teacher-forced, positions predict token t+1, reference_precision=FP8).

Expand Down
74 changes: 74 additions & 0 deletions jang-tools/jang_tools/jangh/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# JANGH: codebook-quantized MoE experts for MLX

JANGH is the expert format used by the `*-JANGH2` bundles on the JANGQ-AI Hub org (GLM-5.3-Flash, Naive-N0.5-Flash).
Routed experts are stored at 2-4 bits with a fixed odd-cubic codebook per bit width, one fp16 scale per output row and a
blockwise Hadamard-32 rotation of the input dimension. Everything else in a bundle stays 8-bit (MXFP8 or affine) or full
precision. On disk the identifiers are `jangtq` (`version: 2`), per-module `"mode": "jangtq2"`, and the tensors
`*.tq2_packed` / `*.tq2_scales`; the packing reuses MLX's own bit layout so the runtime can reuse MLX kernel structure.

## Layout

| module | what it is |
|---|---|
| `format.py` | codebook, bit packing/unpacking, Hadamard-32 rotation, row encode/decode |
| `encode.py` | row-scale search + nearest-level assignment (RTN with the codebook) |
| `gptq.py` | GPTQ with the codebook quantizer |
| `kernels.py`, `switch.py` | Metal kernels and the `TQSwitchGLU` drop-in for mlx_lm's `SwitchGLU` |
| `install.py` | installs JANGH experts into a constructed model before `nn.quantize` (runtime hook) |
| `glm53/` | the GLM-5.3-Flash pipeline: capture, calibration, bit allocation, conversion, audit, KL evaluation, finalize |
| `n05/` | the Naive-N0.5-Flash pipeline (SWA + DSA hybrid attention, chaotic top-8 routing): reference model, capture, Hessians, recipe, conversion, evaluation |
| `tools/` | `rescale_bundle*.py`: scale correction of a finished bundle (see below); `deq_check.py`: decode bundle tensors and compare with the source experts |
| `tests/` | `test_jangtq2.py`, `test_switch.py`: kernel and module correctness gates (must print `ALL PASS` before any build) |

## Installation and entry points

For an installed release containing these modules, use `pip install "jang[jangh]"`.
The extra includes MLX, MLX-LM, Transformers and SciPy. Pipeline commands use
`python -m jang_tools.jangh.<family>.<module> --help`; they are separate from
`jang convert`. Package installation does not establish model quality or runtime compatibility.

## Building a bundle (GLM-5.3-Flash)

Prepare the BF16 source, calibration corpus, imatrix and tensor grid census before
running this example. `grid_census.json` is a JSON list of per-tensor objects with
`k` (tensor name) and `grid` (`mx8` for eligible MXFP8 tensors). It must describe
the exact source tensor grid; this GLM pipeline consumes that producer artifact
and does not generate it. Do not substitute an unrelated model census.

```sh
pip install -e "jang-tools[jangh]" # from the repository root; Apple Silicon
export MLX_ENABLE_TF32=0 # calibration and evaluation only; never let TF32 into Hessians
python -m jang_tools.jangh.tests.test_jangtq2
python -m jang_tools.jangh.tests.test_switch
# 1. reference capture: layer-streamed BF16 forward over the calibration corpus (reservoir rows, routing, per-expert E[x^2])
python -m jang_tools.jangh.glm53.stream_capture --model SRC --seqs corpus.jsonl --stats-out diag.safetensors --ref-out klref.safetensors
# 2. unit curves (error vs bits per layer) and the bit allocation under a byte budget
python -m jang_tools.jangh.glm53.calib_tq --model SRC --diag diag.safetensors --out calib/ --experts 32 --rotation hadamard32
python -m jang_tools.jangh.glm53.plan --model SRC --census grid_census.json --calib calib/calib_tq_h32.json --out plan.json
# 3. convert (GPTQ on gate/up, held-out-gated GPTQ on down, imatrix prior), audit, evaluate, finalize
python -m jang_tools.jangh.glm53.convert_tq --model SRC --plan plan.json --diag diag.safetensors --imatrix imatrix.safetensors --out BUNDLE --rotation hadamard32
python -m jang_tools.jangh.glm53.audit BUNDLE
python -m jang_tools.jangh.glm53.kl_eval_tq --bundle BUNDLE --klref klref.safetensors --metrics-out kl.json
```

The Naive-N0.5 pipeline follows the same steps with `jang_tools.jangh.n05.*` (`build_corpus`, `stream_capture`,
`calib`, `curves`, `plan`, `convert`, `expert_audit`, `stream_eval`, `finalize`). Scripts take the BF16 source and the
tensor-header index through `JANGH_SOURCE` / `JANGH_HEADERS` or explicit arguments; nothing is hard-coded.

## Scale correction (read before shipping a low-bit bundle)

Error-minimizing row scales shrink every quantized matrix along its source row: `<w,q>/<w,w>` is about 0.88 at 2 bits
and 0.965 at 3 bits. Three matrices per expert and dozens of layers deep, strong late decisions are attenuated; the
decision to end a long reasoning block is one of them, and a bundle can then fail to emit `</think>` after a few
thousand reasoning tokens. `tools/rescale_bundle.py` rewrites only the `tq2_scales` tensors to unit gain along the source
row (`scale *= <w,w>/<w,q>`, clipped to [0.5, 2]); codes, size, format and speed are unchanged. `tools/rescale_bundle_data.py`
measures per-expert gains on real routed activations instead (smaller correction, best token-level fidelity). Whether a
model needs the correction must be measured: score `</think>` at the positions where a full-precision reference ends
its reasoning, on transcripts generated by a working engine, at several reasoning lengths.

## Rules that every step here follows

- Verify in the real runtime before calling a bundle done; a Python loader smoke test is not verification.
- Calibration Hessians are computed with TF32 off, per expert, validated for finiteness and positive-definiteness.
- Every bundle ships aligned shards (`jang_tools.format.aligned_safetensors`) and a `jang_config.json` that records
calibration, per-layer expert bits and any scale correction.
1 change: 1 addition & 0 deletions jang-tools/jang_tools/jangh/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""jangtq2 — JANGTQ v2 format + kernels."""
35 changes: 35 additions & 0 deletions jang-tools/jang_tools/jangh/encode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""JANGTQ v2 encoding: per-row scale solved by (optionally importance-weighted) least squares,
alternating with nearest-level assignment on the v2 odd-cubic codebook."""
from __future__ import annotations

import mlx.core as mx

from .format import codebook, nearest_level, pack_bitstream


def encode(W: mx.array, bits: int, col_weight: mx.array | None = None, iters: int = 6):
"""W (..., N, K) float -> (q uint8 (..., N, K), scale float32 (..., N)).
col_weight: (K,) or (..., 1, K) nonnegative input importance (E[x^2]); weights the LS scale objective
sum_k w_k (W_rk - s_r c_rk)^2. Assignment is per element nearest level (independent of w for a fixed scale)."""
W = W.astype(mx.float32)
cb = mx.array(codebook(bits))
wgt = 1.0 if col_weight is None else col_weight.astype(mx.float32)
s = mx.maximum(mx.sqrt(mx.mean(W * W, axis=-1, keepdims=True)), 1e-12)
for _ in range(iters):
c = cb[nearest_level(W / s, cb)]
num = mx.sum(wgt * W * c, axis=-1, keepdims=True)
den = mx.maximum(mx.sum(wgt * c * c, axis=-1, keepdims=True), 1e-20)
s = mx.maximum(num / den, 1e-12)
q = nearest_level(W / s, cb)
return q, s.squeeze(-1)


def dequant(q: mx.array, scale: mx.array, bits: int, scale_dtype=mx.float16) -> mx.array:
"""Exactly what the runtime computes: fp16-stored scale times codebook level."""
cb = mx.array(codebook(bits))
return cb[q] * scale.astype(scale_dtype).astype(mx.float32)[..., None]


def encode_packed(W, bits, col_weight=None):
q, s = encode(W, bits, col_weight)
return pack_bitstream(q, bits), s.astype(mx.float16), q
214 changes: 214 additions & 0 deletions jang-tools/jang_tools/jangh/format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
"""JANGTQ v2 format: Gaussian Lloyd-Max codebooks, MLX-compatible LSB bitstream packing,
Walsh-Hadamard rotation with explicit signs, per-row solved scales.

Invariants (tests/test_format.py):
* pack_bitstream(q, b) is byte-identical to MLX affine packing for b in {2,3,4,6,8}
* unpack(pack(q)) == q
* rotate/unrotate are exact inverses (orthonormal)
"""
from __future__ import annotations

import math
import numpy as np
import mlx.core as mx

SUPPORTED_BITS = (2, 3, 4, 6, 8)


# ---------------------------------------------------------------- codebooks
def _phi(x):
return np.exp(-0.5 * x * x) / math.sqrt(2 * math.pi)


def _Phi(x):
return 0.5 * (1.0 + np.vectorize(math.erf)(x / math.sqrt(2.0)))


def lloyd_max_gaussian(bits: int, iters: int = 2000) -> np.ndarray:
"""MSE-optimal scalar quantizer levels for N(0,1), sorted ascending, float64."""
n = 1 << bits
# init: uniform quantiles
levels = np.array([-_inv_Phi((i + 0.5) / n) for i in range(n)])[::-1].copy()
for _ in range(iters):
b = np.concatenate([[-np.inf], 0.5 * (levels[1:] + levels[:-1]), [np.inf]])
pa, pb = _phi(b[:-1]), _phi(b[1:])
Pa, Pb = _Phi(b[:-1]), _Phi(b[1:])
new = (pa - pb) / np.maximum(Pb - Pa, 1e-300)
if np.max(np.abs(new - levels)) < 1e-12:
levels = new
break
levels = new
levels = 0.5 * (levels - levels[::-1]) # enforce exact symmetry
return levels


def _inv_Phi(p):
# Acklam-style via bisection (only used for init)
lo, hi = -10.0, 10.0
for _ in range(100):
mid = 0.5 * (lo + hi)
if 0.5 * (1 + math.erf(mid / math.sqrt(2))) < p:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)


# v2 codebook family: odd cubic in the centered code index, levels(q) = u * (alpha + beta * u^2), u = q - (2^b - 1)/2.
# (alpha, beta) minimize N(0,1) MSE. 2-bit is EXACTLY Lloyd-Max; 3-bit +0.2% MSE; 4-bit +2% MSE (measured 2026-09-25).
# Kernels evaluate it arithmetically (no table): the decode stays ALU-cheap at every width.
CUBIC_PARAMS = {
2: (0.8929999999999999, 0.05065),
3: (0.47124999999999995, 0.011599999999999997),
4: (0.2405, 0.002100000000000002),
}
_CB_CACHE: dict[int, np.ndarray] = {}


def cubic_params(bits: int) -> tuple[float, float]:
if bits in CUBIC_PARAMS:
return CUBIC_PARAMS[bits]
# 6/8-bit: uniform (beta=0) with the MSE-optimal step for N(0,1), fitted once
n = 1 << bits
u = np.arange(n) - (n - 1) / 2
best = min((_mse_levels(u * s), s) for s in np.linspace(0.2 / n * 16, 8.0 / n, 400))
CUBIC_PARAMS[bits] = (float(best[1]), 0.0)
return CUBIC_PARAMS[bits]


def codebook(bits: int) -> np.ndarray:
"""Levels in code order (ascending) for the v2 cubic family."""
if bits not in _CB_CACHE:
a, b = cubic_params(bits)
n = 1 << bits
u = np.arange(n, dtype=np.float64) - (n - 1) / 2
_CB_CACHE[bits] = (u * (a + b * u * u)).astype(np.float32)
return _CB_CACHE[bits]


def _mse_levels(lv) -> float:
lv = np.sort(np.asarray(lv, np.float64))
b = np.concatenate([[-np.inf], 0.5 * (lv[1:] + lv[:-1]), [np.inf]])
x = np.linspace(-12, 12, 200001)
idx = np.searchsorted(b, x) - 1
return float(np.trapezoid((x - lv[idx]) ** 2 * _phi(x), x))


def gaussian_mse(bits: int) -> float:
"""Expected MSE of the v2 codebook on N(0,1) (2-bit 0.11748 = Lloyd-Max; 3-bit 0.03462; 4-bit 0.00969)."""
return _mse_levels(codebook(bits))


# ---------------------------------------------------------------- packing
def pack_bitstream(q: mx.array, bits: int) -> mx.array:
"""q: uint (..., K) values < 2**bits -> uint32 (..., K*bits/32), continuous LSB-first bitstream per row.
Requires K % 32 == 0 (every 32 values occupy exactly `bits` words)."""
assert bits in SUPPORTED_BITS, bits
*lead, K = q.shape
assert K % 32 == 0, f"K={K} must be a multiple of 32"
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):
start = j * bits
end = start + bits
if end <= w * 32 or start >= (w + 1) * 32:
continue
off = start - w * 32
v = g[..., j]
if off >= 0:
acc = acc | (v << off)
else:
acc = acc | (v >> (-off))
words.append(acc)
out = mx.stack(words, axis=-1) # (..., K/32, bits)
return out.reshape(*lead, K * bits // 32)


def unpack_bitstream(p: mx.array, bits: int, K: int) -> mx.array:
*lead, W = p.shape
assert W == K * bits // 32
g = p.reshape(*lead, K // 32, bits)
mask = (1 << bits) - 1
vals = []
for j in range(32):
start = j * bits
w, off = divmod(start, 32)
v = g[..., w] >> off
if off + bits > 32:
v = v | (g[..., w + 1] << (32 - off))
vals.append(v & mask)
return mx.stack(vals, axis=-1).reshape(*lead, K).astype(mx.uint8)


# ---------------------------------------------------------------- rotation
def make_signs(dim: int, seed: int) -> np.ndarray:
rng = np.random.default_rng(seed)
return rng.choice(np.array([-1, 1], dtype=np.int8), size=dim)


def hadamard_ok(dim: int) -> bool:
for m in (1, 12, 20, 28):
if dim % m == 0 and (dim // m) & (dim // m - 1) == 0:
return True
return False


def rotate_in(W: mx.array, signs: mx.array) -> mx.array:
"""W (..., K) -> W @ R^T where R = H diag(signs) (orthonormal). Computed in float32."""
return mx.hadamard_transform(W.astype(mx.float32) * signs.astype(mx.float32))


def rotate_act(x: mx.array, signs: mx.array) -> mx.array:
"""x (..., K) -> R x. Same operation as rotate_in (H symmetric): H (s * x)."""
return mx.hadamard_transform(x.astype(mx.float32) * signs.astype(mx.float32))


def unrotate_in(Wr: mx.array, signs: mx.array) -> mx.array:
return mx.hadamard_transform(Wr.astype(mx.float32)) * signs.astype(mx.float32)


# ---------------------------------------------------------------- encode
def nearest_level(u: mx.array, cb: mx.array) -> mx.array:
"""u float (..., K) in codebook units -> uint8 index of nearest level (cb sorted)."""
bnd = (cb[1:] + cb[:-1]) * 0.5
q = mx.zeros(u.shape, dtype=mx.uint8)
for i in range(bnd.shape[0]):
q = q + (u > bnd[i]).astype(mx.uint8)
return q


def encode_rows(Wr: mx.array, bits: int, col_weight: mx.array | None = None, iters: int = 4):
"""Quantize rotated rows Wr (N, K) float32 -> (q uint8 (N,K), scale float32 (N,)).
Alternates nearest-level assignment and the (weighted) least-squares scale.
col_weight: optional (K,) or (N,K) nonnegative weights for the LS scale (rotated-basis importance)."""
cb = mx.array(codebook(bits))
s = mx.sqrt(mx.mean(Wr * Wr, axis=-1, keepdims=True)) # N(0, s^2) assumption
s = mx.maximum(s, 1e-12)
wgt = 1.0 if col_weight is None else col_weight
for _ in range(iters):
q = nearest_level(Wr / s, cb)
c = cb[q]
num = mx.sum(wgt * Wr * c, axis=-1, keepdims=True)
den = mx.maximum(mx.sum(wgt * c * c, axis=-1, keepdims=True), 1e-20)
s = mx.maximum(num / den, 1e-12)
q = nearest_level(Wr / s, cb)
return q, s.squeeze(-1)


def dequant_rows(q: mx.array, scale: mx.array, bits: int) -> mx.array:
cb = mx.array(codebook(bits))
return cb[q] * scale[..., None].astype(mx.float32)


# ---------------------------------------------------------------- v2 blockwise rotation (hadamard32)
def h32(x: mx.array) -> mx.array:
"""Blockwise normalized Walsh-Hadamard over the LAST axis in 32-wide blocks (self-inverse), float32."""
shp = x.shape
return mx.hadamard_transform(x.astype(mx.float32).reshape(*shp[:-1], shp[-1] // 32, 32)).reshape(shp)


def h32_both(H: mx.array) -> mx.array:
"""R H R^T for a (..., K, K) matrix with R = blockwise H32 (symmetric): rotate rows and columns."""
return mx.swapaxes(h32(mx.swapaxes(h32(H), -1, -2)), -1, -2)
Empty file.
Loading
Loading