radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# libquant -- the built-in quantisers (spec §4.5). Host C++ only.
#
# It links rad_abi AND NOTHING ELSE, like every plugin: abi/rad_quant.h is the whole contract, and a
# quantiser that reached into core/ would stop being substitutable -- which is the property that
# lets a user ship a quantiser of their own beside it.
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S libquant -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(libquant LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
file(GLOB LQ_SRC CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
rad_add_plugin(libquant quantizers SOURCES ${LQ_SRC} INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
# -ffp-contract=off because a quantiser's output is a stored file: the same weights converted by two
# builds have to give the same bytes, and an FMA the compiler chose in one and not the other moves a
# value on a rounding boundary into the next code.
target_compile_options(libquant PRIVATE -ffp-contract=off)
# OpenMP over rows: GPTQ over a 512-expert layer is N*K^2/2 flops an expert, and round-to-nearest
# over a 51 GB table is a long single-threaded loop. Rows are independent in both, so the result
# does not depend on the thread count. Optional: without it everything is correct and serial.
find_package(OpenMP QUIET)
if(OpenMP_CXX_FOUND)
target_link_libraries(libquant PRIVATE OpenMP::OpenMP_CXX)
else()
message(STATUS "libquant: no OpenMP -- quantisers will run single-threaded")
endif()
+296
View File
@@ -0,0 +1,296 @@
/* lq_autoround.cpp -- AutoRound: rounding by signed gradient descent (Cheng et al., 2023).
*
* WHAT IT DOES. Rounding to nearest decides each value on its own; the output error is a property
* of the whole row against the input it meets. AutoRound learns, for every value, an offset V in
* [-0.5, 0.5] added before the rounding -- q = round(w / s + V) -- and for every scale block a
* factor on its range (one for a symmetric block, one for each end of an asymmetric one, in
* [0.5, 1]), and descends on the output error with the SIGN of each gradient, through the rounding
* by the straight-through estimator: d round(x) / dx = 1. The step is `lr` (by default 1/iters)
* decaying linearly to zero, and every row keeps the parameters of its lowest error seen, so
* the result is never worse than the start -- which is rounding to nearest.
*
* THE ERROR IS THE HESSIAN'S QUADRATIC FORM (lq_hess.h) rather than the block output over
* calibration samples the paper uses: it is the same function of the weight for one linear layer,
* and it decomposes over rows, so every row descends on its own -- no batch, no sample noise, and
* a row block per call. What it costs is N K^2 multiply-adds a step, which at the default 200 steps
* is the whole of a conversion's time; `iters` trades it.
*
* THE GRID is integer codes, symmetric or with a zero, with blocks of one row: the descent is over
* a rounding, so a codebook or a float code has none to learn, and a second level or a scale block
* that spans rows ties rows together.
*/
#include "lq_autoround.h"
#include "lq_hess.h"
#include "lq_quant.h"
#include "lq_common.h"
#include "rad_plugin.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace lq {
std::string autoround_refusal(const Grid& g) {
if (!g.table.empty()) return "a codebook has no rounding to learn";
if (g.is_float) return "a float code has no rounding to learn";
if (g.wide) return "16- and 32-bit codes round to within a part in 30000 already";
if (g.lv2) return "a second scale level ties the blocks of a row together";
if (g.br != 1) return "a scale block spanning rows ties those rows together; use group= or "
"block=1xC";
if (g.rule == Grid::MX || g.rule == Grid::FIXED) return "rule=mx and rule=fixed have no "
"range to learn";
return std::string();
}
namespace {
inline float sgn(float x) { return x > 0.0f ? 1.0f : (x < 0.0f ? -1.0f : 0.0f); }
/* One row's state through a step: its blocks' ranges and the scale, zero and codes they give. */
struct RowState {
const Grid* g = nullptr;
int64_t K = 0, nc = 0, bc = 0;
std::vector<float> s0, lo0, hi0; /* the absmax ends a block, from the weight */
void ends(const float* w) {
lo0.assign((size_t)nc, 0.0f);
hi0.assign((size_t)nc, 0.0f);
s0.assign((size_t)nc, 0.0f);
for (int64_t j = 0; j < nc; ++j) {
const int64_t c0 = j * bc, c1 = std::min(c0 + bc, K);
float lo = 0.0f, hi = 0.0f;
for (int64_t c = c0; c < c1; ++c) { lo = std::min(lo, w[c]); hi = std::max(hi, w[c]); }
lo0[(size_t)j] = lo;
hi0[(size_t)j] = hi;
s0[(size_t)j] = std::max(-lo, hi) / (float)g->qmax;
}
}
/* block j's scale and zero for range factors (a, b): a on the high end, b on the low */
BlockScale block(int64_t j, float a, float b) const {
if (g->asym) {
const float hi = hi0[(size_t)j] * a, lo = lo0[(size_t)j] * b;
return grid_finish(*g, (hi - lo) / (float)g->qmax, lo);
}
return grid_finish(*g, (double)(s0[(size_t)j] * a), 0.0f);
}
};
/* The code of `x` with offset `v` against block `b`, and whether the clamp took it. */
inline int code_v(const Grid& g, const BlockScale& b, float x, float v, bool* clamped) {
const int r = round_away(x * b.inv + v) + (g.asym ? b.zero : 0);
*clamped = r < g.qmin || r > g.qmax;
return clampi(r, g.qmin, g.qmax);
}
} /* namespace */
void autoround_rows(const Grid& g, const float* w, int64_t N, int64_t K, const float* H,
const float* diag, int iters, double lr, const Planes& planes) {
const int64_t bc = g.bc > 0 ? g.bc : K, nc = (K + bc - 1) / bc;
const size_t NK = (size_t)(N * K), NB = (size_t)(N * nc);
std::vector<float> V(NK, 0.0f), bestV(NK, 0.0f), D(NK), G(NK);
std::vector<float> A(NB, 1.0f), B(NB, 1.0f), bestA(NB, 1.0f), bestB(NB, 1.0f);
std::vector<double> loss((size_t)N), best((size_t)N, -1.0);
std::vector<RowState> rs((size_t)N);
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < N; ++r) {
rs[(size_t)r].g = &g;
rs[(size_t)r].K = K;
rs[(size_t)r].nc = nc;
rs[(size_t)r].bc = bc;
rs[(size_t)r].ends(w + r * K);
}
/* the residual D = w_hat - w of the current parameters, every row */
auto forward = [&](const std::vector<float>& v, const std::vector<float>& a,
const std::vector<float>& b) {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < N; ++r)
for (int64_t j = 0; j < nc; ++j) {
const BlockScale bs = rs[(size_t)r].block(j, a[(size_t)(r * nc + j)],
b[(size_t)(r * nc + j)]);
const int64_t c1 = std::min((j + 1) * bc, K);
for (int64_t c = j * bc; c < c1; ++c) {
const size_t i = (size_t)(r * K + c);
bool cl = false;
const int q = code_v(g, bs, w[i], v[i], &cl);
D[i] = (float)(q - (g.asym ? bs.zero : 0)) * bs.s - w[i];
}
}
};
auto errors = [&]() {
if (H) {
mat_hess(D.data(), N, K, H, G.data());
} else {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < N; ++r)
for (int64_t c = 0; c < K; ++c)
G[(size_t)(r * K + c)] = D[(size_t)(r * K + c)] * (diag ? diag[c] : 1.0f);
}
row_dots(D.data(), G.data(), N, K, loss.data());
};
auto keep = [&]() {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < N; ++r) {
if (best[(size_t)r] >= 0.0 && !(loss[(size_t)r] < best[(size_t)r])) continue;
best[(size_t)r] = loss[(size_t)r];
std::memcpy(&bestV[(size_t)(r * K)], &V[(size_t)(r * K)], (size_t)K * sizeof(float));
std::memcpy(&bestA[(size_t)(r * nc)], &A[(size_t)(r * nc)], (size_t)nc * sizeof(float));
std::memcpy(&bestB[(size_t)(r * nc)], &B[(size_t)(r * nc)], (size_t)nc * sizeof(float));
}
};
for (int t = 0; t < iters; ++t) {
forward(V, A, B);
errors();
keep();
const float step = (float)(lr * (1.0 - (double)t / iters));
/* THE GRADIENTS, by the straight-through rounding: dL/dw_hat = 2 G, and w_hat = s (q - z)
* with q = round(w/s + V) + z clamped. Unclamped, dw_hat/dV = s and dw_hat/ds = (q - z) -
* w/s; clamped, the first is 0 and the second (q - z). The range factors reach the loss
* through s alone (the zero is held where the rounding put it). */
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < N; ++r)
for (int64_t j = 0; j < nc; ++j) {
const size_t k = (size_t)(r * nc + j);
const RowState& st = rs[(size_t)r];
const BlockScale bs = st.block(j, A[k], B[k]);
double gs = 0.0;
const int64_t c1 = std::min((j + 1) * bc, K);
for (int64_t c = j * bc; c < c1; ++c) {
const size_t i = (size_t)(r * K + c);
bool cl = false;
const int q = code_v(g, bs, w[i], V[i], &cl);
const float gw = 2.0f * G[i];
const float qz = (float)(q - (g.asym ? bs.zero : 0));
if (!cl) {
V[i] = std::min(0.5f, std::max(-0.5f, V[i] - step * sgn(gw * bs.s)));
gs += (double)gw * (qz - w[i] * bs.inv);
} else {
gs += (double)gw * qz;
}
}
if (g.asym) {
const float da = (float)(gs * st.hi0[(size_t)j] / g.qmax);
const float db = (float)(-gs * st.lo0[(size_t)j] / g.qmax);
A[k] = std::min(1.0f, std::max(0.5f, A[k] - step * sgn(da)));
B[k] = std::min(1.0f, std::max(0.5f, B[k] - step * sgn(db)));
} else {
const float da = (float)(gs * st.s0[(size_t)j]);
A[k] = std::min(1.0f, std::max(0.5f, A[k] - step * sgn(da)));
}
}
}
forward(V, A, B);
errors();
keep();
/* ---- the best parameters, written: each block's scale and zero, then the codes */
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < N; ++r) {
uint8_t* cr = planes.codes + r * planes.codes_row;
uint8_t* sr = planes.scale + r * planes.scale_row;
uint8_t* zr = planes.zero ? planes.zero + r * planes.zero_row : nullptr;
for (int64_t j = 0; j < nc; ++j) {
const size_t k = (size_t)(r * nc + j);
const BlockScale bs = rs[(size_t)r].block(j, bestA[k], bestB[k]);
grid_store_scale(g, bs, sr, zr, j);
const int64_t c1 = std::min((j + 1) * bc, K);
for (int64_t c = j * bc; c < c1; ++c) {
bool cl = false;
const size_t i = (size_t)(r * K + c);
grid_store_code(g, cr, c, code_v(g, bs, w[i], bestV[i], &cl));
}
}
}
}
namespace {
const RadQuantOption kAutoRoundOptions[] = {
LQ_GRID_OPTIONS,
LQ_CALIB_OPTION("the imatrix's diagonal stands in, and with neither the weight is rounded to "
"nearest"),
{ "iters", RAD_P_INT, "200", "descent steps; each costs N K^2 multiply-adds" },
{ "lr", RAD_P_F64, "0", "the step, decaying linearly to zero; 0 is 1 / iters" },
};
int ar_grid(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g) {
const int st = grid_of(o, n_o, w, g);
if (st != RAD_OK) return st;
const std::string no = autoround_refusal(*g);
if (!no.empty()) return refuse(w, ("autoround: " + no).c_str());
if (rad_param_geti(o, n_o, "iters", 200) < 0) return refuse(w, "iters= is >= 0");
return RAD_OK;
}
int ar_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) {
if (declines(w)) return RAD_E_UNSUPPORTED;
Grid g;
const int st = ar_grid(o, n_o, w, &g);
if (st != RAD_OK) return st;
*out = grid_encoding(g);
return RAD_OK;
}
/* Rows descend on their own, so a call is any number of them; 512 keeps the state a few hundred
* megabytes at the widest K while every call still fills the threads. */
int64_t ar_row_block(const RadParam*, int, const RadQuantWeight*) { return 512; }
int ar_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
int64_t rows, void* const* planes) {
Grid g;
const int st = ar_grid(o, n_o, w, &g);
if (st != RAD_OK) return st;
(void)row0;
const int64_t K = w->cols;
grid_transform_rows(g, src, rows, K);
const char* dir = rad_param_gets(o, n_o, "calib", nullptr);
const int iters = (int)rad_param_geti(o, n_o, "iters", 200);
double lr = rad_param_getf(o, n_o, "lr", 0.0);
if (!(lr > 0.0)) lr = iters > 0 ? 1.0 / iters : 0.0;
const Gram Hg = calib_gram(dir, w->name, K, g.fwht, "autoround");
const float* H = Hg ? Hg->data() : nullptr;
const float* diag = (!H && !g.fwht) ? w->importance : nullptr;
const Planes p = grid_planes(g, K, planes);
if (!H && !diag) {
/* with nothing to weigh the error by, the best rounding of each value is the nearest */
return grid_rtn(g, src, row0, rows, K, p, nullptr);
}
if (!H)
std::fprintf(stderr, "libquant: autoround: '%s' has no Hessian; the imatrix's diagonal "
"stands in for it\n", w->name);
autoround_rows(g, src, rows, K, H, diag, iters, lr, p);
return RAD_OK;
}
} /* namespace */
const RadQuantizerInfo& autoround_info() {
static const RadQuantizerInfo q = {
"autoround",
"rounding by signed gradient descent: an offset a value and a range factor a block, "
"learned against the layer's input Hessian through the straight-through rounding, the "
"best of every row kept",
kAutoRoundOptions, (int)(sizeof kAutoRoundOptions / sizeof kAutoRoundOptions[0]),
ar_encoding, ar_row_block, ar_quantize, nullptr,
};
return q;
}
} /* namespace lq */
+19
View File
@@ -0,0 +1,19 @@
/* lq_autoround.h -- AutoRound's rounding descent, as a routine ParoQuant's second stage reuses. */
#pragma once
#include "lq_grid.h"
#include <string>
namespace lq {
/* Can AutoRound run on this grid? Integer codes, symmetric or with a zero, one scale level, blocks
* of one row. Empty when it can, the reason when not. */
std::string autoround_refusal(const Grid& g);
/* Rows [0, N) of `w` [N, K] -- already in the grid's domain, transformed if it has a transform --
* descended on for `iters` steps against H (K x K) or, when H is null, the diagonal `diag` (K), at
* learning rate `lr`; the result's scales into `planes` (the grid's) and its codes too. */
void autoround_rows(const Grid& g, const float* w, int64_t N, int64_t K, const float* H,
const float* diag, int iters, double lr, const Planes& planes);
} /* namespace lq */
+300
View File
@@ -0,0 +1,300 @@
/* lq_awq.cpp -- AWQ: activation-aware weight quantisation (Lin et al., 2023), on any grid.
*
* WHAT IT DOES. A few input channels carry most of a layer's activation energy, and the error a
* weight column contributes to the output scales with its channel's activation. AWQ scales each
* column UP by s_j before quantising -- so the channels that matter use more of the grid -- and the
* reader multiplies the column back down. The scales are s_j = a_j^alpha over the channels'
* activation magnitudes a_j, normalised so their geometric middle is one, and alpha is chosen from
* a grid of `alpha_steps` values in [0, 1) by the output error it gives; alpha = 0 is plain
* rounding, so the search can only improve on it. A per-block clip search follows: each scale
* block's range is pulled in by up to half, in twentieths, and the fraction of least output error
* kept -- which is AWQ's auto_clip, the clamped weight quantised as it stands.
*
* THE OUTPUT ERROR IS THE HESSIAN'S QUADRATIC FORM (lq_hess.h), over a sample of `sample_rows` rows
* for the alpha search and over each block's own columns -- H restricted to them -- for the clip,
* which is the error AWQ measures on its calibration activations, without needing them. a_j is
* sqrt(H_jj), the channel's root mean square. With no Hessian for a weight but an imatrix, the
* imatrix is the diagonal: a_j is sqrt of its importance and the error is diagonal-weighted; with
* neither, alpha is 0 and only the plain grid remains -- each said on stderr.
*
* THE SCALES ARE STORED, NOT FOLDED. AWQ's reference implementation folds 1/s into the layer
* before (a norm or the previous projection), which needs the model's graph; here they are the
* encoding's last scale level, a [* x 1] plane of one value a column, `colscale` wide, and the
* stored value is the multiplier itself, c_j = 1/s_j rounded to that dtype. The weight is divided
* by the ROUNDED c_j before it is quantised, so what a reader multiplies back is what was divided.
*
* NO TRANSFORM: the statistics are of the input's own channels, and a rotated weight's columns are
* not those channels.
*/
#include "lq_hess.h"
#include "lq_quant.h"
#include "lq_common.h"
#include "rad_plugin.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace lq {
namespace {
const RadQuantOption kAwqOptions[] = {
LQ_GRID_OPTIONS,
LQ_CALIB_OPTION("the imatrix's diagonal stands in, and with neither the weight is rounded to "
"nearest with unit column scales"),
{ "colscale", RAD_P_STR, "f16", "the column scales' dtype: f32, bf16, f16" },
{ "alpha_steps", RAD_P_INT, "20", "the exponents searched: k / alpha_steps, k = 0 .. steps-1" },
{ "clip", RAD_P_INT, "1", "1: search each scale block's clipping range (AWQ's auto_clip)" },
{ "sample_rows", RAD_P_INT, "512", "rows the alpha search measures the output error over" },
};
int awq_grid(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g, uint32_t* cdt) {
const int st = grid_of(o, n_o, w, g);
if (st != RAD_OK) return st;
if (g->fwht) return refuse(w, "awq takes no transform= -- its statistics are the input's own "
"channels, and a rotated weight's columns are not those");
const char* c = rad_param_gets(o, n_o, "colscale", "f16");
*cdt = rad_dtype_parse(c);
if (*cdt != RAD_F32 && *cdt != RAD_BF16 && *cdt != RAD_F16)
return refuse(w, "colscale= is f32, bf16 or f16");
if (rad_param_geti(o, n_o, "alpha_steps", 20) < 1) return refuse(w, "alpha_steps= is >= 1");
return RAD_OK;
}
/* The column scale is the chain's next level after the grid's own. */
const char* colscale_role(const Grid& g) { return g.lv2 ? "scale.2" : "scale.1"; }
int awq_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) {
if (declines(w)) return RAD_E_UNSUPPORTED;
Grid g;
uint32_t cdt = 0;
const int st = awq_grid(o, n_o, w, &g, &cdt);
if (st != RAD_OK) return st;
*out = grid_encoding(g);
if (rad_enc_add_plane(out, colscale_role(g), cdt, 0, 1) < 0)
return refuse(w, "the encoding has no room for the column scales");
return RAD_OK;
}
int64_t awq_row_block(const RadParam*, int, const RadQuantWeight*) { return 0; }
float to_dt(uint32_t dt, float v) {
switch (dt) {
case RAD_BF16: return bf16_to_f32(f32_to_bf16(v));
case RAD_F16: return f16_to_f32(f32_to_f16(v));
default: return v;
}
}
/* The output error of a candidate, D = w_hat - w over `rows` rows: the Hessian's form, or the
* diagonal's. */
struct Err {
const float* H = nullptr; /* K x K, or null */
const float* diag = nullptr; /* K, the imatrix, when there is no H */
int64_t K = 0;
double operator()(const float* D, int64_t rows) const {
if (H) {
std::vector<float> G((size_t)(rows * K));
std::vector<double> q((size_t)rows);
mat_hess(D, rows, K, H, G.data());
row_dots(D, G.data(), rows, K, q.data());
double s = 0.0;
for (double x : q) s += x;
return s;
}
double s = 0.0;
for (int64_t r = 0; r < rows; ++r)
for (int64_t j = 0; j < K; ++j) {
const double d = D[r * K + j];
s += (diag ? (double)diag[j] : 1.0) * d * d;
}
return s;
}
};
int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
int64_t rows, void* const* planes) {
Grid g;
uint32_t cdt = 0;
int st = awq_grid(o, n_o, w, &g, &cdt);
if (st != RAD_OK) return st;
if (row0 != 0 || rows != w->rows) return RAD_E_SHAPE;
const int64_t N = w->rows, K = w->cols;
const char* dir = rad_param_gets(o, n_o, "calib", nullptr);
const int steps = (int)rad_param_geti(o, n_o, "alpha_steps", 20);
const bool clip = rad_param_geti(o, n_o, "clip", 1) != 0;
const int64_t want = std::max<long long>(1, rad_param_geti(o, n_o, "sample_rows", 512));
Err err;
err.K = K;
const Gram Hg = calib_gram(dir, w->name, K, g.fwht, "awq");
err.H = Hg ? Hg->data() : nullptr;
if (!err.H && w->importance) {
err.diag = w->importance;
std::fprintf(stderr, "libquant: awq: '%s' has no Hessian; the imatrix's diagonal stands "
"in for it\n", w->name);
}
const bool have = err.H || err.diag;
/* the channels' activation magnitudes, floored as AWQ floors them */
std::vector<double> a((size_t)K, 1.0);
if (have)
for (int64_t j = 0; j < K; ++j) {
const double e = err.H ? (double)err.H[j * K + j] : (double)err.diag[j];
a[(size_t)j] = std::max(std::sqrt(std::max(e, 0.0)), 1e-4);
}
/* THE SAMPLE: whole scale blocks of rows, evenly spread, so a candidate is quantised exactly
* as the full weight will be. */
const int64_t unit = g.br > 0 ? g.br : N;
const int64_t nunits = (N + unit - 1) / unit;
const int64_t take = std::min<int64_t>(nunits, std::max<int64_t>(1, want / unit));
std::vector<int64_t> pick;
for (int64_t i = 0; i < take; ++i) pick.push_back(i * nunits / take);
int64_t srows = 0;
for (int64_t u : pick) srows += std::min(unit, N - u * unit);
std::vector<float> ws((size_t)(srows * K));
{
int64_t at = 0;
for (int64_t u : pick) {
const int64_t n = std::min(unit, N - u * unit);
std::memcpy(ws.data() + at * K, src + u * unit * K, (size_t)(n * K) * sizeof(float));
at += n;
}
}
/* c_j for an exponent: the stored column multiplier, 1 / s_j rounded */
auto colscales = [&](double alpha, std::vector<float>* c) {
std::vector<double> s((size_t)K);
double mx = 0.0, mn = 1e300;
for (int64_t j = 0; j < K; ++j) {
s[(size_t)j] = std::max(std::pow(a[(size_t)j], alpha), 1e-4);
mx = std::max(mx, s[(size_t)j]);
mn = std::min(mn, s[(size_t)j]);
}
const double norm = std::sqrt(mx * mn);
c->resize((size_t)K);
for (int64_t j = 0; j < K; ++j) (*c)[(size_t)j] = to_dt(cdt, (float)(norm / s[(size_t)j]));
};
/* ---- the exponent */
std::vector<float> c, best_c, scaled((size_t)(srows * K)), fake((size_t)(srows * K));
colscales(0.0, &best_c);
if (have) {
double best = -1.0;
int best_k = 0;
for (int k = 0; k < steps; ++k) {
colscales((double)k / steps, &c);
for (int64_t r = 0; r < srows; ++r)
for (int64_t j = 0; j < K; ++j)
scaled[(size_t)(r * K + j)] = ws[(size_t)(r * K + j)] / c[(size_t)j];
grid_fake(g, scaled.data(), srows, K, fake.data());
for (int64_t r = 0; r < srows; ++r)
for (int64_t j = 0; j < K; ++j) {
const size_t i = (size_t)(r * K + j);
fake[i] = fake[i] * c[(size_t)j] - ws[i];
}
const double e = err(fake.data(), srows);
if (best < 0.0 || e < best) { best = e; best_k = k; best_c = c; }
}
std::fprintf(stderr, "libquant: awq: '%s' alpha %.3f\n", w->name, (double)best_k / steps);
}
/* ---- the weight in its scaled form, every row */
for (int64_t r = 0; r < N; ++r)
for (int64_t j = 0; j < K; ++j) src[r * K + j] /= best_c[(size_t)j];
/* ---- the clip, block by block: the clamped block's own quantisation, measured in the
* original units against H over the block's columns */
if (clip && have) {
const int64_t br = g.br > 0 ? g.br : N, bc = g.bc > 0 ? g.bc : K;
const int64_t nr = (N + br - 1) / br, nc = (K + bc - 1) / bc;
#ifdef _OPENMP
#pragma omp parallel for schedule(dynamic, 1)
#endif
for (int64_t kb = 0; kb < nr * nc; ++kb) {
const int64_t r0 = (kb / nc) * br, r1 = std::min(r0 + br, N);
const int64_t c0 = (kb % nc) * bc, c1 = std::min(c0 + bc, K);
const int64_t m = r1 - r0, n = c1 - c0;
std::vector<float> blk((size_t)(m * n)), cl((size_t)(m * n)), dq((size_t)(m * n));
float lo = 0.0f, hi = 0.0f;
for (int64_t r = 0; r < m; ++r)
for (int64_t j = 0; j < n; ++j) {
const float v = src[(r0 + r) * K + c0 + j];
blk[(size_t)(r * n + j)] = v;
lo = std::min(lo, v);
hi = std::max(hi, v);
}
const float amax = std::max(-lo, hi);
double best = -1.0;
float best_f = 1.0f;
for (int i = 0; i < 10; ++i) { /* 1.00, 0.95, ... 0.55 */
const float f = 1.0f - 0.05f * (float)i;
const float l = g.asym ? lo * f : -amax * f, h = g.asym ? hi * f : amax * f;
for (size_t t = 0; t < cl.size(); ++t) cl[t] = std::min(std::max(blk[t], l), h);
const BlockScale b = grid_block_scale(g, cl.data(), n, 0, m, 0, n);
double e = 0.0;
for (int64_t r = 0; r < m; ++r) {
for (int64_t j = 0; j < n; ++j) {
const size_t t = (size_t)(r * n + j);
dq[t] = (grid_decode(g, b, grid_code(g, b, cl[t])) - blk[t]) *
best_c[(size_t)(c0 + j)];
}
const float* d = dq.data() + r * n;
if (err.H) {
for (int64_t x = 0; x < n; ++x) {
double hx = 0.0;
const float* hr = err.H + (c0 + x) * K + c0;
for (int64_t y = 0; y < n; ++y) hx += (double)hr[y] * d[y];
e += d[x] * hx;
}
} else {
for (int64_t x = 0; x < n; ++x) e += (double)err.diag[c0 + x] * d[x] * d[x];
}
}
if (best < 0.0 || e < best) { best = e; best_f = f; }
}
const float l = g.asym ? lo * best_f : -amax * best_f;
const float h = g.asym ? hi * best_f : amax * best_f;
for (int64_t r = 0; r < m; ++r)
for (int64_t j = 0; j < n; ++j) {
float& v = src[(r0 + r) * K + c0 + j];
v = std::min(std::max(v, l), h);
}
}
}
/* ---- the grid over the scaled, clipped weight, and the column scales after it. A column's
* importance in the scaled weight is its own times c_j squared: the error there is c_j times
* larger once the reader multiplies the column back. */
std::vector<float> imp;
if (w->importance) {
imp.resize((size_t)K);
for (int64_t j = 0; j < K; ++j)
imp[(size_t)j] = w->importance[j] * best_c[(size_t)j] * best_c[(size_t)j];
}
st = grid_rtn(g, src, 0, N, K, grid_planes(g, K, planes), imp.empty() ? nullptr : imp.data());
if (st != RAD_OK) return st;
const int cp = grid_encoding(g).n_planes;
for (int64_t j = 0; j < K; ++j) rad_store_f32(planes[cp], cdt, j, best_c[(size_t)j]);
return RAD_OK;
}
} /* namespace */
const RadQuantizerInfo& awq_info() {
static const RadQuantizerInfo q = {
"awq",
"activation-aware: each input column scaled by its activation magnitude to a searched "
"power before the grid, a per-block clip searched after, both against the layer's input "
"Hessian; the column scales are stored as the encoding's last scale level",
kAwqOptions, (int)(sizeof kAwqOptions / sizeof kAwqOptions[0]),
awq_encoding, awq_row_block, awq_quantize, nullptr,
};
return q;
}
} /* namespace lq */
+144
View File
@@ -0,0 +1,144 @@
/* lq_common.h -- the number conversions every libquant quantiser shares, written out once.
*
* WHY THESE ARE NOT rad_plugin.h's. They are the rules the containers in service were quantised by,
* and a converter that wants to reproduce those containers byte for byte has to round exactly as
* they were rounded. Where a rule here and rad_plugin.h's agree on every finite input the
* difference is only in what a NaN becomes; where they could disagree -- the integer round, which
* is half AWAY from zero, and the fp4 encoder, which breaks a tie toward the even CODE -- the
* comment says so. Each is a pure function of its input.
*/
#pragma once
#include "rad_plugin.h"
#include <cmath>
#include <cstdint>
#include <cstring>
namespace lq {
/* bf16, round to nearest even; a NaN stays a NaN. */
inline uint16_t f32_to_bf16(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
if ((u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu))
return (uint16_t)((u >> 16) | 0x40u);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
inline float bf16_to_f32(uint16_t h) {
const uint32_t u = (uint32_t)h << 16;
float f;
std::memcpy(&f, &u, 4);
return f;
}
/* f16, round to nearest even, subnormals kept, overflow to infinity. */
inline uint16_t f32_to_f16(float f) {
uint32_t x;
std::memcpy(&x, &f, 4);
const uint32_t sign = (x >> 16) & 0x8000u;
int32_t exp = (int32_t)((x >> 23) & 0xFFu) - 127 + 15;
uint32_t man = x & 0x7FFFFFu;
if (((x >> 23) & 0xFFu) == 0xFFu) return (uint16_t)(sign | 0x7C00u | (man ? 0x200u : 0u));
if (exp >= 0x1F) return (uint16_t)(sign | 0x7C00u);
if (exp <= 0) {
if (exp < -10) return (uint16_t)sign;
man |= 0x800000u;
const int shift = 14 - exp;
const uint32_t v = man >> shift;
const uint32_t rem = man & ((1u << shift) - 1u);
const uint32_t half = 1u << (shift - 1);
uint32_t out = v;
if (rem > half || (rem == half && (v & 1u))) ++out;
return (uint16_t)(sign | out);
}
uint32_t v = ((uint32_t)exp << 10) | (man >> 13);
const uint32_t rem = man & 0x1FFFu;
if (rem > 0x1000u || (rem == 0x1000u && (v & 1u))) ++v;
return (uint16_t)(sign | v);
}
inline float f16_to_f32(uint16_t h) { return rad_f16_to_f32(h); }
/* E4M3-fn: clamp at 448, round to nearest even on the 3-bit mantissa, a real subnormal rung below
* 2^-6, and a NaN encoded as a signed zero -- a weight is never NaN, and the one place a NaN could
* come from is a scale of zero, which the scale rules below never produce. */
inline uint8_t f32_to_e4m3(float f) {
uint32_t bits;
std::memcpy(&bits, &f, 4);
const uint32_t sign = (bits >> 24) & 0x80u;
float a = std::fabs(f);
if (!(a > 0.0f)) return (uint8_t)sign;
if (a > 448.0f) a = 448.0f;
if (a >= 0x1p-6f) {
uint32_t u;
std::memcpy(&u, &a, 4);
int e = (int)((u >> 23) & 0xFFu) - 127;
uint32_t mm = (u & 0x7FFFFFu) >> 20;
const uint32_t rem = u & 0xFFFFFu, half = 1u << 19;
if (rem > half || (rem == half && (mm & 1u))) { if (++mm == 8u) { mm = 0; ++e; } }
if (e > 8) { e = 8; mm = 7; }
return (uint8_t)(sign | ((uint32_t)(e + 7) << 3) | mm);
}
const float scaled = a * 512.0f;
uint32_t m = (uint32_t)(scaled + 0.5f);
if ((float)m - scaled == 0.5f && (m & 1u)) --m;
if (m > 7u) return (uint8_t)(sign | (1u << 3));
return (uint8_t)(sign | m);
}
/* FP4 e2m1 by nearest magnitude, a tie going to the EVEN CODE -- which on this grid is the
* smaller magnitude except at 2.5, where it is 2.0 (code 4) over 3.0 (code 5), the hardware's
* own round-to-nearest-even. */
inline uint8_t f32_to_e2m1(float v) {
static const float k[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
const uint8_t sign = (v < 0.0f) ? 0x8u : 0x0u;
const float a = v < 0.0f ? -v : v;
int best = 0;
float bd = -1.0f;
for (int i = 0; i < 8; ++i) {
const float d = a > k[i] ? a - k[i] : k[i] - a;
if (bd < 0.0f || d < bd || (d == bd && (i & 1) == 0)) { bd = d; best = i; }
}
return (uint8_t)(sign | (uint8_t)best);
}
/* Any small float grid by exhaustive nearest search over its codes, ties to the even code. For
* fp6 and e5m2, which nothing here needs to be fast. */
inline uint32_t f32_to_small_float(float v, uint32_t dt) {
const int bits = rad_dtype_bits(dt);
const uint32_t n = 1u << bits;
uint32_t best = 0;
float bd = -1.0f;
/* Eight bytes, not one: rad_load_f32 reads any dtype up to 64 bits, and the compiler cannot
* see that `dt` is a small one. */
uint8_t buf[8] = {};
for (uint32_t c = 0; c < n; ++c) {
buf[0] = (uint8_t)c;
const float x = rad_load_f32(buf, dt, 0);
if (std::isnan(x) || std::isinf(x)) continue;
const float d = std::fabs(x - v);
if (bd < 0.0f || d < bd || (d == bd && (c & 1u) == 0)) { bd = d; best = c; }
}
return best;
}
/* The integer round every integer grid here uses: HALF AWAY FROM ZERO, by truncation of v +- 0.5.
* It is what the containers in service were packed with, and lround differs from it only at
* values no representable f32 product reaches -- but "only" is a claim, and the byte-for-byte
* reproduction of those containers is a fact. */
inline int round_away(float v) { return (int)(v < 0.0f ? v - 0.5f : v + 0.5f); }
inline int clampi(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); }
/* The unnormalised Sylvester Walsh-Hadamard transform in place, the butterfly keeping a+b low and
* a-b high: the transform an "fwhtN" encoding names and libr4d's r4d_fwht_wave computes. */
inline void fwht_inplace(float* v, int64_t n) {
for (int64_t h = 1; h < n; h <<= 1)
for (int64_t i = 0; i < n; i += h << 1)
for (int64_t j = i; j < i + h; ++j) {
const float a = v[j], b = v[j + h];
v[j] = a + b;
v[j + h] = a - b;
}
}
} /* namespace lq */
+778
View File
@@ -0,0 +1,778 @@
/* lq_ggml.cpp -- the `ggml` quantiser: llama.cpp's formats, llama.cpp's codes, radiance's planes.
*
* A row is quantised by llama.cpp's own quantize_<type> (lq_ggml_port.h), with the imatrix's
* column importances as its quant_weights, and the GGUF blocks it writes are then UNPACKED into
* the affine planes of rad_encoding.h. The codes and scales are therefore exactly llama.cpp's --
* a llama.cpp model and a radiance container quantised from the same weights and the same imatrix
* hold the same numbers -- while the container holds an encoding every reader decodes, rather
* than a block layout one kernel family was written against.
*
* ===================================================================== THE PLANES
*
* Each type's planes, in order. [R x C] is a TILED plane's block, {R x C} a TABLE's extents, * a
* whole extent; d and dmin are the block's f16 super-scales, copied bit for bit.
*
* q8_0 codes i8; scale f16 [1x32] = d
* q4_0 codes i4 = q-8; scale f16 [1x32] = d
* q5_0 codes i5 = q-16; scale f16 [1x32] = d
* q4_1 codes u4; scale f16 [1x32] = d; min f16 [1x32] = -m
* q5_1 codes u5; scale f16 [1x32] = d; min f16 [1x32] = -m
* q2_K codes u2; scale u4 [1x16]; scale.1 f16 [1x256] = d; min u4 [1x16]; min.1 f16 = dmin
* q3_K codes i3 = q-4 (two low bits and the hmask bit); scale i6 [1x16] = sc-32;
* scale.1 f16 [1x256] = d
* q4_K codes u4; scale u6 [1x32]; scale.1 f16 [1x256] = d; min u6 [1x32]; min.1 f16 = dmin
* q5_K codes u5; otherwise as q4_K
* q6_K codes i6 = q-32; scale i8 [1x16]; scale.1 f16 [1x256] = d
* iq4_nl codes u4; table i8 {1x16} = kvalues_iq4nl; scale f16 [1x32] = d
* iq4_xs codes u4; table i8 {1x16}; scale i6 [1x32] = ls-32; scale.1 f16 [1x256] = d
* iq2_xxs codes u8 [1x8]; grid u8 {256x8}; signs u1; scale u5 [1x32] = 2ls+1;
* scale.1 f16 [1x256] = d; scale.2 f32 [*x*] = 1/8
* iq2_xs codes u9 [1x8]; grid u8 {512x8}; signs u1; scale u5 [1x16] = 2ls+1; scale.1, scale.2
* as iq2_xxs
* iq2_s codes u10 [1x8]; grid u8 {1024x8}; signs u1; scale u5 [1x16] = 2ls+1; scale.1,
* scale.2 as iq2_xxs
* iq3_xxs codes u8 [1x4]; grid u8 {256x4}; signs u1; scale u5 [1x32] = 2ls+1;
* scale.1 f16 [1x256] = d; scale.2 f32 [*x*] = 1/4
* iq3_s codes u9 [1x4]; grid u8 {512x4}; signs u1; scale u5 [1x32] = 2ls+1;
* scale.1 f16 [1x256] = d
* iq1_s codes u11 [1x8]; grid i8 {2048x8}; scale u4 [1x32] = 2ls+1; scale.1 f16 [1x256] = d;
* zero bf16 [1x32] = -delta
* iq1_m codes u11 [1x8]; grid i8 {2048x8}; scale u4 [1x16] = 2ls+1; scale.1 f16 [1x256] = d
* (assembled from the scale words' top nibbles); zero bf16 [1x8] = -delta
*
* Every line is llama.cpp's dequantize_row_<type> rewritten in the affine order, q = code |
* grid | table, negated by its sign, less its zero, times every scale level, less every min level:
* q4_1's `q*d + m` is `q*d - (-m)`, iq1's `dl*(grid + delta)` is `(grid - (-delta))*scale*d`, and
* the IQ2/IQ3 `d*(0.5 + ls)*0.25` is `(2ls+1)*d/8`. Nothing is rounded on the way: every plane
* holds a value of the block exactly, so the planes go back to the same GGUF blocks.
*
* THE 1/8 AND 1/4 ARE A PER-TENSOR LEVEL OF THEIR OWN, NOT FOLDED INTO d. d/8 in f16 is exact only
* while it stays normal, d >= 2^-11, and an IQ2 d is about a super-block's largest value over 155:
* on Gaussian weights of standard deviation 0.02, a transformer linear's usual spread, 98-100% of
* IQ2 and IQ3_XXS super-blocks have d/8 or d/4 below f16's normal range, and folded in they would
* lose up to three bits of their scale. As an f32 [*x*] constant the factor costs four bytes a
* weight and multiplies exactly.
*
* EVERY PRODUCT IN THE DECODE IS EXACT IN F32, so the affine order -- code times sub-scale times
* d, where llama.cpp forms d times sub-scale first -- gives llama.cpp's dequantised values bit for
* bit. d is an f16, eleven significant bits, and a code or grid value times its sub-scale has at
* most twelve (q6_K's 31 x 127 and iq4_xs's 127 x 31 are the widest), so no product of the chain
* rounds in either order; only the subtraction of a min -- q4_1, q5_1, q2_K, q4_K, q5_K -- rounds,
* once, on the same two operands.
*/
#include "lq_ggml.h"
#include "lq_ggml_port.h"
#include "rad_plugin.h"
#include <cctype>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
namespace lq {
namespace {
using namespace lq::ggml;
/* ================================================================== writing a plane row */
/* A plane row written front to back, `bits` an element, lowest bits first -- the bit stream
* rad_encoding.h defines. Thirty-two bits go out at a time and the tail on flush(), so every byte
* of the row is written exactly once and nothing is read back: the row arrives zeroed, but a
* writer that ORs into it would be relying on that, and one that stores whole bytes is not. */
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, the f16 or bf16 bits as they are. */
inline void put16(uint8_t* row, int64_t i, uint16_t h) {
row[2 * i] = (uint8_t)h;
row[2 * i + 1] = (uint8_t)(h >> 8);
}
/* Two 4-bit codes a 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));
}
inline uint32_t le32(const uint8_t* p) {
return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24;
}
/* iq1's delta as the zero the affine order subtracts: zero = -delta, delta = -1/8 when the bit is
* set and +1/8 when it is not. 0x3E00 and 0xBE00 are +-0.125 in bf16, exactly. */
inline uint16_t iq1_zero(bool negative_delta) { return negative_delta ? 0x3E00 : 0xBE00; }
/* ================================================================== unpacking a row's blocks
*
* Each unpack_<type> reads `nb` blocks -- one row -- and writes plane i's row at row[i]; a TABLE
* or per-tensor plane's slot is null and is written once a call, by write_shared. The index
* arithmetic is the inverse of the type's dequantize_row_<type>, value by value. */
void unpack_q8_0(const void* v, int64_t nb, uint8_t* const* row) {
const block_q8_0* b = (const block_q8_0*)v;
for (int64_t i = 0; i < nb; ++i) {
std::memcpy(row[0] + QK8_0 * i, b[i].qs, QK8_0);
put16(row[1], i, b[i].d);
}
}
/* q4_0 and iq4_nl share the 32-value nibble order: value j of a block is the low nibble of qs[j],
* value j+16 the high one. */
inline void nibbles32(const uint8_t* qs, uint8_t* q) {
for (int j = 0; j < 16; ++j) {
q[j] = qs[j] & 15;
q[j + 16] = qs[j] >> 4;
}
}
void unpack_q4_0(const void* v, int64_t nb, uint8_t* const* row) {
const block_q4_0* b = (const block_q4_0*)v;
uint8_t q[QK4_0];
for (int64_t i = 0; i < nb; ++i) {
nibbles32(b[i].qs, q);
for (int j = 0; j < QK4_0; ++j) q[j] ^= 8; /* q - 8 in four bits */
put_nibbles(row[0] + 16 * i, q, QK4_0);
put16(row[1], i, b[i].d);
}
}
void unpack_q4_1(const void* v, int64_t nb, uint8_t* const* row) {
const block_q4_1* b = (const block_q4_1*)v;
uint8_t q[QK4_1];
for (int64_t i = 0; i < nb; ++i) {
nibbles32(b[i].qs, q);
put_nibbles(row[0] + 16 * i, q, QK4_1);
put16(row[1], i, b[i].d);
put16(row[2], i, (uint16_t)(b[i].m ^ 0x8000u));
}
}
/* q5_0 and q5_1: the fifth bit of value j is bit j of qh. */
inline void fives32(const uint8_t* qs, const uint8_t* qh4, uint8_t* q) {
const uint32_t qh = le32(qh4);
nibbles32(qs, q);
for (int j = 0; j < 32; ++j) q[j] |= (uint8_t)(((qh >> j) & 1u) << 4);
}
void unpack_q5_0(const void* v, int64_t nb, uint8_t* const* row) {
const block_q5_0* b = (const block_q5_0*)v;
Bits c(row[0]);
uint8_t q[QK5_0];
for (int64_t i = 0; i < nb; ++i) {
fives32(b[i].qs, b[i].qh, q);
for (int j = 0; j < QK5_0; ++j) c.put((uint32_t)(q[j] - 16), 5);
put16(row[1], i, b[i].d);
}
c.flush();
}
void unpack_q5_1(const void* v, int64_t nb, uint8_t* const* row) {
const block_q5_1* b = (const block_q5_1*)v;
Bits c(row[0]);
uint8_t q[QK5_1];
for (int64_t i = 0; i < nb; ++i) {
fives32(b[i].qs, b[i].qh, q);
for (int j = 0; j < QK5_1; ++j) c.put(q[j], 5);
put16(row[1], i, b[i].d);
put16(row[2], i, (uint16_t)(b[i].m ^ 0x8000u));
}
c.flush();
}
/* q2_K and q3_K: value v's two low bits are bits 2*((v%128)/32) of qs[32*(v/128) + v%32]. */
inline uint32_t k_low2(const uint8_t* qs, int v) {
return (uint32_t)(qs[32 * (v / 128) + v % 32] >> (2 * ((v % 128) / 32))) & 3u;
}
void unpack_q2_K(const void* v, int64_t nb, uint8_t* const* row) {
const block_q2_K* b = (const block_q2_K*)v;
Bits c(row[0]), s(row[1]), m(row[3]);
for (int64_t i = 0; i < nb; ++i) {
for (int k = 0; k < QK_K; ++k) c.put(k_low2(b[i].qs, k), 2);
for (int j = 0; j < QK_K / 16; ++j) {
s.put(b[i].scales[j] & 15u, 4);
m.put(b[i].scales[j] >> 4, 4);
}
put16(row[2], i, b[i].d);
put16(row[4], i, b[i].dmin);
}
c.flush();
s.flush();
m.flush();
}
void unpack_q3_K(const void* v, int64_t nb, uint8_t* const* row) {
const block_q3_K* b = (const block_q3_K*)v;
Bits c(row[0]), s(row[1]);
for (int64_t i = 0; i < nb; ++i) {
const block_q3_K& x = b[i];
/* the high bit of value k is bit k/32 of hmask[k%32] */
for (int k = 0; k < QK_K; ++k)
c.put(k_low2(x.qs, k) + 4u * ((x.hmask[k % 32] >> (k / 32)) & 1u) - 4u, 3);
/* the sixteen 6-bit scales, unpacked as quantize_row_q3_K_ref re-reads them */
for (int j = 0; j < QK_K / 16; ++j) {
const int lo = j < 8 ? x.scales[j] & 0xF : x.scales[j - 8] >> 4;
const int sc = lo | (((x.scales[8 + j % 4] >> (2 * (j / 4))) & 3) << 4);
s.put((uint32_t)(sc - 32), 6);
}
put16(row[2], i, x.d);
}
c.flush();
s.flush();
}
/* q4_K and q5_K: value v's low four bits are a nibble of qs[32*(v/64) + v%32], the low one for
* the first 32 of each 64; q5_K's fifth is bit v/32 of qh[v%32]. 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 - 0] >> 6) << 4);
}
}
void unpack_q4_K(const void* v, int64_t nb, uint8_t* const* row) {
const block_q4_K* b = (const block_q4_K*)v;
Bits s(row[1]), m(row[3]);
uint8_t q[QK_K];
for (int64_t i = 0; i < nb; ++i) {
for (int k = 0; k < QK_K; ++k) q[k] = (uint8_t)k_low4(b[i].qs, k);
put_nibbles(row[0] + (QK_K / 2) * i, q, QK_K);
for (int j = 0; j < QK_K / 32; ++j) {
uint32_t sc, mn;
k4_scale_min(j, b[i].scales, &sc, &mn);
s.put(sc, 6);
m.put(mn, 6);
}
put16(row[2], i, b[i].d);
put16(row[4], i, b[i].dmin);
}
s.flush();
m.flush();
}
void unpack_q5_K(const void* v, int64_t nb, uint8_t* const* row) {
const block_q5_K* b = (const block_q5_K*)v;
Bits c(row[0]), s(row[1]), m(row[3]);
for (int64_t i = 0; i < nb; ++i) {
for (int k = 0; k < QK_K; ++k)
c.put(k_low4(b[i].qs, k) + 16u * ((b[i].qh[k % 32] >> (k / 32)) & 1u), 5);
for (int j = 0; j < QK_K / 32; ++j) {
uint32_t sc, mn;
k4_scale_min(j, b[i].scales, &sc, &mn);
s.put(sc, 6);
m.put(mn, 6);
}
put16(row[2], i, b[i].d);
put16(row[4], i, b[i].dmin);
}
c.flush();
s.flush();
m.flush();
}
/* q6_K: 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]. */
void unpack_q6_K(const void* v, int64_t nb, uint8_t* const* row) {
const block_q6_K* b = (const block_q6_K*)v;
Bits c(row[0]);
for (int64_t i = 0; i < nb; ++i) {
const block_q6_K& x = b[i];
for (int k = 0; k < QK_K; ++k) {
const int n = k / 128, t = (k % 128) / 32, l = k % 32;
const uint8_t lo = x.ql[64 * n + l + 32 * (t & 1)];
const uint32_t q = (uint32_t)(t < 2 ? lo & 15 : lo >> 4) |
(uint32_t)((x.qh[32 * n + l] >> (2 * t)) & 3) << 4;
c.put(q - 32u, 6);
}
std::memcpy(row[1] + (QK_K / 16) * i, x.scales, QK_K / 16);
put16(row[2], i, x.d);
}
c.flush();
}
void unpack_iq4_nl(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq4_nl* b = (const block_iq4_nl*)v;
uint8_t q[QK4_NL];
for (int64_t i = 0; i < nb; ++i) {
nibbles32(b[i].qs, q);
put_nibbles(row[0] + 16 * i, q, QK4_NL);
put16(row[2], i, b[i].d);
}
}
void unpack_iq4_xs(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq4_xs* b = (const block_iq4_xs*)v;
Bits s(row[2]);
uint8_t q[32];
for (int64_t i = 0; i < nb; ++i) {
const block_iq4_xs& x = b[i];
for (int ib = 0; ib < QK_K / 32; ++ib) {
nibbles32(x.qs + 16 * ib, q);
put_nibbles(row[0] + (QK_K / 2) * i + 16 * ib, q, 32);
const int ls = ((x.scales_l[ib / 2] >> 4 * (ib % 2)) & 0xf) |
(((x.scales_h >> 2 * ib) & 3) << 4);
s.put((uint32_t)(ls - 32), 6);
}
put16(row[3], i, x.d);
}
s.flush();
}
/* The IQ2 and IQ3 types: a sign byte covers eight values, bit j value j, which is the u1 plane's
* own order -- so a group of eight's signs are one byte of it. */
void unpack_iq2_xxs(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq2_xxs* b = (const block_iq2_xxs*)v;
Bits s(row[3]);
for (int64_t i = 0; i < nb; ++i) {
for (int ib32 = 0; ib32 < QK_K / 32; ++ib32) {
const uint16_t* q = b[i].qs + 4 * ib32;
const uint32_t a0 = (uint32_t)q[0] | (uint32_t)q[1] << 16;
const uint32_t a1 = (uint32_t)q[2] | (uint32_t)q[3] << 16;
for (int l = 0; l < 4; ++l) {
row[0][32 * i + 4 * ib32 + l] = (uint8_t)(a0 >> 8 * l);
row[2][32 * i + 4 * ib32 + l] = ksigns_iq2xs[(a1 >> 7 * l) & 127];
}
s.put(2 * (a1 >> 28) + 1, 5);
}
put16(row[4], i, b[i].d);
}
s.flush();
}
void unpack_iq2_xs(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq2_xs* b = (const block_iq2_xs*)v;
Bits c(row[0]), s(row[3]);
for (int64_t i = 0; i < nb; ++i) {
for (int ib32 = 0; ib32 < QK_K / 32; ++ib32) {
for (int l = 0; l < 4; ++l) {
const uint16_t q = b[i].qs[4 * ib32 + l];
c.put(q & 511u, 9);
row[2][32 * i + 4 * ib32 + l] = ksigns_iq2xs[q >> 9];
}
s.put(2u * (b[i].scales[ib32] & 0xfu) + 1u, 5);
s.put(2u * (b[i].scales[ib32] >> 4) + 1u, 5);
}
put16(row[4], i, b[i].d);
}
c.flush();
s.flush();
}
void unpack_iq2_s(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq2_s* b = (const block_iq2_s*)v;
Bits c(row[0]), s(row[3]);
for (int64_t i = 0; i < nb; ++i) {
const block_iq2_s& x = b[i];
for (int ib32 = 0; ib32 < QK_K / 32; ++ib32) {
for (int l = 0; l < 4; ++l) {
c.put(x.qs[4 * ib32 + l] | ((x.qh[ib32] << (8 - 2 * l)) & 0x300u), 10);
row[2][32 * i + 4 * ib32 + l] = x.qs[QK_K / 8 + 4 * ib32 + l];
}
s.put(2u * (x.scales[ib32] & 0xfu) + 1u, 5);
s.put(2u * (x.scales[ib32] >> 4) + 1u, 5);
}
put16(row[4], i, x.d);
}
c.flush();
s.flush();
}
void unpack_iq3_xxs(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq3_xxs* b = (const block_iq3_xxs*)v;
Bits s(row[3]);
for (int64_t i = 0; i < nb; ++i) {
const uint8_t* qs = b[i].qs;
std::memcpy(row[0] + (QK_K / 4) * i, qs, QK_K / 4);
for (int ib32 = 0; ib32 < QK_K / 32; ++ib32) {
const uint32_t a = le32(qs + QK_K / 4 + 4 * ib32);
for (int l = 0; l < 4; ++l)
row[2][32 * i + 4 * ib32 + l] = ksigns_iq2xs[(a >> 7 * l) & 127];
s.put(2 * (a >> 28) + 1, 5);
}
put16(row[4], i, b[i].d);
}
s.flush();
}
void unpack_iq3_s(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq3_s* b = (const block_iq3_s*)v;
Bits c(row[0]), s(row[3]);
for (int64_t i = 0; i < nb; ++i) {
const block_iq3_s& x = b[i];
/* the ninth bit of the grid index of 4-group g is bit g%8 of qh[g/8] */
for (int g = 0; g < QK_K / 4; ++g)
c.put(x.qs[g] | (uint32_t)((x.qh[g / 8] >> (g % 8)) & 1) << 8, 9);
std::memcpy(row[2] + (QK_K / 8) * i, x.signs, QK_K / 8);
for (int ib32 = 0; ib32 < QK_K / 32; ++ib32)
s.put(1u + 2u * ((x.scales[ib32 / 2] >> 4 * (ib32 % 2)) & 0xfu), 5);
put16(row[4], i, x.d);
}
c.flush();
s.flush();
}
void unpack_iq1_s(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq1_s* b = (const block_iq1_s*)v;
Bits c(row[0]), s(row[2]);
for (int64_t i = 0; i < nb; ++i) {
for (int ib = 0; ib < QK_K / 32; ++ib) {
const uint16_t h = b[i].qh[ib];
for (int l = 0; l < 4; ++l)
c.put(b[i].qs[4 * ib + l] | (((uint32_t)h >> 3 * l) & 7u) << 8, 11);
s.put(2u * ((h >> 12) & 7u) + 1u, 4);
put16(row[4], (QK_K / 32) * i + ib, iq1_zero(h & 0x8000));
}
put16(row[3], i, b[i].d);
}
c.flush();
s.flush();
}
void unpack_iq1_m(const void* v, int64_t nb, uint8_t* const* row) {
const block_iq1_m* b = (const block_iq1_m*)v;
Bits c(row[0]), s(row[2]);
for (int64_t i = 0; i < nb; ++i) {
const block_iq1_m& x = b[i];
uint16_t sc[4];
for (int k = 0; k < 4; ++k) sc[k] = (uint16_t)(x.scales[2 * k] | x.scales[2 * k + 1] << 8);
const uint16_t d = (uint16_t)((sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) |
((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000));
for (int ib = 0; ib < QK_K / 32; ++ib) {
const uint8_t* qs = x.qs + 4 * ib;
const uint8_t h0 = x.qh[2 * ib], h1 = x.qh[2 * ib + 1];
c.put(qs[0] | ((h0 << 8) & 0x700u), 11);
c.put(qs[1] | ((h0 << 4) & 0x700u), 11);
c.put(qs[2] | ((h1 << 8) & 0x700u), 11);
c.put(qs[3] | ((h1 << 4) & 0x700u), 11);
const int64_t g = (QK_K / 8) * i + 4 * ib;
put16(row[4], g + 0, iq1_zero(h0 & 0x08));
put16(row[4], g + 1, iq1_zero(h0 & 0x80));
put16(row[4], g + 2, iq1_zero(h1 & 0x08));
put16(row[4], g + 3, iq1_zero(h1 & 0x80));
s.put(2u * ((sc[ib / 2] >> (6 * (ib % 2) + 0)) & 7u) + 1u, 4);
s.put(2u * ((sc[ib / 2] >> (6 * (ib % 2) + 3)) & 7u) + 1u, 4);
}
put16(row[3], i, d);
}
c.flush();
s.flush();
}
/* ================================================================== the types */
typedef size_t (*QuantizeFn)(const float*, void*, int64_t, int64_t, const float*);
typedef void (*UnpackFn)(const void* blocks, int64_t nb, uint8_t* const* row);
struct Kind {
const char* name; /* as llama.cpp spells it */
ggml_type type;
int64_t block; /* values one GGUF block covers */
QuantizeFn quantize;
UnpackFn unpack;
};
const Kind kKinds[] = {
{ "q4_0", GGML_TYPE_Q4_0, QK4_0, quantize_q4_0, unpack_q4_0 },
{ "q4_1", GGML_TYPE_Q4_1, QK4_1, quantize_q4_1, unpack_q4_1 },
{ "q5_0", GGML_TYPE_Q5_0, QK5_0, quantize_q5_0, unpack_q5_0 },
{ "q5_1", GGML_TYPE_Q5_1, QK5_1, quantize_q5_1, unpack_q5_1 },
{ "q8_0", GGML_TYPE_Q8_0, QK8_0, quantize_q8_0, unpack_q8_0 },
{ "q2_K", GGML_TYPE_Q2_K, QK_K, quantize_q2_K, unpack_q2_K },
{ "q3_K", GGML_TYPE_Q3_K, QK_K, quantize_q3_K, unpack_q3_K },
{ "q4_K", GGML_TYPE_Q4_K, QK_K, quantize_q4_K, unpack_q4_K },
{ "q5_K", GGML_TYPE_Q5_K, QK_K, quantize_q5_K, unpack_q5_K },
{ "q6_K", GGML_TYPE_Q6_K, QK_K, quantize_q6_K, unpack_q6_K },
{ "iq4_nl", GGML_TYPE_IQ4_NL, QK4_NL, quantize_iq4_nl, unpack_iq4_nl },
{ "iq4_xs", GGML_TYPE_IQ4_XS, QK_K, quantize_iq4_xs, unpack_iq4_xs },
{ "iq2_xxs", GGML_TYPE_IQ2_XXS, QK_K, quantize_iq2_xxs, unpack_iq2_xxs },
{ "iq2_xs", GGML_TYPE_IQ2_XS, QK_K, quantize_iq2_xs, unpack_iq2_xs },
{ "iq2_s", GGML_TYPE_IQ2_S, QK_K, quantize_iq2_s, unpack_iq2_s },
{ "iq3_xxs", GGML_TYPE_IQ3_XXS, QK_K, quantize_iq3_xxs, unpack_iq3_xxs },
{ "iq3_s", GGML_TYPE_IQ3_S, QK_K, quantize_iq3_s, unpack_iq3_s },
{ "iq1_s", GGML_TYPE_IQ1_S, QK_K, quantize_iq1_s, unpack_iq1_s },
{ "iq1_m", GGML_TYPE_IQ1_M, QK_K, quantize_iq1_m, unpack_iq1_m },
};
/* The encoding a type writes; the mapping in the header comment, plane for plane. */
RadEncoding encoding_of(ggml_type t) {
RadEncoding e;
rad_enc_clear(&e);
rad_enc_copy_str(e.scheme, "affine");
auto plane = [&](const char* role, uint32_t dt, int64_t bc) {
rad_enc_add_plane(&e, role, dt, 1, bc);
};
switch (t) {
case GGML_TYPE_Q8_0:
plane("codes", RAD_I8, 1);
plane("scale", RAD_F16, 32);
break;
case GGML_TYPE_Q4_0:
plane("codes", RAD_I4, 1);
plane("scale", RAD_F16, 32);
break;
case GGML_TYPE_Q5_0:
plane("codes", RAD_I5, 1);
plane("scale", RAD_F16, 32);
break;
case GGML_TYPE_Q4_1:
case GGML_TYPE_Q5_1:
plane("codes", t == GGML_TYPE_Q4_1 ? RAD_U4 : RAD_U5, 1);
plane("scale", RAD_F16, 32);
plane("min", RAD_F16, 32);
break;
case GGML_TYPE_Q2_K:
plane("codes", RAD_U2, 1);
plane("scale", RAD_U4, 16);
plane("scale.1", RAD_F16, 256);
plane("min", RAD_U4, 16);
plane("min.1", RAD_F16, 256);
break;
case GGML_TYPE_Q3_K:
plane("codes", RAD_I3, 1);
plane("scale", RAD_I6, 16);
plane("scale.1", RAD_F16, 256);
break;
case GGML_TYPE_Q4_K:
case GGML_TYPE_Q5_K:
plane("codes", t == GGML_TYPE_Q4_K ? RAD_U4 : RAD_U5, 1);
plane("scale", RAD_U6, 32);
plane("scale.1", RAD_F16, 256);
plane("min", RAD_U6, 32);
plane("min.1", RAD_F16, 256);
break;
case GGML_TYPE_Q6_K:
plane("codes", RAD_I6, 1);
plane("scale", RAD_I8, 16);
plane("scale.1", RAD_F16, 256);
break;
case GGML_TYPE_IQ4_NL:
plane("codes", RAD_U4, 1);
rad_enc_add_table(&e, "table", RAD_I8, 1, 16);
plane("scale", RAD_F16, 32);
break;
case GGML_TYPE_IQ4_XS:
plane("codes", RAD_U4, 1);
rad_enc_add_table(&e, "table", RAD_I8, 1, 16);
plane("scale", RAD_I6, 32);
plane("scale.1", RAD_F16, 256);
break;
case GGML_TYPE_IQ2_XXS:
case GGML_TYPE_IQ2_XS:
case GGML_TYPE_IQ2_S: {
const int n = t == GGML_TYPE_IQ2_XXS ? 256 : t == GGML_TYPE_IQ2_XS ? 512 : 1024;
plane("codes", n == 256 ? RAD_U8 : n == 512 ? RAD_U9 : RAD_U10, 8);
rad_enc_add_table(&e, "grid", RAD_U8, n, 8);
plane("signs", RAD_U1, 1);
plane("scale", RAD_U5, t == GGML_TYPE_IQ2_XXS ? 32 : 16);
plane("scale.1", RAD_F16, 256);
rad_enc_add_plane(&e, "scale.2", RAD_F32, 0, 0);
break;
}
case GGML_TYPE_IQ3_XXS:
case GGML_TYPE_IQ3_S:
plane("codes", t == GGML_TYPE_IQ3_XXS ? RAD_U8 : RAD_U9, 4);
rad_enc_add_table(&e, "grid", RAD_U8, t == GGML_TYPE_IQ3_XXS ? 256 : 512, 4);
plane("signs", RAD_U1, 1);
plane("scale", RAD_U5, 32);
plane("scale.1", RAD_F16, 256);
if (t == GGML_TYPE_IQ3_XXS) rad_enc_add_plane(&e, "scale.2", RAD_F32, 0, 0);
break;
case GGML_TYPE_IQ1_S:
case GGML_TYPE_IQ1_M:
plane("codes", RAD_U11, 8);
rad_enc_add_table(&e, "grid", RAD_I8, NGRID_IQ1S, 8);
plane("scale", RAD_U4, t == GGML_TYPE_IQ1_S ? 32 : 16);
plane("scale.1", RAD_F16, 256);
plane("zero", RAD_BF16, t == GGML_TYPE_IQ1_S ? 32 : 8);
break;
}
return e;
}
/* Grid row k of an I type's codebook: the bytes llama.cpp's dequantiser reads at
* (const uint8_t *)(grid + k), lowest first. */
template <class W>
void fill_grid(uint8_t* out, const W* grid, int n) {
for (int k = 0; k < n; ++k)
for (int j = 0; j < (int)sizeof(W); ++j)
out[k * (int)sizeof(W) + j] = (uint8_t)(grid[k] >> (8 * j));
}
/* The planes every row shares -- a codebook, IQ4's levels, IQ2/IQ3's 1/8 or 1/4 -- written whole
* by every call, because rad-convert decodes each call's rows as soon as they are written. */
void write_shared(ggml_type t, const RadEncoding& e, void* const* planes) {
for (int i = 0; i < e.n_planes; ++i) {
const RadEncPlane& p = e.plane[i];
uint8_t* out = (uint8_t*)planes[i];
if (!std::strcmp(p.role, "table")) {
std::memcpy(out, kvalues_iq4nl, 16);
} else if (!std::strcmp(p.role, "grid")) {
switch (t) {
case GGML_TYPE_IQ2_XXS: fill_grid(out, iq2xxs_grid, 256); break;
case GGML_TYPE_IQ2_XS: fill_grid(out, iq2xs_grid, 512); break;
case GGML_TYPE_IQ2_S: fill_grid(out, iq2s_grid, 1024); break;
case GGML_TYPE_IQ3_XXS: fill_grid(out, iq3xxs_grid, 256); break;
case GGML_TYPE_IQ3_S: fill_grid(out, iq3s_grid, 512); break;
default: fill_grid(out, iq1s_grid, NGRID_IQ1S); break;
}
} else if (!std::strcmp(p.role, "scale.2")) {
const float k = t == GGML_TYPE_IQ3_XXS ? 0.25f : 0.125f;
uint32_t u;
std::memcpy(&u, &k, 4);
for (int j = 0; j < 4; ++j) out[j] = (uint8_t)(u >> (8 * j));
}
}
}
/* ================================================================== the quantiser */
bool same_name(const char* a, const char* b) {
for (; *a && *b; ++a, ++b)
if (std::tolower((unsigned char)*a) != std::tolower((unsigned char)*b)) return false;
return *a == *b;
}
const char* wname(const RadQuantWeight* w) { return w && w->name ? w->name : "?"; }
/* The type the options name. RAD_E_INVAL, said with the weight's name, when there is none. */
int kind_of(const RadParam* o, int n_o, const RadQuantWeight* w, const Kind** out) {
const char* t = rad_param_gets(o, n_o, "type", nullptr);
if (!t) {
std::fprintf(stderr, "libquant: %s: type= is required: the llama.cpp type to write, e.g. "
"q4_K, q8_0, iq4_xs\n", wname(w));
return RAD_E_INVAL;
}
for (const Kind& k : kKinds)
if (same_name(t, k.name)) {
*out = &k;
return RAD_OK;
}
std::string all;
for (const Kind& k : kKinds) all += std::string(all.empty() ? "" : " ") + k.name;
std::fprintf(stderr, "libquant: %s: type=%s is not a llama.cpp type this quantiser writes "
"(%s)\n", wname(w), t, all.c_str());
return RAD_E_INVAL;
}
/* A rank-1 weight, and one whose rows do not divide into the type's blocks, is declined: the next
* rule takes it -- a norm, or a 2880-wide projection that a q4_K pattern happened to match. */
int ggml_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) {
if (!w || w->rank < 2) return RAD_E_UNSUPPORTED;
const Kind* k = nullptr;
const int st = kind_of(o, n_o, w, &k);
if (st != RAD_OK) return st;
if (w->cols <= 0 || w->rows <= 0) return RAD_E_SHAPE;
if (w->cols % k->block) return RAD_E_UNSUPPORTED;
*out = encoding_of(k->type);
return RAD_OK;
}
/* Rows are independent in every type: a block never spans two, and the imatrix is per column. */
int64_t ggml_row_block(const RadParam*, int, const RadQuantWeight*) { return 1; }
int ggml_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
int64_t rows, void* const* planes) {
const Kind* k = nullptr;
const int st = kind_of(o, n_o, w, &k);
if (st != RAD_OK) return st;
if (!w || w->rank < 2 || w->cols <= 0 || w->rows <= 0 || w->cols % k->block || row0 < 0 ||
rows < 0 || row0 + rows > w->rows)
return RAD_E_SHAPE;
/* NO SEARCH WITHOUT ITS WEIGHTS. llama.cpp's iq2_xxs, iq2_xs and iq1_s assert the imatrix is
* there and have no other path; substituting one would write a format llama.cpp could not
* have written, under its name. */
if (!w->importance && ggml_quantize_requires_imatrix(k->type)) {
std::fprintf(stderr, "libquant: %s: type=%s needs an imatrix, and the converter has none "
"for this weight (rad-convert --imatrix FILE)\n", wname(w), k->name);
return RAD_E_INVAL;
}
ggml_quantize_init(k->type);
const RadEncoding e = encoding_of(k->type);
const int64_t C = w->cols, nb = C / k->block;
int64_t row_bytes[RAD_ENC_MAX_PLANES] = {};
bool per_row[RAD_ENC_MAX_PLANES] = {};
for (int i = 0; i < e.n_planes; ++i) {
const RadEncPlane& p = e.plane[i];
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&p, w->rows, C, &pr, &pc);
row_bytes[i] = rad_enc_row_bytes(p.dtype, pc);
per_row[i] = p.kind == RAD_PLANE_TILED && p.block[0] == 1;
}
write_shared(k->type, e, planes);
const size_t rsz = ggml_row_size(k->type, C);
const float* imp = w->importance;
#ifdef _OPENMP
#pragma omp parallel
#endif
{
std::vector<uint8_t> blocks(rsz);
#ifdef _OPENMP
#pragma omp for schedule(dynamic, 1)
#endif
for (int64_t r = 0; r < rows; ++r) {
k->quantize(src + r * C, blocks.data(), 1, C, imp);
uint8_t* row[RAD_ENC_MAX_PLANES] = {};
for (int i = 0; i < e.n_planes; ++i)
if (per_row[i]) row[i] = (uint8_t*)planes[i] + r * row_bytes[i];
k->unpack(blocks.data(), nb, row);
}
}
return RAD_OK;
}
const RadQuantOption kOptions[] = {
{ "type", RAD_P_STR, nullptr,
"the llama.cpp type, any case: q4_0 q4_1 q5_0 q5_1 q8_0 q2_K q3_K q4_K q5_K q6_K iq4_nl "
"iq4_xs iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq1_s iq1_m. iq2_xxs, iq2_xs and iq1_s need an "
"imatrix" },
};
} /* namespace */
const RadQuantizerInfo ggml_quantizer = {
"ggml",
"llama.cpp's legacy, K- and I-quants, the codes and scales chosen by llama.cpp's own search "
"(with the imatrix when the converter has one) and stored as affine planes",
kOptions, (int)(sizeof kOptions / sizeof kOptions[0]),
ggml_encoding, ggml_row_block, ggml_quantize, nullptr,
};
} /* namespace lq */
+14
View File
@@ -0,0 +1,14 @@
/* lq_ggml.h -- the `ggml` quantiser: llama.cpp's legacy, K- and I-quant formats, chosen by
* llama.cpp's own searches and stored as the canonical affine planes. lq_ggml.cpp says how each
* format's blocks become planes; lq_ggml_port.h is the search itself.
*/
#pragma once
#include "rad_quant.h"
namespace lq {
/* The quantiser's table row, for lq_registry.cpp. Its initialiser is a constant expression, so it
* is in place before any table that copies it is built. */
extern const RadQuantizerInfo ggml_quantizer;
} /* namespace lq */
File diff suppressed because it is too large. Load diff
+355
View File
@@ -0,0 +1,355 @@
/* lq_ggml_port.h -- llama.cpp's quantisers for its legacy, K- and I-quant formats, ported to C++.
*
* Copyright (c) 2023-2026 The ggml authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===================================================================== WHAT THIS IS
*
* The block layouts, value tables and quantisation searches of llama.cpp's ggml library at commit
* 06938ac12, taken over so that the `ggml` quantiser (lq_ggml.cpp) chooses exactly the codes and
* scales llama.cpp would for the same weight and the same imatrix:
*
* ggml/src/ggml-common.h the block structs below, and the tables in lq_ggml_tables.cpp:
* kmask_iq2xs, ksigns_iq2xs, iq2xxs_grid, iq2xs_grid, iq2s_grid,
* iq3xxs_grid, iq3s_grid, kvalues_iq4nl, iq1s_grid
* ggml/src/ggml-impl.h the f32 <-> f16 conversion (Maratyszcza's, round to nearest even)
* ggml/src/ggml-quants.c everything in lq_ggml_port.cpp: best_index_int8, nearest_int,
* make_qx_quants, make_q3_quants, make_qkx2_quants, make_qkx3_quants,
* make_qp_quants, get_scale_min_k4, quantize_row_<t>_ref and _impl for
* the legacy and K types, iq2xs_init_impl and iq3xs_init_impl with
* their kgrid tables, iq2/iq3_find_best_neighbour,
* iq1_find_best_neighbour2, iq1_sort_helper, quantize_row_iq4_nl_impl,
* the quantize_row_<t>_impl of every I type, and the quantize_<t>
* entry points below
* ggml/src/ggml.c ggml_quantize_init's choice of table per type, and
* ggml_quantize_requires_imatrix's list
*
* THE NUMERICS ARE LLAMA.CPP'S TO THE BIT: the same float operations in the same order, the same
* f16 rounding, the same `nearest_int` magic-number round, the same qsort over the same comparators
* -- so the bytes a quantize_<t> here writes are the bytes llama.cpp's writes, which was checked
* against llama.cpp itself and is pinned in tests/quant_ggml_test.cpp. The port departs from the
* original only where C++ requires it (a cast from void*), where a library inside a converter has
* to (a failed assertion says so on stderr and aborts instead of calling ggml_abort; the Oops
* diagnostics go to stderr, not stdout), and in the one-time table build (std::call_once in place
* of ggml's critical section; the tables live for the life of the process and have no free).
*
* THE MATCH IS WITH LLAMA.CPP AS ITS OWN BUILD COMPILES ggml-quants.c: into ggml-base, with no
* -march, so with no fused multiply-add. libquant's -ffp-contract=off holds the port there on
* every target. A llama.cpp compiled with FMA contraction -- -march=native on x86-64, or any
* aarch64 build, where FMA is in the base instruction set -- rounds inside the searches and writes
* different bytes for most types.
*
* Each quantize_<t> keeps llama.cpp's own dispatch: the legacy and K types take the _ref
* round-to-nearest path when `quant_weights` is null and the _impl search otherwise; the I types
* take their _impl with whatever `quant_weights` is, and three of those assert it is there
* (ggml_quantize_requires_imatrix). `quant_weights` is the imatrix's per-column importance,
* n_per_row of it, shared by every row.
*/
#pragma once
#include <cstddef>
#include <cstdint>
namespace lq::ggml {
typedef uint16_t ggml_half;
typedef uint16_t ggml_fp16_t;
/* The subset of ggml_type this port quantises. The values are ggml.h's, so a type read out of a
* GGUF names the same thing here. */
enum ggml_type {
GGML_TYPE_Q4_0 = 2,
GGML_TYPE_Q4_1 = 3,
GGML_TYPE_Q5_0 = 6,
GGML_TYPE_Q5_1 = 7,
GGML_TYPE_Q8_0 = 8,
GGML_TYPE_Q2_K = 10,
GGML_TYPE_Q3_K = 11,
GGML_TYPE_Q4_K = 12,
GGML_TYPE_Q5_K = 13,
GGML_TYPE_Q6_K = 14,
GGML_TYPE_IQ2_XXS = 16,
GGML_TYPE_IQ2_XS = 17,
GGML_TYPE_IQ3_XXS = 18,
GGML_TYPE_IQ1_S = 19,
GGML_TYPE_IQ4_NL = 20,
GGML_TYPE_IQ3_S = 21,
GGML_TYPE_IQ2_S = 22,
GGML_TYPE_IQ4_XS = 23,
GGML_TYPE_IQ1_M = 29,
};
/* ================================================================== ggml-common.h's blocks */
constexpr int QK_K = 256;
constexpr int K_SCALE_SIZE = 12;
constexpr int QK4_0 = 32;
struct block_q4_0 {
ggml_half d; // delta
uint8_t qs[QK4_0 / 2]; // nibbles / quants
};
static_assert(sizeof(block_q4_0) == sizeof(ggml_half) + QK4_0 / 2, "wrong q4_0 block size/padding");
constexpr int QK4_1 = 32;
struct block_q4_1 {
ggml_half d; // delta
ggml_half m; // min
uint8_t qs[QK4_1 / 2]; // nibbles / quants
};
static_assert(sizeof(block_q4_1) == 2 * sizeof(ggml_half) + QK4_1 / 2, "wrong q4_1 block size/padding");
constexpr int QK5_0 = 32;
struct block_q5_0 {
ggml_half d; // delta
uint8_t qh[4]; // 5-th bit of quants
uint8_t qs[QK5_0 / 2]; // nibbles / quants
};
static_assert(sizeof(block_q5_0) == sizeof(ggml_half) + sizeof(uint32_t) + QK5_0 / 2, "wrong q5_0 block size/padding");
constexpr int QK5_1 = 32;
struct block_q5_1 {
ggml_half d; // delta
ggml_half m; // min
uint8_t qh[4]; // 5-th bit of quants
uint8_t qs[QK5_1 / 2]; // nibbles / quants
};
static_assert(sizeof(block_q5_1) == 2 * sizeof(ggml_half) + sizeof(uint32_t) + QK5_1 / 2, "wrong q5_1 block size/padding");
constexpr int QK8_0 = 32;
struct block_q8_0 {
ggml_half d; // delta
int8_t qs[QK8_0]; // quants
};
static_assert(sizeof(block_q8_0) == sizeof(ggml_half) + QK8_0, "wrong q8_0 block size/padding");
// 2-bit quantization
// weight is represented as x = a * q + b
// 16 blocks of 16 elements each
// Effectively 2.625 bits per weight
struct block_q2_K {
uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits
uint8_t qs[QK_K/4]; // quants
ggml_half d; // super-block scale for quantized scales
ggml_half dmin; // super-block scale for quantized mins
};
static_assert(sizeof(block_q2_K) == 2*sizeof(ggml_half) + QK_K/16 + QK_K/4, "wrong q2_K block size/padding");
// 3-bit quantization
// weight is represented as x = a * q
// 16 blocks of 16 elements each
// Effectively 3.4375 bits per weight
struct block_q3_K {
uint8_t hmask[QK_K/8]; // quants - high bit
uint8_t qs[QK_K/4]; // quants - low 2 bits
uint8_t scales[12]; // scales, quantized with 6 bits
ggml_half d; // super-block scale
};
static_assert(sizeof(block_q3_K) == sizeof(ggml_half) + QK_K / 4 + QK_K / 8 + 12, "wrong q3_K block size/padding");
// 4-bit quantization
// 8 blocks of 32 elements each
// weight is represented as x = a * q + b
// Effectively 4.5 bits per weight
struct block_q4_K {
ggml_half d; // super-block scale for quantized scales
ggml_half dmin; // super-block scale for quantized mins
uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits
uint8_t qs[QK_K/2]; // 4--bit quants
};
static_assert(sizeof(block_q4_K) == 2*sizeof(ggml_half) + K_SCALE_SIZE + QK_K/2, "wrong q4_K block size/padding");
// 5-bit quantization
// 8 blocks of 32 elements each
// weight is represented as x = a * q + b
// Effectively 5.5 bits per weight
struct block_q5_K {
ggml_half d; // super-block scale for quantized scales
ggml_half dmin; // super-block scale for quantized mins
uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits
uint8_t qh[QK_K/8]; // quants, high bit
uint8_t qs[QK_K/2]; // quants, low 4 bits
};
static_assert(sizeof(block_q5_K) == 2*sizeof(ggml_half) + K_SCALE_SIZE + QK_K/2 + QK_K/8, "wrong q5_K block size/padding");
// 6-bit quantization
// weight is represented as x = a * q
// 16 blocks of 16 elements each
// Effectively 6.5625 bits per weight
struct block_q6_K {
uint8_t ql[QK_K/2]; // quants, lower 4 bits
uint8_t qh[QK_K/4]; // quants, upper 2 bits
int8_t scales[QK_K/16]; // scales, quantized with 8 bits
ggml_half d; // super-block scale
};
static_assert(sizeof(block_q6_K) == sizeof(ggml_half) + QK_K / 16 + 3*QK_K/4, "wrong q6_K block size/padding");
// (Almost) "true" 2-bit quantization.
// Due to the need to use blocks as per ggml design, it ends up using
// 2.0625 bpw because of the 16-bit scale for each block of 256.
struct block_iq2_xxs {
ggml_half d;
uint16_t qs[QK_K/8];
};
static_assert(sizeof(block_iq2_xxs) == sizeof(ggml_half) + QK_K/8*sizeof(uint16_t), "wrong iq2_xxs block size/padding");
// 2.3125 bpw quants
struct block_iq2_xs {
ggml_half d;
uint16_t qs[QK_K/8];
uint8_t scales[QK_K/32];
};
static_assert(sizeof(block_iq2_xs) == sizeof(ggml_half) + QK_K/8*sizeof(uint16_t) + QK_K/32, "wrong iq2_xs block size/padding");
// 2.5625 bpw quants
struct block_iq2_s {
ggml_half d;
uint8_t qs[QK_K/4];
uint8_t qh[QK_K/32];
uint8_t scales[QK_K/32];
};
static_assert(sizeof(block_iq2_s) == sizeof(ggml_half) + QK_K/4 + QK_K/16, "wrong iq2_s block size/padding");
// (Almost) "true" 3-bit quantization.
// Due to the need to use blocks as per ggml design, it ends up using
// 3.0625 bpw because of the 16-bit scale for each block of 256.
struct block_iq3_xxs {
ggml_half d;
uint8_t qs[3*QK_K/8];
};
static_assert(sizeof(block_iq3_xxs) == sizeof(ggml_half) + 3*(QK_K/8), "wrong iq3_xxs block size/padding");
// 3.4375 bpw
constexpr int IQ3S_N_SCALE = QK_K/64;
struct block_iq3_s {
ggml_half d;
uint8_t qs[QK_K/4];
uint8_t qh[QK_K/32];
uint8_t signs[QK_K/8];
uint8_t scales[IQ3S_N_SCALE];
};
static_assert(sizeof(block_iq3_s) == sizeof(ggml_half) + 13*(QK_K/32) + IQ3S_N_SCALE, "wrong iq3_s block size/padding");
// 1.5625 bpw
struct block_iq1_s {
ggml_half d;
uint8_t qs[QK_K/8];
uint16_t qh[QK_K/32];
};
static_assert(sizeof(block_iq1_s) == sizeof(ggml_half) + QK_K/8 + QK_K/16, "wrong iq1_s block size/padding");
// 1.75 bpw
struct block_iq1_m {
uint8_t qs[QK_K/8]; // grid index, low 8 bits
uint8_t qh[QK_K/16]; // grid index, high 3 bits + grid shift bit (for two groups of 8)
uint8_t scales[QK_K/32]; // 3-bit block scales (4-bit if QK_K == 64)
};
static_assert(sizeof(block_iq1_m) == QK_K/8 + QK_K/16 + QK_K/32, "wrong iq1_m block size/padding");
// Used by IQ1_M quants
typedef union {
ggml_half f16;
uint16_t u16;
} iq1m_scale_t;
// Non-linear quants
constexpr int QK4_NL = 32;
struct block_iq4_nl {
ggml_half d;
uint8_t qs[QK4_NL/2];
};
static_assert(sizeof(block_iq4_nl) == sizeof(ggml_half) + QK4_NL/2, "wrong iq4_nl block size/padding");
struct block_iq4_xs {
ggml_half d;
uint16_t scales_h;
uint8_t scales_l[QK_K/64];
uint8_t qs[QK_K/2];
};
static_assert(sizeof(block_iq4_xs) == sizeof(ggml_half) + sizeof(uint16_t) + QK_K/64 + QK_K/2, "wrong iq4_xs block size/padding");
/* ================================================================== ggml-common.h's tables */
constexpr int NGRID_IQ1S = 2048;
constexpr float IQ1S_DELTA = 0.125f;
constexpr float IQ1M_DELTA = 0.125f;
extern const uint8_t kmask_iq2xs[8];
extern const uint8_t ksigns_iq2xs[128];
extern const uint64_t iq2xxs_grid[256];
extern const uint64_t iq2xs_grid[512];
extern const uint64_t iq2s_grid[1024];
extern const uint32_t iq3xxs_grid[256];
extern const uint32_t iq3s_grid[512];
extern const int8_t kvalues_iq4nl[16];
extern const uint64_t iq1s_grid[NGRID_IQ1S];
/* ================================================================== the quantisers */
/* Build the search tables an I type needs -- the lattice, its index map and every off-grid
* point's nearest neighbours -- once for the life of the process, whichever thread asks first; a
* no-op for the other types. Every quantize_<t> below expects it to have run for its type. */
void ggml_quantize_init(enum ggml_type type);
/* ggml_quantize_requires_imatrix: the types whose search has no path without `quant_weights`. */
bool ggml_quantize_requires_imatrix(enum ggml_type type);
/* Bytes of one row of `ne` values; `ne` a multiple of the type's block. */
size_t ggml_row_size(enum ggml_type type, int64_t ne);
/* llama.cpp's quantize_<t>: `nrow` rows of `n_per_row` values from `src` into `dst`, returning
* the bytes written. Rows are independent. */
size_t quantize_q4_0(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q4_1(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q5_0(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q5_1(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q8_0(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q2_K(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q3_K(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q4_K(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q5_K(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_q6_K(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq2_xxs(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq2_xs(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq2_s(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq3_xxs(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq3_s(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq1_s(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq1_m(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq4_nl(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
size_t quantize_iq4_xs(const float * src, void * dst, int64_t nrow, int64_t n_per_row,
const float * quant_weights);
} /* namespace lq::ggml */
File diff suppressed because it is too large. Load diff
+299
View File
@@ -0,0 +1,299 @@
/* lq_gptq.cpp -- the Hessian side of GPTQ and the sequential loop. See lq_gptq.h. */
#include "lq_gptq.h"
#include "lq_hess.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <map>
#include <mutex>
#include <string>
#include <vector>
namespace lq {
namespace {
/* H is damped, inverted and re-factorised into the upper triangle U with U^T U = H^-1, the form
* the sequential loop wants: column i's error is divided by U[i][i] and spread over columns j > i
* with weight U[i][j]. Frantar's formulation, followed rather than re-derived. DOUBLE throughout:
* a Cholesky is K^3/6 accumulations deep, and f32 there costs real conditioning on a matrix that
* is near-singular in the directions a rotation flattened. */
bool chol_lower(std::vector<double>& a, int64_t k) {
for (int64_t i = 0; i < k; ++i) {
for (int64_t j = 0; j <= i; ++j) {
double s = a[(size_t)(i * k + j)];
for (int64_t t = 0; t < j; ++t) s -= a[(size_t)(i * k + t)] * a[(size_t)(j * k + t)];
if (i == j) {
if (!(s > 0.0)) return false;
a[(size_t)(i * k + i)] = std::sqrt(s);
} else {
a[(size_t)(i * k + j)] = s / a[(size_t)(j * k + j)];
}
}
for (int64_t j = i + 1; j < k; ++j) a[(size_t)(i * k + j)] = 0.0;
}
return true;
}
/* A = L L^T, factored in place -> A^-1, full and symmetric: L^-1 first, then L^-T L^-1. */
void inv_from_chol(std::vector<double>& l, int64_t k) {
for (int64_t j = 0; j < k; ++j) {
l[(size_t)(j * k + j)] = 1.0 / l[(size_t)(j * k + j)];
for (int64_t i = j + 1; i < k; ++i) {
double s = 0.0;
for (int64_t t = j; t < i; ++t) s += l[(size_t)(i * k + t)] * l[(size_t)(t * k + j)];
l[(size_t)(i * k + j)] = -s / l[(size_t)(i * k + i)];
}
}
std::vector<double> out((size_t)(k * k), 0.0);
for (int64_t i = 0; i < k; ++i)
for (int64_t j = 0; j <= i; ++j) {
double s = 0.0;
for (int64_t t = i; t < k; ++t) s += l[(size_t)(t * k + i)] * l[(size_t)(t * k + j)];
out[(size_t)(i * k + j)] = s;
out[(size_t)(j * k + i)] = s;
}
l.swap(out);
}
/* A -> U upper with A = U^T U. */
bool chol_upper(std::vector<double>& a, int64_t k) {
for (int64_t i = 0; i < k; ++i) {
double d = a[(size_t)(i * k + i)];
for (int64_t t = 0; t < i; ++t) {
const double v = a[(size_t)(t * k + i)];
d -= v * v;
}
if (!(d > 0.0)) return false;
const double u = std::sqrt(d);
a[(size_t)(i * k + i)] = u;
for (int64_t j = i + 1; j < k; ++j) {
double s = a[(size_t)(i * k + j)];
for (int64_t t = 0; t < i; ++t) s -= a[(size_t)(t * k + i)] * a[(size_t)(t * k + j)];
a[(size_t)(i * k + j)] = s / u;
}
for (int64_t j = 0; j < i; ++j) a[(size_t)(i * k + j)] = 0.0;
}
return true;
}
struct Cache {
std::mutex mu;
std::map<std::string, Gram> f; /* null = looked and found nothing */
};
Cache& cache() {
static Cache c;
return c;
}
} /* namespace */
std::vector<int32_t> gptq_act_order(const char* dir, const char* name, int64_t K, int64_t domain) {
std::vector<int32_t> perm((size_t)K);
for (int64_t i = 0; i < K; ++i) perm[(size_t)i] = (int32_t)i;
if (!dir || !*dir || !name || !*name || K <= 0) return perm;
std::vector<double> acc;
if (!calib_sum(dir, calib_resolve(dir, name, K), K, domain, &acc)) return perm;
/* THE COLUMNS OF LARGEST INPUT ENERGY FIRST, a tie in the order the columns sit: the
* recursion has the most freedom to absorb error early, so the columns that cost most to get
* wrong are quantised while every later column is still there to take it. */
std::stable_sort(perm.begin(), perm.end(), [&](int32_t x, int32_t y) {
return acc[(size_t)x * (size_t)K + (size_t)x] > acc[(size_t)y * (size_t)K + (size_t)y];
});
return perm;
}
Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, double damp,
const int32_t* perm) {
if (!dir || !*dir || !name || !*name || K <= 0) return nullptr;
const std::string stem = calib_resolve(dir, name, K);
const bool layer = stem == calib_stem(name);
char dk[32];
std::snprintf(dk, sizeof dk, "%.17g", damp);
const std::string key = std::string(dir) + "|" + stem + "|" + std::to_string(K) + "|" +
std::to_string(domain) + "|" + dk + (perm ? "|act" : "");
/* A LAYER'S FACTOR IS SHARED by every expert that reads it, so it is made once under the
* lock and kept; an expert's own is made for its one call, outside it, so experts quantised
* side by side factor side by side. */
Cache& c = cache();
std::unique_lock<std::mutex> lk(c.mu, std::defer_lock);
if (layer) {
lk.lock();
auto it = c.f.find(key);
if (it != c.f.end()) return it->second;
}
auto keep = [&](Gram u) {
if (layer) c.f.emplace(key, u);
return u;
};
std::vector<double> acc;
const int found = calib_sum(dir, stem, K, domain, &acc);
if (!found) {
std::fprintf(stderr, "libquant: no calibration for '%s' in %s (looked for gram.r*.%s.bin); "
"rounding it to nearest\n", name, dir, stem.c_str());
return keep(nullptr);
}
/* Under act order the Hessian is the PERMUTED one, P H P^T: the recursion runs over the
* columns in the order they are quantised, and that is the order the factor has to be in. */
if (perm) {
std::vector<double> p((size_t)(K * K));
for (int64_t i = 0; i < K; ++i)
for (int64_t j = 0; j < K; ++j)
p[(size_t)(i * K + j)] = acc[(size_t)perm[i] * (size_t)K + (size_t)perm[j]];
acc.swap(p);
}
double tr = 0.0;
int64_t dead = 0;
for (int64_t i = 0; i < K; ++i) {
if (!(acc[(size_t)(i * K + i)] > 0.0)) ++dead;
tr += acc[(size_t)(i * K + i)];
}
/* A DEAD COLUMN IS A CHANNEL THE CORPUS NEVER EXERCISED: its diagonal is zero, the Cholesky
* would fail on it, and the calibration says nothing about it -- so it gets the mean diagonal,
* which makes the recursion leave it alone rather than spend other columns' error on it. */
const double mean = tr / (double)K;
const double lam = damp * mean;
for (int64_t i = 0; i < K; ++i) {
double& d = acc[(size_t)(i * K + i)];
if (!(d > 0.0)) d = mean;
d += lam;
}
if (dead)
std::fprintf(stderr, "libquant: %lld of %lld columns of '%s' were never exercised by the "
"calibration corpus\n", (long long)dead, (long long)K, stem.c_str());
if (!chol_lower(acc, K)) {
std::fprintf(stderr, "libquant: the Hessian for '%s' is not positive definite even "
"damped; rounding it to nearest\n", stem.c_str());
return keep(nullptr);
}
inv_from_chol(acc, K);
if (!chol_upper(acc, K)) {
std::fprintf(stderr, "libquant: the inverse Hessian for '%s' would not factor; rounding "
"it to nearest\n", stem.c_str());
return keep(nullptr);
}
auto u = std::make_shared<std::vector<float>>((size_t)(K * K));
for (size_t i = 0; i < u->size(); ++i) (*u)[i] = (float)acc[i];
if (layer)
std::fprintf(stderr, "libquant: GPTQ quantises '%s' against %d calibration file(s), "
"K=%lld\n", stem.c_str(), found, (long long)K);
return keep(u);
}
void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales, int64_t N,
int64_t K, const float* u) {
if (!w || !codes || N <= 0 || K <= 0) return;
auto one = [&](int64_t n, int64_t i, float v) -> float {
const BlockScale& b = scales.at(n, i);
const int c = grid_code(g, b, v);
codes[(size_t)(n * K + i)] = c;
return grid_decode(g, b, c);
};
if (!u) {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t n = 0; n < N; ++n)
for (int64_t i = 0; i < K; ++i) w[(size_t)(n * K + i)] = one(n, i, w[(size_t)(n * K + i)]);
return;
}
/* COLUMN BLOCKS OUTSIDE, ROWS INSIDE. The recursion is independent per row, so rows are the
* parallelism; but a row that ran the full K alone would stream all K^2 of `u` for itself.
* With the block outside, every row is at the same columns at the same time and the slice of
* `u` they share -- 128 x K -- stays in cache. */
const int64_t B = 128;
std::vector<float> err((size_t)(N * B));
for (int64_t b0 = 0; b0 < K; b0 += B) {
const int64_t b1 = (b0 + B < K) ? b0 + B : K;
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t n = 0; n < N; ++n) {
float* wr = w + (size_t)(n * K);
float* er = err.data() + (size_t)(n * B);
for (int64_t i = b0; i < b1; ++i) {
const float* ur = u + (size_t)(i * K);
const float d = ur[i];
const float v = wr[i];
const float dq = one(n, i, v);
wr[i] = dq;
/* d is U[i][i], strictly positive by construction -- chol_upper refuses otherwise */
const float e = (v - dq) / d;
er[i - b0] = e;
for (int64_t j = i + 1; j < b1; ++j) wr[j] -= e * ur[j];
}
for (int64_t t = b0; t < b1; ++t) {
const float e = er[t - b0];
const float* ur = u + (size_t)(t * K);
for (int64_t j = b1; j < K; ++j) wr[j] -= e * ur[j];
}
}
}
}
void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const Scales& scales,
int64_t N, int64_t K, const float* h, double damp, int passes) {
if (!x || !w || !codes || !h || N <= 0 || K <= 0 || passes <= 0) return;
/* THE DAMPING GPTQ'S FACTOR CARRIES, so the two minimise the same form: lambda is `damp` of
* the mean diagonal, and a column the corpus never exercised takes the mean as its diagonal. */
double tr = 0.0;
for (int64_t i = 0; i < K; ++i) tr += h[(size_t)(i * K + i)];
const double mean = tr / (double)K;
const float lam = (float)(damp * mean);
std::vector<float> dg((size_t)K);
for (int64_t i = 0; i < K; ++i) {
const float d = h[(size_t)(i * K + i)];
dg[(size_t)i] = (d > 0.0f ? d : (float)mean) + lam;
}
/* G = E H for every row at once, by the deterministic blocked product; each row then keeps
* its own G current with one row of H per code that moves. */
std::vector<float> e((size_t)(N * K)), gm((size_t)(N * K));
for (size_t i = 0; i < e.size(); ++i) e[i] = w[i] - x[i];
mat_hess(e.data(), N, K, h, gm.data());
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t n = 0; n < N; ++n) {
float* er = e.data() + (size_t)(n * K);
float* gr = gm.data() + (size_t)(n * K);
const float* xr = x + (size_t)(n * K);
float* wr = w + (size_t)(n * K);
int32_t* cr = codes + (size_t)(n * K);
for (int64_t j = 0; j < K; ++j) gr[j] += lam * er[j];
for (int pass = 0; pass < passes; ++pass) {
int64_t moved = 0;
for (int64_t j = 0; j < K; ++j) {
const float hj = dg[(size_t)j];
/* The row's gradient at j less column j's own term, over the diagonal. */
const float t = xr[j] - (gr[j] - er[j] * hj) / hj;
const BlockScale& b = scales.at(n, j);
const int c = grid_code(g, b, t);
if (c == cr[j]) continue;
const float dq = grid_decode(g, b, c);
const float d = (dq - xr[j]) - er[j];
/* Only a strict improvement moves a code: the change in the form is
* d (2 g_j + d hj), g_j the current gradient, and a tie keeps GPTQ's choice. */
if (!(d * (2.0f * gr[j] + d * hj) < 0.0f)) continue;
const float* hr = h + (size_t)(j * K);
for (int64_t t2 = 0; t2 < K; ++t2) gr[t2] += d * hr[t2];
gr[j] += lam * d;
er[j] += d;
wr[j] = dq;
cr[j] = c;
++moved;
}
if (!moved) break;
}
}
}
} /* namespace lq */
+56
View File
@@ -0,0 +1,56 @@
/* lq_gptq.h -- error-feedback quantisation on any grid, against a calibration Hessian.
*
* GPTQ picks the codes of one column at a time and pushes the rounding error of that column into
* the columns it has not reached yet, weighted by the inverse Hessian of the layer's real input.
* It is the difference between a four-bit expert that serves and one that does not: plain
* rounding treats every column as independent, and a 4-bit grid does not have the levels to
* absorb that.
*
* WHAT IS HERE IS THE HESSIAN AND THE LOOP, not the grid: the codes are chosen on whatever grid
* the rule names (lq_grid.h), against scales fixed BEFORE the loop from the (transformed) weight --
* the "static groups" form, which keeps a scale plane a function of the weight alone.
*
* THE HESSIAN IS AN EXPERT'S OWN WHERE THE TAP RECORDED ONE, the layer's otherwise (lq_hess.h,
* calib_resolve). A layer's pooled Hessian is found from the weight's logical name with an expert
* index stripped, so the experts reading it share one factor and pay for it once; an expert's own
* is factored for its one call. The engine's calibration tap writes both (arch/common/rad_arch.h,
* RADIANCE_CALIB_DIR); docs/MOE-W4.md walks the bootstrap.
*/
#pragma once
#include "lq_grid.h"
#include "lq_hess.h"
namespace lq {
/* The upper Cholesky factor U of the damped inverse Hessian, U^T U = (H + lambda I)^-1, as a K x K
* row-major f32 plane, for the weight named `name`. Null when `dir` has no calibration for it --
* which is not an error, and the weight is then rounded to nearest -- and also null, with a
* message, when a file is there and unusable, so a typo'd directory is not silently a quality
* regression. With `perm` (gptq_act_order's) it is the factor of the permuted Hessian P H P^T.
* `domain` is the grid's transform width, 0 without one (calib_sum). A layer's is cached for the
* life of the process by (dir, stem, K, domain, damp, act order); an expert's own is not. */
Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, double damp,
const int32_t* perm = nullptr);
/* ACT ORDER: the columns by descending Hessian diagonal -- the input energy each one carries --
* ties in column order. The identity when `dir` holds nothing for the weight. */
std::vector<int32_t> gptq_act_order(const char* dir, const char* name, int64_t K, int64_t domain);
/* Quantise `w` [N, K] in place on grid `g` against `scales` (grid_scales'), writing codes to
* `codes` [N, K]. On return `w` holds the decoded values. With `u` null each value is rounded to
* nearest on its own, which is byte-identical to grid_rtn. */
void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales, int64_t N,
int64_t K, const float* u);
/* COORDINATE DESCENT AFTER THE LOOP: `passes` sweeps over the columns of every row, each code
* re-chosen on the grid at its conditional optimum -- the value that minimises the row's
* e (H + lambda I) e^T, e = decoded - x, with every other column held -- against the same damped
* Hessian GPTQ factored. GPTQ chooses each column once, before the columns after it are known;
* a sweep revisits that choice with all of them in place, and never raises the objective.
* `x` [N, K] is the weight GPTQ was handed (transformed), `w` its decoded result, updated in
* place with `codes`. `h` is the undamped Gram (calib_gram's), null for nothing to do. */
void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const Scales& scales,
int64_t N, int64_t K, const float* h, double damp, int passes);
} /* namespace lq */
+1004
View File
File diff suppressed because it is too large. Load diff
+197
View File
@@ -0,0 +1,197 @@
/* lq_grid.h -- a quantisation GRID: what codes a weight may take and how its scales sit over it.
*
* libquant separates three things a recipe names independently (spec.md §4.5): the GRID, which is
* the code type and the scale, zero and transform structure around it; the ALGORITHM that picks
* codes on that grid (round-to-nearest, GPTQ, AWQ, ...); and the encoding the result is stored as,
* which follows from the grid alone. Every algorithm takes the same grid options, so a grid
* written once is available to all of them.
*
* A grid is parsed from a rule's options:
*
* codes=DT the code dtype: i2..i8, i16, i32 (symmetric), u1..u8, u16 with zero=
* (asymmetric), or a float code: fp8_e4m3, fp8_e5m2, fp6_e2m3, fp6_e3m2,
* fp4_e2m1. Required, except beside table=, which implies it.
* table=T a SCALAR CODEBOOK: each code indexes a table of values, which a block's scale
* multiplies. nf4 (QLoRA's NormalFloat), iq4nl (llama.cpp's IQ4_NL values),
* w4nl (the rotated expert grid libr4d's w4nla8h kernel decodes), w5nl (its
* 32-level form, libr4d's w5nl64a8h),
* binary {-1, +1}, ternary {-1, 0, +1}, or the values themselves, `;`-separated.
* The codes are the narrowest unsigned width that indexes it.
* group=N one scale per N columns of a row -- block [1 x N]
* block=RxC the scale block in general; `*` is the whole extent: 128x128, 1x*, *x*
* (default: one scale a row, 1x*)
* scale=DT the scale dtype: f32, bf16, f16, fp8_e4m3, e8m0 (default bf16); under scale2=
* also an integer, u4..u8, i6, i8 -- a K-quant's sub-block scale
* scale2=DT a SECOND SCALE LEVEL the first is relative to: f32, bf16, f16, fp8_e4m3, e8m0.
* NVFP4 is fp4 codes, an fp8_e4m3 scale a [1 x 16] and an f32 scale2 a tensor.
* scale2_value=X the second level FIXED at X for every one of its blocks, rather than taken
* from the largest first-level scale under it: exactly representable in scale2=.
* It is a constant a reader can know -- a first level of E4M3 sub-scales over a
* model whose scales sit inside E4M3's range needs no per-row level, only an
* offset (libr4d's w4nl64a8h experts) -- and a first level it would push past its
* dtype's top is held there, said once on stderr.
* group2=N the second level's block, [1 x N]; or
* block2=RxC in general (default: the whole tensor, *x*). A multiple of the first level's
* block in each extent.
* zero=DT an integer zero point a block, making the grid asymmetric: u8, u4 ...
* transform=fwhtN rotate each row by the unnormalised Hadamard before quantising
* rule=R how a block's scale is chosen: absmax (the default), mx (the OCP shared
* exponent, the default for an e8m0 scale), fixed (scale_value=, every block),
* search (the scale, or the asymmetric range, of least squared error over a
* sweep of candidates and their least-squares refits, weighted by the imatrix's
* column importances when the converter has them)
* scale_value=X the fixed scale for rule=fixed
* clamp=full|sym a signed code's range: [-2^(b-1), 2^(b-1)-1], or symmetric about zero
*
* THE RULES ARE THE ONES THE CONTAINERS IN SERVICE WERE MADE WITH, exactly -- the order of a
* division, which number is rounded to the scale dtype before the codes are chosen against it, and
* what a block of zeros gets -- so a recipe reproduces those containers byte for byte. Each is
* stated where it is implemented. The forms no container in service uses -- a codebook, a second
* level, the searched rule and the 16- and 32-bit codes -- go through a general path of their own,
* which leaves those rules where they are.
*/
#pragma once
#include "rad_quant.h"
#include <string>
#include <vector>
namespace lq {
struct Grid {
uint32_t codes = RAD_DT_INVALID;
bool is_float = false; /* a float code: fp8, fp6, fp4 */
bool asym = false; /* a zero plane */
bool wide = false; /* a 16- or 32-bit integer code, chosen in double */
uint32_t scale_dt = RAD_BF16;
uint32_t zero_dt = RAD_DT_INVALID;
int64_t br = 1, bc = 0; /* the scale block; 0 = the whole extent */
int64_t fwht = 0; /* the transform's order, or 0 */
int qmin = 0, qmax = 0; /* an integer code's range */
float fmax = 0.0f; /* a float code's largest magnitude */
int emax = 0; /* a float code's largest normal exponent, for rule=mx */
enum Rule { ABSMAX, MX, FIXED, SEARCH } rule = ABSMAX;
double fixed = 0.0;
/* A scalar codebook: the value of each code, in code order. */
std::vector<float> table;
uint32_t table_dt = RAD_DT_INVALID;
std::vector<int> table_order; /* the codes, by ascending value */
float tpeak = 0.0f; /* the entry of largest magnitude, signed */
/* The extremes are not mirror images (iq4nl: -127 and +113), so a block's scale takes the
* sign of its largest-magnitude value and that value lands on `tpeak` exactly. */
bool tsigned = false;
/* A second scale level, which the first is relative to. */
bool lv2 = false;
uint32_t scale2_dt = RAD_DT_INVALID;
int64_t br2 = 0, bc2 = 0; /* its block; 0 = the whole extent */
double fixed2 = 0.0; /* scale2_value: every block's stored value, or 0 */
bool l1_int = false; /* the first level is an integer sub-scale */
int l1_lo = 0, l1_hi = 0; /* its range */
float l1max = 0.0f; /* the largest first-level value its dtype holds */
/* The planes of the encoding, by index; -1 when the grid has none. */
int plane_zero() const { return asym ? 2 : -1; }
int plane_scale2() const { return lv2 ? (asym ? 3 : 2) : -1; }
int plane_table() const {
return table.empty() ? -1 : 2 + (asym ? 1 : 0) + (lv2 ? 1 : 0);
}
/* Does this grid take the general path (see the head of the file)? */
bool general() const { return lv2 || rule == SEARCH || !table.empty() || wide; }
};
/* Parse a grid from options. RAD_OK, or RAD_E_INVAL with `why` naming the option. */
int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why);
/* The encoding a grid writes. */
RadEncoding grid_encoding(const Grid& g);
/* The rows one quantize call may take for this grid: a multiple of every level's block rows, or 0
* when a scale covers every row and has to see them all. */
int64_t grid_row_block(const Grid& g, int64_t rows);
/* One block's quantiser state: the scale the codes are chosen against, its stored form, the
* reciprocal, and for an asymmetric grid the zero. */
struct BlockScale {
float s = 1.0f; /* the value codes are chosen against: the stored scale(s), widened */
float inv = 1.0f;
double inv_d = 1.0; /* rule=fixed reads its reciprocal in double; see grid.cpp */
int zero = 0;
int e8 = 0; /* rule=mx: the shared exponent's E8M0 code */
float stored = 1.0f; /* what the scale plane holds: s, divided by a transform's order --
or, under a second level, the first level's own value */
float lo = 0.0f; /* an asymmetric block's low end, which the zero is taken against */
};
/* The scale of the block covering logical rows [r0, r1) and columns [c0, c1) of `w`, f32 [*, cols],
* already transformed. `imp` is a column's importance for rule=search, or null. Under a second
* level this is the first level's ideal scale, unrounded; grid_scales finishes it. */
BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_t r1,
int64_t c0, int64_t c1, const float* imp = nullptr);
/* One value onto the grid: its code, and the value the code decodes to (for error feedback). */
int grid_code(const Grid& g, const BlockScale& b, float v);
float grid_decode(const Grid& g, const BlockScale& b, int code);
/* Write a scale (and a zero) into element `i` of its plane row. */
void grid_store_scale(const Grid& g, const BlockScale& b, void* scale_row, void* zero_row,
int64_t i);
/* The geometry of a quantize call: where each plane's rows for this call start, as the ABI hands
* them over, and the plane row widths in bytes. */
struct Planes {
uint8_t* codes = nullptr;
uint8_t* scale = nullptr;
uint8_t* zero = nullptr;
uint8_t* scale2 = nullptr;
uint8_t* table = nullptr;
int64_t codes_row = 0, scale_row = 0, zero_row = 0, scale2_row = 0; /* bytes */
int64_t scale_cols = 0, scale2_cols = 0; /* elements a row */
};
Planes grid_planes(const Grid& g, int64_t cols, void* const* planes);
/* Rotate rows in place when the grid carries a transform. */
void grid_transform_rows(const Grid& g, float* w, int64_t rows, int64_t cols);
/* Every scale of a call's rows, both levels: the first level block by block in plane order, the
* second level's stored values in theirs. */
struct Scales {
std::vector<BlockScale> b;
int64_t nr = 0, nc = 0; /* first-level blocks */
int64_t br = 1, bc = 1; /* their extents, resolved against the call */
std::vector<float> s2; /* the second level as stored */
int64_t nr2 = 0, nc2 = 0;
const BlockScale& at(int64_t r, int64_t c) const {
return b[(size_t)((r / br) * nc + c / bc)];
}
};
/* The whole scale grid of rows [0, rows) of `w`, without choosing a code -- what round-to-nearest
* codes against and the static-groups form an error-feedback algorithm quantises against. `imp`
* is the columns' importances for rule=search, or null. */
Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols,
const float* imp = nullptr);
/* Write every scale plane, the zeros and the codebook of a call. */
void grid_store_scales(const Grid& g, const Scales& s, const Planes& p);
/* Store one code into element `i` of a code row, any width this grid writes. */
void grid_store_code(const Grid& g, uint8_t* row, int64_t i, int code);
/* Rows [0, rows) of `w` quantised and decoded again, into `out` [rows, cols]: the weight a reader of
* this grid would see, for an algorithm that measures a candidate. `rows` covers whole blocks. */
void grid_fake(const Grid& g, const float* w, int64_t rows, int64_t cols, float* out,
const float* imp = nullptr);
/* A block's state from its scale -- `s` unrounded, `lo` the asymmetric low end the zero is taken
* against -- rounded as the general path rounds one. For an algorithm that chose the scale itself;
* a grid with a second level has its own pass and does not take this. */
BlockScale grid_finish(const Grid& g, double s, float lo);
/* Round-to-nearest over rows [0, rows) of `w` (logical rows [row0, row0+rows)). The block scales
* are taken over each block's own rows, so `rows` must cover whole blocks. */
int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t cols,
const Planes& p, const float* imp = nullptr);
} /* namespace lq */
+332
View File
@@ -0,0 +1,332 @@
/* lq_hess.cpp -- reading the calibration Hessians, and D . H. See lq_hess.h. */
#include "lq_hess.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
#include <mutex>
namespace lq {
namespace {
/* "RADGRAM2", k, rank, rows, domain, a pad word, then k*k f32 row-major: the file the engine's
* calibration tap writes (arch/common/rad_arch.h, calib_write). The header is 32 bytes. */
constexpr int kHdr = 32;
/* The unnormalised Hadamard of width `n` over every n-wide block of a length-k row, in place. */
void fwht_row(double* v, int64_t k, int64_t n) {
for (int64_t b0 = 0; b0 < k; b0 += n)
for (int64_t h = 1; h < n; h *= 2)
for (int64_t i = b0; i < b0 + n; i += 2 * h)
for (int64_t j = i; j < i + h; ++j) {
const double x = v[j], y = v[j + h];
v[j] = x + y;
v[j + h] = x - y;
}
}
/* H -> F H F for the block-diagonal Hadamard F of width `n`: every row, then every column. F is
* symmetric, so the column pass is the row pass over the transpose, and the result stays
* symmetric to the last bit only because both passes are the same butterflies in the same order. */
void rotate_gram(std::vector<double>& h, int64_t k, int64_t n) {
for (int64_t r = 0; r < k; ++r) fwht_row(h.data() + r * k, k, n);
std::vector<double> col((size_t)k);
for (int64_t c = 0; c < k; ++c) {
for (int64_t r = 0; r < k; ++r) col[(size_t)r] = h[(size_t)(r * k + c)];
fwht_row(col.data(), k, n);
for (int64_t r = 0; r < k; ++r) h[(size_t)(r * k + c)] = col[(size_t)r];
}
}
bool read_gram(const std::string& path, int64_t k, int64_t domain, std::vector<double>* acc) {
FILE* f = std::fopen(path.c_str(), "rb");
if (!f) return false;
char hdr[kHdr];
if (std::fread(hdr, 1, kHdr, f) != (size_t)kHdr || std::memcmp(hdr, "RADGRAM2", 8) != 0) {
std::fprintf(stderr, "libquant: %s is not a RADGRAM2 file\n", path.c_str());
std::fclose(f);
return false;
}
uint32_t kk = 0, dom = 0;
std::memcpy(&kk, hdr + 8, 4);
std::memcpy(&dom, hdr + 24, 4);
if ((int64_t)kk != k) {
std::fprintf(stderr, "libquant: %s holds a %u-wide Hessian and this weight's K is %lld\n",
path.c_str(), kk, (long long)k);
std::fclose(f);
return false;
}
/* Two domains meet only through the model's own: a file rotated at one width serves a grid
* rotated at another by going back first, and either width has to tile K. */
const int64_t from = (int64_t)dom;
auto tiles = [k](int64_t n) { return n == 0 || (n >= 2 && (n & (n - 1)) == 0 && k % n == 0); };
if (!tiles(from) || !tiles(domain)) {
std::fprintf(stderr, "libquant: %s is in domain %lld and the weight wants %lld, which do "
"not both tile K=%lld\n", path.c_str(), (long long)from,
(long long)domain, (long long)k);
std::fclose(f);
return false;
}
std::vector<float> buf((size_t)(k * k));
const bool okr = std::fread(buf.data(), 4, buf.size(), f) == buf.size();
std::fclose(f);
if (!okr) {
std::fprintf(stderr, "libquant: %s is short\n", path.c_str());
return false;
}
std::vector<double> h(buf.begin(), buf.end());
if (from != domain) {
if (from != 0) {
rotate_gram(h, k, from);
const double inv = 1.0 / ((double)from * (double)from);
for (double& x : h) x *= inv;
}
if (domain != 0) rotate_gram(h, k, domain);
/* ROUNDED TO WHAT A TAP IN THAT DOMAIN WOULD HAVE STORED: a file is f32, and a Hessian
* brought into a domain is then the same bytes as one summed there -- which is what lets a
* bf16 model's calibration and a rotated container's quantise a weight identically. */
for (double& x : h) x = (double)(float)x;
}
if (acc->empty()) acc->assign(h.size(), 0.0);
for (size_t i = 0; i < h.size(); ++i) (*acc)[i] += h[i];
return true;
}
/* The rows every rank's file for `stem` says it summed, or -1 when `dir` holds none. */
int64_t calib_rows(const char* dir, const std::string& stem) {
int64_t total = -1;
for (int r = 0; r < 16; ++r) {
char path[1024];
std::snprintf(path, sizeof path, "%s/gram.r%d.%s.bin", dir, r, stem.c_str());
FILE* f = std::fopen(path, "rb");
if (!f) continue;
char hdr[kHdr];
if (std::fread(hdr, 1, kHdr, f) == (size_t)kHdr && std::memcmp(hdr, "RADGRAM2", 8) == 0) {
uint64_t n = 0;
std::memcpy(&n, hdr + 16, 8);
total = (total < 0 ? 0 : total) + (int64_t)n;
}
std::fclose(f);
}
return total;
}
/* The name less a `.weight` or `.scale` tail. */
std::string own_stem(const char* name) {
std::string s = name ? name : "";
const char* tails[] = { ".weight", ".scale" };
for (const char* t : tails) {
const size_t n = std::strlen(t);
if (s.size() > n && s.compare(s.size() - n, n, t) == 0) { s.resize(s.size() - n); break; }
}
return s;
}
struct GramCache {
std::mutex mu;
std::map<std::string, Gram> g; /* null = looked and found nothing */
};
GramCache& gram_cache() {
static GramCache c;
return c;
}
/* THE PANEL AND THE BLOCK. A panel is CB columns of H over all K of its rows, PACKED -- copied
* into a buffer of K rows of CB floats -- so a step of k reads one contiguous line rather than one
* line K floats from the last, which is what keeps the product at arithmetic speed and not at the
* cache's (3-5x, measured). A row block is RB rows of D, held as RB*CB accumulators in registers:
* 8 x 32 under AVX-512 and 4 x 16 under AVX2 are sixteen and eight vector registers. Each
* accumulator sums its k in ascending order and is stored once, so the panel, the block and the
* instruction set are a schedule and not a change to any sum. Both are forced inline so that each
* is compiled inside the instruction set of the run that calls it. */
template <int RB, int CB>
__attribute__((always_inline)) inline void panel(const float* D, int64_t K, const float* P,
float* G) {
float acc[RB][CB];
for (int r = 0; r < RB; ++r)
for (int c = 0; c < CB; ++c) acc[r][c] = 0.0f;
for (int64_t k = 0; k < K; ++k) {
const float* h = P + k * CB;
for (int r = 0; r < RB; ++r) {
const float d = D[r * K + k];
#pragma omp simd
for (int c = 0; c < CB; ++c) acc[r][c] += d * h[c];
}
}
for (int r = 0; r < RB; ++r)
for (int c = 0; c < CB; ++c) G[r * K + c] = acc[r][c];
}
/* A task: one panel of H packed, then a run of row blocks against it. */
template <int RB, int CB>
__attribute__((always_inline)) inline void task(const float* D, int64_t K, const float* H,
int64_t j0, float* G, int64_t b0, int64_t b1,
float* pack) {
for (int64_t k = 0; k < K; ++k) std::memcpy(pack + k * CB, H + k * K + j0, CB * sizeof(float));
for (int64_t b = b0; b < b1; ++b) panel<RB, CB>(D + b * RB * K, K, pack, G + b * RB * K + j0);
}
/* The edges: what the blocks leave, one element at a time in the same order. */
void edge(const float* D, int64_t K, const float* H, int64_t r0, int64_t r1, int64_t j0,
int64_t j1, float* G) {
for (int64_t r = r0; r < r1; ++r)
for (int64_t j = j0; j < j1; ++j) {
float s = 0.0f;
for (int64_t k = 0; k < K; ++k) s += D[r * K + k] * H[k * K + j];
G[r * K + j] = s;
}
}
/* The blocked part at one shape, threaded over (panel, run of row blocks). Returns the rows and
* columns it covered. */
template <int RB, int CB>
void blocked(const float* D, int64_t R, int64_t K, const float* H, float* G,
void (*run)(const float*, int64_t, const float*, int64_t, float*, int64_t, int64_t,
float*),
int64_t* rf, int64_t* cf) {
const int64_t nrb = R / RB, ncb = K / CB;
*rf = nrb * RB;
*cf = ncb * CB;
if (nrb == 0 || ncb == 0) { *rf = *cf = 0; return; }
const int64_t chunk = 64; /* row blocks a task */
const int64_t nch = (nrb + chunk - 1) / chunk;
#ifdef _OPENMP
#pragma omp parallel
#endif
{
std::vector<float> pack((size_t)(K * CB));
#ifdef _OPENMP
#pragma omp for collapse(2) schedule(dynamic, 1)
#endif
for (int64_t cb = 0; cb < ncb; ++cb)
for (int64_t ch = 0; ch < nch; ++ch)
run(D, K, H, cb * CB, G, ch * chunk, std::min(nrb, (ch + 1) * chunk), pack.data());
}
}
__attribute__((target("avx512f")))
void run_avx512(const float* D, int64_t K, const float* H, int64_t j0, float* G, int64_t b0,
int64_t b1, float* pack) {
task<8, 32>(D, K, H, j0, G, b0, b1, pack);
}
__attribute__((target("avx2")))
void run_avx2(const float* D, int64_t K, const float* H, int64_t j0, float* G, int64_t b0,
int64_t b1, float* pack) {
task<4, 16>(D, K, H, j0, G, b0, b1, pack);
}
void run_base(const float* D, int64_t K, const float* H, int64_t j0, float* G, int64_t b0,
int64_t b1, float* pack) {
task<4, 8>(D, K, H, j0, G, b0, b1, pack);
}
} /* namespace */
std::string calib_stem(const char* name) {
std::string s = own_stem(name);
const size_t dot = s.rfind('.');
if (dot != std::string::npos && dot + 1 < s.size()) {
bool all_digits = true;
for (size_t i = dot + 1; i < s.size(); ++i)
if (s[i] < '0' || s[i] > '9') { all_digits = false; break; }
if (all_digits) s.resize(dot);
}
return s;
}
int calib_sum(const char* dir, const std::string& stem, int64_t K, int64_t domain,
std::vector<double>* acc) {
/* EVERY RANK'S FILE, SUMMED. Under expert parallelism a rank's `down` Hessian covers only the
* tokens routed to its own experts, so no single file holds the layer's distribution; the
* gate_up files are duplicates across ranks, and summing those multiplies H by the rank count,
* a positive scale every algorithm here is invariant to. 16 bounds the rank count. */
int found = 0;
for (int r = 0; r < 16; ++r) {
char path[1024];
std::snprintf(path, sizeof path, "%s/gram.r%d.%s.bin", dir, r, stem.c_str());
if (read_gram(path, K, domain, acc)) ++found;
}
return found;
}
std::string calib_resolve(const char* dir, const char* name, int64_t K) {
const std::string pooled = calib_stem(name);
const std::string own = own_stem(name);
if (!dir || !*dir || own == pooled) return pooled;
const int64_t rows = calib_rows(dir, own);
if (rows >= kOwnRowsPerK * K) return own;
if (rows >= 0)
std::fprintf(stderr, "libquant: '%s' was routed %lld calibration rows, fewer than %lld; it "
"reads the layer's Hessian '%s'\n", own.c_str(), (long long)rows,
(long long)(kOwnRowsPerK * K), pooled.c_str());
return pooled;
}
Gram calib_gram(const char* dir, const char* name, int64_t K, int64_t domain, const char* who) {
if (!dir || !*dir || !name || !*name || K <= 0) return nullptr;
const std::string stem = calib_resolve(dir, name, K);
int found = 0;
auto read = [&]() -> Gram {
std::vector<double> acc;
found = calib_sum(dir, stem, K, domain, &acc);
if (!found) {
std::fprintf(stderr, "libquant: no calibration for '%s' in %s (looked for "
"gram.r*.%s.bin); %s rounds it to nearest\n", name, dir,
stem.c_str(), who);
return nullptr;
}
auto h = std::make_shared<std::vector<float>>(acc.size());
for (size_t i = 0; i < acc.size(); ++i) (*h)[i] = (float)acc[i];
return h;
};
if (stem != calib_stem(name)) return read();
const std::string key = std::string(dir) + "|" + stem + "|" + std::to_string(K) + "|" +
std::to_string(domain);
GramCache& c = gram_cache();
std::lock_guard<std::mutex> lk(c.mu);
auto it = c.g.find(key);
if (it != c.g.end()) return it->second;
Gram h = read();
if (h)
std::fprintf(stderr, "libquant: %s reads '%s' against %d calibration file(s), K=%lld\n",
who, stem.c_str(), found, (long long)K);
c.g.emplace(key, h);
return h;
}
void mat_hess(const float* D, int64_t R, int64_t K, const float* H, float* G) {
if (R <= 0 || K <= 0) return;
int64_t rf = 0, cf = 0;
if (__builtin_cpu_supports("avx512f")) blocked<8, 32>(D, R, K, H, G, run_avx512, &rf, &cf);
else if (__builtin_cpu_supports("avx2")) blocked<4, 16>(D, R, K, H, G, run_avx2, &rf, &cf);
else blocked<4, 8>(D, R, K, H, G, run_base, &rf, &cf);
/* the column edge of the blocked rows, then the row edge across every column */
if (cf < K && rf > 0) {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < rf; ++r) edge(D, K, H, r, r + 1, cf, K, G);
}
if (rf < R) {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t j = 0; j < K; ++j) edge(D, K, H, rf, R, j, j + 1, G);
}
}
void row_dots(const float* D, const float* G, int64_t R, int64_t K, double* out) {
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < R; ++r) {
double s = 0.0;
for (int64_t k = 0; k < K; ++k) s += (double)D[r * K + k] * (double)G[r * K + k];
out[r] = s;
}
}
} /* namespace lq */
+75
View File
@@ -0,0 +1,75 @@
/* lq_hess.h -- the calibration Hessians every calibrated quantiser reads, and the one product they
* all spend their time in.
*
* WHAT A HESSIAN IS HERE. The engine's calibration tap (arch/common/rad_arch.h, calib_write) sums
* x x^T over the real input of a layer's projection, per rank, into `gram.r<rank>.<stem>.bin`. The
* input is the one the KERNEL multiplies, so a file says which DOMAIN it is in: the model's own
* activation (domain 0), or that activation rotated by the unnormalised Hadamard of width N, block
* by block (domain N) -- what a container that stores its weights rotated multiplies. A reader asks
* for the domain its weight is quantised in, the grid's transform, and each file is brought there
* before the sum: rotating is H -> F H F, and back is the same divided by N^2, F being its own
* inverse up to N. So a calibration run on a bf16 model and one on a rotated four-bit container
* both serve a rotated recipe. A layer-local quantiser's error is then the quadratic form
*
* L = sum over rows r of (w_hat_r - w_r) H (w_hat_r - w_r)^T
*
* which decomposes over rows: two rows of a weight share H and nothing else. GPTQ's recursion,
* AWQ's scale search, AutoRound's rounding descent and ParoQuant's rotation fit are four ways of
* making that number small, and the last three spend their time in D . H, which is what mat_hess
* computes.
*
* THE MOST SPECIFIC HESSIAN THERE IS: a routed expert's own, when the tap recorded one -- the
* engine records one an expert for `down`, whose input is each expert's own intermediate units --
* and otherwise the layer's, pooled over its experts and found from the weight's name with the
* expert index stripped (calib_stem), which a layer's experts share and the process reads once.
*/
#pragma once
#include <cstdint>
#include <memory>
#include <string>
#include <vector>
namespace lq {
/* A Hessian or a factor of one as a quantiser holds it: shared, so one the process does not cache
* -- an expert's own -- lives exactly as long as the call that read it. */
using Gram = std::shared_ptr<const std::vector<float>>;
/* `blk.7.ffn_gate_up_exps.123.weight` -> `blk.7.ffn_gate_up_exps`: the stem a layer's pooled
* Hessian file is named by. */
std::string calib_stem(const char* name);
/* The stem `name`'s Hessian is read from in `dir`: the weight's own -- the name less `.weight`,
* `blk.7.ffn_down_exps.123` -- when every rank's file for it together says at least
* kOwnRowsPerK * K rows, and calib_stem's otherwise, said on stderr. A GPTQ fit to a Gram of few
* rows fits those rows: on Qwen3.8-Flash-Next's down projection an expert's own Gram cuts its
* held-out output error by 20-55% against the pooled one's, except for experts routed under ~2K
* rows, where it is worse than rounding to nearest. Those carry a fraction of a percent of the
* routing. */
constexpr int64_t kOwnRowsPerK = 4;
std::string calib_resolve(const char* dir, const char* name, int64_t K);
/* Every rank's file for `stem` in `dir`, each brought into `domain` (0, or the Hadamard width a
* rotated grid quantises in), summed into `acc` (K x K, double, row-major). Returns how many files
* were read; 0 when there are none. A file that is there and unusable -- the wrong magic, the wrong
* K, short, a domain that cannot be brought to the one asked for -- is said so on stderr and
* skipped. */
int calib_sum(const char* dir, const std::string& stem, int64_t K, int64_t domain,
std::vector<double>* acc);
/* The summed Gram of `name`'s input in `domain` as f32 K x K, from calib_resolve's stem, or null
* when `dir` holds none for it (said once on stderr). A layer's is cached for the life of the
* process by (dir, stem, K, domain); an expert's own is read for the call that asked, since each
* is used once and a model's worth would not fit. */
Gram calib_gram(const char* dir, const char* name, int64_t K, int64_t domain, const char* who);
/* G [R x K] = D [R x K] . H [K x K], H symmetric. Every element of G is summed over k in ascending
* order whatever the thread count and the vector width, so the result is a function of the inputs
* alone -- a quantiser's output is a stored file, and two converts of the same weight must agree.
* Threads over column panels of H and row blocks of D. */
void mat_hess(const float* D, int64_t R, int64_t K, const float* H, float* G);
/* out[r] = D_r . G_r, the quadratic form of each row, summed in double. */
void row_dots(const float* D, const float* G, int64_t R, int64_t K, double* out);
} /* namespace lq */
+432
View File
@@ -0,0 +1,432 @@
/* lq_paro.cpp -- ParoQuant: pairwise rotation quantisation (Liang, Chen, Han, Liu; ICLR 2026).
*
* WHAT IT DOES. An outlier channel stretches the range of every scale group it sits in. ParoQuant
* transforms each row's input channels before the grid -- a channel-wise scaling, then `stages`
* rounds of independent Givens rotations, each a set of disjoint channel pairs inside one rotation
* group of `rot_group` channels -- so the values of a group even out, and LEARNS the angles and the
* scales against the output error. The reader undoes the transform on the activation side: the
* encoding's transform is "givens" (abi/rad_encoding.h), T = D . G_1 ... G_S over row vectors, with
* the scales, the pairs and the angles stored as its tables.
*
* STAGE ONE fits the transform: Adam at `lr` (cosine-decayed to a twentieth, no weight decay) over
* `steps` steps, each on the next `sample_rows` rows of the weight, the angles starting at zero and
* the scales at one, as the paper's. The weight is quantised through the grid at every step and the gradient
* reaches the transform through the straight-through estimator: w_hat = w + E T^-1, the
* quantisation error E held, so a step moves T^-1 to send E where the input does not look.
* STAGE TWO is the paper's fine-tuning of the transformed weight's rounding and scales; here it is
* AutoRound (lq_autoround.h) on the transformed weight against the transformed Hessian
* T^-1 H T^-T, for `iters` steps -- 0 leaves the transformed weight rounded to nearest.
*
* THE PAIRS are drawn at random inside each rotation group, a channel paired at most once a stage
* and a pair, where the group allows, used at most once over all stages -- the paper's diverse
* independent rotations -- from a generator seeded by the weight's name, so two converts of the
* same weight draw the same pairs.
*
* THE OUTPUT ERROR is the Hessian's quadratic form (lq_hess.h) in the weight's own domain -- the
* layer-local form of the paper's per-layer output loss -- or, with no Hessian for the weight but
* an imatrix, its diagonal. With neither the transform stays the identity, which is said.
*
* DETERMINISM: every gradient is summed over rows in row order, whatever the thread count, so the
* transform -- and with it the stored file -- is a function of the weight and the calibration
* alone.
*/
#include "lq_autoround.h"
#include "lq_hess.h"
#include "lq_quant.h"
#include "lq_common.h"
#include "rad_plugin.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
namespace lq {
namespace {
const RadQuantOption kParoOptions[] = {
LQ_GRID_OPTIONS,
LQ_CALIB_OPTION("the imatrix's diagonal stands in, and with neither the transform is the "
"identity and the weight is rounded to nearest"),
{ "stages", RAD_P_INT, "8", "rounds of independent Givens rotations" },
{ "rot_group", RAD_P_INT, "0",
"channels a rotation's pairs stay within: 0 is the grid's group, or 128 without one" },
{ "steps", RAD_P_INT, "200", "stage one's Adam steps" },
{ "lr", RAD_P_F64, "0.05", "stage one's learning rate, for the angles and the scales" },
{ "sample_rows", RAD_P_INT, "512", "rows a stage-one step measures the output error over" },
{ "iters", RAD_P_INT, "100",
"stage two's AutoRound steps on the transformed weight (an integer grid with row blocks); "
"0 rounds it to nearest" },
};
struct Paro {
Grid g;
int stages = 8;
int64_t gr = 128;
};
int paro_setup(const RadParam* o, int n_o, const RadQuantWeight* w, Paro* p) {
const int st = grid_of(o, n_o, w, &p->g);
if (st != RAD_OK) return st;
if (p->g.fwht) return refuse(w, "paroquant writes its own transform, so it takes no "
"transform=");
p->stages = (int)rad_param_geti(o, n_o, "stages", 8);
if (p->stages < 1 || p->stages > 64) return refuse(w, "stages= is 1 to 64");
p->gr = rad_param_geti(o, n_o, "rot_group", 0);
if (p->gr <= 0) p->gr = (p->g.bc > 0 && w->cols % p->g.bc == 0) ? p->g.bc : 128;
if (p->gr < 2 || (p->gr & 1)) return refuse(w, "rot_group= is an even channel count");
if (w->cols % p->gr) {
char m[160];
std::snprintf(m, sizeof m, "paroquant: %lld columns are not a whole number of %lld-channel "
"rotation groups", (long long)w->cols, (long long)p->gr);
return refuse(w, m);
}
return RAD_OK;
}
int paro_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) {
if (declines(w)) return RAD_E_UNSUPPORTED;
Paro p;
const int st = paro_setup(o, n_o, w, &p);
if (st != RAD_OK) return st;
*out = grid_encoding(p.g);
rad_enc_copy_str(out->transform, "givens");
if (rad_enc_add_table(out, "t.scale", RAD_F32, 1, w->cols) < 0 ||
rad_enc_add_table(out, "t.pairs", RAD_I32, p.stages, w->cols) < 0 ||
rad_enc_add_table(out, "t.angle", RAD_F32, p.stages, w->cols / 2) < 0)
return refuse(w, "the encoding has no room for the rotation's tables");
return RAD_OK;
}
int64_t paro_row_block(const RadParam*, int, const RadQuantWeight*) { return 0; }
uint64_t splitmix(uint64_t* s) {
uint64_t z = (*s += 0x9E3779B97F4A7C15ull);
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
return z ^ (z >> 31);
}
/* The pairs: [stages x K], stage s pairing columns (pairs[s][2p], pairs[s][2p+1]). */
std::vector<int32_t> draw_pairs(const char* name, int stages, int64_t K, int64_t gr) {
std::vector<int32_t> pairs((size_t)(stages * K));
for (int64_t g0 = 0; g0 < K; g0 += gr) {
std::vector<uint8_t> used((size_t)(gr * gr), 0);
for (int s = 0; s < stages; ++s) {
uint64_t st = name_seed(name) ^ ((uint64_t)(s + 1) * 0xD1B54A32D192ED03ull) ^
((uint64_t)g0 * 0x8CB92BA72F3D8DD7ull);
std::vector<int> order((size_t)gr);
for (int64_t i = 0; i < gr; ++i) order[(size_t)i] = (int)i;
for (int64_t i = gr - 1; i > 0; --i)
std::swap(order[(size_t)i], order[(size_t)(splitmix(&st) % (uint64_t)(i + 1))]);
std::vector<uint8_t> paired((size_t)gr, 0);
int64_t p = 0;
for (int64_t x = 0; x < gr; ++x) {
const int a = order[(size_t)x];
if (paired[(size_t)a]) continue;
int b = -1;
for (int64_t y = x + 1; y < gr && b < 0; ++y) { /* a pair not used yet */
const int c = order[(size_t)y];
if (!paired[(size_t)c] && !used[(size_t)(a * gr + c)]) b = c;
}
for (int64_t y = x + 1; y < gr && b < 0; ++y) /* else any partner */
if (!paired[(size_t)order[(size_t)y]]) b = order[(size_t)y];
paired[(size_t)a] = paired[(size_t)b] = 1;
used[(size_t)(a * gr + b)] = used[(size_t)(b * gr + a)] = 1;
pairs[(size_t)(s * K + g0 + 2 * p)] = (int32_t)(g0 + a);
pairs[(size_t)(s * K + g0 + 2 * p + 1)] = (int32_t)(g0 + b);
++p;
}
}
}
return pairs;
}
/* The transform's tables, and its forward and inverse over one row. */
struct Rot {
int S = 0;
int64_t K = 0;
std::vector<int32_t> pairs; /* [S x K] */
std::vector<float> angle; /* [S x K/2] */
std::vector<float> scale; /* [K] */
/* v = w . D . G_1 ... G_S, in place */
void forward(float* x) const {
for (int64_t k = 0; k < K; ++k) x[k] *= scale[(size_t)k];
for (int s = 0; s < S; ++s)
for (int64_t p = 0; p < K / 2; ++p) {
const int32_t a = pairs[(size_t)(s * K + 2 * p)], b = pairs[(size_t)(s * K + 2 * p + 1)];
const float t = angle[(size_t)(s * (K / 2) + p)], c = std::cos(t), sn = std::sin(t);
const float xa = x[a], xb = x[b];
x[a] = xa * c + xb * sn;
x[b] = xb * c - xa * sn;
}
}
/* y = e . T^-1, keeping every intermediate: ys[k] after the k-th inverse stage (k = 0 is e);
* the result, divided by the scales, into `out`. */
void inverse(const float* e, float* ys, float* out) const {
std::memcpy(ys, e, (size_t)K * sizeof(float));
for (int k = 1; k <= S; ++k) {
const int s = S - k;
const float* y0 = ys + (size_t)(k - 1) * K;
float* y1 = ys + (size_t)k * K;
std::memcpy(y1, y0, (size_t)K * sizeof(float));
for (int64_t p = 0; p < K / 2; ++p) {
const int32_t a = pairs[(size_t)(s * K + 2 * p)], b = pairs[(size_t)(s * K + 2 * p + 1)];
const float t = angle[(size_t)(s * (K / 2) + p)], c = std::cos(t), sn = std::sin(t);
y1[a] = c * y0[a] - sn * y0[b];
y1[b] = sn * y0[a] + c * y0[b];
}
}
const float* yl = ys + (size_t)S * K;
for (int64_t k = 0; k < K; ++k) out[k] = yl[k] / scale[(size_t)k];
}
};
/* The output error's gradient factor: G = D H, or D times the diagonal. */
void err_grad(const float* D, int64_t R, int64_t K, const float* H, const float* diag, float* G) {
if (H) { mat_hess(D, R, K, H, G); return; }
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < R; ++r)
for (int64_t k = 0; k < K; ++k) G[r * K + k] = D[r * K + k] * diag[k];
}
/* STAGE ONE. */
void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, const float* diag,
int steps, double lr, int64_t want, Rot* rot) {
const Grid& g = p.g;
const int S = rot->S;
const int64_t P = (int64_t)S * (K / 2) + K; /* the angles, then the scales */
const int64_t unit = g.br > 0 ? g.br : N;
const int64_t nunits = (N + unit - 1) / unit;
const int64_t take = std::min<int64_t>(nunits, std::max<int64_t>(1, want / unit));
std::vector<double> m((size_t)P, 0.0), v((size_t)P, 0.0);
double norm = 0.0; /* the first step's loss */
const double b1 = 0.9, b2 = 0.999, eps = 1e-8, lr_min = lr / 20.0;
std::vector<float> ws, vs, fake, E, D, G, ys, part;
for (int t = 0; t < steps; ++t) {
/* this step's rows: the next `take` units, wrapping */
std::vector<int64_t> us;
for (int64_t i = 0; i < take; ++i) us.push_back((t * take + i) % nunits);
std::sort(us.begin(), us.end());
us.erase(std::unique(us.begin(), us.end()), us.end());
int64_t R = 0;
for (int64_t u : us) R += std::min(unit, N - u * unit);
ws.resize((size_t)(R * K));
{
int64_t at = 0;
for (int64_t u : us) {
const int64_t n = std::min(unit, N - u * unit);
std::memcpy(&ws[(size_t)(at * K)], w + u * unit * K, (size_t)(n * K) * sizeof(float));
at += n;
}
}
vs = ws;
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < R; ++r) rot->forward(&vs[(size_t)(r * K)]);
fake.resize(vs.size());
grid_fake(g, vs.data(), R, K, fake.data());
E.resize(vs.size());
for (size_t i = 0; i < vs.size(); ++i) E[i] = fake[i] - vs[i];
D.resize(vs.size());
ys.resize((size_t)(R * (S + 1) * K));
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < R; ++r)
rot->inverse(&E[(size_t)(r * K)], &ys[(size_t)(r * (S + 1) * K)], &D[(size_t)(r * K)]);
G.resize(vs.size());
err_grad(D.data(), R, K, H, diag, G.data());
double loss = 0.0;
{
std::vector<double> q((size_t)R);
row_dots(D.data(), G.data(), R, K, q.data());
for (double x : q) loss += x;
}
if (t == 0) norm = loss > 0.0 ? loss : 1.0;
/* THE BACKWARD PASS, a row at a time into the row's own slot of `part`: dL/dD = 2 G; D =
* y_S / scale; and each inverse stage (a, b) -> (c a - s b, s a + c b) gives
* dL/dt = g_a (-y_b) + g_b y_a over its outputs and sends g back by the transpose. */
part.assign((size_t)(R * P), 0.0f);
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < R; ++r) {
float* gp = &part[(size_t)(r * P)];
std::vector<float> gg((size_t)K);
const float* d = &D[(size_t)(r * K)];
const float* gr = &G[(size_t)(r * K)];
for (int64_t k = 0; k < K; ++k) {
const float sc = rot->scale[(size_t)k];
const float gk = 2.0f * gr[k];
gp[(int64_t)S * (K / 2) + k] = gk * (-d[k] / sc);
gg[(size_t)k] = gk / sc;
}
const float* yr = &ys[(size_t)(r * (S + 1) * K)];
for (int k = S; k >= 1; --k) {
const int s = S - k;
const float* y1 = yr + (size_t)k * K;
for (int64_t q = 0; q < K / 2; ++q) {
const int32_t a = rot->pairs[(size_t)(s * K + 2 * q)];
const int32_t b = rot->pairs[(size_t)(s * K + 2 * q + 1)];
const float th = rot->angle[(size_t)(s * (K / 2) + q)];
const float c = std::cos(th), sn = std::sin(th);
const float ga = gg[(size_t)a], gb = gg[(size_t)b];
gp[s * (K / 2) + q] = ga * (-y1[b]) + gb * y1[a];
gg[(size_t)a] = c * ga + sn * gb;
gg[(size_t)b] = -sn * ga + c * gb;
}
}
}
/* the sum over rows, in row order, and the Adam step on it */
const double lt = lr_min + 0.5 * (lr - lr_min) * (1.0 + std::cos(M_PI * t / steps));
const double c1 = 1.0 - std::pow(b1, t + 1), c2 = 1.0 - std::pow(b2, t + 1);
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t i = 0; i < P; ++i) {
double gsum = 0.0;
for (int64_t r = 0; r < R; ++r) gsum += (double)part[(size_t)(r * P + i)];
gsum /= norm;
m[(size_t)i] = b1 * m[(size_t)i] + (1.0 - b1) * gsum;
v[(size_t)i] = b2 * v[(size_t)i] + (1.0 - b2) * gsum * gsum;
const double upd = lt * (m[(size_t)i] / c1) / (std::sqrt(v[(size_t)i] / c2) + eps);
if (i < (int64_t)S * (K / 2)) {
rot->angle[(size_t)i] = (float)(rot->angle[(size_t)i] - upd);
} else {
float& sc = rot->scale[(size_t)(i - (int64_t)S * (K / 2))];
sc = std::min(20.0f, std::max(0.05f, (float)(sc - upd)));
}
}
if (t == 0 || t + 1 == steps)
std::fprintf(stderr, "libquant: paroquant: step %d of %d, output error %.6g of the "
"first step's\n", t + 1, steps, loss / norm);
}
}
/* T^-1 H T^-T, block by rotation group: T^-1 is block-diagonal over the groups, so its rows for a
* group are formed once, by sending each unit vector through the inverse, and every block of H is
* multiplied on both sides by them. */
std::vector<float> transformed_hessian(const Rot& rot, const float* H, const float* diag,
int64_t K, int64_t gr) {
const int64_t ng = K / gr;
std::vector<float> M((size_t)(K * gr)); /* row i: e_i . T^-1, its group's span */
{
std::vector<float> e((size_t)K, 0.0f), ys((size_t)((rot.S + 1) * K)), out((size_t)K);
for (int64_t i = 0; i < K; ++i) {
e[(size_t)i] = 1.0f;
rot.inverse(e.data(), ys.data(), out.data());
const int64_t g0 = (i / gr) * gr;
for (int64_t j = 0; j < gr; ++j) M[(size_t)(i * gr + j)] = out[(size_t)(g0 + j)];
e[(size_t)i] = 0.0f;
}
}
std::vector<float> Hv((size_t)(K * K), 0.0f);
#ifdef _OPENMP
#pragma omp parallel for collapse(2) schedule(dynamic, 1)
#endif
for (int64_t I = 0; I < ng; ++I)
for (int64_t J = 0; J < ng; ++J) {
if (!H && I != J) continue;
std::vector<double> t1((size_t)(gr * gr), 0.0); /* M_I . H_IJ */
for (int64_t i = 0; i < gr; ++i)
for (int64_t k = 0; k < gr; ++k) {
const double mik = M[(size_t)((I * gr + i) * gr + k)];
if (mik == 0.0) continue;
for (int64_t j = 0; j < gr; ++j) {
const double h = H ? (double)H[(I * gr + k) * K + J * gr + j]
: (k == j ? (double)diag[I * gr + k] : 0.0);
t1[(size_t)(i * gr + j)] += mik * h;
}
}
for (int64_t i = 0; i < gr; ++i)
for (int64_t j = 0; j < gr; ++j) {
double s = 0.0;
for (int64_t k = 0; k < gr; ++k)
s += t1[(size_t)(i * gr + k)] * (double)M[(size_t)((J * gr + j) * gr + k)];
Hv[(size_t)((I * gr + i) * K + J * gr + j)] = (float)s;
}
}
return Hv;
}
int paro_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
int64_t rows, void* const* planes) {
Paro p;
int st = paro_setup(o, n_o, w, &p);
if (st != RAD_OK) return st;
if (row0 != 0 || rows != w->rows) return RAD_E_SHAPE;
const int64_t N = w->rows, K = w->cols;
const char* dir = rad_param_gets(o, n_o, "calib", nullptr);
const int steps = (int)std::max<long long>(0, rad_param_geti(o, n_o, "steps", 200));
const double lr = rad_param_getf(o, n_o, "lr", 0.05);
const int64_t want = std::max<long long>(1, rad_param_geti(o, n_o, "sample_rows", 512));
const int iters = (int)std::max<long long>(0, rad_param_geti(o, n_o, "iters", 100));
/* THE MODEL'S OWN DOMAIN: the grid carries no Hadamard (paroquant_info refuses one), and the
* rotation this fits is applied to the weight and the Hessian here, after the read. */
const Gram Hg = calib_gram(dir, w->name, K, 0, "paroquant");
const float* H = Hg ? Hg->data() : nullptr;
const float* diag = H ? nullptr : w->importance;
if (!H && diag)
std::fprintf(stderr, "libquant: paroquant: '%s' has no Hessian; the imatrix's diagonal "
"stands in for it\n", w->name);
if (!H && !diag)
std::fprintf(stderr, "libquant: paroquant: '%s' has neither a Hessian nor an imatrix; its "
"transform is the identity\n", w->name);
Rot rot;
rot.S = p.stages;
rot.K = K;
rot.pairs = draw_pairs(w->name, p.stages, K, p.gr);
rot.angle.assign((size_t)(p.stages * (K / 2)), 0.0f);
rot.scale.assign((size_t)K, 1.0f);
if ((H || diag) && steps > 0) fit(p, src, N, K, H, diag, steps, lr, want, &rot);
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t r = 0; r < N; ++r) rot.forward(src + r * K);
const Planes pl = grid_planes(p.g, K, planes);
const std::string no = autoround_refusal(p.g);
if ((H || diag) && iters > 0 && !no.empty())
std::fprintf(stderr, "libquant: paroquant: '%s': stage two is AutoRound, and %s; the "
"transformed weight is rounded to nearest\n", w->name, no.c_str());
if ((H || diag) && iters > 0 && no.empty()) {
const std::vector<float> Hv = transformed_hessian(rot, H, diag, K, p.gr);
autoround_rows(p.g, src, N, K, Hv.data(), nullptr, iters, 1.0 / iters, pl);
} else {
st = grid_rtn(p.g, src, 0, N, K, pl, nullptr);
if (st != RAD_OK) return st;
}
const int base = grid_encoding(p.g).n_planes;
std::memcpy(planes[base], rot.scale.data(), rot.scale.size() * sizeof(float));
std::memcpy(planes[base + 1], rot.pairs.data(), rot.pairs.size() * sizeof(int32_t));
std::memcpy(planes[base + 2], rot.angle.data(), rot.angle.size() * sizeof(float));
return RAD_OK;
}
} /* namespace */
const RadQuantizerInfo& paroquant_info() {
static const RadQuantizerInfo q = {
"paroquant",
"pairwise rotation: a channel scaling and rounds of Givens rotations of the input channels, "
"learned against the layer's input Hessian through the straight-through quantiser, then "
"AutoRound on the rotated weight; the transform is the encoding's givens tables",
kParoOptions, (int)(sizeof kParoOptions / sizeof kParoOptions[0]),
paro_encoding, paro_row_block, paro_quantize, nullptr,
};
return q;
}
} /* namespace lq */
+66
View File
@@ -0,0 +1,66 @@
/* lq_quant.h -- what every libquant quantiser shares: the grid's options as a recipe spells them,
* reading a grid off a rule, and the table each algorithm file exports its quantiser through.
*
* lq_registry.cpp holds the plugin's exports and the quantisers that are a few lines each (rtn,
* gptq, cast); an algorithm with a loop of its own (AWQ, AutoRound, ParoQuant) is a file, and its
* RadQuantizerInfo comes back from the function named for it below.
*/
#pragma once
#include "lq_grid.h"
#include <cstdint>
/* The grid options, shared by every quantiser over a grid. */
#define LQ_GRID_OPTIONS \
{ "codes", RAD_P_STR, nullptr, \
"code dtype: i2..i8, i16, i32 (signed, symmetric), u1..u8, u16 with zero= (asymmetric), " \
"fp8_e4m3, fp8_e5m2, fp6_e2m3, fp6_e3m2, fp4_e2m1" }, \
{ "table", RAD_P_STR, nullptr, \
"a codebook the codes index: nf4, iq4nl, w4nl, w5nl, binary, ternary, or values " \
"separated by ;" }, \
{ "group", RAD_P_INT, nullptr, "one scale per this many columns of a row" }, \
{ "block", RAD_P_STR, "1x*", "the scale block RxC, * for a whole extent: 128x128, *x*" }, \
{ "scale", RAD_P_STR, "bf16", \
"scale dtype: f32, bf16, f16, fp8_e4m3, e8m0; under scale2= also u4..u8, i6, i8" }, \
{ "scale2", RAD_P_STR, nullptr, \
"a second scale level the first is relative to: f32, bf16, f16, fp8_e4m3, e8m0" }, \
{ "group2", RAD_P_INT, nullptr, "the second level's block, this many columns of a row" }, \
{ "block2", RAD_P_STR, nullptr, "the second level's block RxC (default *x*, the tensor)" }, \
{ "scale2_value", RAD_P_F64, nullptr, \
"the second level fixed at this value, exact in scale2's dtype, for every block of it" }, \
{ "zero", RAD_P_STR, nullptr, "an integer zero point a block (asymmetric): u8, u4, ..." }, \
{ "transform", RAD_P_STR, nullptr, "fwhtN: rotate each row by the unnormalised Hadamard" }, \
{ "rule", RAD_P_STR, "absmax", \
"absmax | mx (OCP shared exponent) | fixed | search (least squared error, imatrix-" \
"weighted when the converter has one)" }, \
{ "scale_value", RAD_P_F64, nullptr, "the scale every block takes under rule=fixed" }, \
{ "clamp", RAD_P_STR, "full", "a signed code's range: full or sym" }
/* The calibration option every calibrated quantiser takes. */
#define LQ_CALIB_OPTION(WITHOUT) \
{ "calib", RAD_P_STR, nullptr, \
"the directory an engine calibration run wrote (RADIANCE_CALIB_DIR); without one, or for " \
"a weight it holds nothing for, " WITHOUT }
namespace lq {
/* The grid a rule's options describe, checked against the weight; a message on stderr, with the
* weight's name, when it is refused. */
int grid_of(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g);
/* A rank-1 weight -- a norm, a bias -- is declined rather than quantised: nothing in a recipe
* should have to spell out every vector a pattern happens to match. */
inline bool declines(const RadQuantWeight* w) { return !w || w->rank < 2; }
/* Say why a rule is refused, with the weight's name, and return RAD_E_INVAL. */
int refuse(const RadQuantWeight* w, const char* why);
/* A 64-bit hash of a string, for a seed that is the same on every machine and every run. */
uint64_t name_seed(const char* s);
/* The algorithm files' quantisers. */
const RadQuantizerInfo& awq_info();
const RadQuantizerInfo& autoround_info();
const RadQuantizerInfo& paroquant_info();
} /* namespace lq */
+276
View File
@@ -0,0 +1,276 @@
/* lq_registry.cpp -- libquant's quantiser table and plugin exports. spec.md §4.5.
*
* A quantiser here is an ALGORITHM over a GRID (lq_grid.h): `rtn` rounds each value to its nearest
* grid point, `gptq` feeds each column's rounding error into the columns after it, `awq` scales the
* input channels the activations say matter, `autoround` descends on the rounding itself and
* `paroquant` learns a rotation of the input channels first. All of them take the same grid
* options, so a code type, a scale structure or a transform added to the grid is available to each
* the moment it exists. Two are not over a grid: `ggml` writes llama.cpp's own formats by
* llama.cpp's own searches (lq_ggml.h), and `cast` converts a weight to another float dtype.
*/
#include "lq_ggml.h"
#include "lq_gptq.h"
#include "lq_quant.h"
#include "lq_common.h"
#include "rad_plugin.h"
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
namespace lq {
int grid_of(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g) {
std::string why;
const int st = grid_parse(o, n_o, g, &why);
if (st != RAD_OK) {
std::fprintf(stderr, "libquant: %s: %s\n", w && w->name ? w->name : "?", why.c_str());
return st;
}
if (!w || w->cols <= 0 || w->rows <= 0) return RAD_E_SHAPE;
if (g->fwht && w->cols % g->fwht) return RAD_E_SHAPE;
return RAD_OK;
}
int refuse(const RadQuantWeight* w, const char* why) {
std::fprintf(stderr, "libquant: %s: %s\n", w && w->name ? w->name : "?", why);
return RAD_E_INVAL;
}
uint64_t name_seed(const char* s) {
uint64_t h = 0xcbf29ce484222325ull; /* FNV-1a */
for (; s && *s; ++s) h = (h ^ (uint8_t)*s) * 0x100000001b3ull;
return h;
}
} /* namespace lq */
namespace {
using namespace lq;
const RadQuantOption kRtnOptions[] = { LQ_GRID_OPTIONS };
const RadQuantOption kGptqOptions[] = {
LQ_GRID_OPTIONS,
LQ_CALIB_OPTION("every value is rounded to nearest"),
{ "damp", RAD_P_F64, "0.01", "the Hessian's damping, a fraction of its mean diagonal" },
{ "act_order", RAD_P_INT, "0",
"1: quantise the columns by descending input energy, stored in that order with the "
"permutation as the encoding's transform (a kernel permutes its activation to match)" },
{ "cd", RAD_P_INT, "0",
"sweeps of coordinate descent after the loop: every code re-chosen at its conditional "
"optimum against the same damped Hessian, the other columns held (lq_gptq.h)" },
};
const RadQuantOption kCastOptions[] = {
{ "dtype", RAD_P_STR, nullptr,
"the dtype every value is converted to, rounding to nearest even: f32, bf16, f16, "
"fp8_e4m3 (saturating at 448), fp8_e5m2" },
};
/* ------------------------------------------------------------------ rtn */
int rtn_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) {
if (declines(w)) return RAD_E_UNSUPPORTED;
Grid g;
const int st = grid_of(o, n_o, w, &g);
if (st != RAD_OK) return st;
*out = grid_encoding(g);
return RAD_OK;
}
int64_t rtn_row_block(const RadParam* o, int n_o, const RadQuantWeight* w) {
Grid g;
if (grid_of(o, n_o, w, &g) != RAD_OK) return 0;
return grid_row_block(g, w->rows);
}
int rtn_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
int64_t rows, void* const* planes) {
Grid g;
const int st = grid_of(o, n_o, w, &g);
if (st != RAD_OK) return st;
grid_transform_rows(g, src, rows, w->cols);
return grid_rtn(g, src, row0, rows, w->cols, grid_planes(g, w->cols, planes), w->importance);
}
/* ------------------------------------------------------------------ gptq */
/* ACT ORDER IS A TRANSFORM OF THE ENCODING, not a detail of the loop: the codes are stored in the
* order they were quantised, so the scale groups are runs of that order, and the reader is told
* the permutation ("perm", a t.perm table of one i32 a column) to undo it. It does not compose
* with the grid's own rotation -- an encoding carries one transform. */
int gptq_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) {
if (declines(w)) return RAD_E_UNSUPPORTED;
Grid g;
const int st = grid_of(o, n_o, w, &g);
if (st != RAD_OK) return st;
*out = grid_encoding(g);
if (rad_param_geti(o, n_o, "act_order", 0)) {
if (g.fwht) return refuse(w, "act_order=1 and transform= are two transforms, and an "
"encoding carries one");
if (rad_param_geti(o, n_o, "cd", 0))
return refuse(w, "cd= sweeps the columns in their stored order, and act_order=1 "
"stores them permuted; one or the other");
rad_enc_copy_str(out->transform, "perm");
if (rad_enc_add_table(out, "t.perm", RAD_I32, 1, w->cols) < 0)
return refuse(w, "the encoding has no room for the permutation table");
}
return RAD_OK;
}
int64_t whole_weight(const RadParam*, int, const RadQuantWeight*) { return 0; }
int gptq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
int64_t rows, void* const* planes) {
Grid g;
const int st = grid_of(o, n_o, w, &g);
if (st != RAD_OK) return st;
if (row0 != 0 || rows != w->rows) return RAD_E_SHAPE;
const int64_t N = w->rows, K = w->cols;
grid_transform_rows(g, src, N, K);
const char* dir = rad_param_gets(o, n_o, "calib", nullptr);
const double damp = rad_param_getf(o, n_o, "damp", 0.01);
const bool act = rad_param_geti(o, n_o, "act_order", 0) != 0;
std::vector<int32_t> perm;
std::vector<float> imp_p;
const float* imp = w->importance;
if (act) {
perm = gptq_act_order(dir, w->name, K, g.fwht);
std::vector<float> row((size_t)K);
for (int64_t r = 0; r < N; ++r) {
float* wr = src + r * K;
for (int64_t j = 0; j < K; ++j) row[(size_t)j] = wr[perm[(size_t)j]];
std::memcpy(wr, row.data(), (size_t)K * sizeof(float));
}
if (imp) {
imp_p.resize((size_t)K);
for (int64_t j = 0; j < K; ++j) imp_p[(size_t)j] = imp[perm[(size_t)j]];
imp = imp_p.data();
}
}
/* The scales first, from the weight as it stands, and fixed through the loop. */
const Scales sc = grid_scales(g, src, N, K, imp);
const Planes p = grid_planes(g, K, planes);
grid_store_scales(g, sc, p);
const Gram uf = gptq_factor(dir, w->name, K, g.fwht, damp, act ? perm.data() : nullptr);
const float* u = uf ? uf->data() : nullptr;
std::vector<int32_t> codes((size_t)(N * K));
const int cd = (int)rad_param_geti(o, n_o, "cd", 0);
std::vector<float> x0;
if (cd > 0 && u) x0.assign(src, src + (size_t)(N * K));
gptq_quantise(g, src, codes.data(), sc, N, K, u);
if (!x0.empty()) {
const Gram h = calib_gram(dir, w->name, K, g.fwht, "gptq cd");
if (h) gptq_refine(g, x0.data(), src, codes.data(), sc, N, K, h->data(), damp, cd);
}
for (int64_t r = 0; r < N; ++r) {
uint8_t* cr = p.codes + r * p.codes_row;
for (int64_t c = 0; c < K; ++c) grid_store_code(g, cr, c, codes[(size_t)(r * K + c)]);
}
if (act) {
const int tp = grid_encoding(g).n_planes; /* t.perm follows the grid's planes */
std::memcpy(planes[tp], perm.data(), (size_t)K * sizeof(int32_t));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ cast */
/* A FLOAT WEIGHT IN ANOTHER FLOAT DTYPE, rounded to nearest even: an f32 checkpoint served at
* bf16, a bf16 one at f16, or plain fp8 with no scale at all. Every rank is taken, a norm's
* included -- a cast is asked for by name, and a kernel that cannot read the result refuses it at
* declare like any other encoding. */
int cast_dtype(const RadParam* o, int n_o, const RadQuantWeight* w, uint32_t* dt) {
const char* s = rad_param_gets(o, n_o, "dtype", nullptr);
*dt = s ? rad_dtype_parse(s) : (uint32_t)RAD_DT_INVALID;
if (*dt != RAD_F32 && *dt != RAD_BF16 && *dt != RAD_F16 && *dt != RAD_F8E4M3 &&
*dt != RAD_F8E5M2)
return refuse(w, "cast needs dtype= f32, bf16, f16, fp8_e4m3 or fp8_e5m2");
return RAD_OK;
}
int cast_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) {
uint32_t dt = 0;
const int st = cast_dtype(o, n_o, w, &dt);
if (st != RAD_OK) return st;
*out = rad_enc_plain(dt);
return RAD_OK;
}
int64_t cast_row_block(const RadParam*, int, const RadQuantWeight*) { return 1; }
int cast_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
int64_t rows, void* const* planes) {
uint32_t dt = 0;
const int st = cast_dtype(o, n_o, w, &dt);
if (st != RAD_OK) return st;
(void)row0;
const int64_t n = rows * w->cols;
uint8_t* out = (uint8_t*)planes[0];
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
for (int64_t i = 0; i < n; ++i) {
switch (dt) {
case RAD_F32: ((float*)out)[i] = src[i]; break;
case RAD_BF16: ((uint16_t*)out)[i] = f32_to_bf16(src[i]); break;
case RAD_F16: ((uint16_t*)out)[i] = f32_to_f16(src[i]); break;
case RAD_F8E4M3: out[i] = rad_f32_to_fp8e4m3(src[i]); break;
default: out[i] = rad_f32_to_fp8e5m2(src[i]); break;
}
}
return RAD_OK;
}
const RadQuantizerInfo kQuantizers[] = {
{ "rtn",
"round to nearest: every value to its nearest point on the grid, the scale of each block "
"chosen by the grid's rule",
kRtnOptions, (int)(sizeof kRtnOptions / sizeof kRtnOptions[0]),
rtn_encoding, rtn_row_block, rtn_quantize, nullptr },
{ "gptq",
"error feedback against the layer's input Hessian: each column's rounding error is spread "
"over the columns after it, on any grid, the scales fixed from the weight first",
kGptqOptions, (int)(sizeof kGptqOptions / sizeof kGptqOptions[0]),
gptq_encoding, whole_weight, gptq_quantize, nullptr },
{ "cast",
"a float weight converted to another float dtype, to nearest even, with no scale",
kCastOptions, (int)(sizeof kCastOptions / sizeof kCastOptions[0]),
cast_encoding, cast_row_block, cast_quantize, nullptr },
};
/* Every quantiser the plugin offers, in the order --list-quantizers prints them. */
const std::vector<const RadQuantizerInfo*>& table() {
static const std::vector<const RadQuantizerInfo*> t = [] {
std::vector<const RadQuantizerInfo*> v;
for (const RadQuantizerInfo& q : kQuantizers) v.push_back(&q);
v.push_back(&awq_info());
v.push_back(&autoround_info());
v.push_back(&paroquant_info());
v.push_back(&ggml_quantizer);
return v;
}();
return t;
}
const RadPluginInfo kInfo = {
RAD_PLUGIN_QUANT,
"libquant",
"0.2.0",
"the built-in quantisers: round-to-nearest, GPTQ, AWQ, AutoRound and ParoQuant over any "
"integer, float or codebook grid, with grouped, blocked, two-level and shared-exponent scales "
"and a Hadamard, permutation or Givens transform; llama.cpp's legacy, K- and I-quants by its "
"own searches; and a plain float cast (spec.md §4.5)",
"host"
};
} /* namespace */
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
extern "C" int rad_quant_count(void) { return (int)table().size(); }
extern "C" const RadQuantizerInfo* rad_quant_at(int i) {
return (i >= 0 && i < rad_quant_count()) ? table()[(size_t)i] : nullptr;
}