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
9 changes: 9 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,9 @@ if(Python3_Interpreter_FOUND)
# the gate itself needs the GPU and runs on Strix Halo (.github/workflows/hw-gate.yml)
add_test(NAME hw_gate_judges COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/hw_gate_test.py)
add_test(NAME q4nx_pb16i COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/q4nx_pb16i_test.py)
# the t2 chunk kind (docs/npu.md "The t2 chunk kind"): synthetic only, because the real-model
# leg needs 14 GB of Bonsai-2 images. Run tests/q4nx_t2_test.py without --no-model for the gate.
add_test(NAME q4nx_t2 COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/q4nx_t2_test.py --no-model)
# the safetensors -> Q4NX converter and the d3 readout head it packs (engine #653): every
# fixture is synthesised, so this needs numpy and nothing else — no gguf-py, no model, no
# device, no download.
Expand Down Expand Up @@ -571,6 +574,12 @@ add_test(NAME npu_pb16i_layout
COMMAND ${CMAKE_SOURCE_DIR}/tests/npu_pb16i_layout_test.sh
${CMAKE_CXX_COMPILER} ${CMAKE_SOURCE_DIR}/npu/forward/include
${CMAKE_SOURCE_DIR}/tests/npu_pb16i_layout_test.cpp)
# The t2 chunk (npu/q4nx.h, "The t2 chunk kind"): the same kind of contract, but the thing under
# test is the shipped decoder, so it compiles npu/q4nx.cpp as well. No device, no model.
add_test(NAME npu_t2_layout
COMMAND ${CMAKE_SOURCE_DIR}/tests/npu_t2_layout_test.sh
${CMAKE_CXX_COMPILER} ${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/tests/npu_t2_layout_test.cpp)
# The host side of a MoE container: __metadata__.moe, per-expert chunk pointers and the router.
# Crafted directories at run time, so CI needs no 18 GB model; with two arguments it checks the
# same code against a real container and a gate.json from tools/moe_expert_chunks.py gate.
Expand Down
56 changes: 52 additions & 4 deletions docs/npu.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ byte layouts).
| 5120 B | q4_1: bf16 scale and zero per 32 columns of a row | `code * scale + zero` | Qwen3, Llama, Gemma, Phi models |
| 4736 B | Q4_K: u8 scale and min per 32 columns, bf16 `S`, `M` per row | `S * scale * code + M * min` | Qwen3.5-4B projections |
| 8704 B | Q8: bf16 scale per 32 columns, int8 codes | `d * code` | Qwen3.5-4B `lm_head` and embedding |
| 2176 B | **t2**: 2-bit ternary codes, one fp16 scale per 128 columns of a row | `code * scale` | ternary models (Bonsai-2, PTQ1_0/TQ1_0 sources) |

**Q8 has two code layouts under the same chunk size.** Qwen3.5-4B's lm_head (tied to the
embedding) stores code (row r, column k) at byte `k*32 + r`. Qwen3.6-35B-A3B's Q8 tensors
Expand All @@ -97,11 +98,58 @@ apart. Decoding tile (0, 0) of each lm_head and comparing with a GGUF of the sam
gives correlation 0.9998 with the right layout and about 0.01 with the other. `npu/q4nx`
decodes the first layout.

