radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+8 -12
View File
@@ -1,11 +1,9 @@
# 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).
# Links rad_abi and nothing else, like every plugin: abi/rad_quant.h is the whole contract, which
# keeps it substitutable by a third-party quantiser.
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S libquant -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(libquant LANGUAGES CXX)
@@ -17,14 +15,12 @@ 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.
# -ffp-contract=off: quantiser output is a stored file, so two builds must produce the same bytes. A
# compiler-chosen FMA can move 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.
# Optional OpenMP over rows (GPTQ and round-to-nearest over large tables are long serial loops).
# Rows are independent, so the result does not depend on the thread count.
find_package(OpenMP QUIET)
if(OpenMP_CXX_FOUND)
target_link_libraries(libquant PRIVATE OpenMP::OpenMP_CXX)
+21 -24
View File
@@ -1,23 +1,21 @@
/* 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.
* Rounding to nearest decides each value alone, but the output error depends on the whole row.
* AutoRound learns a per-value offset V in [-0.5, 0.5], q = round(w / s + V), and per scale block a
* range factor in [0.5, 1] (one for a symmetric block, one per end for an asymmetric one). It
* 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` (default 1/iters) decaying
* linearly to zero. Each row keeps its lowest-error parameters, so the result is never worse than
* the starting point, round-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.
* Error: the Hessian's quadratic form (lq_hess.h) instead of the paper's block output over
* calibration samples. For one linear layer it is the same function of the weight, and it
* decomposes over rows, so each row descends alone: no batch, no sample noise, a row block per
* call. Cost is N K^2 multiply-adds per step, which dominates conversion time at the default 200
* steps; `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.
* Grid: integer codes, symmetric or with a zero, blocks of one row. A codebook or float code has
* no rounding to learn, and a second level or a multi-row block would tie rows together.
*/
#include "lq_autoround.h"
#include "lq_hess.h"
@@ -156,10 +154,10 @@ void autoround_rows(const Grid& g, const float* w, int64_t N, int64_t K, const f
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)
/* Gradients through 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). */
* through s only (the zero is held where the rounding put it). */
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
@@ -198,7 +196,7 @@ void autoround_rows(const Grid& g, const float* w, int64_t N, int64_t K, const f
errors();
keep();
/* ---- the best parameters, written: each block's scale and zero, then the codes */
/* Write the best parameters: each block's scale and zero, then the codes. */
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
#endif
@@ -235,7 +233,7 @@ int ar_grid(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* 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");
if (rad_param_geti(o, n_o, "iters", 200) < 0) return refuse(w, "iters= must be >= 0");
return RAD_OK;
}
@@ -248,8 +246,8 @@ int ar_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding
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. */
/* Rows descend independently, so any block size works; 512 keeps the state to a few hundred MB at
* the widest K while still filling 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,
@@ -257,7 +255,6 @@ int ar_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src,
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);
@@ -269,7 +266,7 @@ int ar_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src,
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 */
/* With no error weighting, round-to-nearest is optimal. */
return grid_rtn(g, src, row0, rows, K, p, nullptr);
}
if (!H)
+3 -3
View File
@@ -10,9 +10,9 @@ namespace lq {
* 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. */
/* Run `iters` descent steps at learning rate `lr` on rows [0, N) of `w` [N, K], already in the
* grid's (transformed) domain, against H (K x K) or, when H is null, the diagonal `diag` (K).
* Writes the resulting scales and codes into `planes` (the grid's). */
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);
+36 -55
View File
@@ -1,30 +1,27 @@
/* 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.
* A few input channels carry most of a layer's activation energy, and a weight column's output
* error scales with its channel's activation. AWQ scales each column up by s_j before quantising,
* so important channels use more of the grid, and the reader scales it back down. s_j = a_j^alpha
* over the channel activation magnitudes a_j, normalised so their geometric middle is one; alpha
* is picked from `alpha_steps` values in [0, 1) by output error. alpha = 0 is plain rounding, so
* the search never does worse. A per-block clip search follows (AWQ's auto_clip): each scale
* block's range is shrunk in steps of 0.05 and the factor with least output error is kept.
*
* 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.
* Output error: the Hessian's quadratic form (lq_hess.h), over `sample_rows` rows for the alpha
* search and over each block's own columns (H restricted to them) for the clip. This is the error
* AWQ measures on calibration activations, without needing them. a_j = sqrt(H_jj), the channel's
* RMS. With no Hessian but an imatrix, the imatrix is the diagonal (a_j = sqrt(importance), error
* diagonal-weighted); with neither, alpha is 0 and only the plain grid remains. Each fallback is
* reported 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.
* The scales are stored, not folded. The reference implementation folds 1/s into the preceding
* norm or projection, which needs the model graph. Here they are the encoding's last scale level,
* a [* x 1] plane with one `colscale`-typed value per column holding the multiplier c_j = 1/s_j.
* The weight is divided by the rounded c_j, so the reader multiplies back exactly what was divided.
*
* NO TRANSFORM: the statistics are of the input's own channels, and a rotated weight's columns are
* not those channels.
* No transform: the statistics describe the input's own channels, which a rotated weight's columns
* are not.
*/
#include "lq_hess.h"
#include "lq_quant.h"
@@ -59,8 +56,8 @@ int awq_grid(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g, uint3
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 refuse(w, "colscale= must be f32, bf16 or f16");
if (rad_param_geti(o, n_o, "alpha_steps", 20) < 1) return refuse(w, "alpha_steps= must be >= 1");
return RAD_OK;
}
@@ -81,14 +78,6 @@ int awq_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodin
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 {
@@ -139,7 +128,7 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src
}
const bool have = err.H || err.diag;
/* the channels' activation magnitudes, floored as AWQ floors them */
/* Channel 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) {
@@ -147,26 +136,17 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src
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. */
/* The sample: whole row blocks of the scale grid, 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;
}
}
std::vector<float> ws;
const int64_t srows = gather_units(src, N, K, unit, pick, &ws);
/* c_j for an exponent: the stored column multiplier, 1 / s_j rounded */
/* c_j for an exponent: the stored column multiplier 1 / s_j, rounded to its dtype. */
auto colscales = [&](double alpha, std::vector<float>* c) {
std::vector<double> s((size_t)K);
double mx = 0.0, mn = 1e300;
@@ -177,10 +157,11 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src
}
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]));
for (int64_t j = 0; j < K; ++j)
(*c)[(size_t)j] = round_to(cdt, (float)(norm / s[(size_t)j]));
};
/* ---- the exponent */
/* Search 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) {
@@ -203,12 +184,12 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src
std::fprintf(stderr, "libquant: awq: '%s' alpha %.3f\n", w->name, (double)best_k / steps);
}
/* ---- the weight in its scaled form, every row */
/* Scale the whole weight. */
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 */
/* Clip search per block: quantise the clamped block and measure the error in 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;
@@ -267,9 +248,9 @@ int awq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src
}
}
/* ---- 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. */
/* Quantise the scaled, clipped weight, then store the column scales. A column's importance in
* the scaled weight is its own times c_j^2, since its error grows by c_j when the reader
* multiplies the column back. */
std::vector<float> imp;
if (w->importance) {
imp.resize((size_t)K);
+34 -25
View File
@@ -1,11 +1,10 @@
/* lq_common.h -- the number conversions every libquant quantiser shares, written out once.
/* lq_common.h -- number conversions shared by every libquant quantiser.
*
* 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.
* These are kept apart from rad_plugin.h's because they are the rules the containers in service
* were quantised with, and reproducing those containers byte for byte needs the same rounding.
* Where a rule here agrees with rad_plugin.h on every finite input, only the NaN result differs;
* where they can disagree (the integer round is half away from zero, the fp4 encoder breaks ties
* toward the even code) the function's comment says so. Each is a pure function of its input.
*/
#pragma once
#include "rad_plugin.h"
@@ -58,9 +57,9 @@ inline uint16_t f32_to_f16(float f) {
}
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. */
/* E4M3-fn: clamp at 448, round to nearest even on the 3-bit mantissa, real subnormals below 2^-6.
* A NaN encodes as a signed zero: a weight is never NaN, and the only other source, a zero scale,
* is never produced by the scale rules. */
inline uint8_t f32_to_e4m3(float f) {
uint32_t bits;
std::memcpy(&bits, &f, 4);
@@ -85,9 +84,9 @@ inline uint8_t f32_to_e4m3(float f) {
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. */
/* FP4 e2m1 by nearest magnitude, ties to the even code. On this grid that is the smaller magnitude
* except at 2.5, which goes to 2.0 (code 4) over 3.0 (code 5), as hardware round-to-nearest-even
* does. */
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;
@@ -101,15 +100,25 @@ inline uint8_t f32_to_e2m1(float v) {
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. */
/* `v` as a bf16, f16 or E4M3 value holds it, widened back; other dtypes pass it through. */
inline float round_to(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));
case RAD_F8E4M3: return rad_fp8e4m3_to_f32(f32_to_e4m3(v));
default: return v;
}
}
/* Any small float grid by exhaustive nearest search over its codes, ties to the even code. Used for
* fp6 and e5m2, where speed does not matter. */
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. */
/* Eight bytes: rad_load_f32 handles dtypes up to 64 bits, and the compiler cannot see that
* `dt` is small. */
uint8_t buf[8] = {};
for (uint32_t c = 0; c < n; ++c) {
buf[0] = (uint8_t)c;
@@ -121,21 +130,21 @@ inline uint32_t f32_to_small_float(float v, uint32_t dt) {
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. */
/* The integer round of every integer grid: half away from zero, by truncating v +- 0.5. The
* containers in service were packed with it. lround should agree on every value an f32 product
* reaches, but this is what is known to reproduce those containers byte for byte. */
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) {
/* Unnormalised Sylvester Walsh-Hadamard transform in place, butterfly a+b low and a-b high: the
* transform an "fwhtN" encoding names and libr4d's r4d_fwht_wave computes. */
template <class T>
inline void fwht_inplace(T* 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];
const T a = v[j], b = v[j + h];
v[j] = a + b;
v[j + h] = a - b;
}
+50 -62
View File
@@ -1,13 +1,12 @@
/* 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.
* column importances as quant_weights, and the resulting GGUF blocks are unpacked into the affine
* planes of rad_encoding.h. A llama.cpp model and a radiance container quantised from the same
* weights and imatrix therefore hold the same numbers, but the container stores a generic encoding
* instead of a block layout tied to one kernel family.
*
* ===================================================================== THE PLANES
* ===================================================================== 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.
@@ -40,32 +39,30 @@
* 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:
* Each 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 IQ2/IQ3 `d*(0.5 + ls)*0.25` is `(2ls+1)*d/8`. Nothing is rounded: every plane holds a block
* value exactly, so the planes convert 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.
* The 1/8 and 1/4 are a per-tensor level, 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 with std 0.02, typical for transformer linears, 98-100% of IQ2 and IQ3_XXS
* super-blocks have d/8 or d/4 below f16's normal range and would lose up to three bits of scale.
* As an f32 [*x*] constant the factor costs four bytes per tensor 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.
* Every product in the decode is exact in f32, so the affine order (code * sub-scale * d, where
* llama.cpp forms d * sub-scale first) reproduces llama.cpp's dequantised values bit for bit. d is
* an f16 with 11 significant bits and a code or grid value times its sub-scale has at most 12
* (q6_K's 31 x 127 and iq4_xs's 127 x 31 are the widest), so no product rounds in either order.
* Only the min subtraction (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 "lq_quant.h"
#include "rad_plugin.h"
#include <cctype>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
@@ -78,10 +75,9 @@ 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. */
/* Writes a plane row front to back, `bits` per element, lowest bits first (rad_encoding.h's bit
* stream). 32 bits go out at a time and the tail on flush(), so each byte is stored exactly once
* and never read back; this does not rely on the row arriving zeroed. */
class Bits {
public:
explicit Bits(uint8_t* row) : p_(row) {}
@@ -115,7 +111,7 @@ inline void put16(uint8_t* row, int64_t i, uint16_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. */
/* Two 4-bit codes per byte, element 2k low; q[] holds a block's codes in value order. */
inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) {
for (int k = 0; k < n / 2; ++k)
row[k] = (uint8_t)((q[2 * k] & 15) | ((q[2 * k + 1] & 15) << 4));
@@ -131,9 +127,9 @@ inline uint16_t iq1_zero(bool negative_delta) { return negative_delta ? 0x3E00 :
/* ================================================================== 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. */
* Each unpack_<type> reads the `nb` blocks of one row and writes plane i's row at row[i]. A TABLE
* or per-tensor plane's slot is null; write_shared writes those once per call. The index
* arithmetic inverts 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;
@@ -233,10 +229,10 @@ void unpack_q3_K(const void* v, int64_t nb, uint8_t* const* row) {
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] */
/* 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 */
/* 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);
@@ -354,8 +350,8 @@ void unpack_iq4_xs(const void* v, int64_t nb, uint8_t* const* row) {
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. */
/* IQ2 and IQ3: a sign byte covers eight values, bit j for value j. That is the u1 plane's own
* order, so a group of eight's signs is 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]);
@@ -435,7 +431,7 @@ void unpack_iq3_s(const void* v, int64_t nb, uint8_t* const* row) {
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] */
/* The ninth bit of 4-group g's grid index 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);
@@ -529,7 +525,7 @@ const Kind kKinds[] = {
{ "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. */
/* The encoding a type writes, plane for plane as listed in the file header. */
RadEncoding encoding_of(ggml_type t) {
RadEncoding e;
rad_enc_clear(&e);
@@ -634,8 +630,8 @@ void fill_grid(uint8_t* out, const W* grid, int n) {
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. */
/* The planes all rows share (a codebook, IQ4's levels, IQ2/IQ3's 1/8 or 1/4). Every call writes
* them in full, 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];
@@ -668,16 +664,11 @@ bool same_name(const char* a, const char* b) {
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. */
/* The type the options name, or RAD_E_INVAL with a message naming the weight. */
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;
}
if (!t)
return refuse(w, "type= is required: the llama.cpp type to write, e.g. q4_K, q8_0, iq4_xs");
for (const Kind& k : kKinds)
if (same_name(t, k.name)) {
*out = &k;
@@ -685,15 +676,14 @@ int kind_of(const RadParam* o, int n_o, const RadQuantWeight* w, const Kind** ou
}
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;
return refuse(w, ("type=" + std::string(t) + " is not a llama.cpp type this quantiser writes (" +
all + ")").c_str());
}
/* 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. */
/* A rank-1 weight, or one whose rows do not divide into the type's blocks, is declined so the next
* rule takes it (a norm, or a 2880-wide projection 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;
if (declines(w)) return RAD_E_UNSUPPORTED;
const Kind* k = nullptr;
const int st = kind_of(o, n_o, w, &k);
if (st != RAD_OK) return st;
@@ -703,7 +693,7 @@ int ggml_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodi
return RAD_OK;
}
/* Rows are independent in every type: a block never spans two, and the imatrix is per column. */
/* Rows are independent in every type: a block never spans rows, 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,
@@ -714,14 +704,12 @@ int ggml_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr
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;
}
/* llama.cpp's iq2_xxs, iq2_xs and iq1_s require the imatrix and have no other path;
* substituting one would write, under llama.cpp's type name, data llama.cpp could not have
* produced. */
if (!w->importance && ggml_quantize_requires_imatrix(k->type))
return refuse(w, ("type=" + std::string(k->name) + " needs an imatrix, and the converter "
"has none for this weight (rad-convert --imatrix FILE)").c_str());
ggml_quantize_init(k->type);
const RadEncoding e = encoding_of(k->type);
+8 -9
View File
@@ -19,10 +19,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* The functions below are ggml/src/ggml-quants.c's at 06938ac12, in that file's order, each under
* a `ggml-quants.c:A-B` marker naming the lines it came from; the conversions and the init
* dispatch at the head and the foot are ggml-impl.h's and ggml.c's. The bodies are left as
* upstream wrote them -- their comments, their spacing, their commented-out lines -- because the
* point of the port is that it can be read against the original line by line.
* a `ggml-quants.c:A-B` marker naming its source lines; the conversions at the head and the init
* dispatch at the foot are ggml-impl.h's and ggml.c's. The bodies keep upstream's comments,
* spacing and commented-out lines so the port can be diffed against the original line by line.
*/
#include "lq_ggml_port.h"
@@ -42,8 +41,8 @@ namespace lq::ggml {
#define GGML_RESTRICT __restrict__
/* ggml.h's assertion, which aborts the process with a message in every build: a broken invariant
* in a quantiser is a corrupt container if it is allowed to continue. */
/* ggml.h's assertion: prints and aborts in every build, since a quantiser that continues past a
* broken invariant writes a corrupt container. */
#define GGML_ABORT(msg) \
do { \
std::fprintf(stderr, "libquant: ggml port: %s:%d: %s\n", __FILE__, __LINE__, msg); \
@@ -4245,9 +4244,9 @@ size_t quantize_iq2_s(const float * GGML_RESTRICT src, void * GGML_RESTRICT dst,
/* ================================================================== ggml.c: ggml_quantize_init
*
* ggml guards the table build with a global critical section and the build itself with an `if
* (grid) return`; one std::once_flag a table does both. IQ1_S and IQ1_M share a table (the same
* lattice and the same neighbour count), and so share a flag. */
* ggml guards the table build with a global critical section plus an `if (grid) return`; here one
* std::once_flag per table does both. IQ1_S and IQ1_M share a table (same lattice and neighbour
* count) and so share a flag. */
void ggml_quantize_init(enum ggml_type type) {
static std::once_flag once_iq2[4];
static std::once_flag once_iq3[2];
+22 -24
View File
@@ -17,11 +17,11 @@
* 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
* ===================================================================== Overview
*
* 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:
* 06938ac12, so that the `ggml` quantiser (lq_ggml.cpp) chooses the same codes and scales as
* llama.cpp for the same weight and 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,
@@ -38,26 +38,24 @@
* 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 numerics match llama.cpp bit for bit: the same float operations in the same order, the same
* f16 rounding, the same `nearest_int` magic-number round and the same qsort comparators, so each
* quantize_<t> writes the bytes llama.cpp writes (pinned in tests/quant_ggml_test.cpp). The port
* departs from upstream only where C++ requires it (a cast from void*), where a library inside a
* converter must (a failed assertion prints to 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
* instead of ggml's critical section; the tables live for the process and are never freed).
*
* 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.
* The match is with llama.cpp as its own build compiles ggml-quants.c: into ggml-base with no
* -march, so without fused multiply-add. libquant's -ffp-contract=off holds the port there on
* every target. A llama.cpp built with FMA contraction (-march=native on x86-64, or any aarch64
* build, where FMA is baseline) 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.
* Each quantize_<t> keeps llama.cpp's dispatch: legacy and K types take the _ref round-to-nearest
* path when `quant_weights` is null and the _impl search otherwise; I types always take _impl,
* and three of them assert `quant_weights` is set (ggml_quantize_requires_imatrix).
* `quant_weights` is the imatrix's per-column importance, n_per_row values shared by every row.
*/
#pragma once
@@ -300,9 +298,9 @@ 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. */
/* Build the search tables an I type needs (the lattice, its index map and each off-grid point's
* nearest neighbours) once per process, on whichever thread asks first; a no-op for other types.
* Every quantize_<t> below requires 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`. */
+3 -3
View File
@@ -19,9 +19,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ggml/src/ggml-common.h at 06938ac12, the GGML_COMMON_IMPL_C tables, verbatim. These are the
* tables llama.cpp's DEquantisers read: an I-quant's grid index means the entry here, which is
* what the `ggml` quantiser copies into an encoding's grid and table planes. The searches build
* their own lattices from the kgrid tables in lq_ggml_port.cpp, in the same index order.
* tables llama.cpp's dequantisers read; the `ggml` quantiser copies them into an encoding's grid
* and table planes. The searches build their own lattices from the kgrid tables in
* lq_ggml_port.cpp, in the same index order.
*/
#include "lq_ggml_port.h"
+29 -30
View File
@@ -16,11 +16,11 @@ 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. */
/* H is damped, inverted and re-factorised into upper 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 et al.'s formulation). Double throughout: a Cholesky is K^3/6 accumulations
* deep, and f32 loses real conditioning on a matrix 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) {
@@ -98,9 +98,8 @@ std::vector<int32_t> gptq_act_order(const char* dir, const char* name, int64_t K
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. */
/* Largest input energy first, ties in column order. The recursion absorbs error best early,
* so the costliest columns are quantised while every later column can still 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];
});
@@ -117,9 +116,8 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d
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. */
/* A layer's factor is shared by its experts, so it is built once under the lock and cached.
* An expert's own is built for its one call outside the lock, so experts factor in parallel. */
Cache& c = cache();
std::unique_lock<std::mutex> lk(c.mu, std::defer_lock);
if (layer) {
@@ -139,8 +137,8 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d
"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. */
/* Under act order the factor is of P H P^T, since the recursion runs over columns in
* quantisation order. */
if (perm) {
std::vector<double> p((size_t)(K * K));
for (int64_t i = 0; i < K; ++i)
@@ -155,9 +153,9 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d
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. */
/* 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. It gets the mean diagonal, so
* the recursion does not 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) {
@@ -206,10 +204,9 @@ void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales
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. */
/* Column blocks outside, rows inside. Rows are independent and are the parallelism, but a row
* running all of K alone would stream all K^2 of `u`. With the block loop outside, all rows
* work on the same columns together and the shared 128 x K slice of `u` 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) {
@@ -226,7 +223,7 @@ void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales
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 */
/* d is U[i][i], strictly positive: 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];
@@ -243,19 +240,21 @@ void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales
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. */
/* Same damping as gptq_factor, so both minimise the same form: lambda is `damp` times the mean
* diagonal, and an unexercised column takes the mean as its diagonal. `ad` is what the form
* adds to H's diagonal, `dg` the resulting 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);
std::vector<float> ad((size_t)K), dg((size_t)K);
for (int64_t i = 0; i < K; ++i) {
const float d = h[(size_t)(i * K + i)];
ad[(size_t)i] = (d > 0.0f ? 0.0f : (float)mean) + lam;
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. */
/* G = E (H + diag(ad)) for all rows by the deterministic blocked product; each row then keeps
* its G current by adding one row of it 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());
@@ -268,7 +267,7 @@ void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const
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 (int64_t j = 0; j < K; ++j) gr[j] += ad[(size_t)j] * er[j];
for (int pass = 0; pass < passes; ++pass) {
int64_t moved = 0;
for (int64_t j = 0; j < K; ++j) {
@@ -280,12 +279,12 @@ void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const
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. */
/* Only a strict improvement moves a code: the form changes by d (2 g_j + d hj),
* g_j the current gradient; 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;
gr[j] += ad[(size_t)j] * d;
er[j] += d;
wr[j] = dq;
cr[j] = c;
+26 -29
View File
@@ -1,20 +1,18 @@
/* 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.
* GPTQ picks the codes one column at a time and pushes each column's rounding error into the
* columns not yet reached, weighted by the inverse Hessian of the layer's real input. Plain
* rounding treats every column as independent, and a 4-bit grid lacks 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.
* This file holds the Hessian and the loop, not the grid: codes are chosen on whatever grid the
* rule names (lq_grid.h), against scales fixed before the loop from the (transformed) weight. This
* "static groups" form 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.
* The Hessian is the expert's own where the tap recorded one, else the layer's (lq_hess.h,
* calib_resolve). A layer's pooled Hessian is found from the weight's logical name with the expert
* index stripped, so its experts share one factor; 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 describes the bootstrap.
*/
#pragma once
#include "lq_grid.h"
@@ -22,18 +20,18 @@
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. */
/* 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 weight `name`. Null when `dir` has no calibration for it (not an error:
* the weight is then rounded to nearest). Also null, with a message, when a file exists but is
* unusable, so a mistyped directory is not a silent quality loss. With `perm` (gptq_act_order's)
* it factors the permuted Hessian P H P^T. `domain` is the grid's transform width, 0 without one
* (calib_sum). A layer's factor is cached for 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. */
/* Act order: columns by descending Hessian diagonal (the input energy each 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
@@ -42,13 +40,12 @@ std::vector<int32_t> gptq_act_order(const char* dir, const char* name, int64_t K
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. */
/* Coordinate descent after the GPTQ loop: `passes` sweeps over each row's columns, re-choosing each
* code at its conditional optimum (the value minimising the row's e (H + lambda I) e^T,
* e = decoded - x, other columns held) against the same damped Hessian. GPTQ fixes each column
* before later ones are known; a sweep revisits it with all in place and never raises the
* objective. `x` [N, K] is the (transformed) weight GPTQ was given, `w` its decoded result,
* updated in place with `codes`. `h` is the undamped Gram (calib_gram's); null means no-op. */
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);
+111 -98
View File
@@ -1,5 +1,5 @@
/* lq_grid.cpp -- parsing a grid, choosing a block's scale, and round-to-nearest on it. See
* lq_grid.h for the options, and for why every rule below is exactly the one it is. */
* lq_grid.h for the options and why the rules must not change. */
#include "lq_grid.h"
#include "lq_common.h"
@@ -44,18 +44,8 @@ bool is_scale_dt(uint32_t dt) {
return dt == RAD_F32 || dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F8E4M3 || dt == RAD_E8M0;
}
/* `v` as the scale dtype holds it, widened back. */
float round_to(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));
case RAD_F8E4M3: return rad_fp8e4m3_to_f32(f32_to_e4m3(v));
default: return v;
}
}
/* The smallest positive value a float scale dtype holds: what a scale that would round to zero
* becomes, so its reciprocal stays finite. */
/* The smallest positive value of a float scale dtype; a scale that would round to zero becomes
* this, so its reciprocal stays finite. */
float tiny_of(uint32_t dt) {
switch (dt) {
case RAD_F16: return 0x1p-24f;
@@ -65,8 +55,8 @@ float tiny_of(uint32_t dt) {
}
}
/* `v` rounded to a float scale dtype, never to zero: the general path's scales are finite and
* nonzero whatever the block held. */
/* `v` rounded to a float scale dtype, never to zero: general-path scales are always finite and
* nonzero. */
float round_nz(uint32_t dt, float v) {
float r = round_to(dt, v);
if (r == 0.0f || !std::isfinite(r)) r = std::copysign(tiny_of(dt), v == 0.0f ? 1.0f : v);
@@ -87,22 +77,20 @@ const std::vector<NamedTable>& named_tables() {
0.7229568362236023f, 1.0f } },
/* llama.cpp's IQ4_NL values: a non-linear 4-bit grid with no zero and unequal ends. */
{ "iq4nl", { -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 } },
/* A Hadamard-rotated weight's own sixteen levels: Lloyd's quantiser fitted to the
* rotated, amax-normalised Qwen3.8-Flash-Next experts, the same in every layer and both
* projections, each level then rounded to the nearest E4M3 value. Every entry is exact in
* E4M3, so libr4d's w4nla8h kernel expands a code to the byte the fp8 WMMA reads with no
* rounding; its table (r4d_args.h, kW4nlTable) is these values in this CODE ORDER --
* magnitudes ascending, then their negatives -- and a container whose table differs is
* refused at load. Against -8..7 under the same searched scale it is ~11% less output
* error at the same bytes. */
/* Sixteen levels for Hadamard-rotated weights: Lloyd's quantiser fitted to the rotated,
* amax-normalised Qwen3.8-Flash-Next experts (the same in every layer and both
* projections), each level rounded to the nearest E4M3 value. Being exact in E4M3, a code
* expands with no rounding to the byte libr4d's w4nla8h fp8 WMMA reads. Its table
* (r4d_args.h, kW4nlTable) holds these values in this code order (magnitudes ascending,
* then their negatives), and a container whose table differs is refused at load. About
* 11% less output error than -8..7 under the same searched scale, at the same bytes. */
{ "w4nl", { 1.125f, 3.25f, 5.5f, 8.0f, 11.0f, 14.0f, 18.0f, 22.0f,
-1.125f, -3.25f, -5.5f, -8.0f, -11.0f, -14.0f, -18.0f, -22.0f } },
/* Its 32-level form, libr4d's w5nl64a8h: Lloyd's quantiser with sixteen magnitudes, fitted
* the same way at groups of 64 -- again the same in every layer and projection -- and
* rounded to E4M3 at the top level that leaves the sixteen distinct and moved least.
* Magnitudes ascending, then their negatives, so a code's high bit is its sign. Against
* w4nl under the same scales, GPTQ and coordinate descent: ~72% less output error energy
* for one more bit a weight. */
/* The 32-level form for libr4d's w5nl64a8h: sixteen magnitudes fitted the same way at
* groups of 64 (again shared by every layer and projection), rounded to E4M3 at the top
* level that keeps all sixteen distinct with least movement. Magnitudes ascending, then
* their negatives, so a code's high bit is its sign. About 72% less output error energy
* than w4nl under the same scales, GPTQ and coordinate descent, for one more bit. */
{ "w5nl", { 0.8125f, 2.5f, 4.0f, 5.5f, 7.5f, 9.0f, 11.0f, 12.0f,
14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 24.0f, 26.0f, 30.0f,
-0.8125f, -2.5f, -4.0f, -5.5f, -7.5f, -9.0f, -11.0f, -12.0f,
@@ -168,7 +156,7 @@ bool l1_int_range(uint32_t dt, int* lo, int* hi) {
/* ------------------------------------------------------------------ one code, the general path */
/* The unit value -- before the scale -- of code `c`. */
/* The unit value (before the scale) of code `c`. */
double unit_of(const Grid& g, int c) {
if (!g.table.empty()) return g.table[(size_t)c];
if (g.is_float) {
@@ -178,7 +166,7 @@ double unit_of(const Grid& g, int c) {
return (double)c;
}
/* The codebook entry nearest `u`, a tie going to the lower value. */
/* The codebook entry nearest `u`, ties to the lower value. */
int nearest_entry(const Grid& g, float u) {
const std::vector<int>& o = g.table_order;
size_t a = 0, b = o.size();
@@ -231,16 +219,14 @@ Fit block_fit(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_t r
return f;
}
/* THE SEARCH, symmetric: a sweep of 21 multiples of the absmax scale from 0.70 to 1.10, and each
* candidate's least-squares refit -- the scale that minimises the error for the codes that
* candidate chose -- every one rounded to the scale dtype before it is judged, unless a second
* level will round it later. What is returned is the best of the 42, unrounded only in that case.
* The sweep is llama.cpp's make_qx_quants idea over any code; the refit is what makes a coarse
* sweep enough.
/* Symmetric search: 21 multiples of the absmax scale from 0.70 to 1.10, plus each candidate's
* least-squares refit (the scale minimising the error for the codes it chose). Each is rounded to
* the scale dtype before being judged, unless a second level will round it later, in which case
* the best is returned unrounded. The sweep is llama.cpp's make_qx_quants idea over any code; the
* refit makes a coarse sweep sufficient.
*
* `t2` IS THE SECOND LEVEL ONCE IT IS KNOWN: every candidate is then judged as it will be stored,
* its first level rounded to the scale dtype relative to t2 (and held inside that dtype's range),
* so the search chooses among the scales a reader can actually decode. */
* `t2` is the second level once known: candidates are then judged as stored, the first level
* rounded relative to t2 and clamped to its dtype's range, so only decodable scales are chosen. */
double search_sym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_t r1, int64_t c0,
int64_t c1, const float* imp, double s0, double t2 = 0.0) {
if (s0 == 0.0) return s0;
@@ -265,9 +251,9 @@ double search_sym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64
return best;
}
/* And asymmetric: both ends of the range pulled in, each to six fractions from 1.00 to 0.80, the
* pair of least error kept. The zero is chosen against each candidate's rounded scale, as the
* absmax rule chooses it. */
/* Asymmetric search: both range ends shrunk to six fractions from 1.00 to 0.80; the pair with
* least error is kept. The zero is chosen against each candidate's rounded scale, as under the
* absmax rule. */
void search_asym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_t r1, int64_t c0,
int64_t c1, const float* imp, float* lo, float* hi) {
const float lo0 = *lo, hi0 = *hi;
@@ -284,6 +270,22 @@ void search_asym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_
}
}
/* A first-level scale as stored under a transform. The plane holds s / N in the scale dtype and the
* reader undoes the transform after multiplying by it, so a code is decoded against N times the
* stored value, and codes are chosen against that. Dividing by N (a power of two) is exact unless
* it leaves the dtype's normal range (an f16 or E4M3 scale in its subnormals, or below them); only
* then does the scale the codes see move, and the stored value is never zero, so a non-empty block
* decodes to something. Without a transform the stored value is the scale itself. */
void store_first_level(const Grid& g, float resid, BlockScale* b) {
b->stored = round_to(g.scale_dt, b->s * resid);
if (resid == 1.0f || b->stored / resid == b->s) return;
if (b->stored == 0.0f) b->stored = round_nz(g.scale_dt, b->s * resid);
b->s = b->stored / resid;
b->inv = 1.0f / b->s;
b->inv_d = 1.0 / (double)b->s;
if (g.asym) b->zero = clampi((int)(-b->lo / b->s + 0.5f), 0, g.qmax);
}
} /* namespace */
int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
@@ -355,7 +357,7 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
g->asym = true;
}
if (tab) {
/* the codebook gave everything an integer code needs */
/* The codebook already set the code dtype. */
} else if (!g->is_float) {
if (g->asym && sgn) {
if (why) *why = fmt("codes=%s is signed; an asymmetric grid's codes are unsigned "
@@ -394,7 +396,7 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
}
}
/* THE SECOND LEVEL first, because it decides which dtypes the first may be. */
/* The second level first, because it decides which dtypes the first may use. */
if (const char* s2 = rad_param_gets(o, n_o, "scale2", nullptr)) {
g->lv2 = true;
g->scale2_dt = rad_dtype_parse(s2);
@@ -477,7 +479,7 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
return RAD_E_INVAL;
}
if (g->lv2) {
/* each second-level block is a whole number of first-level ones */
/* Each second-level block must be a whole number of first-level ones. */
auto nests = [](int64_t b1, int64_t b2) {
if (b1 == 0) return b2 == 0;
return b2 == 0 || b2 % b1 == 0;
@@ -546,8 +548,7 @@ RadEncoding grid_encoding(const Grid& g) {
return e;
}
int64_t grid_row_block(const Grid& g, int64_t rows) {
(void)rows;
int64_t grid_row_block(const Grid& g) {
if (g.lv2) return g.br2; /* a multiple of the first level's, or 0 */
if (g.br > 0) return g.br;
return g.rule == Grid::FIXED ? 1 : 0;
@@ -559,10 +560,9 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
const float resid = g.fwht ? 1.0f / (float)g.fwht : 1.0f;
if (g.rule == Grid::FIXED) {
/* THE RECIPROCAL IS THE UNROUNDED VALUE'S, IN DOUBLE, and the stored scale is the value
* rounded. That is the n-gram table's rule, whose scale was chosen to be exact in bf16 --
* so the two agree there, and a value that is not exact is quantised against what was
* asked rather than against its rounding. */
/* The reciprocal is of the unrounded value, in double; the stored scale is the rounded
* value. This is the n-gram table's rule, whose scale is exact in bf16 so the two agree;
* an inexact value is quantised against what was asked, not its rounding. */
b.s = round_to(g.scale_dt, (float)g.fixed);
b.inv_d = 1.0 / g.fixed;
b.inv = (float)b.inv_d;
@@ -571,10 +571,10 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
}
if (g.general()) {
/* THE GENERAL PATH. The ideal scale of the block for its code -- signed for a codebook
* whose ends are not mirror images -- searched when the rule says so, then rounded to
* the scale dtype and never to zero. Under a second level it is returned unrounded, and
* grid_scales rounds it relative to that level. */
/* General path: the block's ideal scale for its code (signed for a codebook with unequal
* ends), searched under rule=search, then rounded to the scale dtype, never to zero.
* Under a second level it is returned unrounded and grid_scales rounds it relative to
* that level. */
if (g.asym) {
float lo = 0.0f, hi = 0.0f;
for (int64_t r = r0; r < r1; ++r)
@@ -592,7 +592,8 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
b.inv = 1.0f / b.s;
b.inv_d = 1.0 / (double)b.s;
b.zero = clampi((int)(-lo / b.s + 0.5f), 0, g.qmax);
b.stored = g.lv2 ? b.s : round_to(g.scale_dt, b.s * resid);
if (g.lv2) b.stored = b.s;
else store_first_level(g, resid, &b);
return b;
}
float amax = 0.0f, peak = 0.0f;
@@ -611,15 +612,16 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
b.s = g.lv2 ? (float)s0 : round_nz(g.scale_dt, (float)s0);
b.inv = b.s != 0.0f ? 1.0f / b.s : 0.0f;
b.inv_d = b.s != 0.0f ? 1.0 / (double)b.s : 0.0;
b.stored = g.lv2 ? b.s : round_to(g.scale_dt, b.s * resid);
if (g.lv2) b.stored = b.s;
else store_first_level(g, resid, &b);
return b;
}
if (g.asym) {
/* [lo, hi] widened to include 0, so a block of all-positive weights still has an exact
* zero; the scale spans it in (levels - 1) steps, is rounded to its dtype, and the integer
* zero is chosen against the ROUNDED scale -- which is what makes (code - zero) * scale
* decode to the grid point the code was chosen as. */
/* [lo, hi] is widened to include 0 so an all-positive block still has an exact zero. The
* scale spans it in (levels - 1) steps and is rounded to its dtype; the integer zero is
* chosen against the rounded scale, so (code - zero) * scale decodes to the grid point the
* code was chosen as. */
float lo = 0.0f, hi = 0.0f;
bool first = true;
for (int64_t r = r0; r < r1; ++r)
@@ -633,10 +635,11 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
if (hi < 0.0f) hi = 0.0f;
float s = (hi - lo) / (float)(g.qmax);
if (!(s > 0.0f)) s = 1e-12f;
b.lo = lo;
b.s = round_to(g.scale_dt, s);
b.inv = 1.0f / b.s;
b.zero = clampi((int)(-lo / b.s + 0.5f), 0, g.qmax);
b.stored = round_to(g.scale_dt, b.s * resid);
store_first_level(g, resid, &b);
return b;
}
@@ -649,9 +652,9 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
}
if (g.rule == Grid::MX) {
/* THE OCP RULE, SATURATION INCLUDED: X = 2^(floor(log2 amax) - emax), so amax / X lands in
/* The OCP rule, saturation included: X = 2^(floor(log2 amax) - emax), so amax / X lands in
* [2^emax, 2^(emax+1)) and the top of that range saturates to the code's largest value.
* Bumping the exponent would double the step for every other element to save one. */
* Bumping the exponent instead would double the step for every other element. */
int exp = -127;
if (amax > 0.0f) {
uint32_t u;
@@ -659,34 +662,44 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
exp = (int)((u >> 23) & 0xFFu) - 127 - g.emax;
}
b.e8 = clampi(exp + 127, 0, 254);
/* 2^-(e8 - 127) in the exponent field, exact and with no libm call */
/* 2^-(e8 - 127) built in the exponent field: exact, no libm call. */
const uint32_t ui = (uint32_t)clampi(254 - b.e8, 1, 254) << 23;
std::memcpy(&b.inv, &ui, 4);
b.inv_d = b.inv;
b.s = rad_e8m0_to_f32((uint8_t)b.e8);
b.stored = b.s;
if (g.fwht) {
/* The exponent stored is the transform's order lower, exactly; codes are chosen
* against N times it, which differs only where the exponent's floor clamps it. */
int sh = 0;
while (((int64_t)1 << sh) < g.fwht) ++sh;
b.e8 = clampi(b.e8 - sh, 0, 254);
b.stored = rad_e8m0_to_f32((uint8_t)b.e8);
b.s = b.stored * (float)g.fwht;
b.inv = 1.0f / b.s;
b.inv_d = b.inv;
}
return b;
}
if (g.is_float) {
/* A BLOCK OF ZEROS IS SCALED BY ONE, so its reciprocal is finite and its codes are zero.
* The quotient is formed by multiplying by 1/fmax when the scale is narrower than f32 and
* by dividing when it is f32 -- the two forms the block-fp8 linears and the fp8 hyper-
* connection rows were each quantised with, which differ in the last place of the f32 and
* can therefore round a narrow scale differently. */
/* An all-zero block gets scale 1, so its reciprocal is finite and its codes zero. The
* quotient multiplies by 1/fmax for a scale narrower than f32 and divides for f32: the
* forms the block-fp8 linears and the fp8 hyper-connection rows were quantised with. They
* differ in the last f32 place and can round a narrow scale differently. */
float s = 1.0f;
if (amax > 0.0f) s = g.scale_dt == RAD_F32 ? amax / g.fmax : amax * (1.0f / g.fmax);
b.s = round_to(g.scale_dt, s);
b.inv = 1.0f / b.s;
} else {
/* A BLOCK OF ZEROS GETS 1e-12, whose reciprocal is finite and whose codes are zero. */
/* An all-zero block gets 1e-12: finite reciprocal, zero codes. */
float s = amax / (float)g.qmax;
if (!(s > 0.0f)) s = 1e-12f;
b.s = round_to(g.scale_dt, s);
b.inv = 1.0f / b.s;
}
b.inv_d = b.inv;
b.stored = round_to(g.scale_dt, b.s * resid);
store_first_level(g, resid, &b);
return b;
}
@@ -786,14 +799,13 @@ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, co
}
if (!g.lv2) return s;
/* THE SECOND LEVEL. Each of its blocks takes the largest first-level magnitude under it over
* the largest value the first level's dtype holds -- so the widest block's sub-scale is the
* dtype's top and every other one is a fraction of it -- rounded to its own dtype (up to a
* power of two for e8m0, which may not round down past the top). Each first-level scale is
* then stored relative to it: rounded half away for an integer sub-scale, to nearest even for
* a float one, and never to zero for a block that held anything, which would decode it to
* nothing. The codes are chosen against the product, as a reader multiplies it. The
* transform's 1/N goes to the second level. */
/* Second level: each block takes the largest first-level magnitude under it divided by the
* first level's dtype maximum, so the widest sub-scale sits at the dtype's top. It is rounded
* to its own dtype (up to a power of two for e8m0, so it never rounds down past the top).
* Each first-level scale is then stored relative to it: half away from zero for an integer
* sub-scale, nearest even for a float one, and never zero for a non-empty block (which would
* decode to nothing). Codes are chosen against the product, as the reader multiplies it. The
* transform's 1/N goes into the second level. */
const int64_t br2 = g.br2 > 0 ? g.br2 : rows, bc2 = g.bc2 > 0 ? g.bc2 : cols;
s.nr2 = (rows + br2 - 1) / br2;
s.nc2 = (cols + bc2 - 1) / bc2;
@@ -807,8 +819,8 @@ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, co
s.s2.resize(peak.size());
for (size_t k = 0; k < peak.size(); ++k) {
if (g.fixed2 > 0.0) {
/* FIXED: the stored value is the one asked for, and the level the first is relative to
* is that over the transform's residual -- what the reader's product undoes. */
/* Fixed: store the requested value; the first level is relative to it divided by the
* transform's residual, which the reader's product undoes. */
s.s2[k] = (float)g.fixed2;
s2r[k] = (float)(g.fixed2 / (double)resid);
continue;
@@ -826,11 +838,13 @@ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, co
s2r[k] = round_nz(g.scale2_dt, v);
s.s2[k] = round_nz(g.scale2_dt, s2r[k] * resid);
}
/* As for a first level alone (store_first_level): the first level is taken relative to
* what the reader multiplies by, which is N times the stored second level. */
s2r[k] = s.s2[k] / resid;
}
/* A SEARCHED FLOAT FIRST LEVEL IS SEARCHED AGAIN, now that its second level is known, over the
* candidates as they will be stored: an E4M3 sub-scale moves by up to 1/16 when it is rounded,
* which is most of what the first search won. The second level stays where the first search's
* peaks put it. */
/* A searched float first level is searched again against the now-known second level, over
* candidates as stored: rounding moves an E4M3 sub-scale by up to 1/16, most of what the first
* search gained. The second level stays where the first search's peaks put it. */
if (g.rule == Grid::SEARCH && !g.l1_int && !g.asym) {
#ifdef _OPENMP
#pragma omp parallel for schedule(dynamic, 1) if (s.nr * s.nc > 64)
@@ -867,8 +881,8 @@ Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, co
b.inv_d = 1.0 / (double)b.s;
if (g.asym) b.zero = clampi((int)(-b.lo / b.s + 0.5f), 0, g.qmax);
}
/* Only a fixed second level can put a first-level scale past its dtype's top: a derived one
* maps the largest under it to the top by construction. */
/* Only a fixed second level can push a first-level scale past its dtype's top; a derived one
* maps the largest under it exactly to the top. */
if (held)
std::fprintf(stderr, "libquant: %lld of %lld scales sat past %s's top under scale2_value=%g "
"and were held there\n", (long long)held, (long long)(s.nr * s.nc),
@@ -927,14 +941,14 @@ BlockScale grid_finish(const Grid& g, double s, float lo) {
b.inv = 1.0f / b.s;
b.inv_d = 1.0 / (double)b.s;
if (g.asym) b.zero = clampi((int)(-lo / b.s + 0.5f), 0, g.qmax);
b.stored = round_to(g.scale_dt, b.s * resid);
store_first_level(g, resid, &b);
return b;
}
int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t cols,
const Planes& p, const float* imp) {
if (g.general()) {
const int64_t rb = grid_row_block(g, rows);
const int64_t rb = grid_row_block(g);
if (rb > 0 && row0 % rb) return RAD_E_SHAPE;
const Scales sc = grid_scales(g, w, rows, cols, imp);
grid_store_scales(g, sc, p);
@@ -953,8 +967,8 @@ int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t
const int64_t bc = g.bc > 0 ? g.bc : cols;
if (g.br > 0 && row0 % g.br) return RAD_E_SHAPE;
const int64_t nband = (rows + br - 1) / br;
/* A fixed scale over the whole extent is one element, written once rather than by every band
* at once. */
/* A fixed scale over the whole extent is one element, written once here rather than by every
* band concurrently. */
const bool one_scale = g.br == 0;
const bool int4 = g.codes == RAD_I4 && !g.is_float && !g.asym && g.rule != Grid::FIXED &&
g.rule != Grid::MX;
@@ -967,7 +981,7 @@ int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t
#endif
for (int64_t band = 0; band < nband; ++band) {
const int64_t r0 = band * br, r1 = r0 + br < rows ? r0 + br : rows;
/* the scale plane's row for this band, relative to the call's first */
/* The scale plane's row for this band, relative to the call's first. */
const int64_t srow = g.br > 0 ? band : 0;
uint8_t* sr = p.scale + srow * p.scale_row;
uint8_t* zr = p.zero ? p.zero + srow * p.zero_row : nullptr;
@@ -975,9 +989,9 @@ int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t
const int64_t c1 = c0 + bc < cols ? c0 + bc : cols;
const BlockScale b = grid_block_scale(g, w, cols, r0, r1, c0, c1);
if (!(one_scale && g.rule == Grid::FIXED)) grid_store_scale(g, b, sr, zr, j);
/* SYMMETRIC INT4 OVER AN EVEN SPAN, two codes a byte: grid_code's arithmetic for this
* grid without its per-element branches, and a byte written whole instead of a
* nibble read, masked and written back. Every routed expert of a w4 model is this. */
/* Fast path for symmetric int4 over an even span (every routed expert of a w4 model):
* grid_code's arithmetic without per-element branches, two codes written as one whole
* byte instead of a nibble read-modify-write. */
if (int4 && !(c0 & 1) && !((c1 - c0) & 1)) {
for (int64_t r = r0; r < r1; ++r) {
uint8_t* cr = p.codes + r * p.codes_row;
@@ -997,7 +1011,6 @@ int grid_rtn(const Grid& g, const float* w, int64_t row0, int64_t rows, int64_t
}
}
}
(void)row0;
return RAD_OK;
}
+30 -33
View File
@@ -1,17 +1,16 @@
/* lq_grid.h -- a quantisation GRID: what codes a weight may take and how its scales sit over it.
/* lq_grid.h -- a quantisation grid: the 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.
* libquant separates three things a recipe names independently (spec.md §4.5): the grid (code type
* plus the scale, zero and transform structure around it); the algorithm that picks codes on it
* (round-to-nearest, GPTQ, AWQ, ...); and the stored encoding, which follows from the grid alone.
* Every algorithm takes the same grid options.
*
* 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
* 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),
@@ -22,14 +21,13 @@
* (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.
* 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 per [1 x 16] and an f32 scale2 per tensor.
* scale2_value=X the second level fixed at X for all its blocks instead of derived from the
* largest first-level scale under it; must be exact in scale2=. For E4M3
* sub-scales over a model whose scales fit E4M3's range, only a known offset is
* needed (libr4d's w4nl64a8h experts). A first-level value it would push past its
* dtype's top is clamped there, reported 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.
@@ -43,12 +41,11 @@
* 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.
* The rules are exactly those the containers in service were made with (the order of a division,
* which number is rounded to the scale dtype before codes are chosen, what an all-zero block gets),
* so a recipe reproduces those containers byte for byte. Each is stated where it is implemented.
* Forms no container in service uses (a codebook, a second level, rule=search, 16- and 32-bit
* codes) take a separate general path, which leaves those rules untouched.
*/
#pragma once
#include "rad_quant.h"
@@ -97,7 +94,7 @@ struct Grid {
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)? */
/* Whether this grid takes the general path (see the file header). */
bool general() const { return lv2 || rule == SEARCH || !table.empty() || wide; }
};
@@ -109,7 +106,7 @@ 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);
int64_t grid_row_block(const Grid& g);
/* One block's quantiser state: the scale the codes are chosen against, its stored form, the
* reciprocal, and for an asymmetric grid the zero. */
@@ -119,8 +116,8 @@ struct BlockScale {
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 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 */
};
@@ -167,9 +164,9 @@ struct Scales {
}
};
/* 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. */
/* The whole scale grid of rows [0, rows) of `w`, without choosing codes: what round-to-nearest and
* the static-groups form of an error-feedback algorithm quantise 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);
@@ -179,14 +176,14 @@ 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. */
/* Quantise and decode rows [0, rows) of `w` into `out` [rows, cols]: the weight a reader would see,
* for algorithms that measure 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. */
/* A block's state from an unrounded scale `s` and the asymmetric low end `lo` the zero is taken
* against, rounded as the general path rounds. For algorithms that choose the scale themselves;
* not for grids with a second level, which have their own pass. */
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
+33 -39
View File
@@ -1,5 +1,6 @@
/* lq_hess.cpp -- reading the calibration Hessians, and D . H. See lq_hess.h. */
#include "lq_hess.h"
#include "lq_common.h"
#include <algorithm>
#include <cstdio>
@@ -15,21 +16,21 @@ namespace {
* calibration tap writes (arch/common/rad_arch.h, calib_write). The header is 32 bytes. */
constexpr int kHdr = 32;
/* One file per rank, ranks 0 .. kMaxRanks - 1. */
constexpr int kMaxRanks = 16;
std::string gram_path(const char* dir, int rank, const std::string& stem) {
return std::string(dir) + "/gram.r" + std::to_string(rank) + "." + stem + ".bin";
}
/* 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;
}
for (int64_t b0 = 0; b0 < k; b0 += n) fwht_inplace(v + b0, n);
}
/* 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. */
* symmetric, so the column pass is the row pass over the transpose; the result stays bit-exactly
* symmetric only because both passes run 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);
@@ -58,8 +59,8 @@ bool read_gram(const std::string& path, int64_t k, int64_t domain, std::vector<d
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. */
/* Domains convert only through the model's own (domain 0): a file rotated at one width is
* rotated back before rotating to another. Both widths must 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)) {
@@ -84,9 +85,9 @@ bool read_gram(const std::string& path, int64_t k, int64_t domain, std::vector<d
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. */
/* Round to f32, as a tap in that domain would have stored it, so a converted Hessian
* matches one summed there and 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);
@@ -94,13 +95,11 @@ bool read_gram(const std::string& path, int64_t k, int64_t domain, std::vector<d
return true;
}
/* The rows every rank's file for `stem` says it summed, or -1 when `dir` holds none. */
/* The total rows summed by every rank's file for `stem`, 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");
for (int r = 0; r < kMaxRanks; ++r) {
FILE* f = std::fopen(gram_path(dir, r, stem).c_str(), "rb");
if (!f) continue;
char hdr[kHdr];
if (std::fread(hdr, 1, kHdr, f) == (size_t)kHdr && std::memcmp(hdr, "RADGRAM2", 8) == 0) {
@@ -134,14 +133,12 @@ GramCache& gram_cache() {
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. */
/* A panel is CB columns of H over all K rows, packed into a K x CB buffer so each k step reads one
* contiguous line instead of striding K floats; this keeps the product compute-bound (3-5x faster
* than unpacked). A row block is RB rows of D held as RB*CB register accumulators: 8 x 32 under
* AVX-512 and 4 x 16 under AVX2 use sixteen and eight vector registers. Each accumulator sums k in
* ascending order and is stored once, so panel, block and instruction set change the schedule, not
* any sum. Both functions are forced inline so each compiles under its caller's target ISA. */
template <int RB, int CB>
__attribute__((always_inline)) inline void panel(const float* D, int64_t K, const float* P,
float* G) {
@@ -169,7 +166,7 @@ __attribute__((always_inline)) inline void task(const float* D, int64_t K, const
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. */
/* The edges the blocks leave, one element at a time in the same k 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)
@@ -238,16 +235,13 @@ std::string calib_stem(const char* name) {
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. */
/* Sum every rank's file. Under expert parallelism a rank's `down` Hessian covers only tokens
* routed to its own experts, so no single file holds the layer's distribution. The gate_up
* files are duplicated across ranks; summing them scales H by the rank count, which every
* algorithm here is invariant to. */
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;
}
for (int r = 0; r < kMaxRanks; ++r)
if (read_gram(gram_path(dir, r, stem), K, domain, acc)) ++found;
return found;
}
@@ -303,7 +297,7 @@ void mat_hess(const float* D, int64_t R, int64_t K, const float* H, float* G) {
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 */
/* 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)
+38 -40
View File
@@ -1,27 +1,27 @@
/* lq_hess.h -- the calibration Hessians every calibrated quantiser reads, and the one product they
* all spend their time in.
/* lq_hess.h -- the calibration Hessians the calibrated quantisers read, and the product they 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
* 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 each file records its domain: the model's own activation (domain 0),
* or that activation rotated block by block by the unnormalised Hadamard of width N (domain N),
* which is what a container storing rotated weights multiplies. A reader asks for its grid's
* transform domain and each file is converted before the sum: rotating is H -> F H F, and back is
* the same divided by N^2 (F is its own inverse up to N). So calibration from a bf16 model and from
* a rotated 4-bit container both serve a rotated recipe.
*
* A layer-local quantiser's error is 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.
* which decomposes over rows: rows share H and nothing else. GPTQ, AWQ's scale search, AutoRound's
* rounding descent and ParoQuant's rotation fit all minimise it; the last three spend their time
* in D . H (mat_hess).
*
* 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.
* The most specific Hessian available is used: a routed expert's own when the tap recorded one (it
* does for `down`, whose input is the expert's own intermediate units), else the layer's, pooled
* over its experts and found from the name with the expert index stripped (calib_stem). A layer's
* experts share that one and the process reads it once.
*/
#pragma once
#include <cstdint>
@@ -31,42 +31,40 @@
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. */
/* A Hessian or a factor of one. Shared, so an uncached one (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. */
/* 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 its rank files together hold at least kOwnRowsPerK * K rows,
* else calib_stem's, noted on stderr. A GPTQ fit to a Gram of few rows overfits them: on
* Qwen3.8-Flash-Next's down projection an expert's own Gram cuts held-out output error by 20-55%
* versus the pooled one, except for experts routed under ~2K rows, where it is worse than
* round-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. */
/* Every rank's file for `stem` in `dir`, each converted into `domain` (0, or the Hadamard width a
* rotated grid quantises in), summed into `acc` (K x K, double, row-major). Returns the number of
* files read, 0 when there are none. A file that exists but is unusable (wrong magic, wrong K,
* short, or a domain that cannot be converted) is reported 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. */
* when `dir` holds none (noted once on stderr). A layer's is cached for the process by (dir, stem,
* K, domain); an expert's own is read per call, 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. */
/* G [R x K] = D [R x K] . H [K x K], H symmetric. Each element of G sums over k in ascending order
* regardless of thread count and vector width, so the result depends on the inputs alone: two
* converts of the same weight must write the same file. 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. */
+41 -53
View File
@@ -1,34 +1,32 @@
/* 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.
* 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 within one group of `rot_group` channels)
* so a group's values even out, and learns the angles and 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 scales, pairs and 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.
* Stage one fits the transform with Adam at `lr` (cosine-decayed to lr/20, no weight decay) over
* `steps` steps, each on the next `sample_rows` rows; angles start at zero and scales at one, as in
* the paper. Each step quantises through the grid and the gradient reaches the transform by the
* straight-through estimator: w_hat = w + E T^-1 with the quantisation error E held, so a step
* moves T^-1 to send E where the input does not look.
* Stage two replaces the paper's fine-tuning of rounding and scales with AutoRound
* (lq_autoround.h) on the transformed weight against T^-1 H T^-T, for `iters` steps; 0 rounds the
* transformed weight 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.
* Pairs are drawn at random within each rotation group: a channel is paired at most once per stage
* and, where the group allows, a pair is used at most once over all stages (the paper's diverse
* independent rotations). The generator is seeded by the weight's name, so converts are repeatable.
*
* 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.
* Output error: the Hessian's quadratic form (lq_hess.h) in the weight's own domain, the
* layer-local form of the paper's loss; with no Hessian but an imatrix, its diagonal. With neither,
* the transform stays the identity (reported on stderr).
*
* 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.
* Determinism: gradients are summed over rows in row order regardless of thread count, so the
* stored file depends only on the weight and the calibration.
*/
#include "lq_autoround.h"
#include "lq_hess.h"
@@ -73,10 +71,10 @@ int paro_setup(const RadParam* o, int n_o, const RadQuantWeight* w, Paro* p) {
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");
if (p->stages < 1 || p->stages > 64) return refuse(w, "stages= must be 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 (p->gr < 2 || (p->gr & 1)) return refuse(w, "rot_group= must be 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 "
@@ -109,7 +107,7 @@ uint64_t splitmix(uint64_t* s) {
return z ^ (z >> 31);
}
/* The pairs: [stages x K], stage s pairing columns (pairs[s][2p], pairs[s][2p+1]). */
/* The pairs, [stages x K]: stage s pairs columns pairs[s][2p] and 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) {
@@ -127,7 +125,7 @@ std::vector<int32_t> draw_pairs(const char* name, int stages, int64_t K, int64_t
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 */
for (int64_t y = x + 1; y < gr && b < 0; ++y) { /* an unused pair */
const int c = order[(size_t)y];
if (!paired[(size_t)c] && !used[(size_t)(a * gr + c)]) b = c;
}
@@ -152,7 +150,7 @@ struct Rot {
std::vector<float> angle; /* [S x K/2] */
std::vector<float> scale; /* [K] */
/* v = w . D . G_1 ... G_S, in place */
/* 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)
@@ -164,8 +162,8 @@ struct Rot {
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`. */
/* y = e . T^-1, keeping every intermediate in ys[k] (after the k-th inverse stage; k = 0 is
* e). The result, divided by the scales, goes to `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) {
@@ -195,7 +193,7 @@ void err_grad(const float* D, int64_t R, int64_t K, const float* H, const float*
for (int64_t k = 0; k < K; ++k) G[r * K + k] = D[r * K + k] * diag[k];
}
/* STAGE ONE. */
/* Stage one: fit the transform. */
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;
@@ -210,22 +208,12 @@ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, co
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 */
/* This step's rows: the next `take` row 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;
}
}
const int64_t R = gather_units(w, N, K, unit, us, &ws);
vs = ws;
#ifdef _OPENMP
#pragma omp parallel for schedule(static)
@@ -252,8 +240,8 @@ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, co
}
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
/* Backward pass, one 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
@@ -286,7 +274,7 @@ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, co
}
}
}
/* the sum over rows, in row order, and the Adam step on it */
/* Sum over rows in row order, then take the Adam step. */
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
@@ -312,9 +300,9 @@ void fit(const Paro& p, const float* w, int64_t N, int64_t K, const float* H, co
}
}
/* 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. */
/* T^-1 H T^-T by rotation group. T^-1 is block-diagonal over the groups, so its rows are formed
* once by sending each unit vector through the inverse, and each block of H is multiplied by them
* on both sides. */
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;
@@ -371,8 +359,8 @@ int paro_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr
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. */
/* Domain 0: the grid carries no Hadamard (paro_setup refuses one), and the fitted rotation 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;
+26 -7
View File
@@ -1,14 +1,17 @@
/* 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_quant.h -- shared by every libquant quantiser: the grid options a recipe spells, 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.
* lq_registry.cpp holds the plugin's exports and the short quantisers (rtn, gptq, cast). An
* algorithm with its own loop (AWQ, AutoRound, ParoQuant) has its own file and returns its
* RadQuantizerInfo from the function named for it below.
*/
#pragma once
#include "lq_grid.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <vector>
/* The grid options, shared by every quantiser over a grid. */
#define LQ_GRID_OPTIONS \
@@ -48,8 +51,8 @@ namespace lq {
* 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. */
/* Rank-1 weights (norms, biases) are declined rather than quantised, so a recipe pattern need not
* exclude every vector it 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. */
@@ -58,6 +61,22 @@ 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 rows of `w` [N, K] in the listed row units of `unit` rows each (the last unit may be short),
* packed in list order into `out`. Returns the row count. */
inline int64_t gather_units(const float* w, int64_t N, int64_t K, int64_t unit,
const std::vector<int64_t>& units, std::vector<float>* out) {
int64_t rows = 0;
for (int64_t u : units) rows += std::min(unit, N - u * unit);
out->resize((size_t)(rows * K));
int64_t at = 0;
for (int64_t u : units) {
const int64_t n = std::min(unit, N - u * unit);
std::memcpy(out->data() + at * K, w + u * unit * K, (size_t)(n * K) * sizeof(float));
at += n;
}
return rows;
}
/* The algorithm files' quantisers. */
const RadQuantizerInfo& awq_info();
const RadQuantizerInfo& autoround_info();
+25 -31
View File
@@ -1,11 +1,10 @@
/* 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
* Most quantisers are 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 later columns, `awq` scales the input
* channels the activations say matter, `autoround` descends on the rounding itself and `paroquant`
* first learns a rotation of the input channels. They share the grid options, so anything added to
* the grid is available to all. Two are not over a grid: `ggml` writes llama.cpp's formats by
* llama.cpp's own searches (lq_ggml.h), and `cast` converts a weight to another float dtype.
*/
#include "lq_ggml.h"
@@ -23,11 +22,7 @@ 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 (grid_parse(o, n_o, g, &why) != RAD_OK) return refuse(w, why.c_str());
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;
@@ -81,7 +76,7 @@ int rtn_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodin
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);
return grid_row_block(g);
}
int rtn_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
@@ -94,10 +89,10 @@ int rtn_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src
}
/* ------------------------------------------------------------------ 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. */
/* Act order is a transform of the encoding: codes are stored in quantisation order, so scale
* groups are runs of that order, and the reader gets the permutation ("perm", a t.perm table of one
* i32 per column) to undo it. It cannot combine with the grid's rotation, since 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;
@@ -149,7 +144,7 @@ int gptq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr
}
}
/* The scales first, from the weight as it stands, and fixed through the loop. */
/* Scales come first, from the weight as it stands, and stay 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);
@@ -178,10 +173,9 @@ int gptq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr
}
/* ------------------------------------------------------------------ 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. */
/* A float weight in another float dtype, round to nearest even: an f32 checkpoint served as bf16,
* bf16 as f16, or plain unscaled fp8. Every rank is accepted, norms included: a cast is requested 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;
@@ -201,25 +195,25 @@ int cast_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodi
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,
int cast_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t,
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];
auto each = [n](auto store) {
#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;
}
for (int64_t i = 0; i < n; ++i) store(i);
};
switch (dt) {
case RAD_F32: std::memcpy(out, src, (size_t)n * sizeof(float)); break;
case RAD_BF16: each([&](int64_t i) { ((uint16_t*)out)[i] = f32_to_bf16(src[i]); }); break;
case RAD_F16: each([&](int64_t i) { ((uint16_t*)out)[i] = f32_to_f16(src[i]); }); break;
case RAD_F8E4M3: each([&](int64_t i) { out[i] = rad_f32_to_fp8e4m3(src[i]); }); break;
default: each([&](int64_t i) { out[i] = rad_f32_to_fp8e5m2(src[i]); }); break;
}
return RAD_OK;
}