core/format, tools: GGUF Q8_0, Q4_K and Q6_K tensors import as their planes -- rad-convert writes them without a recipe

A GGUF tensor of block type Q8_0, Q4_K or Q6_K could only be dequantised, so rad-convert reached it
through a recipe rule and re-quantised what was already quantised. ckpt_resolve now states the
planes libquant's ggml quantiser writes for the same blocks and marks the weight imported, and
ckpt_plane_rows splits each row's blocks into them bit for bit. The split is
core/format/ggml_planes.h, the reader's copy of lq_ggml's unpack functions, since the core cannot
call libquant; a type there is one table row, its planes and its split. Pieces of one block type
joined along rows import, an expert's slices of a stacked tensor included; mixed types and column
joins keep a GGUF reason.

The weight is not trivial, so the loader refuses it with the hint to serve the container
rad-convert writes, and ckpt_rows_f32 still dequantises it for a recipe. A rule that declines such
a weight is an error in rad-convert, since keeping its planes would hide that the rule did not
apply (spec.md §4.4).

Tests: quant_ggml_test holds every type of the reader's table to the quantiser's encoding,
checkpoint_test decodes the planes of Q8_0, Q4_K (one-block rows and a row join) and Q6_K against
the block definition and holds an expert's gate|up, two slices of stacked Q4_K tensors, to the same
blocks stored on their own, and convert_test runs a declining rule over a Q8_0 tensor, with the
GGUF writer moved to tests/gguf_writer.h for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NunzeandClaude Opus 5.5 authored and StillDeadcode committed 2026-10-28 12:48:13 +01:00
1 parent 6f034d989f
commit 385318f81a
10 files changed
+602 -57

No files matched your search