`npu/q4nx.h` decodes all three, and repacks Q4_K into q4_1 (exact apart from rounding
`npu/q4nx.h` decodes all four, and repacks Q4_K into q4_1 (exact apart from rounding
`S * scale` and `M * min` to bf16), so code that reads q4_1 runs Q4_K weights unchanged. Q8 does
not fit q4_1. `tests/npu_q4nx_test.cpp` checks the decoders bit for bit against reference decoders
on real Qwen3.5-4B and Qwen3-0.6B tiles (committed in `tests/golden/q4nx`), and the repack against
its rounding bound.
not fit q4_1, and neither does t2 (per-128 fp16 scale against q4_1's per-32 bf16 one): a t2 tensor
is expanded on the target, never repacked. `tests/npu_q4nx_test.cpp` checks the decoders bit for bit
against reference decoders on real Qwen3.5-4B and Qwen3-0.6B tiles (committed in
`tests/golden/q4nx`), and the repack against its rounding bound; t2 has its own contract test
(`tests/npu_t2_layout_test.sh`) and oracle (`tests/q4nx_t2_test.py`).

#### The t2 chunk kind

A ternary model stores every weight as `code * d` with `code` in {-1, 0, +1} and one `d` per 128
columns of a row. t2 is that, in the same 32x256 tile grid as every other chunk, at **2.125
bits/weight** — the stream a 27B ternary model is meant to be read at, instead of the 4.5 b/w
`pb16i` image (int4 codes + one int16 magnitude per 32 K) that the exact path streams today.

```
t2 tile, 2176 bytes, 32 rows (N) x 256 columns (K) of one tensor
[0, 2048) 2-bit codes: byte r*64 + c/4, code c%4 at bits 2*(c%4)
value 0 = -1, 1 = 0, 2 = +1, 3 = reserved (no converter emits it)
[2048, 2176) IEEE fp16 scales: half at 2048 + r*4 + 2*g, g = c/128
w[r][c] = code * scale
```

Tile order is the container's everywhere: row-major over the `[N/32][K/256]` grid, so one
32-column block's whole K extent is contiguous. Geometry: `N % 32 == 0`, `K % 256 == 0`.

**The scale is fp16, not bf16, and that is load bearing.** Every source format already stores this
scale as fp16 — PTQ1_0's, TQ1_0's and TQ2_0's `d` are `ggml_half`, and `pb16i`'s `ms * 2^e_ref` is an
int16 with a per-column exponent — while bf16 has 8 significand bits against fp16's 11. Measured on
the 431 ternary Bonsai-2 images (416 layers + the 15 MTP head tensors, 25.66 G weights):
**174,982,781 of 200,499,200 scales (87.27 %) are not bf16-representable**, worst relative error
3.89e-3; fp16 is exact on all 200,499,200. fp16 and bf16 are both two bytes, so asking for bf16 buys
nothing and costs the bit-exact gate. A target whose arithmetic wants bf16 converts at load, in the
kernel, and owns that rounding — the chunk keeps the exact value.

A reserved code (3) decodes as **0**, on both paths — `npu/q4nx.cpp::dequant_tile` and `tools/q4nx_t2.py::unpack` — so a corrupt byte cannot become a weight no converter wrote, and it can never be a `2 * scale` value that no ternary encoder can produce. No converter emits one; `q4nx::t2_reserved()` counts them, and that is what a loader or a test refuses on. (An all-zero code byte is **code -1**, not code 0 — the value table is `code - 1`, the same convention Q2_0 uses.)

| what | measured |
|---|---|
| ternary codes in the 431 images | all `{-1, 0, +1}`, no reserved pattern |
| one scale per 128 K is enough (the four per-32 magnitudes agree) | 100 % of blocks |
| fp16 scale exact vs the pb16i floats | 200,499,200 / 200,499,200 |
| 27B size | pb16i 14.44 GB -> **t2 6.82 GB** (416 layers 6.46 GB, 15 head tensors 0.36 GB) |
| 2.125 b/w | `2176*8/8192` exactly |

The oracle is bit-exact, not approximate: `tools/q4nx_t2.py from_pb16i` refuses anything it cannot
represent exactly (a non-ternary code, magnitudes that differ inside a 128-K block, a scale that is
not fp16-exact), and `tests/q4nx_t2_test.py` re-decodes the result and compares against the pb16i
dequantisation of the same image, float for float, on all 431 images when they are on the machine.
Converters: `from_pb16i` (the engine's integer-exact image), `from_ptq1_0` and `from_tq1_0` (both
ternary with an fp16 scale, lossless). `from_tq2_0` is refused unless asked, because TQ2_0's code 3
means **+2** — it is not a ternary format, and clamping it to +1 changes weights.

### From a GGUF

Expand Down
68 changes: 67 additions & 1 deletion npu/q4nx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,72 @@ void put16(uint8_t* p, uint16_t v) {
// the q4_1 code byte and nibble of row r, column c
size_t q41_code_at(int r, int c) { return 1024 + size_t((r / 16) * 8 + c / kGroup) * 256 + 8 * (c % kGroup) + (r % 16) / 2; }

// IEEE binary16 -> float, exactly (every finite half is a float; subnormals included, because a
// scale of 1e-6 is a subnormal and decoding it as zero would be a silent weight of zero).
float half(uint16_t h) {
const uint32_t sign = uint32_t(h & 0x8000) << 16;
const uint32_t exp = (h >> 10) & 0x1F, man = h & 0x3FF;
uint32_t bits;
if (exp == 0) {
if (man == 0) {
bits = sign; // +-0
} else {
// subnormal: normalize it, 1.0 <= m < 2
int e = -1;
uint32_t m = man;
do {
m <<= 1;
e++;
} while ((m & 0x400) == 0);
bits = sign | uint32_t(127 - 15 - e) << 23 | (m & 0x3FF) << 13;
}
} else if (exp == 0x1F) {
bits = sign | 0x7F800000u | (man << 13); // inf / nan
} else {
bits = sign | ((exp - 15 + 127) << 23) | (man << 13);
}
float f;
std::memcpy(&f, &bits, 4);
return f;
}

// The t2 tile: 2048 B of 2-bit codes, row-major over the 32x256 tile (byte r*64 + c/4, code
// c%4 at bits 2*(c%4)), then 128 B of fp16 scales, one per (128-K block, row).
inline uint8_t t2_packed(const uint8_t* t, int r, int c) { return t[size_t(r) * 64 + size_t(c) / 4]; }

} // namespace

Chunk chunk_of(const Tensor& t) {
const int64_t last = t.shape.empty() ? 0 : t.shape.back();
if ((t.shape.size() == 2 || t.shape.size() == 3) &&
(last == int64_t(Chunk::Q4_1) || last == int64_t(Chunk::Q4K) || last == int64_t(Chunk::Q8)))
(last == int64_t(Chunk::Q4_1) || last == int64_t(Chunk::Q4K) || last == int64_t(Chunk::Q8) ||
last == int64_t(Chunk::T2)))
return Chunk(last);
throw std::runtime_error("not a Q4NX chunked tensor (last dimension " + std::to_string(last) + ")");
}

int t2_code(const uint8_t* t, int r, int c) {
const int code = (t2_packed(t, r, c) >> (2 * (c % 4))) & 3;
return code == 3 ? kReserved : code - 1; // 0 -> -1, 1 -> 0, 2 -> +1
}

float t2_scale(const uint8_t* t, int r, int c) {
const uint8_t* p = t + kT2CodeBytes + size_t(r) * 4 + 2 * size_t(c / kT2Group);
return half(uint16_t(p[0] | (p[1] << 8)));
}

size_t t2_reserved(const uint8_t* t) {
size_t n = 0;
const uint8_t* p = t;
for (int r = 0; r < kT2Rows; r++)
for (int b = 0; b < 64; b++) {
const uint8_t v = p[size_t(r) * 64 + b];
for (int s = 0; s < 4; s++)
if (((v >> (2 * s)) & 3) == 3) n++;
}
return n;
}

void dequant_tile(Chunk kind, const uint8_t* t, float* out, int ld) {
for (int r = 0; r < kRows; r++) {
for (int c = 0; c < kCols; c++) {
Expand All @@ -66,6 +122,13 @@ void dequant_tile(Chunk kind, const uint8_t* t, float* out, int ld) {
const uint8_t b = t[512 + c * 16 + r / 2];
const int code = (r % 2 == 0) ? (b & 15) : (b >> 4);
w = bf16(t + 4608 + 2 * r) * float(t[i]) * float(code) + bf16(t + 4672 + 2 * r) * float(t[256 + i]);
} else if (kind == Chunk::T2) {
// A reserved code (3) decodes as 0 -- a corrupt byte must not become a weight no
// converter wrote, and it must certainly not become +2 * scale, which is what the
// raw sentinel would multiply to. The converters refuse to emit one and
// t2_reserved() is what a loader checks; this is the decode-time half of that rule.
const int code = t2_code(t, r, c);
w = code == kReserved ? 0.0f : (float)code * t2_scale(t, r, c);
} else {
w = bf16(t + 2 * i) * float(int8_t(t[512 + c * kRows + r]));
}
Expand Down Expand Up @@ -107,6 +170,9 @@ std::vector<uint8_t> as_q4_1(const Tensor& t) {
const size_t n = size_t(t.bytes / uint64_t(kind));
if (kind == Chunk::Q4_1) return std::vector<uint8_t>(t.data, t.data + n * size_t(kind));
if (kind == Chunk::Q8) throw std::runtime_error("a Q8 tensor does not fit q4_1 (8-bit codes)");
if (kind == Chunk::T2)
throw std::runtime_error("a t2 tensor does not fit q4_1 (per-128 fp16 scale vs per-32 bf16); "
"expand it on the target instead");
std::vector<uint8_t> out(n * size_t(Chunk::Q4_1));
for (size_t i = 0; i < n; i++) q4k_to_q4_1(t.data + i * size_t(kind), out.data() + i * size_t(Chunk::Q4_1));
return out;
Expand Down
36 changes: 32 additions & 4 deletions npu/q4nx.h
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,22 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The three Q4NX chunk kinds, decoded. A Q4NX weight is a grid of 32-row x 256-column
// The Q4NX chunk kinds, decoded. A Q4NX weight is a grid of 32-row x 256-column
// tiles, each one chunk; a tensor's chunk kind is the last dimension of its shape
// ([tiles, 5120] or [tile rows, tile cols, chunk bytes]), and tiles are stored row-major
// over the grid. Index g*32 + r means column group g (32 columns) of row r.
//
// t2 2176 B 2-bit ternary codes, 4 per byte, row-major: byte r*64 + c/4, code c%4
// at bits 2*(c%4), value 0 -> -1, 1 -> 0, 2 -> +1, 3 reserved; then one
// IEEE fp16 scale per (128-K block, row) at 2048 + r*4 + 2*(c/128).
// w = code * (float)scale
// 2.125 bits/weight. NOT bf16: the source formats already store this
// scale as fp16 (PTQ1_0/TQ1_0/TQ2_0 d, and pb16i's int16 ms * 2^e_ref),
// and a bf16 re-encode is not exact -- measured on the 431 ternary
// Bonsai-2 images, 87.5 % of the scales are not bf16-representable
// (worst |rel| 3.9e-3) while 100 % are fp16-exact. Same 2 bytes, so the
// 2.125 b/w is unchanged. See docs/npu.md "The t2 chunk kind".
//
// q4_1 5120 B bf16 scale[g*32+r] @0, bf16 zero[g*32+r] @512, then 4-bit codes in 16
// regions of 256 B: region h*8+g (h = r/16), byte 8*j + (r%16)/2, even
// row in the low nibble. w = code * scale + zero
Expand Down Expand Up @@ -48,14 +59,30 @@ namespace onebit::npu::q4nx {

constexpr int kRows = 32, kCols = 256, kGroup = 32;

enum class Chunk : uint32_t { Q4_1 = 5120, Q4K = 4736, Q8 = 8704 };
// The t2 chunk: 2048 B of 2-bit codes + 128 B of fp16 scales per 32x256 tile.
constexpr int kT2Tile = 2176, kT2CodeBytes = 2048, kT2Rows = 32, kT2Cols = 256, kT2Group = 128;

enum class Chunk : uint32_t { Q4_1 = 5120, Q4K = 4736, Q8 = 8704, T2 = kT2Tile };

// The chunk kind of a quantized tensor; throws if its shape names none of the three.
// The chunk kind of a quantized tensor; throws if its shape names none of them.
Chunk chunk_of(const Tensor& t);

// One tile to f32: out[r * ld + c] for r < 32, c < 256.
void dequant_tile(Chunk kind, const uint8_t* tile, float* out, int ld);

// t2 only: the ternary code and the fp16 scale of element (r, c) of a tile, exposed because the
// converters and the layout test need the mapping without a float round trip. code_of() returns
// -1, 0 or +1, and kReserved (2) for the reserved bit pattern, which no converter may emit.
// kReserved is a SENTINEL, not a value: dequant_tile() decodes it as 0, never as 2 * scale.
constexpr int kReserved = 2;
int t2_code(const uint8_t* tile, int r, int c);
float t2_scale(const uint8_t* tile, int r, int c);

// t2 only: how many of the tile's 8192 codes carry the reserved pattern (3). Zero for a
// converter's output; the loader uses it to refuse a corrupt t2 tensor instead of decoding
// the reserved value as a weight.
size_t t2_reserved(const uint8_t* tile);

// A whole rows x cols tensor to f32 (rows % 32 == 0, cols % 256 == 0).
void dequant(const Tensor& t, int rows, int cols, float* out);

Expand All @@ -64,7 +91,8 @@ void dequant(const Tensor& t, int rows, int cols, float* out);
void q4k_to_q4_1(const uint8_t* q4k, uint8_t* q41);

// The tensor's tiles as q4_1: a copy for q4_1, converted for Q4_K. Throws for Q8, whose
// 8-bit codes do not fit q4_1.
// 8-bit codes do not fit q4_1, and for t2, whose per-128 fp16 scale does not fit q4_1's
// per-32 bf16 one (a t2 tensor is expanded on the target, not repacked through q4_1).
std::vector<uint8_t> as_q4_1(const Tensor& t);

} // namespace onebit::npu::q4nx
Loading
Loading