+46
View File
@@ -1,5 +1,6 @@
/* checkpoint.cpp -- see checkpoint.h. */
#include "checkpoint.h"
#include "ggml_planes.h"
#include "rad_plugin.h"
#include <nlohmann/json.hpp>
@@ -2499,6 +2500,26 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
if (dt == RAD_DT_INVALID) {
out->why = std::string("'") + p0.name + "' is a GGUF " +
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
/* Q8_0, Q4_K and Q6_K become their planes when every piece is of that type and they join
* along rows, so each row of the weight is one source row of blocks; the loader still
* refuses them, since the blocks interleave what the planes hold apart. */
bool one_type = true;
for (const SrcTensor* pk : out->pieces) one_type = one_type && pk->ggml == p0.ggml;
RadEncoding enc;
if (!one_type) {
out->why = "its GGUF pieces are of different block types";
} else if (ggml_plane_encoding(p0.ggml, &enc)) {
if (out->pieces.size() > 1 && (d != 0 || out->rank < 2)) {
out->why = "its GGUF pieces are joined along a column, across their blocks";
} else {
out->imported = true;
out->ggml_blocks = true;
out->enc = enc;
out->why = std::string("it is a GGUF ") + gguf_dtype(p0.ggml)->name +
" tensor, which rad-convert imports as its planes -- serve the "
"container it writes";
}
}
} else if (!same) {
out->why = "its pieces are stored in different dtypes";
} else if (p0.pbits) {
@@ -3395,6 +3416,31 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
}
return RAD_OK;
}
if (w.ggml_blocks) {
/* GGUF blocks, split one row at a time into every plane's row: a call pays the whole row
* for the one plane it keeps, and rad-convert asks plane by plane. */
int64_t at[RAD_ENC_MAX_PLANES + 1] = { 0 };
for (int i = 0; i < w.enc.n_planes; ++i) {
int64_t qr = 0, qc = 0;
rad_enc_plane_dims(&w.enc.plane[i], 1, w.cols, &qr, &qc);
at[i + 1] = at[i] + rad_enc_row_bytes(w.enc.plane[i].dtype, qc);
}
std::vector<uint8_t> split((size_t)at[w.enc.n_planes]);
uint8_t* row[RAD_ENC_MAX_PLANES] = { nullptr };
for (int i = 0; i < w.enc.n_planes; ++i) row[i] = split.data() + at[i];
int64_t base = 0;
for (const SrcTensor* piece : w.pieces) {
const int64_t prows = piece->numel() / w.cols, rb = piece->bytes / prows;
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + prows); ++r) {
ggml_plane_row(piece->ggml, (const uint8_t*)piece->data + (r - base) * rb, w.cols,
row);
std::memcpy(o, row[k], (size_t)(at[k + 1] - at[k]));
o += at[k + 1] - at[k];
}
base += prows;
}
return RAD_OK;
}
if (k == 0) {
/* Codes: the pieces joined, bytes as stored. Sub-byte codes (MXFP4) join along rows of even
* width, so every run is byte-aligned. */
+3
View File
@@ -282,6 +282,9 @@ struct CkptWeight {
* from `pq_meta`. */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale, pq_meta;
/* GGUF Q8_0, Q4_K or Q6_K blocks (also `imported`): ckpt_plane_rows splits each row's blocks
* into the planes of `enc` (ggml_planes.h), and ckpt_rows_f32 dequantises them. */
bool ggml_blocks = false;
/* A weight-normalised tensor (RAD_MAP_WNORM): `pieces` is its direction v alone, and every
* element of v with first index i reads times wnorm_scale[i] = g_i / ||v_i||. Not trivial
* (the values change), so a recipe rule stores it. */
+191
View File
@@ -0,0 +1,191 @@
/* ggml_planes.h -- llama.cpp's Q8_0, Q4_K and Q6_K blocks as the affine planes libquant/lq_ggml.cpp
* writes them, for reading a GGUF without a recipe. The core cannot call libquant, so this is the
* reader's copy; quant_ggml_test holds the two to the same encoding, and checkpoint_test decodes
* the planes against the block definition.
*
* The planes are bit for bit what lq_ggml's unpack_<type> writes from the same blocks (its header
* lists them), so a container holds the same numbers whichever way a GGUF reached it. The blocks
* are read as raw bytes at their GGUF offsets, so no struct layout is assumed, and gguf_dtype gives
* their size.
*/
#pragma once
#include "rad_encoding.h"
#include "../text/gguf.h"
#include <cstdint>
#include <cstring>
namespace rad {
namespace ggml_planes {
constexpr int kQK8_0 = 32, kQK_K = 256;
/* Writes a plane row front to back, `bits` per element, lowest bits first (rad_encoding.h's bit
* stream). 32 bits go out at a time and the tail on flush(), so each byte is stored exactly once
* and never read back; this does not rely on the row arriving zeroed. */
class Bits {
public:
explicit Bits(uint8_t* row) : p_(row) {}
void put(uint32_t v, int bits) {
acc_ |= (uint64_t)(v & ((1u << bits) - 1u)) << n_;
n_ += bits;
if (n_ >= 32) {
p_[0] = (uint8_t)acc_;
p_[1] = (uint8_t)(acc_ >> 8);
p_[2] = (uint8_t)(acc_ >> 16);
p_[3] = (uint8_t)(acc_ >> 24);
p_ += 4;
acc_ >>= 32;
n_ -= 32;
}
}
void flush() {
for (; n_ > 0; n_ -= 8, acc_ >>= 8) *p_++ = (uint8_t)acc_;
n_ = 0;
}
private:
uint8_t* p_;
uint64_t acc_ = 0;
int n_ = 0;
};
/* Element i of a 16-bit plane row: an f16 super-scale's two bytes as the block holds them. */
inline void copy16(uint8_t* row, int64_t i, const uint8_t* half) {
row[2 * i] = half[0];
row[2 * i + 1] = half[1];
}
/* Two 4-bit codes per byte, element 2k low; q[] holds a block's codes in value order. */
inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) {
for (int k = 0; k < n / 2; ++k)
row[k] = (uint8_t)((q[2 * k] & 15) | ((q[2 * k + 1] & 15) << 4));
}
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. The
* 6-bit scale and min of sub-block j are get_scale_min_k4's. */
inline uint32_t k_low4(const uint8_t* qs, int v) {
const uint8_t q = qs[32 * (v / 64) + v % 32];
return (uint32_t)((v % 64) < 32 ? q & 15 : q >> 4);
}
inline void k4_scale_min(int j, const uint8_t* q, uint32_t* d, uint32_t* m) {
if (j < 4) {
*d = q[j] & 63u;
*m = q[j + 4] & 63u;
} else {
*d = (q[j + 4] & 0xFu) | ((uint32_t)(q[j - 4] >> 6) << 4);
*m = (uint32_t)(q[j + 4] >> 4) | ((uint32_t)(q[j] >> 6) << 4);
}
}
/* block_q8_0: d f16 @0, qs i8[32] @2. */
inline void split_q8_0(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
for (int64_t i = 0; i < nb; ++i) {
const uint8_t* b = blocks + bb * i;
std::memcpy(row[0] + kQK8_0 * i, b + 2, kQK8_0);
copy16(row[1], i, b);
}
}
/* block_q4_K: d f16 @0, dmin f16 @2, scales u8[12] @4, qs u8[128] @16. */
inline void split_q4_K(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
Bits s(row[1]), m(row[3]);
uint8_t q[kQK_K];
for (int64_t i = 0; i < nb; ++i) {
const uint8_t* b = blocks + bb * i;
for (int k = 0; k < kQK_K; ++k) q[k] = (uint8_t)k_low4(b + 16, k);
put_nibbles(row[0] + (kQK_K / 2) * i, q, kQK_K);
for (int j = 0; j < kQK_K / 32; ++j) {
uint32_t sc, mn;
k4_scale_min(j, b + 4, &sc, &mn);
s.put(sc, 6);
m.put(mn, 6);
}
copy16(row[2], i, b);
copy16(row[4], i, b + 2);
}
s.flush();
m.flush();
}
/* block_q6_K: ql u8[128] @0, qh u8[64] @128, scales i8[16] @192, d f16 @208. In each 128 values,
* quarter t of 32 takes its low four bits from ql[64n + l (+32 for odd t)] (the high nibble for
* t >= 2) and its top two from bits 2t of qh[32n + l]. */
inline void split_q6_K(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
Bits c(row[0]);
for (int64_t i = 0; i < nb; ++i) {
const uint8_t* b = blocks + bb * i;
const uint8_t *ql = b, *qh = b + 128;
for (int k = 0; k < kQK_K; ++k) {
const int n = k / 128, t = (k % 128) / 32, l = k % 32;
const uint8_t lo = ql[64 * n + l + 32 * (t & 1)];
const uint32_t q = (uint32_t)(t < 2 ? lo & 15 : lo >> 4) |
(uint32_t)((qh[32 * n + l] >> (2 * t)) & 3) << 4;
c.put(q - 32u, 6);
}
std::memcpy(row[1] + (kQK_K / 16) * i, b + 192, kQK_K / 16);
copy16(row[2], i, b + 208);
}
c.flush();
}
/* A plane as lq_ggml's encoding_of lists it: one row high, `block` values wide. */
struct Plane {
const char* role;
uint32_t dtype;
int64_t block;
};
/* A block type this header splits: ggml's type number, its planes in encoding order (the rest
* empty), and the split of a row's `nb` blocks of `bb` bytes into one row of each. */
struct Type {
uint32_t ggml;
Plane planes[RAD_ENC_MAX_PLANES];
void (*split)(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row);
};
inline constexpr Type kTypes[] = {
{ 8, { { "codes", RAD_I8, 1 }, { "scale", RAD_F16, 32 } }, split_q8_0 },
{ 12,
{ { "codes", RAD_U4, 1 }, { "scale", RAD_U6, 32 }, { "scale.1", RAD_F16, 256 },
{ "min", RAD_U6, 32 }, { "min.1", RAD_F16, 256 } },
split_q4_K },
{ 14, { { "codes", RAD_I6, 1 }, { "scale", RAD_I8, 16 }, { "scale.1", RAD_F16, 256 } },
split_q6_K },
};
inline const Type* type_of(uint32_t ggml_type) {
for (const Type& t : kTypes)
if (t.ggml == ggml_type) return &t;
return nullptr;
}
} /* namespace ggml_planes */
/* The encoding a GGUF block type is read as, plane for plane as lq_ggml's encoding_of lists it.
* False for a type this header does not split. */
inline bool ggml_plane_encoding(uint32_t ggml_type, RadEncoding* e) {
const ggml_planes::Type* t = ggml_planes::type_of(ggml_type);
if (!t) return false;
rad_enc_clear(e);
rad_enc_copy_str(e->scheme, "affine");
for (const ggml_planes::Plane& p : t->planes) {
if (!p.role) break;
rad_enc_add_plane(e, p.role, p.dtype, 1, p.block);
}
return true;
}
/* One row of `cols` values held as GGUF blocks, split into one row of every plane of
* ggml_plane_encoding's encoding: plane i's row goes to row[i], sized rad_enc_plane_dims and
* rad_enc_row_bytes give for a one-row weight. `cols` is a whole number of blocks, and the type one
* ggml_plane_encoding accepts. */
inline void ggml_plane_row(uint32_t ggml_type, const uint8_t* blocks, int64_t cols,
uint8_t* const* row) {
const GgufDtype& gd = *gguf_dtype(ggml_type);
ggml_planes::type_of(ggml_type)->split(blocks, cols / gd.blck, gd.block_bytes, row);
}
} /* namespace rad */
+1
View File
@@ -520,6 +520,7 @@ dequantisation where the architecture's kernels read another form, and NVFP4 alw
| `compressed-tensors` with an `nvfp4-pack-quantized` config group (`weights`: 4-bit float, group 16) | `fp4_e2m1*f32[1x16]` | the packed e2m1 codes beside an f32 scale per 16 of K, `weight_scale / weight_global_scale`: the global scale is a divisor, as compressed-tensors' dequantise and vLLM read it. Each piece keeps its own global, so a fused gate\|up reads both exactly. No kernel serves NVFP4, so every NVFP4 weight takes a recipe rule (`data/recipes/q38-27b-nvfp4-df2.recipe` makes it MXFP4) |
| `compressed-tensors` whose config groups are all `float-quantized` with 8-bit `float` weights | `fp8_e4m3*<scale>[1x*]` or `[RxC]` | nothing is imported: each `X.weight` reads stock as FP8 with `X.weight_scale` beside it, one scale a row (`[N, 1]` or `[N]`, the channel strategy) or a block plane; a per-tensor scale (`[1]`) is written once a row, so it is imported rather than byte for byte. The quantisation is still the tool's, so the family's quantised plugin serves it |
| `modelopt` (NVIDIA ModelOpt) with `quant_algo` `NVFP4`, `FP8`, or `MIXED_PRECISION` whose `quantized_layers` are each NVFP4 (group 16) or FP8 (e.g. ukisai's Swift 1.5 27B NVFP4) | NVFP4: `fp4_e2m1*f32[1x16]`; FP8: `fp8_e4m3*f32[1x*]` | NVFP4: `X.weight` (U8 `[N, K/2]`, the even k in the low nibble) beside an f32 scale per 16 of K, `float(X.weight_scale) * X.weight_scale_2`: ModelOpt's second level multiplies, where compressed-tensors' global scale divides. FP8: `X.weight` E4M3 with its one f32 `X.weight_scale`, written once a row. `X.input_scale` (a static activation scale) is not read: activations are quantised from their own values. Any other algorithm is refused by name. No kernel serves NVFP4, and none an FP8 scale per tensor, so both take recipe rules (`data/recipes/q38-27b-modelopt-nvfp4.recipe`) |
| GGUF `Q8_0`, `Q4_K` and `Q6_K` tensors (a GGUF file, not a `quantization_config`) | `i8*f16[1x32]`, `affine:codes=u4[1x1],scale=u6[1x32],scale.1=f16[1x256],min=u6[1x32],min.1=f16[1x256]` and `i6*i8[1x16]*f16[1x256]` | the blocks split into their planes, bit for bit; a rule re-quantises from the exact dequantisation. Not served as they stand: the loader refuses them with the hint to serve the container `rad-convert` writes |
The width is read per tensor, so a release mixing int4 experts with int8 projections imports both.
A mixed-precision release (NVFP4 MLPs beside FP8 or bf16 linears, the usual NVFP4 layout) reads
+7 -1
View File
@@ -659,6 +659,10 @@ same path runs. Trivial means served as stored:
`fp4_e2m1*e8m0[1x32]`, byte for byte;
- GGUF `F32`, `F16` and `BF16`.
A GGUF `Q8_0`, `Q4_K` or `Q6_K` tensor is not trivial, because its blocks interleave what the planes
of §4.1 hold apart. `rad-convert` imports it without a recipe as those planes, bit for bit, and the
loader refuses it with that hint. Other GGUF block types are dequantised for a recipe or refused.
**A torch.save file beside the safetensors is read as data** (`core/format/torch_zip.h`), for a
model part that ships only that way (Fish Audio drama-3's `codec.pth`): its tensors join the
namespace under `<stem>.`. The zip's stored entries are mapped, and its pickle is read by a machine
@@ -697,7 +701,9 @@ A rule names an algorithm (`rtn`, `gptq`, `cast`); its options name the grid (`c
`group` or `block`, `scale`, a second level `scale2`, `zero`, `rule`) and the transform
(`transform=fwht128`) (§4.5). First match wins, so a protected expert's `cast` rule sits above the
rule every other expert takes. A quantiser that declines a weight (`rtn` declines a rank-1 tensor)
leaves it to the checkpoint's encoding, so a broad pattern need not exclude every norm.
leaves it to the checkpoint's encoding, so a broad pattern need not exclude every norm. A GGUF block
tensor is the exception: a rule that declines it is an error, since keeping its planes would hide
that the rule did not apply.
`--recipe FILE` names a file and `--quant 'PATTERN=QUANTISER:k=v,...'` adds rules ahead of it.
`$NAME` in an option is read from the environment.
+211 -54
View File
@@ -7,6 +7,7 @@
* back.
*/
#include "rad_test.h"
#include "gguf_writer.h"
#include "format/checkpoint.h"
#include "format/encoding.h"
#include "rad_plugin.h"
@@ -2054,60 +2055,9 @@ TEST(a_concat_declared_in_pieces_joins_every_piece_in_order) {
* shape everything else uses; the legacy and Q4_K/Q6_K block types decode by their definitions. */
namespace {
struct GKv {
std::string key;
uint32_t type; /* 4 u32, 6 f32, 8 string, 9 array of strings */
double num = 0;
std::vector<std::string> strs;
};
struct GTensor { std::string name; uint32_t type; std::vector<uint64_t> ne; std::vector<uint8_t> bytes; };
void put_bytes(std::string* b, const void* p, size_t n) { b->append((const char*)p, n); }
void put_str(std::string* b, const std::string& s) {
const uint64_t n = s.size();
put_bytes(b, &n, 8);
b->append(s);
}
/* A GGUF v3 file of `kvs` and `ts`, every tensor at a 32-byte aligned offset. */
void write_gguf(const std::string& path, const std::vector<GKv>& kvs, const std::vector<GTensor>& ts) {
std::string b = "GGUF";
const uint32_t ver = 3;
const uint64_t nt = ts.size(), nk = kvs.size();
put_bytes(&b, &ver, 4);
put_bytes(&b, &nt, 8);
put_bytes(&b, &nk, 8);
for (const GKv& kv : kvs) {
put_str(&b, kv.key);
put_bytes(&b, &kv.type, 4);
if (kv.type == 4) { const uint32_t v = (uint32_t)kv.num; put_bytes(&b, &v, 4); }
else if (kv.type == 6) { const float v = (float)kv.num; put_bytes(&b, &v, 4); }
else if (kv.type == 8) put_str(&b, kv.strs.at(0));
else {
const uint32_t et = 8;
const uint64_t n = kv.strs.size();
put_bytes(&b, &et, 4);
put_bytes(&b, &n, 8);
for (const std::string& s : kv.strs) put_str(&b, s);
}
}
uint64_t off = 0;
for (const GTensor& t : ts) {
put_str(&b, t.name);
const uint32_t nd = (uint32_t)t.ne.size();
put_bytes(&b, &nd, 4);
for (uint64_t d : t.ne) put_bytes(&b, &d, 8);
put_bytes(&b, &t.type, 4);
put_bytes(&b, &off, 8);
off += (t.bytes.size() + 31) / 32 * 32;
}
while (b.size() % 32) b.push_back('\0');
for (const GTensor& t : ts) {
b.append((const char*)t.bytes.data(), t.bytes.size());
while (b.size() % 32) b.push_back('\0');
}
write_file(path, b);
}
using ggufw::GKv;
using ggufw::GTensor;
using ggufw::write_gguf;
uint16_t h16(float v) { return rad_f32_to_f16(v); }
@@ -2308,6 +2258,213 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) {
}
}
namespace {
/* `rows` x `cols` blocks of Q4_K (type 12) or Q6_K (type 14) with arbitrary quants and scales and
* finite f16 super-scales: random bits there would make NaNs, which equal nothing. */
GTensor k_blocks(const char* name, uint32_t type, int64_t rows, int64_t cols, uint32_t seed) {
GTensor t{ name, type, { (uint64_t)cols, (uint64_t)rows }, {} };
uint32_t x = seed;
auto fill = [&](int n) {
for (int i = 0; i < n; ++i) {
x = x * 1664525u + 1013904223u;
t.bytes.push_back((uint8_t)(x >> 24));
}
};
auto push16 = [&](float v) {
const uint16_t h = h16(v);
t.bytes.push_back((uint8_t)h);
t.bytes.push_back((uint8_t)(h >> 8));
};
for (int64_t b = 0; b < rows * cols / 256; ++b) {
const float d = 0.0625f * (float)(1 + (b + seed) % 7);
if (type == 12) {
push16(d);
push16(d / 2);
fill(12 + 128);
} else {
fill(128 + 64 + 16);
push16(d);
}
}
return t;
}
/* Every plane of `w` through ckpt_plane_rows, and the weight those planes decode to. */
void read_planes(const CkptWeight& w, std::vector<std::vector<uint8_t>>* planes,
std::vector<float>* values) {
std::string why;
planes->assign((size_t)w.enc.n_planes, {});
const void* data[RAD_ENC_MAX_PLANES] = { nullptr };
for (int k = 0; k < w.enc.n_planes; ++k) {
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
(*planes)[(size_t)k].resize((size_t)(pr * rad_enc_row_bytes(w.enc.plane[k].dtype, pc)));
CHECK_EQ(ckpt_plane_rows(w, k, 0, pr, (*planes)[(size_t)k].data(), &why), (int)RAD_OK);
data[k] = (*planes)[(size_t)k].data();
}
EncodedView v;
enc_view(w.enc, w.rows, w.cols, data, &v);
values->assign((size_t)(w.rows * w.cols), 0.0f);
CHECK_EQ(enc_decode_rows(v, 0, w.rows, values->data(), &why), (int)RAD_OK);
}
/* The planes of `w` decode to exactly what the block definition gives (ckpt_rows_f32). */
void check_planes_decode_by_definition(const CkptWeight& w) {
std::vector<std::vector<uint8_t>> planes;
std::vector<float> got, want((size_t)(w.rows * w.cols));
std::string why;
read_planes(w, &planes, &got);
REQUIRE_EQ(ckpt_rows_f32(w, 0, w.rows, want.data(), &why), (int)RAD_OK);
int bad = 0, nonzero = 0;
for (size_t i = 0; i < want.size(); ++i) {
bad += !(got[i] == want[i]);
nonzero += want[i] != 0.0f;
}
if (bad) std::fprintf(stderr, " %d of %zu value(s) differ\n", bad, want.size());
CHECK_EQ(bad, 0);
CHECK(nonzero > (int)want.size() / 2);
}
} /* namespace */
TEST(a_gguf_q8_0_q4_k_or_q6_k_tensor_is_imported_as_its_planes) {
const std::string path = fresh_dir() + "/m.gguf";
std::vector<float> w8;
const GTensor q8 = legacy_blocks("t.q8_0", 8, &w8);
const GTensor g = k_blocks("g", 12, 2, 512, 1), u = k_blocks("u", 12, 3, 512, 2);
const GTensor s = k_blocks("s", 12, 2, 256, 3), k6 = k_blocks("k6", 14, 2, 256, 4);
const GTensor q5{ "t.q5_k", 13, { 256, 1 }, std::vector<uint8_t>(176, 0) };
write_gguf(path, llama_kvs(15), { q8, g, u, s, k6, q5 });
Checkpoint ck;
REQUIRE_EQ(ck.open(path), RAD_OK);
Program prog;
prog.name_map.push_back(map("t.q8_0", RAD_MAP_COPY, { "t.q8_0" }));
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "g", "u" }));
prog.name_map.push_back(map("s", RAD_MAP_COPY, { "s" }));
prog.name_map.push_back(map("k6", RAD_MAP_COPY, { "k6" }));
prog.name_map.push_back(map("mix", RAD_MAP_CONCAT, { "s", "k6" }));
prog.name_map.push_back(map("across", RAD_MAP_CONCAT, { "g", "s" }, {}, 1));
prog.name_map.push_back(map("t.q5_k", RAD_MAP_COPY, { "t.q5_k" }));
std::string why;
/* Q8_0: the codes plane is each block's quants and the scale plane its d, byte for byte. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "t.q8_0", false, &w, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
CHECK(!w.trivial);
CHECK(has(w.why, "GGUF"));
REQUIRE(rad_enc_valid(&w.enc));
REQUIRE_EQ(w.enc.n_planes, 2);
std::vector<std::vector<uint8_t>> planes;
std::vector<float> f;
read_planes(w, &planes, &f);
REQUIRE_EQ(planes[0].size(), (size_t)(8 * 32));
REQUIRE_EQ(planes[1].size(), (size_t)(8 * 2));
int bad = 0;
for (int b = 0; b < 8; ++b) {
bad += std::memcmp(planes[0].data() + 32 * b, q8.bytes.data() + 34 * b + 2, 32) != 0;
bad += std::memcmp(planes[1].data() + 2 * b, q8.bytes.data() + 34 * b, 2) != 0;
}
CHECK_EQ(bad, 0);
int differ = 0;
for (size_t i = 0; i < w8.size(); ++i) differ += f[i] != w8[i];
CHECK_EQ(differ, 0);
}
/* Q4_K, gate and up joined along rows: the planes decode to the block definition, and a
* range that starts in the first piece and ends in the second is the same bytes. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
CHECK(!w.trivial);
CHECK_EQ(w.rows, (int64_t)5);
CHECK_EQ(w.cols, (int64_t)512);
REQUIRE(rad_enc_valid(&w.enc));
REQUIRE_EQ(w.enc.n_planes, 5);
check_planes_decode_by_definition(w);
std::vector<std::vector<uint8_t>> planes;
std::vector<float> f;
read_planes(w, &planes, &f);
for (int k = 0; k < w.enc.n_planes; ++k) {
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
const int64_t rb = rad_enc_row_bytes(w.enc.plane[k].dtype, pc);
std::vector<uint8_t> part((size_t)(3 * rb));
REQUIRE_EQ(ckpt_plane_rows(w, k, 1, 3, part.data(), &why), RAD_OK);
CHECK_EQ(std::memcmp(part.data(), planes[(size_t)k].data() + rb, part.size()), 0);
}
}
/* A row of one block ends its 6-bit planes mid-word. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "s", false, &w, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
check_planes_decode_by_definition(w);
}
/* Q6_K. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "k6", false, &w, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
CHECK(!w.trivial);
REQUIRE(rad_enc_valid(&w.enc));
REQUIRE_EQ(w.enc.n_planes, 3);
check_planes_decode_by_definition(w);
}
/* What it does not import keeps the GGUF reason. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "mix", false, &w, &why), RAD_OK);
CHECK(!w.imported && !w.ggml_blocks && !w.trivial);
CHECK(has(w.why, "different block types"));
REQUIRE_EQ(ckpt_resolve(ck, prog, "across", false, &w, &why), RAD_OK);
CHECK(!w.imported && !w.ggml_blocks && !w.trivial);
CHECK(has(w.why, "joined along a column"));
REQUIRE_EQ(ckpt_resolve(ck, prog, "t.q5_k", false, &w, &why), RAD_OK);
CHECK(!w.imported && !w.ggml_blocks && !w.trivial);
CHECK(has(w.why, "GGUF"));
}
}
/* llama.cpp stacks an MoE's experts in one rank-3 tensor of blocks, and an expert's gate|up is two
* dim-0 slices joined along rows: their planes are those of the same blocks stored on their own. */
TEST(a_slice_of_a_stacked_gguf_block_tensor_is_imported_as_its_planes) {
const std::string path = fresh_dir() + "/m.gguf";
const int64_t E = 4, N = 3, K = 512;
GTensor gate = k_blocks("gate_exps", 12, E * N, K, 5);
GTensor up = k_blocks("up_exps", 12, E * N, K, 6);
gate.ne = up.ne = { (uint64_t)K, (uint64_t)N, (uint64_t)E };
const size_t eb = gate.bytes.size() / E;
GTensor own{ "gu2", 12, { (uint64_t)K, (uint64_t)(2 * N) }, {} };
own.bytes.assign(gate.bytes.begin() + 2 * eb, gate.bytes.begin() + 3 * eb);
own.bytes.insert(own.bytes.end(), up.bytes.begin() + 2 * eb, up.bytes.begin() + 3 * eb);
write_gguf(path, llama_kvs(15), { gate, up, own });
Checkpoint ck;
REQUIRE_EQ(ck.open(path), RAD_OK);
Program prog;
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "gate_exps", "up_exps" }, { 2, 2 }));
prog.name_map.push_back(map("gu2", RAD_MAP_COPY, { "gu2" }));
std::string why;
CkptWeight w, o;
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu2", false, &o, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
CHECK_EQ(w.rows, 2 * N);
CHECK_EQ(w.cols, K);
REQUIRE(rad_enc_equal(&w.enc, &o.enc));
std::vector<std::vector<uint8_t>> got, want;
std::vector<float> fg, fo;
read_planes(w, &got, &fg);
read_planes(o, &want, &fo);
for (int k = 0; k < w.enc.n_planes; ++k) CHECK(got[(size_t)k] == want[(size_t)k]);
}
TEST(hyv3_gguf_metadata_normalizes_architecture_and_config_fields) {
const std::string path = fresh_dir() + "/hyv3.gguf";
const std::vector<GKv> kvs = {
+44
View File
@@ -6,6 +6,7 @@
* checkpoint holds them, so one conversion writes a quantised and a copied weight of every kind.
*/
#include "rad_test.h"
#include "gguf_writer.h"
#include "tiny_model.h"
#include "format/encoding.h"
@@ -756,6 +757,49 @@ TEST(a_recipe_or_flag_that_cannot_be_honoured_is_refused_before_writing) {
}
}
/* A rule that declines a GGUF block tensor stops the run rather than keep the tensor's planes: the
* tiny LLaMA as a GGUF with its first attn_norm in Q8_0, under an `rtn` rule, which declines a
* rank-1 tensor. */
TEST(a_rule_that_declines_a_gguf_block_tensor_is_an_error) {
World& w = world();
REQUIRE(w.ok);
tiny::TempDir d("convert_gguf");
const tiny::Llama s;
const std::vector<ggufw::GKv> kvs = {
{ "general.architecture", 8, 0, { "llama" } },
{ "llama.block_count", 4, (double)s.layers, {} },
{ "llama.embedding_length", 4, (double)s.hidden, {} },
{ "llama.attention.head_count", 4, (double)s.heads, {} },
{ "llama.attention.head_count_kv", 4, (double)s.kv_heads, {} },
{ "llama.attention.key_length", 4, (double)s.head_dim, {} },
{ "llama.feed_forward_length", 4, (double)s.ffn, {} },
{ "llama.context_length", 4, (double)s.ctx, {} },
{ "llama.vocab_size", 4, (double)s.vocab, {} },
};
std::vector<ggufw::GTensor> ts;
for (const auto& [name, t] : w.src) {
ggufw::GTensor g{ name, t.dtype == "F32" ? 0u : 30u, {}, t.bytes };
g.ne.assign(t.shape.rbegin(), t.shape.rend());
if (name == "model.layers.0.input_layernorm.weight") {
g.type = 8;
g.bytes.clear();
for (uint64_t b = 0; b < g.ne[0] / 32; ++b) {
g.bytes.insert(g.bytes.end(), { 0x00, 0x3C }); /* d = 1 in f16 */
g.bytes.insert(g.bytes.end(), 32, 1);
}
}
ts.push_back(std::move(g));
}
REQUIRE(ggufw::write_gguf(d / "llama.gguf", kvs, ts));
std::string log;
CHECK(convert(d / "llama.gguf",
{ "-o", d / "g.rad", "--recipe", w.recipe, "--quant",
"blk.0.attn_norm.weight=rtn:codes=i8,group=32,scale=bf16" },
&log) != 0);
CHECK(has(log, "(rtn) refuses it"));
CHECK(!exists(d / "g.rad"));
}
/* ================================================================== an int4 release */
namespace {
+76
View File
@@ -0,0 +1,76 @@
/* gguf_writer.h -- GGUF v3 files written by tests: header keys and tensors, the tensors' bytes as
* the caller built them. */
#pragma once
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
namespace ggufw {
struct GKv {
std::string key;
uint32_t type; /* 4 u32, 6 f32, 8 string, 9 array of strings */
double num = 0;
std::vector<std::string> strs;
};
struct GTensor {
std::string name;
uint32_t type;
std::vector<uint64_t> ne; /* fastest dimension first, as GGUF stores it */
std::vector<uint8_t> bytes;
};
inline void put_bytes(std::string* b, const void* p, size_t n) { b->append((const char*)p, n); }
inline void put_str(std::string* b, const std::string& s) {
const uint64_t n = s.size();
put_bytes(b, &n, 8);
b->append(s);
}
/* A GGUF v3 file of `kvs` and `ts`, every tensor at a 32-byte aligned offset. */
inline bool write_gguf(const std::string& path, const std::vector<GKv>& kvs,
const std::vector<GTensor>& ts) {
std::string b = "GGUF";
const uint32_t ver = 3;
const uint64_t nt = ts.size(), nk = kvs.size();
put_bytes(&b, &ver, 4);
put_bytes(&b, &nt, 8);
put_bytes(&b, &nk, 8);
for (const GKv& kv : kvs) {
put_str(&b, kv.key);
put_bytes(&b, &kv.type, 4);
if (kv.type == 4) { const uint32_t v = (uint32_t)kv.num; put_bytes(&b, &v, 4); }
else if (kv.type == 6) { const float v = (float)kv.num; put_bytes(&b, &v, 4); }
else if (kv.type == 8) put_str(&b, kv.strs.at(0));
else {
const uint32_t et = 8;
const uint64_t n = kv.strs.size();
put_bytes(&b, &et, 4);
put_bytes(&b, &n, 8);
for (const std::string& s : kv.strs) put_str(&b, s);
}
}
uint64_t off = 0;
for (const GTensor& t : ts) {
put_str(&b, t.name);
const uint32_t nd = (uint32_t)t.ne.size();
put_bytes(&b, &nd, 4);
for (uint64_t d : t.ne) put_bytes(&b, &d, 8);
put_bytes(&b, &t.type, 4);
put_bytes(&b, &off, 8);
off += (t.bytes.size() + 31) / 32 * 32;
}
while (b.size() % 32) b.push_back('\0');
for (const GTensor& t : ts) {
b.append((const char*)t.bytes.data(), t.bytes.size());
while (b.size() % 32) b.push_back('\0');
}
FILE* f = std::fopen(path.c_str(), "wb");
if (!f) return false;
const bool ok = std::fwrite(b.data(), 1, b.size(), f) == b.size();
return std::fclose(f) == 0 && ok;
}
} /* namespace ggufw */
+19
View File
@@ -10,6 +10,7 @@
* The error bounds carry margin and catch a wrong plane layout, which decodes to noise.
*/
#include "quant_fixture.h"
#include "format/ggml_planes.h"
#include <cstdint>
@@ -134,6 +135,24 @@ TEST(ggml_writes_each_type_as_its_affine_planes) {
}
}
/* The core cannot call libquant, so a GGUF is read through its own copy of the encodings
* (core/format/ggml_planes.h); this holds every type of the copy to the quantiser's. */
TEST(the_reader_names_the_planes_the_quantiser_writes) {
NEED_LIBQUANT();
const RadQuantizerInfo* q = quantizer("ggml");
REQUIRE(q != nullptr);
for (const ggml_planes::Type& t : ggml_planes::kTypes) {
Opts o;
o.s("type", gguf_dtype(t.ggml)->name);
const RadQuantWeight qw = weight_of("w", 4, 512, nullptr);
RadEncoding written, read;
REQUIRE_EQ(q->encoding(o.data(), o.n(), &qw, &written), RAD_OK);
REQUIRE(ggml_plane_encoding(t.ggml, &read));
CHECK_EQ(enc_name(read), enc_name(written));
CHECK(rad_enc_equal(&read, &written));
}
}
TEST(every_type_decodes_within_its_bound) {
NEED_LIBQUANT();
const int64_t C = 1024;
+4 -2
View File
@@ -589,8 +589,10 @@ int main(int argc, char** argv) {
const RadQuantWeight qw = quant_weight(L, nullptr);
const int st = L.rule->q->encoding(L.rule->params.data(), (int)L.rule->params.size(),
&qw, &L.enc);
if (st == RAD_E_UNSUPPORTED && (L.src.trivial || L.src.imported)) {
/* declined (e.g. a norm under a matrix pattern): keep as is */
if (st == RAD_E_UNSUPPORTED &&
(L.src.trivial || (L.src.imported && !L.src.ggml_blocks))) {
/* declined (e.g. a norm under a matrix pattern): keep as is. Not a GGUF block
* tensor: keeping its planes would hide that the rule did not apply. */
L.rule = nullptr;
L.enc = L.src.enc;
} else if (st != RAD_OK) {