Archived
radiance 1.15.0
New models and formats: - IQR for Qwen3.8-27B: weights on the int8 grid under GPTQ, a trellis down each GPTQ column (IQR-V2), and IQR-V3, a computed trellis code under one scale a row, kept at its codes' width in VRAM and decoded in the GEMM; 15 IQR-V3 recipes from ~2 to ~7 bits a weight (data/recipes/q38-27b-*-v3.recipe, docs/IQR.md) - libhalo: a kernel library for Strix Halo (gfx1151), preferred there over libr3d - Nemotron 3.5 Embed 1B and 8B (nemotron35_embed): text and image embeddings through a Pixtral tower, on the card and on the CPU - Nemotron 3.5 Rerank 8B - /v1/systemone: Cloudflare's clef and clef-flash, Convai Innovations' Laya and Mica beside LiquidAI d1; scored steps read the candidates' logits from the head table with no lm_head pass - LFM2's 8-bit trunk: block-fp8 or int8 linears with the fused producers, and the d1-3B recipe - DeepSeek-V4.1's reply format with DSML tool calls and typed argument tags Weights on the drive: - The file tier reads only the experts the pass routes rows to; the draft head's weights stay in the host pool - A hot VRAM cache for routed experts read off the drive, reads deposited straight into free host pool slots, and copyless evictions; the file tier's counters are now ssd_* - GLM-5 Next shards its routed experts by expert, not by width, so they can live on the drive - The stall watch counts drive reads as progress, and the DMA lane's room check reads the lane's own completion fence Quantisation tooling: - --calib-corpus, --calib-dir and --calib-layers record each linear's input Hessian; beside --kld-record the reference's own run records them - --kld-top N records a sparse KL reference (the N most likely tokens and the tail's mass) - GPTQ in a third of the time with the same codes, trellis GPTQ on the card, vector codebooks with coordinate descent, and rad-convert --reuse repeated, each container supplying what the earlier ones lack Speculation: - Prompt lookup alone (--spec-ngram K, --spec-ngram-min/-max): each sequence keeps an index of its n-grams, and a proposal is verified only when its measured step cost says it pays; --draft-window adaptive follows it Speed: - IQR decode: the narrow tile splits K for four times the int8 tile's waves and folds each 128-K block once; at 8 tokens down and the output projections run in 0.61-0.82x and 0.70-0.92x FP8's time (2-6 bits); IQ6R-S-V3 with its DFlash2 drafter steps in 26.3 ms at TP2, against 29.4 ms before and FP8's 27.3 - Qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8 - libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and rope; KLATE again for the head-256 gqa6 paged prefill; gram_accum on the matrix cores Features: - /health, /v1/health and /ping answer 503 with "status": "stuck" once the device has advanced nothing for a minute or a queue has faulted, so a supervisor can restart a wedged server (#356) - --image-gen-max-pixels and --image-gen-max-refs size an image generator's buffers (#344) - The startup report lists only the options not at their default, with a count; -v lists all (#250) - --preempt-wait-ms bounds how long a preempted prefill waits for its whole-recompute room - --placement layer_offload spills dense layers so one --max-model-len sequence fits - Startup refuses amdgpu with CWSR off and says how to fix it; --proceed-with-incompatible-configuration starts anyway under an UNSUPPORTED banner Fixes: - The n-gram read-ahead hands each row to the reader once and reads only as far ahead as the row cache holds, and pauses while decode reads: about one drive read a row instead of two (#355) - A file-tier window reads each of its runs once, not once a run per run - The decode split law's verify floor is bounded by the batch's workgroups: max_seqs 256 no longer declares 64x the scratch (#342) - A prefetch DMA list's mark stays out of the signal pool until the engine has read it, and a prefill stage copies only the blocks its own tables name (#343) - The split-KV row sum is read with fetch-inactive (#328) - LFM2 on the host backend: libref and libavx serve the row-form ops it declares (#348) - The preempted-prefill gate skips a KV group that holds no blocks (#352) - Every request entry point bounded, gated and sanitised (JSON depth, invalid UTF-8, control bytes in the log, the dashboard's CSP, cross-origin browsers on the loopback-only routes); a prompt id outside the vocabulary refused at admission; --api-key "" refused at startup - The telemetry the HTTP thread reads is atomic - An RMS norm row no longer depends on how many rows its launch carries; prefill attention's rescale is decided by live rows only - A --kld-record prefill chunk that finishes no sequence gets its logits on a tied-head model - A kernel's lazily made counter block is zeroed outside the lock other ranks take (a TP2 first-step hang) Changes: Plugin ABI 32. Every plugin exports a layout fingerprint of the ABI structs and the loader refuses a plugin without it or with another (#302), so out-of-tree plugins must be rebuilt. Appended: RadBuildCtx calib_* and gen_max_*, RadArchProbe gen_max_*, RadBatch score_only and plugin_words, RadDeviceProps::unified, RadChatFormat arg_json_value_prefix.
This commit is contained in:
commit
9ed3ef7a7b
452 files changed
+167762
-1346
No files matched your search
+20
-4
@@ -1,7 +1,8 @@
|
||||
# libquant -- the built-in quantisers (spec §4.5). Host C++ only.
|
||||
# libquant -- the built-in quantisers (spec §4.5). Host C++, and trellis GPTQ's card path where
|
||||
# radiance has a device build.
|
||||
#
|
||||
# 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.
|
||||
# Links rad_abi and nothing else, like every plugin (beside the HIP runtime for the card path):
|
||||
# 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)
|
||||
@@ -9,11 +10,26 @@ if(NOT COMMAND rad_add_plugin)
|
||||
project(libquant LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
if(RAD_HIP_FOUND)
|
||||
enable_language(HIP)
|
||||
rad_hip_rule_fixes()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
file(GLOB LQ_SRC CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
|
||||
|
||||
rad_add_plugin(libquant quantizers SOURCES ${LQ_SRC} INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
# Trellis GPTQ on the card (lq_gpu.h) where radiance has a device build; the host-only build answers
|
||||
# --gpus with RAD_E_UNSUPPORTED (lq_gpu.cpp).
|
||||
set(LQ_HIP_SRC "")
|
||||
if(RAD_HIP_FOUND)
|
||||
set(LQ_HIP_SRC ${CMAKE_CURRENT_SOURCE_DIR}/lq_tcq_gpu.hip)
|
||||
endif()
|
||||
|
||||
rad_add_plugin(libquant quantizers SOURCES ${LQ_SRC} HIP_SOURCES ${LQ_HIP_SRC}
|
||||
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
if(LQ_HIP_SRC)
|
||||
target_compile_definitions(libquant PRIVATE LQ_CARD=1)
|
||||
endif()
|
||||
|
||||
# -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.
|
||||
|
||||
+451
-112
@@ -1,15 +1,21 @@
|
||||
/* lq_gptq.cpp -- the Hessian side of GPTQ and the sequential loop. See lq_gptq.h. */
|
||||
#include "lq_gptq.h"
|
||||
#include "lq_gpu.h"
|
||||
#include "lq_hess.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#ifdef _OPENMP
|
||||
#include <omp.h>
|
||||
#endif
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -24,60 +30,42 @@ namespace {
|
||||
* deep, and f32 loses real conditioning on a matrix near-singular in the directions a rotation
|
||||
* flattened. */
|
||||
#ifdef RAD_LQ_LAPACK
|
||||
/* LAPACK, column-major, Fortran calling convention (OpenBLAS). See the three functions below. */
|
||||
/* LAPACK, column-major, Fortran calling convention (OpenBLAS). */
|
||||
extern "C" void dpotrf_(const char* uplo, const int* n, double* a, const int* lda, int* info);
|
||||
extern "C" void dpotri_(const char* uplo, const int* n, double* a, const int* lda, int* info);
|
||||
extern "C" void dtrtri_(const char* uplo, const char* diag, const int* n, double* a, const int* lda,
|
||||
int* info);
|
||||
|
||||
/* dpotrf rejects a non-positive pivot but lets a NaN through, where the loops' !(s > 0) refuses
|
||||
* it: a factor whose diagonal is not finite and positive is refused here as there. */
|
||||
static bool diag_ok(const std::vector<double>& a, int64_t k) {
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
const double d = a[(size_t)(i * k + i)];
|
||||
if (!(d > 0.0) || !std::isfinite(d)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Zero the row-major strict upper (upper = true) or strict lower triangle. */
|
||||
static void zero_triangle(std::vector<double>& a, int64_t k, bool upper) {
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
if (upper) for (int64_t j = i + 1; j < k; ++j) a[(size_t)(i * k + j)] = 0.0;
|
||||
else for (int64_t j = 0; j < i; ++j) a[(size_t)(i * k + j)] = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
bool chol_lower_lapack(std::vector<double>& a, int64_t k) {
|
||||
const int n = (int)k;
|
||||
int info = 0;
|
||||
dpotrf_("U", &n, a.data(), &n, &info);
|
||||
if (info != 0) return false;
|
||||
zero_triangle(a, k, true);
|
||||
return diag_ok(a, k);
|
||||
}
|
||||
|
||||
void inv_from_chol_lapack(std::vector<double>& l, int64_t k) {
|
||||
const int n = (int)k;
|
||||
int info = 0;
|
||||
dpotri_("U", &n, l.data(), &n, &info);
|
||||
/* Column-major upper is row-major lower: mirror it into the row-major upper half. */
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t i = 0; i < k; ++i)
|
||||
for (int64_t j = i + 1; j < k; ++j) l[(size_t)(i * k + j)] = l[(size_t)(j * k + i)];
|
||||
}
|
||||
|
||||
bool chol_upper_lapack(std::vector<double>& a, int64_t k) {
|
||||
/* H (damped, row-major) -> U upper with U^T U = H^-1, in f32, by one Cholesky and one triangular
|
||||
* inverse instead of a Cholesky, an inverse and a second Cholesky. With J the reversal, J H J =
|
||||
* L L^T makes H = M M^T for the upper M = J L J, so H^-1 = M^-T M^-1 and U = M^-1 = J L^-1 J.
|
||||
* Reversing a symmetric matrix is reversing its storage, so J H J is `a` read backwards; the factor
|
||||
* and the inverse are LAPACK's, in column-major lower, and U[i][j] = L^-1[K-1-i][K-1-j] is read
|
||||
* from there. Half the f64 work of the three-step form. */
|
||||
bool inv_upper_lapack(std::vector<double>& a, int64_t k, float* u) {
|
||||
std::reverse(a.begin(), a.end());
|
||||
const int n = (int)k;
|
||||
int info = 0;
|
||||
dpotrf_("L", &n, a.data(), &n, &info);
|
||||
if (info != 0) return false;
|
||||
zero_triangle(a, k, false);
|
||||
return diag_ok(a, k);
|
||||
dtrtri_("L", "N", &n, a.data(), &n, &info);
|
||||
if (info != 0) return false;
|
||||
const double* l = a.data();
|
||||
bool ok = true;
|
||||
#pragma omp parallel for schedule(static) reduction(&& : ok)
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
float* ur = u + i * k;
|
||||
for (int64_t j = 0; j < i; ++j) ur[j] = 0.0f;
|
||||
/* Column-major (r, c) is l[r + c * k]; here r = k-1-i and c = k-1-j. */
|
||||
for (int64_t j = i; j < k; ++j) ur[j] = (float)l[(k - 1 - i) + (k - 1 - j) * k];
|
||||
ok = ok && ur[i] > 0.0f && std::isfinite(ur[i]);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
#endif /* RAD_LQ_LAPACK */
|
||||
|
||||
/* The single-threaded loops: the reference, and the only path without OpenBLAS. */
|
||||
bool chol_lower_loop(std::vector<double>& a, int64_t k) {
|
||||
bool chol_lower(std::vector<double>& a, int64_t k) {
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
for (int64_t j = 0; j <= i; ++j) {
|
||||
double s = a[(size_t)(i * k + j)];
|
||||
@@ -95,7 +83,7 @@ bool chol_lower_loop(std::vector<double>& a, int64_t k) {
|
||||
}
|
||||
|
||||
/* A = L L^T, factored in place -> A^-1, full and symmetric: L^-1 first, then L^-T L^-1. */
|
||||
void inv_from_chol_loop(std::vector<double>& l, int64_t k) {
|
||||
void inv_from_chol(std::vector<double>& l, int64_t k) {
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
l[(size_t)(j * k + j)] = 1.0 / l[(size_t)(j * k + j)];
|
||||
for (int64_t i = j + 1; i < k; ++i) {
|
||||
@@ -116,7 +104,7 @@ void inv_from_chol_loop(std::vector<double>& l, int64_t k) {
|
||||
}
|
||||
|
||||
/* A -> U upper with A = U^T U. */
|
||||
bool chol_upper_loop(std::vector<double>& a, int64_t k) {
|
||||
bool chol_upper(std::vector<double>& a, int64_t k) {
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
double d = a[(size_t)(i * k + i)];
|
||||
for (int64_t t = 0; t < i; ++t) {
|
||||
@@ -145,33 +133,59 @@ bool use_lapack() {
|
||||
}
|
||||
#endif
|
||||
|
||||
bool chol_lower(std::vector<double>& a, int64_t k) {
|
||||
#ifdef RAD_LQ_LAPACK
|
||||
if (use_lapack()) return chol_lower_lapack(a, k);
|
||||
#endif
|
||||
return chol_lower_loop(a, k);
|
||||
}
|
||||
/* Rows a tile of GPTQ's loop: the tail update keeps a tile's columns in registers across the
|
||||
* block's 128 errors. */
|
||||
constexpr int64_t kTileRows = 8;
|
||||
constexpr int64_t kTileCols = 32;
|
||||
|
||||
void inv_from_chol(std::vector<double>& l, int64_t k) {
|
||||
#ifdef RAD_LQ_LAPACK
|
||||
if (use_lapack()) return inv_from_chol_lapack(l, k);
|
||||
#endif
|
||||
inv_from_chol_loop(l, k);
|
||||
}
|
||||
|
||||
bool chol_upper(std::vector<double>& a, int64_t k) {
|
||||
#ifdef RAD_LQ_LAPACK
|
||||
if (use_lapack()) return chol_upper_lapack(a, k);
|
||||
#endif
|
||||
return chol_upper_loop(a, k);
|
||||
/* w[r][j] -= e[r][t] * u[t][j] for t over the block [b0, b1), j over [b1, K), r over `rows`
|
||||
* (<= kTileRows) rows of `w` (row stride K) and `e` (row stride 128). Each element takes its terms
|
||||
* one at a time in ascending t, a product then a subtraction, as a row running alone would apply
|
||||
* them, so the result does not depend on the vector width, the tile or the threads. Built for each
|
||||
* of these instruction sets and chosen at load. */
|
||||
__attribute__((target_clones("avx512f", "avx2", "default")))
|
||||
void gptq_tail(float* w, const float* e, int64_t rows, const float* u, int64_t K, int64_t b0,
|
||||
int64_t b1) {
|
||||
int64_t j0 = b1;
|
||||
if (rows == kTileRows) {
|
||||
for (; j0 + kTileCols <= K; j0 += kTileCols) {
|
||||
float acc[kTileRows][kTileCols];
|
||||
for (int64_t r = 0; r < kTileRows; ++r)
|
||||
for (int64_t c = 0; c < kTileCols; ++c) acc[r][c] = w[r * K + j0 + c];
|
||||
for (int64_t t = b0; t < b1; ++t) {
|
||||
const float* ut = u + t * K + j0;
|
||||
for (int64_t r = 0; r < kTileRows; ++r) {
|
||||
const float er = e[r * 128 + (t - b0)];
|
||||
for (int64_t c = 0; c < kTileCols; ++c) acc[r][c] -= er * ut[c];
|
||||
}
|
||||
}
|
||||
for (int64_t r = 0; r < kTileRows; ++r)
|
||||
for (int64_t c = 0; c < kTileCols; ++c) w[r * K + j0 + c] = acc[r][c];
|
||||
}
|
||||
}
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* wr = w + r * K;
|
||||
for (int64_t t = b0; t < b1; ++t) {
|
||||
const float er = e[r * 128 + (t - b0)];
|
||||
const float* ut = u + t * K;
|
||||
for (int64_t j = j0; j < K; ++j) wr[j] -= er * ut[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Layer factors kept at once. */
|
||||
constexpr size_t kFactors = 4;
|
||||
|
||||
struct Cache {
|
||||
/* One layer factor: built by the first caller under its own lock, which later callers wait on. */
|
||||
struct Slot {
|
||||
std::mutex mu;
|
||||
std::map<std::string, Gram> f; /* null = looked and found nothing */
|
||||
bool done = false;
|
||||
Gram g; /* null = looked and found nothing */
|
||||
};
|
||||
|
||||
struct Cache {
|
||||
std::mutex mu; /* the map, held only to find or add a slot */
|
||||
std::map<std::string, std::shared_ptr<Slot>> f;
|
||||
std::deque<std::string> order; /* f's keys, oldest first */
|
||||
};
|
||||
|
||||
@@ -206,28 +220,38 @@ 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 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. */
|
||||
/* A layer's factor is shared by its experts, so it is built once and cached, under a lock of
|
||||
* its own: weights quantised side by side (rad-convert --gpus) factor different layers at
|
||||
* once. An expert's own is built for its one call outside any lock, so experts factor in
|
||||
* parallel. A few layer factors are kept, the oldest dropped first: a dense model reads each
|
||||
* layer's once, and a 21504-wide factor is 1.85 GB in f32 (every one kept OOM-killed
|
||||
* TranslateGemma 27B's conversion at layer 25). A MoE layer's experts run in parallel and
|
||||
* alternate between its gate_up and down stems, so one kept factor would be recomputed over
|
||||
* and over. */
|
||||
Cache& c = cache();
|
||||
std::unique_lock<std::mutex> lk(c.mu, std::defer_lock);
|
||||
std::shared_ptr<Slot> slot;
|
||||
std::unique_lock<std::mutex> lk;
|
||||
if (layer) {
|
||||
lk.lock();
|
||||
auto it = c.f.find(key);
|
||||
if (it != c.f.end()) return it->second;
|
||||
{
|
||||
std::lock_guard<std::mutex> g(c.mu);
|
||||
auto it = c.f.find(key);
|
||||
if (it == c.f.end()) {
|
||||
while (c.order.size() >= kFactors) {
|
||||
c.f.erase(c.order.front());
|
||||
c.order.pop_front();
|
||||
}
|
||||
it = c.f.emplace(key, std::make_shared<Slot>()).first;
|
||||
c.order.push_back(key);
|
||||
}
|
||||
slot = it->second;
|
||||
}
|
||||
lk = std::unique_lock<std::mutex>(slot->mu);
|
||||
if (slot->done) return slot->g;
|
||||
}
|
||||
auto keep = [&](Gram u) {
|
||||
/* A few layer factors, the oldest dropped first: a dense model reads each layer's
|
||||
* once, and a 21504-wide factor is 1.85 GB in f32 (every one kept OOM-killed
|
||||
* TranslateGemma 27B's conversion at layer 25). A MoE layer's experts run in parallel
|
||||
* and alternate between its gate_up and down stems, so one kept factor would be
|
||||
* recomputed over and over. */
|
||||
if (layer && !c.f.count(key)) {
|
||||
while (c.order.size() >= kFactors) {
|
||||
c.f.erase(c.order.front());
|
||||
c.order.pop_front();
|
||||
}
|
||||
c.f.emplace(key, u);
|
||||
c.order.push_back(key);
|
||||
if (slot) {
|
||||
slot->g = u;
|
||||
slot->done = true;
|
||||
}
|
||||
return u;
|
||||
};
|
||||
@@ -268,6 +292,20 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d
|
||||
if (dead)
|
||||
std::fprintf(stderr, "libquant: %lld of %lld columns of '%s' were never exercised by the "
|
||||
"calibration corpus\n", (long long)dead, (long long)K, stem.c_str());
|
||||
auto u = std::make_shared<std::vector<float>>((size_t)(K * K));
|
||||
#ifdef RAD_LQ_LAPACK
|
||||
if (use_lapack()) {
|
||||
if (!inv_upper_lapack(acc, K, u->data())) {
|
||||
std::fprintf(stderr, "libquant: the Hessian for '%s' is not positive definite even "
|
||||
"damped; rounding it to nearest\n", stem.c_str());
|
||||
return keep(nullptr);
|
||||
}
|
||||
if (layer)
|
||||
std::fprintf(stderr, "libquant: GPTQ quantises '%s' against %d calibration file(s), "
|
||||
"K=%lld\n", stem.c_str(), found, (long long)K);
|
||||
return keep(u);
|
||||
}
|
||||
#endif
|
||||
if (!chol_lower(acc, K)) {
|
||||
std::fprintf(stderr, "libquant: the Hessian for '%s' is not positive definite even "
|
||||
"damped; rounding it to nearest\n", stem.c_str());
|
||||
@@ -279,7 +317,6 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d
|
||||
"it to nearest\n", stem.c_str());
|
||||
return keep(nullptr);
|
||||
}
|
||||
auto u = std::make_shared<std::vector<float>>((size_t)(K * K));
|
||||
for (size_t i = 0; i < u->size(); ++i) (*u)[i] = (float)acc[i];
|
||||
if (layer)
|
||||
std::fprintf(stderr, "libquant: GPTQ quantises '%s' against %d calibration file(s), "
|
||||
@@ -287,9 +324,138 @@ Gram gptq_factor(const char* dir, const char* name, int64_t K, int64_t domain, d
|
||||
return keep(u);
|
||||
}
|
||||
|
||||
void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales, int64_t N,
|
||||
int64_t K, const float* u) {
|
||||
if (!w || !codes || N <= 0 || K <= 0) return;
|
||||
void gptq_tcq_dyn_scales(const Grid& g, const float* w, int64_t K, Scales& scales, int64_t r0,
|
||||
int64_t r1, int64_t b0, int64_t b1) {
|
||||
/* Rows are independent. The host loop calls this per run inside its own parallel loop; the
|
||||
* card's driver calls it once for all its rows. */
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static, 64) if (!omp_in_parallel() && r1 - r0 > 256)
|
||||
#endif
|
||||
for (int64_t r = r0; r < r1; ++r) {
|
||||
BlockScale b = grid_block_scale(g, w, K, r, r + 1, b0, b1, nullptr);
|
||||
if (g.lv2) {
|
||||
const int64_t i2 = g.br2 > 0 ? r / g.br2 : 0, j2 = g.bc2 > 0 ? b0 / g.bc2 : 0;
|
||||
b = grid_tcq_block_lv2(g, b.s, scales.s2[(size_t)(i2 * scales.nc2 + j2)]);
|
||||
}
|
||||
scales.b[(size_t)(r * scales.nc + b0 / 128)] = b;
|
||||
}
|
||||
}
|
||||
|
||||
void gptq_tcq_col_scales(const Grid& g, const Scales& scales, int64_t n0, int64_t n, int64_t col,
|
||||
float* s, float* rt) {
|
||||
const float cf = scales.colf.empty() ? 1.0f : scales.colf[(size_t)(col / 128)];
|
||||
for (int64_t r = 0; r < n; ++r) s[r] = scales.at(n0 + r, col).s * cf;
|
||||
/* tcq_rb: each row's values on its row block's grid (Grid::tcq_rb). n0 is a multiple of
|
||||
* tcq_rows, which tcq_rb divides, so the blocks are the GEMM's. */
|
||||
if (g.tcq_rb)
|
||||
for (int64_t r0 = 0; r0 < n; r0 += g.tcq_rb) {
|
||||
const int64_t r1 = std::min(n, r0 + g.tcq_rb);
|
||||
float bm = 0.0f;
|
||||
for (int64_t r = r0; r < r1; ++r) bm = std::max(bm, s[r]);
|
||||
for (int64_t r = r0; r < r1; ++r) {
|
||||
rt[r] = bm > 0.0f ? s[r] / bm : 0.0f;
|
||||
s[r] = bm;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* gptq_quantise over a trellis grid. A trellis runs down a column, so the loop turns: each run of
|
||||
* tcq_rows rows (a tile, and the parallelism) takes the block's columns in order, the trellis
|
||||
* choosing that column's codes for all the tile's rows at once; every row then feeds its error on
|
||||
* to the block's later columns as a row alone would, and the tail takes the block's errors as
|
||||
* before. All rows of a column share its weight in the Hessian's metric, so the trellis's own
|
||||
* squared error is GPTQ's objective for the column. lq_tcq_gpu.hip runs the same loop on the
|
||||
* cards. */
|
||||
void gptq_quantise_tcq(const Grid& g, float* w, int32_t* codes, Scales& scales, int64_t N,
|
||||
int64_t K, const float* u, bool dynamic) {
|
||||
const int64_t T = g.tcq_rows, B = 128;
|
||||
std::vector<float> err(u ? (size_t)(N * B) : 0);
|
||||
for (int64_t b0 = 0; b0 < K; b0 += B) {
|
||||
const int64_t b1 = (b0 + B < K) ? b0 + B : K;
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(dynamic, 1)
|
||||
#endif
|
||||
for (int64_t n0 = 0; n0 < N; n0 += T) {
|
||||
const int64_t n1 = n0 + T < N ? n0 + T : N, n = n1 - n0;
|
||||
thread_local TcqWork work;
|
||||
thread_local std::vector<float> x, s, dq, rt;
|
||||
thread_local std::vector<int32_t> cs;
|
||||
x.resize((size_t)n); s.resize((size_t)n); dq.resize((size_t)n); cs.resize((size_t)n);
|
||||
rt.resize(g.tcq_rb ? (size_t)n : 0);
|
||||
if (dynamic) gptq_tcq_dyn_scales(g, w, K, scales, n0, n1, b0, b1);
|
||||
for (int64_t i = b0; i < b1; ++i) {
|
||||
for (int64_t r = 0; r < n; ++r) x[(size_t)r] = w[(size_t)((n0 + r) * K + i)];
|
||||
gptq_tcq_col_scales(g, scales, n0, n, i, s.data(), rt.data());
|
||||
grid_tcq_run(g, x.data(), s.data(), n, cs.data(), dq.data(), work,
|
||||
g.tcq_rb ? rt.data() : nullptr);
|
||||
for (int64_t r = 0; r < n; ++r) {
|
||||
float* wr = w + (size_t)((n0 + r) * K);
|
||||
codes[(size_t)((n0 + r) * K + i)] = cs[(size_t)r];
|
||||
wr[i] = dq[(size_t)r];
|
||||
if (!u) continue;
|
||||
const float* ur = u + (size_t)(i * K);
|
||||
const float e = (x[(size_t)r] - dq[(size_t)r]) / ur[i];
|
||||
err[(size_t)((n0 + r) * B + (i - b0))] = e;
|
||||
for (int64_t j = i + 1; j < b1; ++j) wr[j] -= e * ur[j];
|
||||
}
|
||||
}
|
||||
if (u)
|
||||
for (int64_t m0 = n0; m0 < n1; m0 += kTileRows)
|
||||
gptq_tail(w + (size_t)(m0 * K), err.data() + (size_t)(m0 * B),
|
||||
(m0 + kTileRows < n1 ? m0 + kTileRows : n1) - m0, u, K, b0, b1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
bool gptq_dynamic_ok(const Grid& g, const Scales& s) {
|
||||
return (!g.lv2 || g.tcq_L) && g.rule != Grid::FIXED && s.br == 1 && s.bc == 128;
|
||||
}
|
||||
|
||||
void gptq_tcq_colf(const float* w, Scales& scales, int64_t N, int64_t K) {
|
||||
/* Block kb's factor: the root of its share of the weight's energy over the mean block's; then
|
||||
* each row's scale, which was its whole row's rms, is taken against the factors, so its values
|
||||
* span the table the same over the row. */
|
||||
const int64_t nb = K / 128;
|
||||
std::vector<double> ms((size_t)(N * nb), 0.0), col((size_t)nb, 0.0);
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static)
|
||||
#endif
|
||||
for (int64_t r = 0; r < N; ++r)
|
||||
for (int64_t b = 0; b < nb; ++b) {
|
||||
double ss = 0.0;
|
||||
for (int64_t c = b * 128; c < b * 128 + 128; ++c) ss += (double)w[r * K + c] * w[r * K + c];
|
||||
ms[(size_t)(r * nb + b)] = ss / 128.0;
|
||||
}
|
||||
double tot = 0.0;
|
||||
for (int64_t b = 0; b < nb; ++b) {
|
||||
for (int64_t r = 0; r < N; ++r) col[(size_t)b] += ms[(size_t)(r * nb + b)];
|
||||
tot += col[(size_t)b];
|
||||
}
|
||||
scales.colf.assign((size_t)nb, 1.0f);
|
||||
for (int64_t b = 0; b < nb; ++b)
|
||||
scales.colf[(size_t)b] = tot > 0.0 && col[(size_t)b] > 0.0
|
||||
? (float)std::sqrt(col[(size_t)b] * (double)nb / tot) : 1.0f;
|
||||
for (int64_t r = 0; r < N; ++r) {
|
||||
double raw = 0.0, adj = 0.0;
|
||||
for (int64_t b = 0; b < nb; ++b) {
|
||||
const double c = scales.colf[(size_t)b];
|
||||
raw += ms[(size_t)(r * nb + b)];
|
||||
adj += ms[(size_t)(r * nb + b)] / (c * c);
|
||||
}
|
||||
BlockScale& bs = scales.b[(size_t)(r * scales.nc)];
|
||||
const float f = raw > 0.0 ? (float)std::sqrt(adj / raw) : 1.0f;
|
||||
bs.s *= f;
|
||||
bs.stored *= f;
|
||||
bs.inv = 1.0f / bs.s;
|
||||
bs.inv_d = 1.0 / (double)bs.s;
|
||||
}
|
||||
}
|
||||
|
||||
int gptq_quantise(const Grid& g, float* w, int32_t* codes, Scales& scales, int64_t N,
|
||||
int64_t K, const float* u, bool dynamic, std::string* why) {
|
||||
if (!w || !codes || N <= 0 || K <= 0) return RAD_OK;
|
||||
auto one = [&](int64_t n, int64_t i, float v) -> float {
|
||||
const BlockScale& b = scales.at(n, i);
|
||||
const int c = grid_code(g, b, v);
|
||||
@@ -297,18 +463,54 @@ void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales
|
||||
return grid_decode(g, b, c);
|
||||
};
|
||||
|
||||
/* A vector grid's codeword for the `vdim` columns from i, into codes and `out`. */
|
||||
const int64_t V = g.vq.empty() ? 0 : g.vdim;
|
||||
auto vec = [&](int64_t n, int64_t i, const float* v, float* out) {
|
||||
const BlockScale& b = scales.at(n, i);
|
||||
const int c = grid_vq_code(g, b, v);
|
||||
for (int64_t j = 0; j < V; ++j) {
|
||||
codes[(size_t)(n * K + i + j)] = c;
|
||||
out[j] = g.vq[(size_t)(c * V + j)] * b.s;
|
||||
}
|
||||
};
|
||||
|
||||
if (g.tcq_L && g.tcq_colf) {
|
||||
if (scales.bc < K || dynamic || g.lv2 || g.tcq_rb) {
|
||||
if (why) *why = "tcq_colf=1 takes one static scale a row (block=1x*, no dyn, scale2 or "
|
||||
"row blocks)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
gptq_tcq_colf(w, scales, N, K);
|
||||
}
|
||||
if (g.tcq_L) {
|
||||
if (gpu_enabled()) {
|
||||
std::string w1;
|
||||
const int st = gptq_tcq_gpu(g, w, codes, scales, N, K, u, dynamic, &w1);
|
||||
if (st != RAD_OK && why) *why = w1;
|
||||
return st;
|
||||
}
|
||||
gptq_quantise_tcq(g, w, codes, scales, N, K, u, dynamic);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (!u) {
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static)
|
||||
#endif
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t i = 0; i < K; ++i) w[(size_t)(n * K + i)] = one(n, i, w[(size_t)(n * K + i)]);
|
||||
return;
|
||||
for (int64_t n = 0; n < N; ++n) {
|
||||
float* wr = w + (size_t)(n * K);
|
||||
if (V) {
|
||||
for (int64_t i = 0; i < K; i += V) vec(n, i, wr + i, wr + i);
|
||||
continue;
|
||||
}
|
||||
for (int64_t i = 0; i < K; ++i) wr[i] = one(n, i, wr[i]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* Column blocks outside, row tiles inside. Rows are independent and are the parallelism; with
|
||||
* the block loop outside, every tile works on the same columns and the block's 128 x K slice
|
||||
* of `u` stays in cache. Within a tile each row runs the block's columns in order, then the
|
||||
* tile's tail (the columns after the block) takes the block's errors (gptq_tail). */
|
||||
const int64_t B = 128;
|
||||
std::vector<float> err((size_t)(N * B));
|
||||
for (int64_t b0 = 0; b0 < K; b0 += B) {
|
||||
@@ -316,28 +518,100 @@ void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static)
|
||||
#endif
|
||||
for (int64_t n = 0; n < N; ++n) {
|
||||
float* wr = w + (size_t)(n * K);
|
||||
float* er = err.data() + (size_t)(n * B);
|
||||
for (int64_t i = b0; i < b1; ++i) {
|
||||
const float* ur = u + (size_t)(i * K);
|
||||
const float d = ur[i];
|
||||
const float v = wr[i];
|
||||
const float dq = one(n, i, v);
|
||||
wr[i] = dq;
|
||||
/* d is U[i][i], strictly positive: chol_upper refuses otherwise. */
|
||||
const float e = (v - dq) / d;
|
||||
er[i - b0] = e;
|
||||
for (int64_t j = i + 1; j < b1; ++j) wr[j] -= e * ur[j];
|
||||
for (int64_t n0 = 0; n0 < N; n0 += kTileRows) {
|
||||
const int64_t n1 = n0 + kTileRows < N ? n0 + kTileRows : N;
|
||||
for (int64_t n = n0; n < n1; ++n) {
|
||||
float* wr = w + (size_t)(n * K);
|
||||
float* er = err.data() + (size_t)(n * B);
|
||||
if (dynamic)
|
||||
scales.b[(size_t)(n * scales.nc + b0 / 128)] =
|
||||
grid_block_scale(g, w, K, n, n + 1, b0, b1, nullptr);
|
||||
/* A vector grid chooses each codeword at its first column from the values the
|
||||
* error has moved the vector to; its columns then feed their error on in turn. */
|
||||
float vbuf[16];
|
||||
for (int64_t i = b0; i < b1; ++i) {
|
||||
const float* ur = u + (size_t)(i * K);
|
||||
const float d = ur[i];
|
||||
const float v = wr[i];
|
||||
if (V && (i - b0) % V == 0) vec(n, i, wr + i, vbuf);
|
||||
const float dq = V ? vbuf[(i - b0) % V] : one(n, i, v);
|
||||
wr[i] = dq;
|
||||
/* d is U[i][i], strictly positive: the factor refuses otherwise. */
|
||||
const float e = (v - dq) / d;
|
||||
er[i - b0] = e;
|
||||
for (int64_t j = i + 1; j < b1; ++j) wr[j] -= e * ur[j];
|
||||
}
|
||||
}
|
||||
for (int64_t t = b0; t < b1; ++t) {
|
||||
const float e = er[t - b0];
|
||||
const float* ur = u + (size_t)(t * K);
|
||||
for (int64_t j = b1; j < K; ++j) wr[j] -= e * ur[j];
|
||||
gptq_tail(w + (size_t)(n0 * K), err.data() + (size_t)(n0 * B), n1 - n0, u, K, b0, b1);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* gptq_refine over a trellis grid: a trellis code moves the states of the rows after it, so a
|
||||
* column moves whole. Each run of tcq_rows rows takes its columns in order, searching each one
|
||||
* again against the exact descent target of its own values given every other column's (the
|
||||
* row's gradient at the column less the column's own term, over the diagonal), on the scales the
|
||||
* loop chose; the column's new codes are kept when the form, summed over the run's rows, strictly
|
||||
* falls. */
|
||||
void gptq_tcq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const Scales& scales,
|
||||
int64_t N, int64_t K, const float* h, const float* ad, const float* dg,
|
||||
float* e, float* gm, int passes) {
|
||||
const int64_t T = g.tcq_rows;
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(dynamic, 1)
|
||||
#endif
|
||||
for (int64_t n0 = 0; n0 < N; n0 += T) {
|
||||
const int64_t n1 = n0 + T < N ? n0 + T : N, n = n1 - n0;
|
||||
TcqWork work;
|
||||
std::vector<float> t((size_t)n), s((size_t)n), dq((size_t)n), rt(g.tcq_rb ? (size_t)n : 0),
|
||||
d((size_t)n);
|
||||
std::vector<int32_t> cs((size_t)n);
|
||||
for (int64_t r = n0; r < n1; ++r) {
|
||||
float* gr = gm + (size_t)(r * K);
|
||||
const float* er = e + (size_t)(r * K);
|
||||
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) {
|
||||
const float hj = dg[(size_t)j];
|
||||
for (int64_t r = 0; r < n; ++r) {
|
||||
const size_t ix = (size_t)((n0 + r) * K + j);
|
||||
t[(size_t)r] = x[ix] - (gm[ix] - e[ix] * hj) / hj;
|
||||
}
|
||||
gptq_tcq_col_scales(g, scales, n0, n, j, s.data(), rt.data());
|
||||
grid_tcq_run(g, t.data(), s.data(), n, cs.data(), dq.data(), work,
|
||||
g.tcq_rb ? rt.data() : nullptr);
|
||||
double delta = 0.0;
|
||||
bool same = true;
|
||||
for (int64_t r = 0; r < n; ++r) {
|
||||
const size_t ix = (size_t)((n0 + r) * K + j);
|
||||
same &= cs[(size_t)r] == codes[ix];
|
||||
d[(size_t)r] = (dq[(size_t)r] - x[ix]) - e[ix];
|
||||
delta += (double)d[(size_t)r] * (2.0f * gm[ix] + d[(size_t)r] * hj);
|
||||
}
|
||||
if (same || !(delta < 0.0)) continue;
|
||||
const float* hr = h + (size_t)(j * K);
|
||||
for (int64_t r = 0; r < n; ++r) {
|
||||
const size_t ix = (size_t)((n0 + r) * K + j);
|
||||
codes[ix] = cs[(size_t)r];
|
||||
const float dl = d[(size_t)r];
|
||||
if (dl == 0.0f) continue;
|
||||
float* gr = gm + (size_t)((n0 + r) * K);
|
||||
for (int64_t t2 = 0; t2 < K; ++t2) gr[t2] += dl * hr[t2];
|
||||
gr[j] += ad[(size_t)j] * dl;
|
||||
e[ix] += dl;
|
||||
w[ix] = dq[(size_t)r];
|
||||
}
|
||||
++moved;
|
||||
}
|
||||
if (!moved) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
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) {
|
||||
@@ -360,6 +634,20 @@ void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const
|
||||
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());
|
||||
if (g.tcq_L) {
|
||||
gptq_tcq_refine(g, x, w, codes, scales, N, K, h, ad.data(), dg.data(), e.data(), gm.data(),
|
||||
passes);
|
||||
return;
|
||||
}
|
||||
/* A vector grid's pair products c_a c_b (a <= b) per codeword, for its descent. */
|
||||
std::vector<float> cpp;
|
||||
if (!g.vq.empty()) {
|
||||
const int64_t V = g.vdim;
|
||||
for (int64_t k = 0; k < g.ventries; ++k)
|
||||
for (int64_t a = 0; a < V; ++a)
|
||||
for (int64_t c = a; c < V; ++c)
|
||||
cpp.push_back(g.vq[(size_t)(k * V + a)] * g.vq[(size_t)(k * V + c)]);
|
||||
}
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static)
|
||||
#endif
|
||||
@@ -370,9 +658,60 @@ void gptq_refine(const Grid& g, const float* x, float* w, int32_t* codes, const
|
||||
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] += ad[(size_t)j] * er[j];
|
||||
const int64_t V = g.vq.empty() ? 0 : g.vdim;
|
||||
for (int pass = 0; pass < passes; ++pass) {
|
||||
int64_t moved = 0;
|
||||
for (int64_t j = 0; j < K; ++j) {
|
||||
/* A vector grid moves a whole codeword. For codeword k, decoded s c_k against the
|
||||
* current values w, the form changes by 2 s c_k.u + s^2 c_k^T A c_k + const, with
|
||||
* A = H_VV + diag(ad) and u = g_V - A w; the most negative change is taken when it
|
||||
* beats keeping the codeword. c_k^T A c_k is A's upper triangle against the codeword's
|
||||
* pair products, which are the same for every vector (cpp). */
|
||||
for (int64_t j0 = 0; V && j0 < K; j0 += V) {
|
||||
const BlockScale& b = scales.at(n, j0);
|
||||
float A[16][16], u[16], up[136];
|
||||
for (int64_t a = 0; a < V; ++a)
|
||||
for (int64_t c = 0; c < V; ++c)
|
||||
A[a][c] = h[(size_t)((j0 + a) * K + j0 + c)] + (a == c ? ad[(size_t)(j0 + a)] : 0.0f);
|
||||
for (int64_t a = 0; a < V; ++a) {
|
||||
float aw = 0.0f;
|
||||
for (int64_t c = 0; c < V; ++c) aw += A[a][c] * wr[j0 + c];
|
||||
u[a] = gr[j0 + a] - aw;
|
||||
}
|
||||
int64_t t = 0;
|
||||
for (int64_t a = 0; a < V; ++a)
|
||||
for (int64_t c = a; c < V; ++c, ++t) up[t] = a == c ? A[a][a] : 2.0f * A[a][c];
|
||||
const int64_t P = t;
|
||||
const float s1 = b.s, s2 = b.s * b.s;
|
||||
auto f = [&](int64_t k) {
|
||||
const float* ck = g.vq.data() + k * V;
|
||||
const float* pk = cpp.data() + k * P;
|
||||
float lin = 0.0f, quad = 0.0f;
|
||||
for (int64_t a = 0; a < V; ++a) lin += ck[a] * u[a];
|
||||
for (int64_t q = 0; q < P; ++q) quad += pk[q] * up[q];
|
||||
return 2.0f * s1 * lin + s2 * quad;
|
||||
};
|
||||
const float keep = f(cr[j0]);
|
||||
int best = -1;
|
||||
float bestv = keep;
|
||||
for (int64_t k = 0; k < g.ventries; ++k) {
|
||||
if (k == cr[j0]) continue;
|
||||
const float v = f(k);
|
||||
if (v < bestv) { bestv = v; best = (int)k; }
|
||||
}
|
||||
if (best < 0) continue;
|
||||
for (int64_t a = 0; a < V; ++a) {
|
||||
const float qn = g.vq[(size_t)(best * V + a)] * b.s;
|
||||
const float dl = qn - wr[j0 + a];
|
||||
const float* hr = h + (size_t)((j0 + a) * K);
|
||||
for (int64_t t2 = 0; t2 < K; ++t2) gr[t2] += dl * hr[t2];
|
||||
gr[j0 + a] += ad[(size_t)(j0 + a)] * dl;
|
||||
er[j0 + a] += dl;
|
||||
wr[j0 + a] = qn;
|
||||
cr[j0 + a] = best;
|
||||
}
|
||||
++moved;
|
||||
}
|
||||
for (int64_t j = 0; !V && j < K; ++j) {
|
||||
const float hj = dg[(size_t)j];
|
||||
/* The row's gradient at j less column j's own term, over the diagonal. */
|
||||
const float t = xr[j] - (gr[j] - er[j] * hj) / hj;
|
||||
|
||||
+27
-3
@@ -18,6 +18,8 @@
|
||||
#include "lq_grid.h"
|
||||
#include "lq_hess.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace lq {
|
||||
|
||||
/* Upper Cholesky factor U of the damped inverse Hessian, U^T U = (H + lambda I)^-1, as a K x K
|
||||
@@ -36,9 +38,31 @@ std::vector<int32_t> gptq_act_order(const char* dir, const char* name, int64_t K
|
||||
|
||||
/* Quantise `w` [N, K] in place on grid `g` against `scales` (grid_scales'), writing codes to
|
||||
* `codes` [N, K]. On return `w` holds the decoded values. With `u` null each value is rounded to
|
||||
* nearest on its own, which is byte-identical to grid_rtn. */
|
||||
void gptq_quantise(const Grid& g, float* w, int32_t* codes, const Scales& scales, int64_t N,
|
||||
int64_t K, const float* u);
|
||||
* nearest on its own, which is byte-identical to grid_rtn. A trellis grid runs on the cards when
|
||||
* gpu_set_devices named any (lq_gpu.h), with the same result; RAD_OK, or the card's failure with
|
||||
* the reason in *why.
|
||||
*
|
||||
* `dynamic`: each row's scale for a 128-column group is chosen again when the loop reaches the
|
||||
* group, from the values the earlier columns' error has moved it to (GPTQ's own grouping), rather
|
||||
* than from the weight as it stood; `scales` is updated. Needs a one-row, 128-column scale grid
|
||||
* with one level (gptq_dynamic_ok). */
|
||||
int gptq_quantise(const Grid& g, float* w, int32_t* codes, Scales& scales, int64_t N,
|
||||
int64_t K, const float* u, bool dynamic = false, std::string* why = nullptr);
|
||||
/* tcq_colf: the blocks' shared factors into scales.colf and each row's scale against them, from
|
||||
* the weight `w` [N, K] as it stands (Grid::tcq_colf). */
|
||||
void gptq_tcq_colf(const float* w, Scales& scales, int64_t N, int64_t K);
|
||||
|
||||
bool gptq_dynamic_ok(const Grid& g, const Scales& s);
|
||||
|
||||
/* The trellis loop's two scale steps, shared by the host loop and the card's (lq_tcq_gpu.hip).
|
||||
* gptq_tcq_dyn_scales: under dyn=1, rows [r0, r1)'s scales for the block [b0, b1), chosen from
|
||||
* `w` as it stands. gptq_tcq_col_scales: for the n rows from n0 (a multiple of tcq_rows), the
|
||||
* scale each row's values take in column `col`, and under tcq_rb the row's own scale over its row
|
||||
* block's into `rt` (Grid::tcq_rb). */
|
||||
void gptq_tcq_dyn_scales(const Grid& g, const float* w, int64_t K, Scales& scales, int64_t r0,
|
||||
int64_t r1, int64_t b0, int64_t b1);
|
||||
void gptq_tcq_col_scales(const Grid& g, const Scales& scales, int64_t n0, int64_t n, int64_t col,
|
||||
float* s, float* rt);
|
||||
|
||||
/* 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,
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
/* lq_gpu.cpp -- the host-only build's answer to lq_gpu.h: no card path (lq_tcq_gpu.hip is built
|
||||
* only where radiance has a device build). */
|
||||
#include "lq_gpu.h"
|
||||
|
||||
#ifndef LQ_CARD
|
||||
namespace lq {
|
||||
|
||||
int gpu_set_devices(const int*, int n) { return n > 0 ? RAD_E_UNSUPPORTED : RAD_OK; }
|
||||
|
||||
bool gpu_enabled() { return false; }
|
||||
|
||||
int gptq_tcq_gpu(const Grid&, float*, int32_t*, Scales&, int64_t, int64_t, const float*, bool,
|
||||
std::string* why) {
|
||||
*why = "this libquant was built without a device path";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
} /* namespace lq */
|
||||
#endif
|
||||
@@ -0,0 +1,37 @@
|
||||
/* lq_gpu.h -- GPTQ over a trellis grid on the card.
|
||||
*
|
||||
* The trellis's Viterbi search is nearly all of a trellis recipe's conversion time: every value
|
||||
* of every column takes a pass over the 2^L states. Each run of tcq_rows rows is independent of
|
||||
* every other through the whole loop (the error feedback stays inside a row, the search inside a
|
||||
* run), so a run is one workgroup and a weight is as many workgroups as it has runs.
|
||||
*
|
||||
* The card performs the host loop's operations in the host's order: the same products, sums and
|
||||
* comparisons, in f32 without contraction (-ffp-contract=off on both sides), ties to the first
|
||||
* state, IEEE division and rounding. The codes and the decoded weight are therefore the host's,
|
||||
* bit for bit, which quant_tcq_gpu_test checks. The scales a dyn=1 block chooses are computed on
|
||||
* the host by the host's own code, from the block's columns as the card left them.
|
||||
*
|
||||
* Only built where radiance has a device build (RAD_HIP_FOUND); elsewhere gpu_set_devices
|
||||
* answers RAD_E_UNSUPPORTED and the host loop is the only one.
|
||||
*/
|
||||
#pragma once
|
||||
#include "lq_grid.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace lq {
|
||||
|
||||
/* The cards trellis GPTQ runs on (rad_quant.h, RadQuantDevicesFn); n = 0 is the host alone.
|
||||
* RAD_E_UNSUPPORTED without a device build, RAD_E_DEVICE for a card that is not there. */
|
||||
int gpu_set_devices(const int* ids, int n);
|
||||
|
||||
/* Whether gpu_set_devices named any card. */
|
||||
bool gpu_enabled();
|
||||
|
||||
/* gptq_quantise over a trellis grid (lq_gptq.cpp's gptq_quantise_tcq) on the cards: the same
|
||||
* codes, the same decoded `w` and the same `scales`. RAD_OK, or a failure with the reason in
|
||||
* *why; nothing is written to `codes` then. */
|
||||
int gptq_tcq_gpu(const Grid& g, float* w, int32_t* codes, Scales& scales, int64_t N, int64_t K,
|
||||
const float* u, bool dynamic, std::string* why);
|
||||
|
||||
} /* namespace lq */
|
||||
+566
-6
@@ -1,6 +1,10 @@
|
||||
/* 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 why the rules must not change. */
|
||||
#include "lq_grid.h"
|
||||
|
||||
#if defined(__x86_64__)
|
||||
#include <immintrin.h>
|
||||
#endif
|
||||
#include "lq_common.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -270,6 +274,38 @@ void search_asym(const Grid& g, const float* w, int64_t cols, int64_t r0, int64_
|
||||
}
|
||||
}
|
||||
|
||||
/* x with Phi(x) = p, the standard normal's quantile, by bisection. */
|
||||
double normal_quantile(double p) {
|
||||
double lo = -10.0, hi = 10.0;
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
const double m = 0.5 * (lo + hi);
|
||||
(0.5 * std::erfc(-m / std::sqrt(2.0)) < p ? lo : hi) = m;
|
||||
}
|
||||
return 0.5 * (lo + hi);
|
||||
}
|
||||
|
||||
/* A trellis's default values: the 2^L quantiles of a normal at (i + 0.5) / 2^L, scaled so the
|
||||
* outermost lands on 127 and rounded, dealt to the states in a fixed random order (Fisher-Yates
|
||||
* over splitmix64), so a state's 2^k successors fall at unrelated levels. */
|
||||
std::vector<float> tcq_default_lut(int L) {
|
||||
const int64_t S = (int64_t)1 << L;
|
||||
const double sigma = 127.0 / normal_quantile(1.0 - 0.5 / (double)S);
|
||||
std::vector<float> lut((size_t)S);
|
||||
for (int64_t i = 0; i < S; ++i) {
|
||||
const double v = std::nearbyint(sigma * normal_quantile(((double)i + 0.5) / (double)S));
|
||||
lut[(size_t)i] = (float)(v < -127.0 ? -127.0 : v > 127.0 ? 127.0 : v);
|
||||
}
|
||||
uint64_t x = 0x5EEDu + (uint64_t)L;
|
||||
for (int64_t i = S - 1; i > 0; --i) {
|
||||
uint64_t z = (x += 0x9E3779B97F4A7C15ull);
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
|
||||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
|
||||
z ^= z >> 31;
|
||||
std::swap(lut[(size_t)i], lut[(size_t)(z % (uint64_t)(i + 1))]);
|
||||
}
|
||||
return lut;
|
||||
}
|
||||
|
||||
/* 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
|
||||
@@ -291,6 +327,156 @@ void store_first_level(const Grid& g, float resid, BlockScale* b) {
|
||||
int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
|
||||
*g = Grid{};
|
||||
const char* codes = rad_param_gets(o, n_o, "codes", nullptr);
|
||||
if (const char* vf = rad_param_gets(o, n_o, "vq", nullptr)) {
|
||||
/* One codeword a line, its integers separated by spaces; a line "# unit X" names the
|
||||
* units a unit-rms vector spans (default: the entries' rms). */
|
||||
FILE* f = std::fopen(vf, "r");
|
||||
if (!f) {
|
||||
if (why) *why = fmt("vq=%s cannot be opened", vf);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
char line[4096];
|
||||
double unit = 0.0;
|
||||
while (std::fgets(line, sizeof line, f)) {
|
||||
if (line[0] == '#') {
|
||||
double u = 0.0;
|
||||
if (std::sscanf(line, "# unit %lf", &u) == 1) unit = u;
|
||||
continue;
|
||||
}
|
||||
std::vector<float> row;
|
||||
char* p = line;
|
||||
for (;;) {
|
||||
char* end = nullptr;
|
||||
const long v = std::strtol(p, &end, 10);
|
||||
if (end == p) break;
|
||||
row.push_back((float)v);
|
||||
p = end;
|
||||
}
|
||||
if (row.empty()) continue;
|
||||
if (g->vdim == 0) g->vdim = (int64_t)row.size();
|
||||
bool ok = (int64_t)row.size() == g->vdim;
|
||||
for (float v : row) ok = ok && v >= -127.0f && v <= 127.0f;
|
||||
if (!ok) {
|
||||
std::fclose(f);
|
||||
if (why) *why = fmt("vq=%s: every codeword has %lld integers in -127..127", vf,
|
||||
(long long)g->vdim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g->vq.insert(g->vq.end(), row.begin(), row.end());
|
||||
}
|
||||
std::fclose(f);
|
||||
g->ventries = g->vdim ? (int64_t)g->vq.size() / g->vdim : 0;
|
||||
if (g->ventries < 2 || g->vdim < 2 || g->vdim > 16 || 128 % g->vdim) {
|
||||
if (why)
|
||||
*why = fmt("vq=%s holds %lld codewords", vf, (long long)g->ventries) +
|
||||
fmt(" of width %s%lld; a vector grid needs 2 or more, their width (2..16) "
|
||||
"dividing 128", "", (long long)g->vdim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!(unit > 0.0)) {
|
||||
double ss = 0.0;
|
||||
for (float v : g->vq) ss += (double)v * v;
|
||||
unit = std::sqrt(ss / (double)g->vq.size());
|
||||
}
|
||||
g->vq_unit = unit;
|
||||
g->vq_soa.resize(g->vq.size());
|
||||
g->vq_n2.assign((size_t)g->ventries, 0.0f);
|
||||
for (int64_t k = 0; k < g->ventries; ++k)
|
||||
for (int64_t j = 0; j < g->vdim; ++j) {
|
||||
const float c = g->vq[(size_t)(k * g->vdim + j)];
|
||||
g->vq_soa[(size_t)(j * g->ventries + k)] = c;
|
||||
g->vq_n2[(size_t)k] += c * c;
|
||||
}
|
||||
if (rad_param_gets(o, n_o, "table", nullptr) || rad_param_gets(o, n_o, "zero", nullptr) ||
|
||||
rad_param_gets(o, n_o, "scale2", nullptr)) {
|
||||
if (why) *why = "vq= is the codebook: no table=, zero= or scale2= beside it";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const uint32_t need = index_dtype((size_t)g->ventries);
|
||||
if (codes && rad_dtype_parse(codes) != need) {
|
||||
if (why) *why = fmt("vq=%s has %lld codewords, which a code of exactly ", vf,
|
||||
(long long)g->ventries) + rad_dtype_name(need) + " indexes";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g->codes = need;
|
||||
}
|
||||
if (const int64_t L = rad_param_geti(o, n_o, "tcq", 0)) {
|
||||
int sg = 0;
|
||||
const uint32_t cdt = codes ? rad_dtype_parse(codes) : (uint32_t)RAD_DT_INVALID;
|
||||
const int k = cdt == RAD_U8 ? 8
|
||||
: rad_dtype_packed_int(cdt, &sg) > 0 && !sg ? rad_dtype_bits(cdt) : 0;
|
||||
if (!k || L <= k || L > 16) {
|
||||
if (why) *why = "tcq=L is a trellis of 2^L states over unsigned codes of k bits, "
|
||||
"codes=u1..u8, k < L <= 16";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!g->vq.empty() || rad_param_gets(o, n_o, "table", nullptr) ||
|
||||
rad_param_gets(o, n_o, "zero", nullptr)) {
|
||||
if (why) *why = "tcq= is the codebook: no vq=, table= or zero= beside it";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g->tcq_L = (int)L;
|
||||
g->tcq_k = k;
|
||||
g->tcq_rows = rad_param_geti(o, n_o, "tcq_rows", 256);
|
||||
if (g->tcq_rows < 1) {
|
||||
if (why) *why = "tcq_rows= is the rows one trellis runs over, 1 or more";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t S = (int64_t)1 << L;
|
||||
double lut_unit = 0.0;
|
||||
if (const char* code = rad_param_gets(o, n_o, "tcq_code", nullptr)) {
|
||||
if (std::strcmp(code, "mad") != 0 || rad_param_gets(o, n_o, "tcq_lut", nullptr)) {
|
||||
if (why) *why = "tcq_code=mad computes the states' values: no tcq_lut=";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g->tcq_mad = true;
|
||||
g->tcq_a = (uint32_t)rad_param_geti(o, n_o, "tcq_a", 0xB5297B) & 0xFFFFFFu;
|
||||
g->tcq_b = (uint32_t)rad_param_geti(o, n_o, "tcq_b", 0x2545F491);
|
||||
g->tcq_lut = tcq_lut_mad((int)L, g->tcq_a, g->tcq_b);
|
||||
} else if (const char* lf = rad_param_gets(o, n_o, "tcq_lut", nullptr)) {
|
||||
/* The states' values, integers in -127..127 separated by white space, in state order;
|
||||
* a line "# unit X" names the units a unit-rms block spans (default: the values' rms). */
|
||||
FILE* f = std::fopen(lf, "r");
|
||||
if (!f) {
|
||||
if (why) *why = fmt("tcq_lut=%s cannot be opened", lf);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
long v = 0;
|
||||
char tok[64];
|
||||
while (std::fscanf(f, "%63s", tok) == 1) {
|
||||
if (tok[0] == '#') {
|
||||
char rest[256] = {};
|
||||
if (!std::fgets(rest, sizeof rest, f)) break;
|
||||
double u = 0.0;
|
||||
if (std::sscanf(rest, " unit %lf", &u) == 1) lut_unit = u;
|
||||
continue;
|
||||
}
|
||||
v = std::strtol(tok, nullptr, 10);
|
||||
g->tcq_lut.push_back((float)(v < -127 ? -127 : v > 127 ? 127 : v));
|
||||
}
|
||||
std::fclose(f);
|
||||
if ((int64_t)g->tcq_lut.size() != S) {
|
||||
if (why) *why = fmt("tcq_lut=%s holds %lld values; tcq= wants one a state", lf,
|
||||
(long long)g->tcq_lut.size());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else {
|
||||
g->tcq_lut = tcq_default_lut((int)L);
|
||||
}
|
||||
double ss = 0.0;
|
||||
for (float v2 : g->tcq_lut) ss += (double)v2 * v2;
|
||||
g->vq_unit = (lut_unit > 0.0 ? lut_unit : std::sqrt(ss / (double)S)) /
|
||||
rad_param_getf(o, n_o, "tcq_gain", 1.0);
|
||||
if (rad_param_geti(o, n_o, "tcq_peak", 0))
|
||||
for (float v2 : g->tcq_lut) g->tcq_peak = std::max(g->tcq_peak, std::fabs(v2));
|
||||
g->tcq_rb = rad_param_geti(o, n_o, "tcq_rb", 0);
|
||||
g->tcq_colf = rad_param_geti(o, n_o, "tcq_colf", 0) != 0;
|
||||
if (g->tcq_rb < 0 || (g->tcq_rb && g->tcq_rows % g->tcq_rb)) {
|
||||
if (why) *why = "tcq_rb= is the rows one int8 scale covers; it must divide tcq_rows";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g->codes = cdt;
|
||||
}
|
||||
const char* tab = rad_param_gets(o, n_o, "table", nullptr);
|
||||
if (tab) {
|
||||
if (!parse_table(tab, &g->table, why)) return RAD_E_INVAL;
|
||||
@@ -324,14 +510,16 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
|
||||
}
|
||||
g->tpeak = -mn >= mx ? mn : mx;
|
||||
g->tsigned = -mn != mx;
|
||||
} else if (!codes) {
|
||||
} else if (!codes && g->vq.empty()) {
|
||||
if (why) *why = "codes= is required: the code dtype, e.g. i4, u2, fp8_e4m3, fp4_e2m1 -- "
|
||||
"or table= for a codebook";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!tab) g->codes = rad_dtype_parse(codes);
|
||||
/* A codebook, scalar or vector, sets the code dtype itself: its codes index entries. */
|
||||
const bool cb = tab || !g->vq.empty() || g->tcq_L;
|
||||
if (!cb) g->codes = rad_dtype_parse(codes);
|
||||
const int bits = rad_dtype_bits(g->codes);
|
||||
g->is_float = tab ? false : is_float_code(g->codes);
|
||||
g->is_float = cb ? false : is_float_code(g->codes);
|
||||
int sgn = 0;
|
||||
bool packed = rad_dtype_packed_int(g->codes, &sgn) > 0 || g->codes == RAD_I8 ||
|
||||
g->codes == RAD_U8;
|
||||
@@ -341,7 +529,7 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
|
||||
g->wide = true;
|
||||
sgn = g->codes != RAD_U16;
|
||||
}
|
||||
if (!tab && !g->is_float && !packed) {
|
||||
if (!cb && !g->is_float && !packed) {
|
||||
if (why) *why = fmt("codes=%s is not a code dtype this grid writes", codes);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -356,7 +544,7 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
|
||||
}
|
||||
g->asym = true;
|
||||
}
|
||||
if (tab) {
|
||||
if (cb) {
|
||||
/* The codebook already set the code dtype. */
|
||||
} else if (!g->is_float) {
|
||||
if (g->asym && sgn) {
|
||||
@@ -537,9 +725,24 @@ int grid_parse(const RadParam* o, int n_o, Grid* g, std::string* why) {
|
||||
|
||||
RadEncoding grid_encoding(const Grid& g) {
|
||||
RadEncoding e = rad_enc_affine(g.codes, g.scale_dt, g.br, g.bc);
|
||||
if (!g.vq.empty()) e.plane[0].block[1] = g.vdim; /* one code a vector */
|
||||
if (g.asym) rad_enc_add_plane(&e, "zero", g.zero_dt, g.br, g.bc);
|
||||
if (g.lv2) rad_enc_add_plane(&e, "scale.1", g.scale2_dt, g.br2, g.bc2);
|
||||
if (!g.table.empty()) rad_enc_add_table(&e, "table", g.table_dt, 1, (int64_t)g.table.size());
|
||||
if (!g.vq.empty()) rad_enc_add_table(&e, "grid", RAD_I8, g.ventries, g.vdim);
|
||||
if (g.tcq_L) {
|
||||
/* Its own scheme: a value is its state's, not its code's, so the core's affine reading
|
||||
* would be wrong; libquant decodes it (grid_tcq_decode). The states' values are a table,
|
||||
* whose block is otherwise unused and here holds the rows one trellis runs over and the
|
||||
* rows one int8 scale covers (tcq_rb; 1, each row its own, is the plain trellis). */
|
||||
rad_enc_copy_str(e.scheme, "trellis");
|
||||
const int i = rad_enc_add_table(&e, "trellis", RAD_I8, (int64_t)1 << g.tcq_L, 1);
|
||||
if (i >= 0) e.plane[i].block[0] = g.tcq_rows, e.plane[i].block[1] = g.tcq_rb ? g.tcq_rb : 1;
|
||||
/* tcq_code=mad: A and B, the code a reader computes the table from */
|
||||
if (g.tcq_mad) rad_enc_add_table(&e, "trellis.mad", RAD_U32, 2, 1);
|
||||
/* one scale a row: each 128-column block's factor, one for all rows (Grid::row_scaled) */
|
||||
if (g.row_scaled()) rad_enc_add_plane(&e, "scale.col", RAD_F32, 0, 128);
|
||||
}
|
||||
if (g.fwht) {
|
||||
char t[RAD_ENC_STR];
|
||||
std::snprintf(t, sizeof t, "fwht%lld", (long long)g.fwht);
|
||||
@@ -559,6 +762,35 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
|
||||
BlockScale b;
|
||||
const float resid = g.fwht ? 1.0f / (float)g.fwht : 1.0f;
|
||||
|
||||
if (!g.vq.empty() || g.tcq_L) {
|
||||
/* A vector grid or a trellis: the block's rms in the codebook's units. */
|
||||
double ss = 0.0;
|
||||
int64_t n = 0;
|
||||
for (int64_t r = r0; r < r1; ++r)
|
||||
for (int64_t c = c0; c < c1; ++c, ++n) ss += (double)w[r * cols + c] * w[r * cols + c];
|
||||
double s0 = n > 0 && ss > 0.0 ? std::sqrt(ss / (double)n) / g.vq_unit : 1e-12;
|
||||
if (g.tcq_peak > 0.0f) {
|
||||
/* No value past the table's reach: an unrotated weight's outlying values would
|
||||
* otherwise be clipped to it. */
|
||||
double amax = 0.0;
|
||||
for (int64_t r = r0; r < r1; ++r)
|
||||
for (int64_t c = c0; c < c1; ++c) amax = std::max(amax, (double)std::fabs(w[r * cols + c]));
|
||||
s0 = std::max(s0, amax / g.tcq_peak);
|
||||
}
|
||||
if (g.lv2) {
|
||||
/* The first level's ideal scale, which the second level's pass rounds. */
|
||||
b.s = b.stored = (float)s0;
|
||||
b.inv = 1.0f / b.s;
|
||||
b.inv_d = 1.0 / (double)b.s;
|
||||
return b;
|
||||
}
|
||||
b.s = round_nz(g.scale_dt, (float)s0);
|
||||
b.inv = 1.0f / b.s;
|
||||
b.inv_d = 1.0 / (double)b.s;
|
||||
store_first_level(g, resid, &b);
|
||||
return b;
|
||||
}
|
||||
|
||||
if (g.rule == Grid::FIXED) {
|
||||
/* 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;
|
||||
@@ -727,6 +959,291 @@ int grid_code(const Grid& g, const BlockScale& b, float v) {
|
||||
return clampi(round_away(x), g.qmin, g.qmax);
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* |c|^2 - 2 x.c for every entry into `d`, entries in a tile at a time; the first minimum wins.
|
||||
* Built for each instruction set and chosen at load; the sums run in the same order everywhere. */
|
||||
__attribute__((target_clones("avx512f", "avx2", "default")))
|
||||
int vq_argmin(const float* soa, const float* n2, int64_t E, int64_t D, const float* x) {
|
||||
constexpr int64_t kT = 256;
|
||||
float d[kT];
|
||||
int best = 0;
|
||||
float bd = 0.0f;
|
||||
for (int64_t e0 = 0; e0 < E; e0 += kT) {
|
||||
const int64_t n = E - e0 < kT ? E - e0 : kT;
|
||||
for (int64_t k = 0; k < n; ++k) d[k] = n2[e0 + k];
|
||||
for (int64_t j = 0; j < D; ++j) {
|
||||
const float m = -2.0f * x[j];
|
||||
const float* c = soa + j * E + e0;
|
||||
for (int64_t k = 0; k < n; ++k) d[k] += m * c[k];
|
||||
}
|
||||
for (int64_t k = 0; k < n; ++k)
|
||||
if ((e0 == 0 && k == 0) || d[k] < bd) { bd = d[k]; best = (int)(e0 + k); }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
int grid_vq_code(const Grid& g, const BlockScale& b, const float* v) {
|
||||
float x[16];
|
||||
for (int64_t j = 0; j < g.vdim; ++j) x[j] = v[j] * b.inv;
|
||||
return vq_argmin(g.vq_soa.data(), g.vq_n2.data(), g.ventries, g.vdim, x);
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* A tcq_rb value: v * rt rounded to an integer, nearest even -- of the product as an f32 (rintf),
|
||||
* or for a computed code (Grid::tcq_mad) of the exact product, which one fma against 1.5 * 2^23
|
||||
* rounds (|v * rt| <= 127), as the GEMMs decode it in one instruction. */
|
||||
inline float rb_round(float v, float rt, bool fused) {
|
||||
return fused ? std::fma(v, rt, 12582912.0f) - 12582912.0f : rintf(v * rt);
|
||||
}
|
||||
|
||||
/* One trellis step over every state: the cheaper of each state's 2^k predecessors into `best`
|
||||
* and `from` (which one, by its top k bits; the first on a tie), then each state's cost, its
|
||||
* squared error plus its predecessor's. State st's predecessors are q + t * Q for t < 2^k,
|
||||
* q = st >> k, Q = 2^(L-k). A state's value is s * lut[st], or with `rt` >= 0 (tcq_rb)
|
||||
* s * rint(lut[st] * rt). The AVX-512 form computes the same operations in the same order, so
|
||||
* the two give the same codes. */
|
||||
__attribute__((target_clones("avx2", "default")))
|
||||
void tcq_step_generic(const float* cost, float* next, float* best, uint8_t* from, const float* lut,
|
||||
int64_t Q, int B, float x, float s, float rt, bool fused) {
|
||||
for (int64_t q = 0; q < Q; ++q) { best[q] = cost[q]; from[q] = 0; }
|
||||
for (int t = 1; t < B; ++t) {
|
||||
const float* c = cost + (int64_t)t * Q;
|
||||
for (int64_t q = 0; q < Q; ++q)
|
||||
if (c[q] < best[q]) { best[q] = c[q]; from[q] = (uint8_t)t; }
|
||||
}
|
||||
const int64_t S = Q * B;
|
||||
for (int64_t st = 0; st < S; ++st) {
|
||||
const float d = x - s * (rt >= 0.0f ? rb_round(lut[st], rt, fused) : lut[st]);
|
||||
next[st] = d * d + best[st / B];
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(__x86_64__)
|
||||
__attribute__((target("avx512f,avx512bw,avx512vl")))
|
||||
void tcq_step_avx512(const float* cost, float* next, float* best, uint8_t* from, const float* lut,
|
||||
int64_t Q, int B, float x, float s, float rt, bool fused) {
|
||||
for (int64_t q = 0; q < Q; q += 16) {
|
||||
__m512 m = _mm512_loadu_ps(cost + q);
|
||||
__m512i a = _mm512_setzero_si512();
|
||||
for (int t = 1; t < B; ++t) {
|
||||
const __m512 c = _mm512_loadu_ps(cost + (int64_t)t * Q + q);
|
||||
const __mmask16 lt = _mm512_cmp_ps_mask(c, m, _CMP_LT_OQ);
|
||||
m = _mm512_mask_mov_ps(m, lt, c);
|
||||
a = _mm512_mask_mov_epi32(a, lt, _mm512_set1_epi32(t));
|
||||
}
|
||||
_mm512_storeu_ps(best + q, m);
|
||||
_mm_storeu_si128((__m128i*)(from + q), _mm512_cvtepi32_epi8(a));
|
||||
}
|
||||
const int64_t S = Q * B;
|
||||
const __m512 xv = _mm512_set1_ps(x), sv = _mm512_set1_ps(s), rv = _mm512_set1_ps(rt);
|
||||
/* Lane j of a 16-state run takes best[(st + j) / B]: a permute for B <= 16, else one value. */
|
||||
const int per = B < 16 ? 16 / B : 1;
|
||||
alignas(64) int32_t lane[16];
|
||||
for (int j = 0; j < 16; ++j) lane[j] = B < 16 ? j / B : 0;
|
||||
const __m512i idx = _mm512_load_si512(lane);
|
||||
const __mmask16 take = (__mmask16)((1u << per) - 1u);
|
||||
for (int64_t st = 0; st < S; st += 16) {
|
||||
const __m512 bq = _mm512_permutexvar_ps(idx, _mm512_maskz_loadu_ps(take, best + st / B));
|
||||
__m512 v = _mm512_loadu_ps(lut + st);
|
||||
/* rintf's rounding: to nearest, ties to even; fused, of the exact product (rb_round) */
|
||||
if (rt >= 0.0f && fused) {
|
||||
const __m512 mg = _mm512_set1_ps(12582912.0f);
|
||||
v = _mm512_sub_ps(_mm512_fmadd_ps(v, rv, mg), mg);
|
||||
} else if (rt >= 0.0f) {
|
||||
v = _mm512_roundscale_ps(_mm512_mul_ps(v, rv), _MM_FROUND_TO_NEAREST_INT |
|
||||
_MM_FROUND_NO_EXC);
|
||||
}
|
||||
const __m512 d = _mm512_sub_ps(xv, _mm512_mul_ps(sv, v));
|
||||
_mm512_storeu_ps(next + st, _mm512_add_ps(_mm512_mul_ps(d, d), bq));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void tcq_step(const float* cost, float* next, float* best, uint8_t* from, const float* lut,
|
||||
int64_t Q, int B, float x, float s, float rt, bool fused) {
|
||||
#if defined(__x86_64__)
|
||||
static const bool avx512 = __builtin_cpu_supports("avx512f") &&
|
||||
__builtin_cpu_supports("avx512bw") &&
|
||||
__builtin_cpu_supports("avx512vl");
|
||||
if (avx512 && Q % 16 == 0) return tcq_step_avx512(cost, next, best, from, lut, Q, B, x, s, rt, fused);
|
||||
#endif
|
||||
tcq_step_generic(cost, next, best, from, lut, Q, B, x, s, rt, fused);
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
namespace {
|
||||
/* Viterbi over n rows: from predecessor state `start`, or from any state when start < 0; the path
|
||||
* of least cost ending in state `end`, or in the cheapest when end < 0. Its states into `path`. */
|
||||
void tcq_viterbi(const Grid& g, const float* x, const float* s, const float* rt, int64_t n,
|
||||
int64_t start, int64_t end, int64_t* path, TcqWork& w) {
|
||||
const int L = g.tcq_L, k = g.tcq_k, B = 1 << k;
|
||||
const int64_t S = (int64_t)1 << L, Q = S >> k, mask = S - 1;
|
||||
const float* lut = g.tcq_lut.data();
|
||||
const float inf = 3.0e38f;
|
||||
for (int64_t st = 0; st < S; ++st) {
|
||||
const float d = x[0] - s[0] * (rt ? rb_round(lut[st], rt[0], g.tcq_mad) : lut[st]);
|
||||
w.cost[(size_t)st] = start < 0 || (st >> k) == (start & (Q - 1)) ? d * d : inf;
|
||||
}
|
||||
for (int64_t r = 1; r < n; ++r) {
|
||||
tcq_step(w.cost.data(), w.next.data(), w.best.data(), w.back.data() + r * Q, lut, Q, B,
|
||||
x[r], s[r], rt ? rt[r] : -1.0f, g.tcq_mad);
|
||||
w.cost.swap(w.next);
|
||||
}
|
||||
int64_t st = end;
|
||||
if (st < 0) {
|
||||
st = 0;
|
||||
for (int64_t i = 1; i < S; ++i)
|
||||
if (w.cost[(size_t)i] < w.cost[(size_t)st]) st = i;
|
||||
}
|
||||
for (int64_t r = n - 1; r >= 0; --r) {
|
||||
path[r] = st;
|
||||
if (r > 0) {
|
||||
const int64_t q = st >> k;
|
||||
st = (q + (int64_t)w.back[(size_t)(r * Q + q)] * Q) & mask;
|
||||
}
|
||||
}
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
void grid_tcq_run(const Grid& g, const float* x, const float* s, int64_t n, int32_t* codes,
|
||||
float* dq, TcqWork& w, const float* ratio) {
|
||||
const int k = g.tcq_k;
|
||||
const int64_t S = (int64_t)1 << g.tcq_L;
|
||||
w.cost.resize((size_t)S);
|
||||
w.next.resize((size_t)S);
|
||||
w.best.resize((size_t)(S >> k));
|
||||
w.back.resize((size_t)(n * (S >> k)));
|
||||
w.rx.resize((size_t)n);
|
||||
w.rs.resize((size_t)n);
|
||||
w.rr.resize(ratio ? (size_t)n : 0);
|
||||
w.path.resize((size_t)n);
|
||||
/* Tail-biting: the run's state before its first row is its state after its last, so no bits
|
||||
* go to a start. The boundary state is taken from the best free path over a window across
|
||||
* the seam -- the run's last h rows, then its first h -- at the seam; survivor paths merge
|
||||
* within a few state lengths, so a window of 8 of them finds the state the whole rotated run
|
||||
* would. The run is then searched from and to that state. */
|
||||
const int64_t c = (g.tcq_L + k - 1) / k;
|
||||
const int64_t h = 8 * c < n / 2 ? 8 * c : n / 2;
|
||||
for (int64_t i = 0; i < 2 * h; ++i) {
|
||||
const int64_t r = i < h ? n - h + i : i - h;
|
||||
w.rx[(size_t)i] = x[r];
|
||||
w.rs[(size_t)i] = s[r];
|
||||
if (ratio) w.rr[(size_t)i] = ratio[r];
|
||||
}
|
||||
tcq_viterbi(g, w.rx.data(), w.rs.data(), ratio ? w.rr.data() : nullptr, 2 * h, -1, -1,
|
||||
w.path.data(), w);
|
||||
const int64_t seam = w.path[(size_t)(h - 1)];
|
||||
tcq_viterbi(g, x, s, ratio, n, seam, seam, w.path.data(), w);
|
||||
const float* lut = g.tcq_lut.data();
|
||||
for (int64_t r = 0; r < n; ++r) {
|
||||
const int64_t st = w.path[(size_t)r];
|
||||
codes[r] = (int32_t)(st & ((1 << k) - 1));
|
||||
dq[r] = (ratio ? rb_round(lut[st], ratio[r], g.tcq_mad) : lut[st]) * s[r];
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<float> tcq_lut_mad(int L, uint32_t a, uint32_t b) {
|
||||
std::vector<float> lut((size_t)1 << L);
|
||||
for (uint32_t st = 0; st < (1u << L); ++st) {
|
||||
const uint32_t h = (((st & 0xFFFFFFu) * (a & 0xFFFFFFu)) + b) & 0x3F3F3F3Fu;
|
||||
lut[st] = (float)((int)((h & 0xFFu) + ((h >> 8) & 0xFFu) + ((h >> 16) & 0xFFu) + (h >> 24)) - 126);
|
||||
}
|
||||
return lut;
|
||||
}
|
||||
|
||||
int grid_tcq_decode(const RadEncoding* e, int64_t rows_all, int64_t cols, const void* const* planes,
|
||||
int64_t row0, int64_t rows, float* out) {
|
||||
const int nm = (rad_enc_plane(e, "trellis.mad") ? 1 : 0) + (rad_enc_plane(e, "scale.col") ? 1 : 0);
|
||||
if (!rad_enc_is(e, "trellis") || (e->n_planes - nm != 3 && e->n_planes - nm != 4))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const RadEncPlane *cp = &e->plane[0], *sp = rad_enc_plane(e, "scale"),
|
||||
*s2p = rad_enc_plane(e, "scale.1"), *tp = rad_enc_plane(e, "trellis");
|
||||
int sg = 0;
|
||||
const int bits = cp->dtype == RAD_U8 ? 8
|
||||
: rad_dtype_packed_int(cp->dtype, &sg) > 0 && !sg ? rad_dtype_bits(cp->dtype) : 0;
|
||||
if (!bits || !sp || !tp || sp->kind != RAD_PLANE_TILED || sp->block[0] != 1 ||
|
||||
sp->block[1] < 0 || tp->kind != RAD_PLANE_TABLE || tp->dtype != RAD_I8 ||
|
||||
tp->extent[1] != 1 || tp->block[0] < 1 || (e->n_planes - nm == 4) != (s2p != nullptr))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
/* a scale block of 0 columns is the whole row (tcq_colf's one scale a row) */
|
||||
const int64_t S = tp->extent[0], T = tp->block[0], bc = sp->block[1] ? sp->block[1] : cols,
|
||||
rb = tp->block[1];
|
||||
const RadEncPlane* cfp = rad_enc_plane(e, "scale.col");
|
||||
const float* cf = cfp ? (const float*)planes[cfp - e->plane] : nullptr;
|
||||
if (S < 2 || (S & (S - 1)) || cols % bc || rb < 1 || T % rb) return RAD_E_FORMAT;
|
||||
if (row0 % T || (rows % T && row0 + rows != rows_all)) return RAD_E_SHAPE;
|
||||
int L = 0;
|
||||
while (((int64_t)1 << L) < S) ++L;
|
||||
const int64_t c = (L + bits - 1) / bits, fw = rad_enc_fwht(e);
|
||||
const uint32_t mask = (uint32_t)(S - 1);
|
||||
const uint8_t* codes = (const uint8_t*)planes[0];
|
||||
const uint8_t* scale = (const uint8_t*)planes[1];
|
||||
const int8_t* lut = (const int8_t*)planes[tp - e->plane];
|
||||
const int64_t crow = rad_enc_row_bytes(cp->dtype, cols);
|
||||
const int64_t srow = rad_enc_row_bytes(sp->dtype, cols / bc);
|
||||
/* A block's scale as the int8 GEMMs read it: the first level, or the bf16 of the first level
|
||||
* times the second (grid_tcq_settle). */
|
||||
const uint8_t* s2 = s2p ? (const uint8_t*)planes[s2p - e->plane] : nullptr;
|
||||
int64_t s2c = 1, s2rb = 0, s2cb = 0, s2row = 0;
|
||||
if (s2p) {
|
||||
s2rb = s2p->block[0];
|
||||
s2cb = s2p->block[1];
|
||||
s2c = s2cb > 0 ? (cols + s2cb - 1) / s2cb : 1;
|
||||
s2row = rad_enc_row_bytes(s2p->dtype, s2c);
|
||||
}
|
||||
auto block_scale = [&](int64_t r, int64_t j) -> float {
|
||||
const float l1 = rad_load_f32(scale + r * srow, sp->dtype, j / bc);
|
||||
if (!s2) return l1;
|
||||
const int64_t i2 = s2rb > 0 ? r / s2rb : 0, j2 = s2cb > 0 ? j / s2cb : 0;
|
||||
return round_to(RAD_BF16, l1 * rad_load_f32(s2 + i2 * s2row, s2p->dtype, j2));
|
||||
};
|
||||
/* With rows per int8 scale rb > 1 (Grid::tcq_rb), row r's value is
|
||||
* B * rint(lut[state] * (s_r / B)), B the largest of its rb-row block's scales. */
|
||||
/* Runs decode independently. Only the last can be short; one shorter than a state's codes
|
||||
* cannot hold its seam. */
|
||||
if (rows > 0 && std::min(row0 + rows, rows_all) - (row0 + (rows - 1) / T * T) < c)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t runs = (rows + T - 1) / T;
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(dynamic, 1) if (runs > 1 && rows * cols > (1 << 20))
|
||||
#endif
|
||||
for (int64_t ri = 0; ri < runs; ++ri) {
|
||||
const int64_t r0 = row0 + ri * T;
|
||||
const int64_t r1 = std::min(r0 + T, rows_all);
|
||||
std::vector<float> bmax(rb > 1 ? (size_t)(cols / bc) : 0);
|
||||
std::vector<uint32_t> st((size_t)cols, 0u);
|
||||
for (int64_t t = r1 - c; t < r1; ++t)
|
||||
for (int64_t j = 0; j < cols; ++j)
|
||||
st[(size_t)j] = ((st[(size_t)j] << bits) |
|
||||
(uint32_t)rad_load_bits(codes + t * crow, bits, j)) & mask;
|
||||
for (int64_t r = r0; r < r1; ++r) {
|
||||
float* o = out + (r - row0) * cols;
|
||||
if (rb > 1 && r % rb == 0)
|
||||
for (int64_t jb = 0; jb < cols / bc; ++jb) {
|
||||
float m = 0.0f;
|
||||
for (int64_t q = r; q < std::min(r + rb, rows_all); ++q)
|
||||
m = std::max(m, block_scale(q, jb * bc));
|
||||
bmax[(size_t)jb] = m;
|
||||
}
|
||||
for (int64_t j = 0; j < cols; ++j) {
|
||||
st[(size_t)j] = ((st[(size_t)j] << bits) |
|
||||
(uint32_t)rad_load_bits(codes + r * crow, bits, j)) & mask;
|
||||
const float sr = block_scale(r, j);
|
||||
if (rb > 1) {
|
||||
const float bm = bmax[(size_t)(j / bc)];
|
||||
o[j] = bm > 0.0f ? rb_round((float)lut[st[(size_t)j]], sr / bm, nm != 0) * bm : 0.0f;
|
||||
} else {
|
||||
o[j] = (float)lut[st[(size_t)j]] * (cf ? sr * cf[j / 128] : sr);
|
||||
}
|
||||
}
|
||||
if (fw > 0)
|
||||
for (int64_t j = 0; j < cols; j += fw) fwht_inplace(o + j, fw);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
float grid_decode(const Grid& g, const BlockScale& b, int code) {
|
||||
if (!g.table.empty()) return g.table[(size_t)code] * b.s;
|
||||
if (g.is_float) {
|
||||
@@ -761,7 +1278,7 @@ Planes grid_planes(const Grid& g, int64_t cols, void* const* planes) {
|
||||
p.codes = (uint8_t*)planes[0];
|
||||
p.scale = (uint8_t*)planes[1];
|
||||
p.zero = g.asym ? (uint8_t*)planes[2] : nullptr;
|
||||
p.codes_row = rad_dtype_bytes(g.codes, cols);
|
||||
p.codes_row = rad_dtype_bytes(g.codes, g.vq.empty() ? cols : cols / g.vdim);
|
||||
p.scale_row = rad_dtype_bytes(g.scale_dt, sc);
|
||||
p.zero_row = g.asym ? rad_dtype_bytes(g.zero_dt, sc) : 0;
|
||||
p.scale_cols = sc;
|
||||
@@ -771,15 +1288,42 @@ Planes grid_planes(const Grid& g, int64_t cols, void* const* planes) {
|
||||
p.scale2_row = rad_dtype_bytes(g.scale2_dt, p.scale2_cols);
|
||||
}
|
||||
if (!g.table.empty()) p.table = (uint8_t*)planes[g.plane_table()];
|
||||
if (!g.vq.empty() || g.tcq_L) p.grid = (uint8_t*)planes[g.plane_grid()];
|
||||
if (g.tcq_mad) p.mad = (uint8_t*)planes[g.plane_mad()];
|
||||
if (g.row_scaled()) {
|
||||
p.colf = (uint8_t*)planes[g.plane_colf()];
|
||||
p.colf_cols = cols / 128;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
void grid_transform_rows(const Grid& g, float* w, int64_t rows, int64_t cols) {
|
||||
if (!g.fwht) return;
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static) if (rows * cols > (1 << 20))
|
||||
#endif
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < cols; c += g.fwht) fwht_inplace(w + r * cols + c, g.fwht);
|
||||
}
|
||||
|
||||
void grid_tcq_settle(const Grid& g, float s2, BlockScale* b) {
|
||||
const float resid = g.fwht ? 1.0f / (float)g.fwht : 1.0f;
|
||||
const float eff = round_to(RAD_BF16, b->stored * s2);
|
||||
b->s = eff != 0.0f ? eff / resid : s2 / resid;
|
||||
b->inv = 1.0f / b->s;
|
||||
b->inv_d = 1.0 / (double)b->s;
|
||||
}
|
||||
|
||||
BlockScale grid_tcq_block_lv2(const Grid& g, double ideal, float s2) {
|
||||
const float resid = g.fwht ? 1.0f / (float)g.fwht : 1.0f;
|
||||
const double t = (double)s2 / resid;
|
||||
const float q = (float)std::min(std::max(ideal / t, 0.0), (double)g.l1max);
|
||||
BlockScale b;
|
||||
b.stored = q > 0.0f ? round_nz(g.scale_dt, q) : round_nz(g.scale_dt, tiny_of(g.scale_dt));
|
||||
grid_tcq_settle(g, s2, &b);
|
||||
return b;
|
||||
}
|
||||
|
||||
Scales grid_scales(const Grid& g, const float* w, int64_t rows, int64_t cols, const float* imp) {
|
||||
Scales s;
|
||||
s.br = g.br > 0 ? g.br : rows;
|
||||
@@ -881,6 +1425,11 @@ 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);
|
||||
}
|
||||
if (g.tcq_L)
|
||||
for (int64_t i = 0; i < s.nr; ++i)
|
||||
for (int64_t j = 0; j < s.nc; ++j)
|
||||
grid_tcq_settle(g, s.s2[(size_t)(((i * s.br) / br2) * s.nc2 + (j * s.bc) / bc2)],
|
||||
&s.b[(size_t)(i * s.nc + j)]);
|
||||
/* 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)
|
||||
@@ -913,6 +1462,17 @@ void grid_store_scales(const Grid& g, const Scales& s, const Planes& p) {
|
||||
rad_store_f32(row, g.scale2_dt, j, v);
|
||||
}
|
||||
}
|
||||
if (p.grid)
|
||||
for (size_t k = 0; k < g.vq.size(); ++k) ((int8_t*)p.grid)[k] = (int8_t)g.vq[k];
|
||||
if (p.grid)
|
||||
for (size_t k = 0; k < g.tcq_lut.size(); ++k) ((int8_t*)p.grid)[k] = (int8_t)g.tcq_lut[k];
|
||||
if (p.mad) {
|
||||
((uint32_t*)p.mad)[0] = g.tcq_a;
|
||||
((uint32_t*)p.mad)[1] = g.tcq_b;
|
||||
}
|
||||
if (p.colf)
|
||||
for (int64_t k = 0; k < p.colf_cols; ++k)
|
||||
((float*)p.colf)[k] = s.colf.empty() ? 1.0f : s.colf[(size_t)k];
|
||||
if (p.table)
|
||||
for (size_t k = 0; k < g.table.size(); ++k) {
|
||||
if (g.table_dt == RAD_I8) ((int8_t*)p.table)[k] = (int8_t)g.table[k];
|
||||
|
||||
@@ -88,9 +88,56 @@ struct Grid {
|
||||
int l1_lo = 0, l1_hi = 0; /* its range */
|
||||
float l1max = 0.0f; /* the largest first-level value its dtype holds */
|
||||
|
||||
/* A vector codebook (vq=FILE): one code per `vdim` consecutive columns, indexing `vq`
|
||||
* (`ventries` rows of `vdim` integer values in -127..127), stored as the encoding's `grid`
|
||||
* table. A block's scale matches its rms to the codebook's: a value v is the entry over
|
||||
* `vq_unit`, the units a unit-rms vector the codebook was fitted to spans. */
|
||||
std::vector<float> vq;
|
||||
int64_t vdim = 0, ventries = 0;
|
||||
double vq_unit = 1.0;
|
||||
/* The search's layout: vq_soa[j * ventries + k] = entry k's j-th value, vq_n2[k] its squared
|
||||
* norm, so the distances to every entry vectorise across entries. */
|
||||
std::vector<float> vq_soa, vq_n2;
|
||||
|
||||
/* A trellis (tcq=L): the codes of a column, one per row, are the bits a bitshift trellis
|
||||
* shifts in. Row r's value is tcq_lut[state_r] times its block's scale, where state_r =
|
||||
* (state_{r-1} << k | code_r) mod 2^L, k the code's bits. Each run of tcq_rows rows is
|
||||
* tail-biting: the state before its first row is the one after its last, which its last
|
||||
* ceil(L/k) codes make. A block's scale matches its rms to the table's, as a vector grid's
|
||||
* does (vq_unit). */
|
||||
int tcq_L = 0, tcq_k = 0;
|
||||
int64_t tcq_rows = 0;
|
||||
std::vector<float> tcq_lut; /* 2^L integer values in -127..127 */
|
||||
float tcq_peak = 0.0f; /* tcq_peak=1: the table's largest magnitude, which no
|
||||
block's largest value may pass; else 0 */
|
||||
/* tcq_rb=R: the values on the int8 grid an int8 GEMM reads with one scale per R rows (and the
|
||||
* block's 128 columns), the largest of the R rows' scales: row r's value is
|
||||
* B * rint(lut[state] * (s_r / B)), B that largest. The row holding it keeps its values; the
|
||||
* others' are rounded onto B's grid, inside the trellis's search. 0: off. */
|
||||
int64_t tcq_rb = 0;
|
||||
/* tcq_colf=1 (one scale a row, block=1x*): each 128-column block's values also take a factor
|
||||
* shared by every row, its share of the weight's energy, so a value's scale is its row's times
|
||||
* its block's. A GEMM folds the factor into the activation's per-128 scale, which it multiplies
|
||||
* anyway, and the row's in its epilogue. Chosen from the weight before GPTQ. */
|
||||
bool tcq_colf = false;
|
||||
/* tcq_code=mad: the states' values are computed, not chosen: with h = (st * A + B) mod 2^32
|
||||
* (the product of the factors' low 24 bits), state st's value is bytesum(h & 0x3F3F3F3F) - 126
|
||||
* (tcq_lut_mad). A reader needs no table: a multiply-add, a mask and a byte-sum dot a value. The
|
||||
* table is still stored, A and B beside it ("trellis.mad"). */
|
||||
bool tcq_mad = false;
|
||||
uint32_t tcq_a = 0, tcq_b = 0;
|
||||
|
||||
/* The planes of the encoding, by index; -1 when the grid has none. */
|
||||
int plane_zero() const { return asym ? 2 : -1; }
|
||||
int plane_grid() const {
|
||||
return vq.empty() && !tcq_L ? -1 : 2 + (asym ? 1 : 0) + (lv2 ? 1 : 0);
|
||||
}
|
||||
int plane_scale2() const { return lv2 ? (asym ? 3 : 2) : -1; }
|
||||
int plane_mad() const { return tcq_mad ? plane_grid() + 1 : -1; }
|
||||
/* A trellis under one scale a row (block=1x*) carries the 128-column blocks' factors beside it,
|
||||
* tcq_colf's or ones, so a reader has one form for both (libr4d's kRowF32). */
|
||||
bool row_scaled() const { return tcq_L && br == 1 && bc == 0 && !lv2; }
|
||||
int plane_colf() const { return row_scaled() ? plane_grid() + (tcq_mad ? 2 : 1) : -1; }
|
||||
int plane_table() const {
|
||||
return table.empty() ? -1 : 2 + (asym ? 1 : 0) + (lv2 ? 1 : 0);
|
||||
}
|
||||
@@ -129,8 +176,41 @@ BlockScale grid_block_scale(const Grid& g, const float* w, int64_t cols, int64_t
|
||||
|
||||
/* One value onto the grid: its code, and the value the code decodes to (for error feedback). */
|
||||
int grid_code(const Grid& g, const BlockScale& b, float v);
|
||||
/* A vector grid's code for the `vdim` values at `v`: the entry nearest v times b.inv. */
|
||||
int grid_vq_code(const Grid& g, const BlockScale& b, const float* v);
|
||||
float grid_decode(const Grid& g, const BlockScale& b, int code);
|
||||
|
||||
/* tcq_code=mad's value of every one of the 2^L states (Grid::tcq_mad). */
|
||||
std::vector<float> tcq_lut_mad(int L, uint32_t a, uint32_t b);
|
||||
|
||||
/* A trellis grid's search state for one run, reused across runs. */
|
||||
struct TcqWork {
|
||||
std::vector<float> cost, next, best, rx, rs, rr;
|
||||
std::vector<uint8_t> back;
|
||||
std::vector<int64_t> path;
|
||||
};
|
||||
/* A trellis grid's codes for a run of n <= tcq_rows rows of one column: a tail-biting path (the
|
||||
* state before the first row is the state after the last) of least sum over the rows of
|
||||
* (x_r - v_r)^2, v_r = s_r * lut[state_r], its codes into `codes` and the values they decode to
|
||||
* into `dq`. With `ratio` (tcq_rb), v_r = s_r * rint(lut[state_r] * ratio_r) instead: s_r is then
|
||||
* the row block's scale and ratio_r the row's own scale over it. */
|
||||
void grid_tcq_run(const Grid& g, const float* x, const float* s, int64_t n, int32_t* codes,
|
||||
float* dq, TcqWork& w, const float* ratio = nullptr);
|
||||
|
||||
/* A trellis grid's two-level scales are read as one bf16 a block: the bf16 of the first level
|
||||
* (b->stored) times the second's stored value s2, which is what libr4d widens them to for its
|
||||
* int8 GEMMs. Settle b's scale to that. */
|
||||
void grid_tcq_settle(const Grid& g, float s2, BlockScale* b);
|
||||
/* A trellis block's two-level scale from its ideal (unrounded) scale under the second level's
|
||||
* stored s2, settled: dyn=1's choice when GPTQ reaches the block. */
|
||||
BlockScale grid_tcq_block_lv2(const Grid& g, double ideal, float s2);
|
||||
|
||||
/* Rows [row0, row0 + rows) of a "trellis" weight of rows_all x cols back to f32 in its logical
|
||||
* basis (the transform undone), from the plane starts: abi/rad_quant.h's decode hook. Whole runs
|
||||
* only, but for the weight's last. RAD_E_UNSUPPORTED for any other encoding. */
|
||||
int grid_tcq_decode(const RadEncoding* e, int64_t rows_all, int64_t cols, const void* const* planes,
|
||||
int64_t row0, int64_t rows, float* out);
|
||||
|
||||
/* Write a scale (and a zero) into element `i` of its plane row. */
|
||||
void grid_store_scale(const Grid& g, const BlockScale& b, void* scale_row, void* zero_row,
|
||||
int64_t i);
|
||||
@@ -143,6 +223,10 @@ struct Planes {
|
||||
uint8_t* zero = nullptr;
|
||||
uint8_t* scale2 = nullptr;
|
||||
uint8_t* table = nullptr;
|
||||
uint8_t* grid = nullptr;
|
||||
uint8_t* mad = nullptr;
|
||||
uint8_t* colf = nullptr;
|
||||
int64_t colf_cols = 0;
|
||||
int64_t codes_row = 0, scale_row = 0, zero_row = 0, scale2_row = 0; /* bytes */
|
||||
int64_t scale_cols = 0, scale2_cols = 0; /* elements a row */
|
||||
};
|
||||
@@ -159,6 +243,7 @@ struct Scales {
|
||||
int64_t br = 1, bc = 1; /* their extents, resolved against the call */
|
||||
std::vector<float> s2; /* the second level as stored */
|
||||
int64_t nr2 = 0, nc2 = 0;
|
||||
std::vector<float> colf; /* tcq_colf: each 128-column block's factor, all rows' */
|
||||
const BlockScale& at(int64_t r, int64_t c) const {
|
||||
return b[(size_t)((r / br) * nc + c / bc)];
|
||||
}
|
||||
|
||||
+36
-8
@@ -6,6 +6,7 @@
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
|
||||
@@ -31,15 +32,31 @@ void fwht_row(double* v, int64_t k, int64_t 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; the result stays bit-exactly
|
||||
* symmetric only because both passes run the same butterflies in the same order. */
|
||||
* symmetric only because both passes run the same butterflies in the same order. The column pass
|
||||
* runs fwht_inplace's butterflies on whole rows of a block of `n` rows, so each column sees the
|
||||
* same operations in the same order as the transform of that column alone; rows, and blocks of
|
||||
* rows, are independent, so threads change nothing. */
|
||||
void rotate_gram(std::vector<double>& h, int64_t k, int64_t n) {
|
||||
for (int64_t r = 0; r < k; ++r) fwht_row(h.data() + r * k, k, n);
|
||||
std::vector<double> col((size_t)k);
|
||||
for (int64_t c = 0; c < k; ++c) {
|
||||
for (int64_t r = 0; r < k; ++r) col[(size_t)r] = h[(size_t)(r * k + c)];
|
||||
fwht_row(col.data(), k, n);
|
||||
for (int64_t r = 0; r < k; ++r) h[(size_t)(r * k + c)] = col[(size_t)r];
|
||||
}
|
||||
double* d = h.data();
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static)
|
||||
#endif
|
||||
for (int64_t r = 0; r < k; ++r) fwht_row(d + r * k, k, n);
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static)
|
||||
#endif
|
||||
for (int64_t b0 = 0; b0 < k; b0 += n)
|
||||
for (int64_t s = 1; s < n; s <<= 1)
|
||||
for (int64_t i = b0; i < b0 + n; i += s << 1)
|
||||
for (int64_t j = i; j < i + s; ++j) {
|
||||
double* x = d + j * k;
|
||||
double* y = d + (j + s) * k;
|
||||
for (int64_t c = 0; c < k; ++c) {
|
||||
const double a = x[c], b = y[c];
|
||||
x[c] = a + b;
|
||||
y[c] = a - b;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool read_gram(const std::string& path, int64_t k, int64_t domain, std::vector<double>* acc) {
|
||||
@@ -124,9 +141,15 @@ std::string own_stem(const char* name) {
|
||||
return s;
|
||||
}
|
||||
|
||||
/* A few layers' Grams, the oldest dropped first: a MoE layer's experts read their layer's again
|
||||
* and again, a dense model reads each once, and every layer's kept at once outgrows the host
|
||||
* (Qwen3.8-27B's are ~100 GB; a GPTQ convert with descent was OOM-killed at layer 50). */
|
||||
constexpr size_t kGrams = 4;
|
||||
|
||||
struct GramCache {
|
||||
std::mutex mu;
|
||||
std::map<std::string, Gram> g; /* null = looked and found nothing */
|
||||
std::deque<std::string> order; /* g's keys, oldest first */
|
||||
};
|
||||
|
||||
GramCache& gram_cache() {
|
||||
@@ -342,7 +365,12 @@ Gram calib_gram(const char* dir, const char* name, int64_t K, int64_t domain, co
|
||||
if (h)
|
||||
std::fprintf(stderr, "libquant: %s reads '%s' against %d calibration file(s), K=%lld\n",
|
||||
who, stem.c_str(), found, (long long)K);
|
||||
while (c.order.size() >= kGrams) {
|
||||
c.g.erase(c.order.front());
|
||||
c.order.pop_front();
|
||||
}
|
||||
c.g.emplace(key, h);
|
||||
c.order.push_back(key);
|
||||
return h;
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -63,9 +63,9 @@ int calib_sum(const char* dir, const std::string& stem, int64_t K, int64_t domai
|
||||
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 (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. */
|
||||
* when `dir` holds none (noted once on stderr). The last few layers' are cached by (dir, stem, K,
|
||||
* domain), for a MoE layer's experts; 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. Each element of G sums over k in ascending order
|
||||
|
||||
+20
-1
@@ -21,6 +21,25 @@
|
||||
{ "table", RAD_P_STR, nullptr, \
|
||||
"a codebook the codes index: nf4, iq4nl, w4nl, w5nl, binary, ternary, or values " \
|
||||
"separated by ;" }, \
|
||||
{ "vq", RAD_P_STR, nullptr, \
|
||||
"a vector codebook file: one codeword a line, its integers (-127..127) separated by " \
|
||||
"spaces; one code a codeword's width of columns" }, \
|
||||
{ "tcq", RAD_P_INT, nullptr, \
|
||||
"a trellis of 2^L states down each column over codes=uK, one code a row (gptq)" }, \
|
||||
{ "tcq_rows", RAD_P_INT, "256", "the rows one tail-biting trellis runs over" }, \
|
||||
{ "tcq_gain", RAD_P_F64, "1", "a trellis block's rms over the table's, its scale's divisor" }, \
|
||||
{ "tcq_peak", RAD_P_INT, "0", \
|
||||
"1: a trellis block's scale never puts its largest value past the table's" }, \
|
||||
{ "tcq_rb", RAD_P_INT, "0", \
|
||||
"R: a trellis's values on the int8 grid of one scale per R rows (the block's largest)" }, \
|
||||
{ "tcq_code", RAD_P_STR, nullptr, \
|
||||
"mad: the states' values computed, bytesum((st*A+B) & 0x3F3F3F3F) - 126 (no tcq_lut=)" }, \
|
||||
{ "tcq_a", RAD_P_INT, "11872635", "tcq_code=mad's multiplier A (24 bits)" }, \
|
||||
{ "tcq_b", RAD_P_INT, "625341585", "tcq_code=mad's addend B" }, \
|
||||
{ "tcq_colf", RAD_P_INT, "0", \
|
||||
"1: one scale a row times a factor a 128-column block shared by all rows (block=1x*)" }, \
|
||||
{ "tcq_lut", RAD_P_STR, nullptr, \
|
||||
"the trellis's 2^L state values, integers in -127..127 (default: normal quantiles)" }, \
|
||||
{ "group", RAD_P_INT, nullptr, "one scale per this many columns of a row" }, \
|
||||
{ "block", RAD_P_STR, "1x*", "the scale block RxC, * for a whole extent: 128x128, *x*" }, \
|
||||
{ "scale", RAD_P_STR, "bf16", \
|
||||
@@ -49,7 +68,7 @@ namespace lq {
|
||||
|
||||
/* The grid a rule's options describe, checked against the weight; a message on stderr, with the
|
||||
* weight's name, when it is refused. */
|
||||
int grid_of(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g);
|
||||
int grid_of(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g, bool vq_ok = false);
|
||||
|
||||
/* Rank-1 weights (norms, biases) are declined rather than quantised, so a recipe pattern need not
|
||||
* exclude every vector it happens to match. */
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
*/
|
||||
#include "lq_ggml.h"
|
||||
#include "lq_gptq.h"
|
||||
#include "lq_gpu.h"
|
||||
#include "lq_quant.h"
|
||||
#include "lq_common.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "rad_abi_layout.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -20,9 +22,12 @@
|
||||
|
||||
namespace lq {
|
||||
|
||||
int grid_of(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g) {
|
||||
int grid_of(const RadParam* o, int n_o, const RadQuantWeight* w, Grid* g, bool vq_ok) {
|
||||
std::string why;
|
||||
if (grid_parse(o, n_o, g, &why) != RAD_OK) return refuse(w, why.c_str());
|
||||
/* Only GPTQ's loop chooses vector codewords. */
|
||||
if (!g->vq.empty() && !vq_ok) return refuse(w, "vq= is quantised by gptq");
|
||||
if (g->tcq_L && !vq_ok) return refuse(w, "tcq= is quantised by gptq");
|
||||
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;
|
||||
@@ -56,6 +61,9 @@ const RadQuantOption kGptqOptions[] = {
|
||||
{ "cd", RAD_P_INT, "0",
|
||||
"sweeps of coordinate descent after the loop: every code re-chosen at its conditional "
|
||||
"optimum against the same damped Hessian, the other columns held (lq_gptq.h)" },
|
||||
{ "dyn", RAD_P_INT, "0",
|
||||
"1: each 128-column group's scale chosen when the loop reaches it, from the values earlier "
|
||||
"columns' error has moved it to (one scale level, groups of 128)" },
|
||||
};
|
||||
const RadQuantOption kCastOptions[] = {
|
||||
{ "dtype", RAD_P_STR, nullptr,
|
||||
@@ -96,7 +104,7 @@ int rtn_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src
|
||||
int gptq_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncoding* out) {
|
||||
if (declines(w)) return RAD_E_UNSUPPORTED;
|
||||
Grid g;
|
||||
const int st = grid_of(o, n_o, w, &g);
|
||||
const int st = grid_of(o, n_o, w, &g, true);
|
||||
if (st != RAD_OK) return st;
|
||||
*out = grid_encoding(g);
|
||||
if (rad_param_geti(o, n_o, "act_order", 0)) {
|
||||
@@ -105,6 +113,8 @@ int gptq_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodi
|
||||
if (rad_param_geti(o, n_o, "cd", 0))
|
||||
return refuse(w, "cd= sweeps the columns in their stored order, and act_order=1 "
|
||||
"stores them permuted; one or the other");
|
||||
if (!g.vq.empty()) return refuse(w, "act_order=1 and vq= : a codeword spans adjacent columns");
|
||||
if (g.tcq_L) return refuse(w, "act_order=1 and tcq= : the columns are stored in order");
|
||||
rad_enc_copy_str(out->transform, "perm");
|
||||
if (rad_enc_add_table(out, "t.perm", RAD_I32, 1, w->cols) < 0)
|
||||
return refuse(w, "the encoding has no room for the permutation table");
|
||||
@@ -114,10 +124,18 @@ int gptq_encoding(const RadParam* o, int n_o, const RadQuantWeight* w, RadEncodi
|
||||
|
||||
int64_t whole_weight(const RadParam*, int, const RadQuantWeight*) { return 0; }
|
||||
|
||||
/* gptq's one scheme the core does not decode: a trellis grid's. */
|
||||
int gptq_decode(const RadEncoding* e, const RadQuantWeight* w, const void* const* planes,
|
||||
int64_t row0, int64_t rows, float* out) {
|
||||
if (!rad_enc_is(e, "trellis")) return RAD_E_UNSUPPORTED;
|
||||
if (!w || w->rows <= 0 || w->cols <= 0) return RAD_E_SHAPE;
|
||||
return grid_tcq_decode(e, w->rows, w->cols, planes, row0, rows, out);
|
||||
}
|
||||
|
||||
int gptq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* src, int64_t row0,
|
||||
int64_t rows, void* const* planes) {
|
||||
Grid g;
|
||||
const int st = grid_of(o, n_o, w, &g);
|
||||
const int st = grid_of(o, n_o, w, &g, true);
|
||||
if (st != RAD_OK) return st;
|
||||
if (row0 != 0 || rows != w->rows) return RAD_E_SHAPE;
|
||||
const int64_t N = w->rows, K = w->cols;
|
||||
@@ -144,10 +162,14 @@ int gptq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr
|
||||
}
|
||||
}
|
||||
|
||||
/* 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);
|
||||
/* Scales come first, from the weight as it stands, and stay fixed through the loop -- or with
|
||||
* dyn=1 each group's is chosen again as the loop reaches it (gptq_quantise). */
|
||||
Scales sc = grid_scales(g, src, N, K, imp);
|
||||
const Planes p = grid_planes(g, K, planes);
|
||||
grid_store_scales(g, sc, p);
|
||||
const bool dyn = rad_param_geti(o, n_o, "dyn", 0) != 0;
|
||||
if (dyn && !gptq_dynamic_ok(g, sc))
|
||||
return refuse(w, "dyn=1 chooses a 128-column group's scale as GPTQ reaches it, which needs "
|
||||
"one scale level per row and 128 columns");
|
||||
|
||||
const Gram uf = gptq_factor(dir, w->name, K, g.fwht, damp, act ? perm.data() : nullptr);
|
||||
const float* u = uf ? uf->data() : nullptr;
|
||||
@@ -156,14 +178,26 @@ int gptq_quantize(const RadParam* o, int n_o, const RadQuantWeight* w, float* sr
|
||||
const int cd = (int)rad_param_geti(o, n_o, "cd", 0);
|
||||
std::vector<float> x0;
|
||||
if (cd > 0 && u) x0.assign(src, src + (size_t)(N * K));
|
||||
gptq_quantise(g, src, codes.data(), sc, N, K, u);
|
||||
{
|
||||
std::string why;
|
||||
const int st = gptq_quantise(g, src, codes.data(), sc, N, K, u, dyn && u, &why);
|
||||
if (st != RAD_OK) {
|
||||
std::fprintf(stderr, "libquant: %s: %s\n", w->name ? w->name : "?", why.c_str());
|
||||
return st;
|
||||
}
|
||||
}
|
||||
grid_store_scales(g, sc, p);
|
||||
if (!x0.empty()) {
|
||||
const Gram h = calib_gram(dir, w->name, K, g.fwht, "gptq cd");
|
||||
if (h) gptq_refine(g, x0.data(), src, codes.data(), sc, N, K, h->data(), damp, cd);
|
||||
}
|
||||
const int64_t V = g.vq.empty() ? 1 : g.vdim; /* one code a vector */
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static) if (N * K > (1 << 20))
|
||||
#endif
|
||||
for (int64_t r = 0; r < N; ++r) {
|
||||
uint8_t* cr = p.codes + r * p.codes_row;
|
||||
for (int64_t c = 0; c < K; ++c) grid_store_code(g, cr, c, codes[(size_t)(r * K + c)]);
|
||||
for (int64_t c = 0; c < K; c += V) grid_store_code(g, cr, c / V, codes[(size_t)(r * K + c)]);
|
||||
}
|
||||
if (act) {
|
||||
const int tp = grid_encoding(g).n_planes; /* t.perm follows the grid's planes */
|
||||
@@ -228,7 +262,7 @@ const RadQuantizerInfo kQuantizers[] = {
|
||||
"error feedback against the layer's input Hessian: each column's rounding error is spread "
|
||||
"over the columns after it, on any grid, the scales fixed from the weight first",
|
||||
kGptqOptions, (int)(sizeof kGptqOptions / sizeof kGptqOptions[0]),
|
||||
gptq_encoding, whole_weight, gptq_quantize, nullptr },
|
||||
gptq_encoding, whole_weight, gptq_quantize, gptq_decode },
|
||||
{ "cast",
|
||||
"a float weight converted to another float dtype, to nearest even, with no scale",
|
||||
kCastOptions, (int)(sizeof kCastOptions / sizeof kCastOptions[0]),
|
||||
@@ -264,8 +298,10 @@ const RadPluginInfo kInfo = {
|
||||
} /* namespace */
|
||||
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
RAD_PLUGIN_ABI_LAYOUT_EXPORT
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
|
||||
extern "C" int rad_quant_count(void) { return (int)table().size(); }
|
||||
extern "C" const RadQuantizerInfo* rad_quant_at(int i) {
|
||||
return (i >= 0 && i < rad_quant_count()) ? table()[(size_t)i] : nullptr;
|
||||
}
|
||||
extern "C" int rad_quant_devices(const int* ids, int n) { return lq::gpu_set_devices(ids, n); }
|
||||
@@ -0,0 +1,644 @@
|
||||
/* lq_tcq_gpu.hip -- GPTQ over a trellis grid on the card. See lq_gpu.h.
|
||||
*
|
||||
* One workgroup is one run of tcq_rows rows, and takes a 128-column block's columns in order as
|
||||
* the host loop does (lq_gptq.cpp, gptq_quantise_tcq): for each column the seam window's free
|
||||
* Viterbi, the tail-biting search from and to its state, the codes, the decoded values, the errors
|
||||
* and their feedback into the block's later columns. A second kernel applies the block's errors to
|
||||
* the columns after it (gptq_tail's arithmetic). The host chooses the next block's dyn=1 scales
|
||||
* from its columns while the card finishes the rest of the tail.
|
||||
*
|
||||
* The states are spread so the threads holding a group hold all its predecessors: state
|
||||
* st = q + t * Q with Q = 2^(L-k), t < 2^k, the group q's t-th, sits with q's lanes (one, or for
|
||||
* the wide codes a few adjacent ones, each with a share of t). A step is then each group's
|
||||
* cheapest predecessor (within a thread or across its lanes), one barrier, and each state's cost
|
||||
* from its own group's cheapest, read from LDS.
|
||||
*/
|
||||
#include "lq_gpu.h"
|
||||
#include "lq_gptq.h"
|
||||
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace lq {
|
||||
|
||||
namespace {
|
||||
|
||||
std::vector<int>& devices() {
|
||||
static std::vector<int> d;
|
||||
return d;
|
||||
}
|
||||
|
||||
/* tcq_viterbi's cost of a state no path may start in. */
|
||||
constexpr float kUnreached = 3.0e38f;
|
||||
|
||||
/* Everything one block launch reads, for the device's rows [0, nl). */
|
||||
struct TcqArgs {
|
||||
float* w; /* [nl, K] the weight as the loop has left it */
|
||||
int32_t* codes; /* [nl, K] */
|
||||
float* err; /* [nl, 128] this block's errors, or null without a Hessian */
|
||||
const float* u; /* [K, K] the factor, or null */
|
||||
const float* lut; /* [2^L] the states' values */
|
||||
const float* s; /* [nl] the scale each row's values take in this block */
|
||||
const float* rt; /* [nl] tcq_rb's ratio, or null */
|
||||
uint8_t* back; /* per run, [rows, Q] each group's cheapest predecessor */
|
||||
int64_t K, nl, b0, b1;
|
||||
int T;
|
||||
bool fused; /* tcq_rb's rounding of the exact product (a computed code) */
|
||||
};
|
||||
|
||||
/* A thread's E states' table values. With PACK they sit four to a register as the int8 they are
|
||||
* (the table holds integers in -127..127), for the wide forms. */
|
||||
template <int E, bool PACK>
|
||||
struct Lut {
|
||||
float f[PACK ? 1 : E];
|
||||
uint32_t p[PACK ? E / 4 : 1];
|
||||
__device__ void set(int e, float v) {
|
||||
if (PACK) {
|
||||
const uint32_t b = (uint32_t)(uint8_t)(int8_t)(int)v;
|
||||
if (e % 4 == 0) p[e / 4] = b;
|
||||
else p[e / 4] |= b << (8 * (e % 4));
|
||||
} else {
|
||||
f[e] = v;
|
||||
}
|
||||
}
|
||||
__device__ float at(int e) const {
|
||||
if (PACK) return (float)(int8_t)(p[e / 4] >> (8 * (e % 4)));
|
||||
return f[e];
|
||||
}
|
||||
};
|
||||
|
||||
/* A workgroup barrier that orders LDS alone: __syncthreads() also waits for every global store to
|
||||
* land and invalidates the vector cache. */
|
||||
__device__ inline void lds_barrier() {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
|
||||
__builtin_amdgcn_s_barrier();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
|
||||
}
|
||||
|
||||
/* (cost, state) a is cheaper than b: the lower cost, a NaN above every number, then the lower
|
||||
* state. A total order, so any reduction order finds tcq_viterbi's state. */
|
||||
__device__ inline bool cheaper(float ac, int ai, float bc, int bi) {
|
||||
const bool an = ac != ac, bn = bc != bc;
|
||||
if (an != bn) return bn;
|
||||
if (an) return ai < bi;
|
||||
return ac < bc || (ac == bc && ai < bi);
|
||||
}
|
||||
|
||||
/* One run's block of columns for 2^L states and KB-bit codes: M groups a thread, SH lanes a group,
|
||||
* the table packed or not, WPE waves an EU (the compiler's register budget, 1 for its own), HR
|
||||
* tcq_rb, NB the groups' cheapest held in one LDS buffer or two (one: a second barrier a step, for
|
||||
* the state counts whose two do not fit). The geometry is compile-time, so a state's LDS address
|
||||
* is an immediate offset from the thread's. */
|
||||
template <int L, int KB, int M, int SH, bool PACK, int WPE, bool HR, int NB = 2>
|
||||
__global__ void __launch_bounds__((1 << (L - KB)) * SH / M)
|
||||
__attribute__((amdgpu_waves_per_eu(WPE))) tcq_block(TcqArgs a) {
|
||||
/* SH lanes share a group's predecessors, BT each; a thread holds M groups' worth. */
|
||||
constexpr int B = 1 << KB, Q = 1 << (L - KB), TH = Q * SH / M, BT = B / SH, E = M * BT;
|
||||
constexpr int G = TH / SH; /* groups a slot of the thread's */
|
||||
/* The group of state st is st >> KB; it splits into the thread's part and a constant when
|
||||
* G and Q are multiples of B. */
|
||||
constexpr bool split = G % B == 0 && Q % B == 0;
|
||||
extern __shared__ float lds[];
|
||||
const int j = (int)threadIdx.x, gj = j / SH, hj = j % SH;
|
||||
const int64_t K = a.K;
|
||||
float* bestl = lds; /* [NB][Q] */
|
||||
float* xs = bestl + NB * Q; /* [T] the column */
|
||||
float* ss = xs + a.T; /* [T] */
|
||||
float* rs = ss + a.T; /* [T] */
|
||||
float* es = rs + a.T; /* [T] the rows' errors */
|
||||
int* path = (int*)(es + a.T); /* [T] */
|
||||
float* redc = (float*)(path + a.T); /* [32] */
|
||||
int* redi = (int*)(redc + 32); /* [32] */
|
||||
|
||||
const int64_t n0 = (int64_t)blockIdx.x * a.T;
|
||||
const int n = (int)(a.nl - n0 < a.T ? a.nl - n0 : a.T);
|
||||
uint8_t* back = a.back + (size_t)blockIdx.x * (size_t)a.T * (size_t)Q;
|
||||
constexpr int c = (L + KB - 1) / KB;
|
||||
const int h = 8 * c < n / 2 ? 8 * c : n / 2;
|
||||
/* The thread's state e: group gj + (e / BT) * G, predecessor hj * BT + e % BT. */
|
||||
auto state = [&](int e) { return gj + (e / BT) * G + (hj * BT + e % BT) * Q; };
|
||||
auto group = [&](int e) {
|
||||
if constexpr (split)
|
||||
return (gj >> KB) + hj * BT * (Q / B) + ((e / BT) * G + (e % BT) * Q) / B;
|
||||
else return state(e) >> KB;
|
||||
};
|
||||
|
||||
Lut<E, PACK> lv;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < E; ++e) lv.set(e, a.lut[state(e)]);
|
||||
float cost[E];
|
||||
int buf = 0;
|
||||
|
||||
/* A state's value in row r: s * lut, or under tcq_rb s * rint(lut * rt) (a computed code's
|
||||
* rounding of the exact product, rb_round). */
|
||||
auto value = [&](int e, float s, float rt) {
|
||||
return s * (HR ? (a.fused ? __builtin_fmaf(lv.at(e), rt, 12582912.0f) - 12582912.0f
|
||||
: __builtin_rintf(lv.at(e) * rt))
|
||||
: lv.at(e));
|
||||
};
|
||||
/* Row r's first costs: from any state (start < 0), or from predecessor state `start`. */
|
||||
auto first = [&](int r, int start) {
|
||||
const float x = xs[r], s = ss[r], rt = HR ? rs[r] : 0.0f;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < E; ++e) {
|
||||
const float d = x - value(e, s, rt);
|
||||
cost[e] = start < 0 || group(e) == (start & (Q - 1)) ? d * d : kUnreached;
|
||||
}
|
||||
};
|
||||
/* One trellis step into row r (tcq_step): each group's cheapest predecessor, the first on a
|
||||
* tie, into LDS and `from`; then each state's squared error plus its group's cheapest.
|
||||
* Shared by SH lanes, the first scans from its first predecessor as tcq_step does, the others
|
||||
* from +inf, which no cost is below, and the lanes combine in predecessor order taking the
|
||||
* later only when strictly cheaper: the first of the lowest, as one scan would find. */
|
||||
auto step = [&](int r, uint8_t* from) {
|
||||
float* bl = bestl + (NB == 2 ? buf : 0) * Q;
|
||||
/* one buffer: every thread has read the last step's before any writes this one's */
|
||||
if constexpr (NB == 1) lds_barrier();
|
||||
/* A packed table is unpacked where it is used: hoisted out of the row loop it would hold
|
||||
* a register a state again. */
|
||||
if constexpr (PACK) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < E / 4; ++q) asm volatile("" : "+v"(lv.p[q]));
|
||||
}
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M; ++m) {
|
||||
float b = SH == 1 || hj == 0 ? cost[m * BT] : __builtin_inff();
|
||||
int bt = SH == 1 || hj == 0 ? 0 : -1;
|
||||
#pragma unroll
|
||||
for (int t = SH == 1 ? 1 : 0; t < BT; ++t) {
|
||||
const bool lt = cost[m * BT + t] < b;
|
||||
b = lt ? cost[m * BT + t] : b;
|
||||
bt = lt ? hj * BT + t : bt;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int o = 1; o < SH; o <<= 1) {
|
||||
const float ob = __shfl_xor(b, o);
|
||||
const int obt = __shfl_xor(bt, o);
|
||||
const bool hi = (j & o) != 0;
|
||||
const float lb = hi ? ob : b, hb = hi ? b : ob;
|
||||
const int lt = hi ? obt : bt, ht = hi ? bt : obt;
|
||||
b = hb < lb ? hb : lb;
|
||||
bt = hb < lb ? ht : lt;
|
||||
}
|
||||
if (SH == 1 || hj == 0) {
|
||||
bl[gj + m * G] = b;
|
||||
from[gj + m * G] = (uint8_t)bt;
|
||||
}
|
||||
}
|
||||
/* The step exchanges only LDS; `from` is read after the run's last step, behind a full
|
||||
* barrier, so the stores to it need not land before this one. */
|
||||
lds_barrier();
|
||||
const float x = xs[r], s = ss[r], rt = HR ? rs[r] : 0.0f;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < E; ++e) {
|
||||
const float d = x - value(e, s, rt);
|
||||
cost[e] = d * d + bl[group(e)];
|
||||
}
|
||||
buf ^= 1;
|
||||
};
|
||||
auto prev = [&](int st, int r) {
|
||||
const int q = st >> KB;
|
||||
return q + (int)back[(size_t)r * Q + q] * Q;
|
||||
};
|
||||
|
||||
for (int64_t i = a.b0; i < a.b1; ++i) {
|
||||
for (int r = j; r < n; r += TH) {
|
||||
xs[r] = a.w[(n0 + r) * K + i];
|
||||
ss[r] = a.s[n0 + r];
|
||||
if (HR) rs[r] = a.rt[n0 + r];
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
/* The seam: the best free path over the run's last h rows then its first h, and its
|
||||
* state at the seam (grid_tcq_run). Window row ii is run row ii < h ? n - h + ii : ii - h. */
|
||||
first(n - h, -1);
|
||||
for (int ii = 1; ii < 2 * h; ++ii) step(ii < h ? n - h + ii : ii - h, back + (size_t)ii * Q);
|
||||
{
|
||||
float bc = cost[0];
|
||||
int bi = state(0);
|
||||
#pragma unroll
|
||||
for (int e = 1; e < E; ++e)
|
||||
if (cheaper(cost[e], state(e), bc, bi)) { bc = cost[e]; bi = state(e); }
|
||||
for (int o = warpSize / 2; o > 0; o /= 2) {
|
||||
const float oc = __shfl_xor(bc, o);
|
||||
const int oi = __shfl_xor(bi, o);
|
||||
if (cheaper(oc, oi, bc, bi)) { bc = oc; bi = oi; }
|
||||
}
|
||||
if (j % warpSize == 0) { redc[j / warpSize] = bc; redi[j / warpSize] = bi; }
|
||||
/* tcq_viterbi scans from state 0 and moves only to a strictly lower cost, so a NaN at
|
||||
* state 0 keeps it; state 0 is thread 0's e = 0. */
|
||||
const bool nan0 = j == 0 && cost[0] != cost[0];
|
||||
__syncthreads();
|
||||
if (j == 0) {
|
||||
for (int wv = 1; wv < (TH + warpSize - 1) / warpSize; ++wv)
|
||||
if (cheaper(redc[wv], redi[wv], bc, bi)) { bc = redc[wv]; bi = redi[wv]; }
|
||||
int st = nan0 ? 0 : bi;
|
||||
for (int r = 2 * h - 1; r >= h; --r) st = prev(st, r);
|
||||
path[0] = st;
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
const int seam = path[0];
|
||||
__syncthreads();
|
||||
|
||||
/* The run, from and to the seam's state. */
|
||||
first(0, seam);
|
||||
for (int r = 1; r < n; ++r) step(r, back + (size_t)r * Q);
|
||||
__syncthreads();
|
||||
if (j == 0) {
|
||||
int st = seam;
|
||||
path[n - 1] = st;
|
||||
for (int r = n - 1; r > 0; --r) {
|
||||
st = prev(st, r);
|
||||
path[r - 1] = st;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
|
||||
for (int r = j; r < n; r += TH) {
|
||||
const int st = path[r];
|
||||
const float v = a.lut[st];
|
||||
const float dq = (HR ? (a.fused ? __builtin_fmaf(v, rs[r], 12582912.0f) - 12582912.0f
|
||||
: __builtin_rintf(v * rs[r]))
|
||||
: v) * ss[r];
|
||||
a.codes[(n0 + r) * K + i] = st & (B - 1);
|
||||
a.w[(n0 + r) * K + i] = dq;
|
||||
if (a.u) {
|
||||
const float e = (xs[r] - dq) / a.u[i * K + i];
|
||||
a.err[(n0 + r) * 128 + (i - a.b0)] = e;
|
||||
es[r] = e;
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if (a.u && i + 1 < a.b1) {
|
||||
const int cols = (int)(a.b1 - i - 1);
|
||||
const float* ur = a.u + i * K + i + 1;
|
||||
for (int x = j; x < n * cols; x += TH) {
|
||||
const int r = x / cols, cc = x % cols;
|
||||
float* p = a.w + (n0 + r) * K + i + 1 + cc;
|
||||
*p = *p - es[r] * ur[cc];
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
|
||||
/* gptq_tail on the card: w[r][j] -= e[r][t] * u[b0 + t][j] for t < nb, j over [j0, j1), each
|
||||
* element's terms one at a time in ascending t, a product then a subtraction. */
|
||||
constexpr int kTailRows = 32, kTailCols = 256;
|
||||
__global__ void __launch_bounds__(kTailCols) tcq_tail(float* w, const float* err, const float* u,
|
||||
int64_t K, int64_t nl, int64_t j0, int64_t j1,
|
||||
int64_t b0, int nb) {
|
||||
__shared__ float e[kTailRows][128];
|
||||
const int64_t r0 = (int64_t)blockIdx.y * kTailRows;
|
||||
const int rows = (int)(nl - r0 < kTailRows ? nl - r0 : kTailRows);
|
||||
for (int x = (int)threadIdx.x; x < kTailRows * 128; x += kTailCols) {
|
||||
const int r = x / 128, t = x % 128;
|
||||
e[r][t] = r < rows && t < nb ? err[(r0 + r) * 128 + t] : 0.0f;
|
||||
}
|
||||
__syncthreads();
|
||||
const int64_t jj = j0 + (int64_t)blockIdx.x * kTailCols + threadIdx.x;
|
||||
if (jj >= j1) return;
|
||||
float acc[kTailRows];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < kTailRows; ++r) acc[r] = r < rows ? w[(r0 + r) * K + jj] : 0.0f;
|
||||
for (int t = 0; t < nb; ++t) {
|
||||
const float ut = u[(b0 + t) * K + jj];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < kTailRows; ++r) acc[r] = acc[r] - e[r][t] * ut;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int r = 0; r < kTailRows; ++r)
|
||||
if (r < rows) w[(r0 + r) * K + jj] = acc[r];
|
||||
}
|
||||
|
||||
using BlockKernel = void (*)(TcqArgs);
|
||||
|
||||
/* The forms built, each the fastest of its sweep over groups a thread (M), lanes a group (SH), a
|
||||
* packed table and an occupancy target (R9700, a 96-run weight of 5120 columns): fewer threads a
|
||||
* run let more runs share a WGP, until the states a thread holds spill. 1024 threads at most, the
|
||||
* wide codes' groups split over lanes. The 2^10-state forms are the default sizing, for tests. */
|
||||
struct Form { int L, k; BlockKernel plain, rb; int threads, nb; };
|
||||
#define LQ_FORM(l, kb, m, sh, pack, wpe) \
|
||||
{ l, kb, tcq_block<l, kb, m, sh, pack, wpe, false>, tcq_block<l, kb, m, sh, pack, wpe, true>, \
|
||||
(1 << (l - kb)) * sh / m, 2 }
|
||||
#define LQ_FORM1(l, kb, m, sh, pack, wpe) \
|
||||
{ l, kb, tcq_block<l, kb, m, sh, pack, wpe, false, 1>, \
|
||||
tcq_block<l, kb, m, sh, pack, wpe, true, 1>, (1 << (l - kb)) * sh / m, 1 }
|
||||
const Form kForms[] = {
|
||||
LQ_FORM(10, 2, 1, 1, false, 1), LQ_FORM(10, 3, 2, 1, false, 1), LQ_FORM(10, 4, 1, 1, false, 1),
|
||||
LQ_FORM(10, 5, 1, 1, false, 1),
|
||||
LQ_FORM(12, 2, 4, 1, false, 16), LQ_FORM(12, 3, 2, 1, false, 1), LQ_FORM(12, 4, 1, 1, false, 1),
|
||||
LQ_FORM(12, 5, 1, 1, false, 1), LQ_FORM(12, 6, 1, 2, false, 1), LQ_FORM(12, 7, 1, 8, false, 1),
|
||||
LQ_FORM(14, 2, 8, 1, false, 12), LQ_FORM(14, 3, 4, 1, false, 12), LQ_FORM(14, 4, 2, 1, false, 12),
|
||||
LQ_FORM(14, 5, 1, 1, false, 12), LQ_FORM(14, 6, 1, 2, false, 12), LQ_FORM(14, 7, 1, 2, true, 1),
|
||||
/* 2^16 states: a run's two cost buffers fit the LDS from 4-bit codes up, one at 3 bits; 2^15
|
||||
* states at 2 bits in one; not yet swept */
|
||||
LQ_FORM1(15, 2, 8, 1, true, 1), LQ_FORM1(16, 3, 8, 1, true, 1), LQ_FORM(16, 4, 4, 1, true, 1), LQ_FORM(16, 5, 2, 1, true, 1), LQ_FORM(16, 6, 1, 1, true, 1),
|
||||
LQ_FORM(16, 7, 1, 2, true, 1),
|
||||
};
|
||||
#undef LQ_FORM
|
||||
#undef LQ_FORM1
|
||||
|
||||
const Form* pick_form(int L, int k) {
|
||||
for (const Form& f : kForms)
|
||||
if (f.L == L && f.k == k) return &f;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string hip_fail(const char* what, hipError_t e) {
|
||||
return std::string(what) + ": " + hipGetErrorString(e);
|
||||
}
|
||||
|
||||
#define LQ_HIP(x) \
|
||||
do { \
|
||||
const hipError_t e_ = (x); \
|
||||
if (e_ != hipSuccess) { *why = hip_fail(#x, e_); return RAD_E_DEVICE; } \
|
||||
} while (0)
|
||||
|
||||
/* A device allocation freed with its scope. */
|
||||
template <typename T>
|
||||
struct DevBuf {
|
||||
T* p = nullptr;
|
||||
DevBuf() = default;
|
||||
DevBuf(const DevBuf&) = delete;
|
||||
DevBuf& operator=(const DevBuf&) = delete;
|
||||
~DevBuf() { if (p) (void)hipFree(p); }
|
||||
hipError_t alloc(size_t n) { return hipMalloc((void**)&p, n * sizeof(T) + (n ? 0 : 1)); }
|
||||
};
|
||||
|
||||
/* Page-locked host memory freed with its scope. Every copy goes through it: the runtime's own
|
||||
* staging for pageable memory gave wrong bytes under copies from several threads to two cards at
|
||||
* once (two weights each split over both). */
|
||||
template <typename T>
|
||||
struct HostBuf {
|
||||
T* p = nullptr;
|
||||
HostBuf() = default;
|
||||
HostBuf(const HostBuf&) = delete;
|
||||
HostBuf& operator=(const HostBuf&) = delete;
|
||||
~HostBuf() { if (p) (void)hipHostFree(p); }
|
||||
hipError_t alloc(size_t n) { return hipHostMalloc((void**)&p, n * sizeof(T) + (n ? 0 : 1)); }
|
||||
};
|
||||
|
||||
/* `bytes` from host `src` to device `dst` (or back with `down`) through `bounce`, kBounce bytes of
|
||||
* pinned memory, a chunk at a time on stream `s`. */
|
||||
constexpr size_t kBounce = (size_t)32 << 20;
|
||||
hipError_t bounce_copy(void* dst, const void* src, size_t bytes, bool down, uint8_t* bounce,
|
||||
hipStream_t s) {
|
||||
for (size_t off = 0; off < bytes; off += kBounce) {
|
||||
const size_t n = std::min(kBounce, bytes - off);
|
||||
hipError_t e;
|
||||
if (down) {
|
||||
e = hipMemcpyAsync(bounce, (const uint8_t*)src + off, n, hipMemcpyDeviceToHost, s);
|
||||
if (e == hipSuccess) e = hipStreamSynchronize(s);
|
||||
if (e != hipSuccess) return e;
|
||||
std::memcpy((uint8_t*)dst + off, bounce, n);
|
||||
} else {
|
||||
std::memcpy(bounce, (const uint8_t*)src + off, n);
|
||||
e = hipMemcpyAsync((uint8_t*)dst + off, bounce, n, hipMemcpyHostToDevice, s);
|
||||
if (e == hipSuccess) e = hipStreamSynchronize(s);
|
||||
if (e != hipSuccess) return e;
|
||||
}
|
||||
}
|
||||
return hipSuccess;
|
||||
}
|
||||
|
||||
struct Streams {
|
||||
hipStream_t s0 = nullptr, s1 = nullptr;
|
||||
hipEvent_t next = nullptr, down = nullptr, rest = nullptr;
|
||||
~Streams() {
|
||||
if (s0) (void)hipStreamSynchronize(s0);
|
||||
if (s1) (void)hipStreamSynchronize(s1);
|
||||
for (hipEvent_t e : { next, down, rest })
|
||||
if (e) (void)hipEventDestroy(e);
|
||||
for (hipStream_t s : { s0, s1 })
|
||||
if (s) (void)hipStreamDestroy(s);
|
||||
}
|
||||
};
|
||||
|
||||
/* Rows [ra, rb) of the weight on card `dev`: ra and rb are multiples of tcq_rows (rb may be N). */
|
||||
int run_rows(const Grid& g, const Form& f, float* w, int32_t* codes, Scales& scales, int64_t ra,
|
||||
int64_t rb, int64_t K, const float* u, bool dynamic, int dev, std::string* why) {
|
||||
LQ_HIP(hipSetDevice(dev));
|
||||
const int T = (int)g.tcq_rows, L = g.tcq_L, k = g.tcq_k;
|
||||
const int Q = 1 << (L - k), TH = f.threads;
|
||||
int lanes = 0;
|
||||
LQ_HIP(hipDeviceGetAttribute(&lanes, hipDeviceAttributeWarpSize, dev));
|
||||
if (lanes <= 0 || TH % lanes) {
|
||||
*why = "tcq=" + std::to_string(L) + " with " + std::to_string(k) + "-bit codes is " +
|
||||
std::to_string(TH) + " threads a run, not whole waves of " + std::to_string(lanes);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int64_t nl = rb - ra, runs = (nl + T - 1) / T, nb = (K + 127) / 128;
|
||||
const size_t lds = (size_t)(f.nb * Q + 5 * T + 64) * sizeof(float);
|
||||
|
||||
DevBuf<float> dw, derr, du, dlut, ds, drt;
|
||||
DevBuf<int32_t> dcodes;
|
||||
DevBuf<uint8_t> dback;
|
||||
LQ_HIP(dw.alloc((size_t)(nl * K)));
|
||||
LQ_HIP(dcodes.alloc((size_t)(nl * K)));
|
||||
LQ_HIP(dlut.alloc(g.tcq_lut.size()));
|
||||
LQ_HIP(ds.alloc((size_t)(nl * nb)));
|
||||
if (g.tcq_rb) LQ_HIP(drt.alloc((size_t)(nl * nb)));
|
||||
LQ_HIP(dback.alloc((size_t)runs * (size_t)T * (size_t)Q));
|
||||
if (u) {
|
||||
LQ_HIP(derr.alloc((size_t)(2 * nl * 128)));
|
||||
LQ_HIP(du.alloc((size_t)(K * K)));
|
||||
}
|
||||
Streams st;
|
||||
LQ_HIP(hipStreamCreateWithFlags(&st.s0, hipStreamNonBlocking));
|
||||
LQ_HIP(hipStreamCreateWithFlags(&st.s1, hipStreamNonBlocking));
|
||||
LQ_HIP(hipEventCreateWithFlags(&st.next, hipEventDisableTiming));
|
||||
LQ_HIP(hipEventCreateWithFlags(&st.down, hipEventDisableTiming));
|
||||
LQ_HIP(hipEventCreateWithFlags(&st.rest, hipEventDisableTiming));
|
||||
|
||||
HostBuf<uint8_t> bounce;
|
||||
HostBuf<float> hs, hrt, hblk;
|
||||
LQ_HIP(bounce.alloc(kBounce));
|
||||
LQ_HIP(hs.alloc((size_t)(nl * nb)));
|
||||
if (g.tcq_rb) LQ_HIP(hrt.alloc((size_t)(nl * nb)));
|
||||
if (dynamic) LQ_HIP(hblk.alloc((size_t)nl * 128));
|
||||
LQ_HIP(bounce_copy(dw.p, w + ra * K, (size_t)(nl * K) * sizeof(float), false, bounce.p, st.s0));
|
||||
LQ_HIP(bounce_copy(dlut.p, g.tcq_lut.data(), g.tcq_lut.size() * sizeof(float), false,
|
||||
bounce.p, st.s0));
|
||||
if (u)
|
||||
LQ_HIP(bounce_copy(du.p, u, (size_t)(K * K) * sizeof(float), false, bounce.p, st.s0));
|
||||
|
||||
std::vector<float> dummy(g.tcq_rb ? 0 : (size_t)T);
|
||||
int64_t down_c0 = 0, down_c1 = 0; /* the columns the last block's download holds */
|
||||
bool rest_pending = false;
|
||||
for (int64_t bi = 0; bi < nb; ++bi) {
|
||||
const int64_t b0 = bi * 128, b1 = std::min(K, b0 + 128);
|
||||
if (dynamic) {
|
||||
/* The block's columns as the card left them, then each row's scale from them. */
|
||||
if (bi > 0) {
|
||||
LQ_HIP(hipEventSynchronize(st.down));
|
||||
const int64_t wc = down_c1 - down_c0;
|
||||
for (int64_t r = 0; r < nl; ++r)
|
||||
std::memcpy(w + (ra + r) * K + down_c0, hblk.p + r * 128,
|
||||
(size_t)wc * sizeof(float));
|
||||
}
|
||||
gptq_tcq_dyn_scales(g, w, K, scales, ra, rb, b0, b1);
|
||||
}
|
||||
float* hsb = hs.p + bi * nl;
|
||||
float* hrb = g.tcq_rb ? hrt.p + bi * nl : nullptr;
|
||||
for (int64_t r = ra; r < rb; r += T) {
|
||||
const int64_t n = std::min(rb, r + T) - r;
|
||||
gptq_tcq_col_scales(g, scales, r, n, b0, hsb + (r - ra),
|
||||
hrb ? hrb + (r - ra) : dummy.data());
|
||||
}
|
||||
LQ_HIP(hipMemcpyAsync(ds.p + bi * nl, hsb, (size_t)nl * sizeof(float),
|
||||
hipMemcpyHostToDevice, st.s0));
|
||||
if (hrb)
|
||||
LQ_HIP(hipMemcpyAsync(drt.p + bi * nl, hrb, (size_t)nl * sizeof(float),
|
||||
hipMemcpyHostToDevice, st.s0));
|
||||
|
||||
TcqArgs a{};
|
||||
a.w = dw.p;
|
||||
a.codes = dcodes.p;
|
||||
a.err = u ? derr.p + (bi & 1) * nl * 128 : nullptr;
|
||||
a.u = u ? du.p : nullptr;
|
||||
a.lut = dlut.p;
|
||||
a.s = ds.p + bi * nl;
|
||||
a.rt = hrb ? drt.p + bi * nl : nullptr;
|
||||
a.back = dback.p;
|
||||
a.K = K;
|
||||
a.nl = nl;
|
||||
a.b0 = b0;
|
||||
a.b1 = b1;
|
||||
a.T = T;
|
||||
a.fused = g.tcq_mad;
|
||||
void* args[] = { &a };
|
||||
LQ_HIP(hipLaunchKernel((const void*)(hrb ? f.rb : f.plain), dim3((unsigned)runs),
|
||||
dim3((unsigned)TH), args, lds, st.s0));
|
||||
if (!u || b1 >= K) continue;
|
||||
|
||||
/* The tail: the next block's columns first, so the host can take them while the card
|
||||
* applies the rest. The rest of block bi and the next block's run touch different
|
||||
* columns; the next block's first part waits for it. */
|
||||
const int64_t c1 = std::min(K, b1 + 128);
|
||||
const dim3 tb((unsigned)((c1 - b1 + kTailCols - 1) / kTailCols),
|
||||
(unsigned)((nl + kTailRows - 1) / kTailRows));
|
||||
if (rest_pending) LQ_HIP(hipStreamWaitEvent(st.s0, st.rest, 0));
|
||||
hipLaunchKernelGGL(tcq_tail, tb, dim3(kTailCols), 0, st.s0, dw.p, a.err, du.p, K, nl, b1,
|
||||
c1, b0, (int)(b1 - b0));
|
||||
LQ_HIP(hipGetLastError());
|
||||
LQ_HIP(hipEventRecord(st.next, st.s0));
|
||||
LQ_HIP(hipStreamWaitEvent(st.s1, st.next, 0));
|
||||
if (dynamic) {
|
||||
LQ_HIP(hipMemcpy2DAsync(hblk.p, 128 * sizeof(float), dw.p + b1,
|
||||
(size_t)K * sizeof(float), (size_t)(c1 - b1) * sizeof(float),
|
||||
(size_t)nl, hipMemcpyDeviceToHost, st.s1));
|
||||
LQ_HIP(hipEventRecord(st.down, st.s1));
|
||||
down_c0 = b1;
|
||||
down_c1 = c1;
|
||||
}
|
||||
if (c1 < K) {
|
||||
const dim3 rbk((unsigned)((K - c1 + kTailCols - 1) / kTailCols),
|
||||
(unsigned)((nl + kTailRows - 1) / kTailRows));
|
||||
hipLaunchKernelGGL(tcq_tail, rbk, dim3(kTailCols), 0, st.s1, dw.p, a.err, du.p, K, nl,
|
||||
c1, K, b0, (int)(b1 - b0));
|
||||
LQ_HIP(hipGetLastError());
|
||||
}
|
||||
LQ_HIP(hipEventRecord(st.rest, st.s1));
|
||||
rest_pending = true;
|
||||
}
|
||||
LQ_HIP(hipStreamSynchronize(st.s1));
|
||||
LQ_HIP(hipStreamSynchronize(st.s0));
|
||||
LQ_HIP(bounce_copy(w + ra * K, dw.p, (size_t)(nl * K) * sizeof(float), true, bounce.p, st.s0));
|
||||
LQ_HIP(bounce_copy(codes + ra * K, dcodes.p, (size_t)(nl * K) * sizeof(int32_t), true,
|
||||
bounce.p, st.s0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int gpu_set_devices(const int* ids, int n) {
|
||||
int count = 0;
|
||||
if (n > 0 && hipGetDeviceCount(&count) != hipSuccess) count = 0;
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (ids[i] < 0 || ids[i] >= count) {
|
||||
std::fprintf(stderr, "libquant: card %d is not there (%d visible)\n", ids[i], count);
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
devices().assign(ids, ids + (n > 0 ? n : 0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool gpu_enabled() { return !devices().empty(); }
|
||||
|
||||
int gptq_tcq_gpu(const Grid& g, float* w, int32_t* codes, Scales& scales, int64_t N, int64_t K,
|
||||
const float* u, bool dynamic, std::string* why) {
|
||||
const Form* f = pick_form(g.tcq_L, g.tcq_k);
|
||||
const int64_t T = g.tcq_rows;
|
||||
if (!f) {
|
||||
*why = "the card has no trellis kernel for tcq=" + std::to_string(g.tcq_L) + " with " +
|
||||
std::to_string(g.tcq_k) + "-bit codes";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int Q = 1 << (g.tcq_L - g.tcq_k);
|
||||
if ((size_t)(f->nb * Q + 5 * T + 64) * sizeof(float) > 65536) {
|
||||
*why = "a run's working set does not fit the card's 64 KB of LDS (tcq_rows=" +
|
||||
std::to_string(T) + ")";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (N % T == 1) {
|
||||
*why = "a run of one row (rows " + std::to_string(N) + ", tcq_rows " + std::to_string(T) +
|
||||
") has no seam";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* A 128-column block's scale is one per row (gptq_tcq_col_scales at the block's first
|
||||
* column stands for all its columns). */
|
||||
if (!(scales.bc % 128 == 0 || scales.bc >= K)) {
|
||||
*why = "the card takes scale groups of a multiple of 128 columns, not " +
|
||||
std::to_string(scales.bc);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* A weight of many runs is split across the cards; a small one goes whole to the next card
|
||||
* in turn, so weights quantised side by side spread over them. */
|
||||
const std::vector<int>& dv = devices();
|
||||
const int64_t runs = (N + T - 1) / T;
|
||||
std::vector<std::pair<int64_t, int64_t>> part;
|
||||
std::vector<int> on;
|
||||
if (dv.size() > 1 && runs >= 32) {
|
||||
for (size_t d = 0; d < dv.size(); ++d) {
|
||||
const int64_t a = runs * (int64_t)d / (int64_t)dv.size() * T;
|
||||
const int64_t b = std::min(N, runs * (int64_t)(d + 1) / (int64_t)dv.size() * T);
|
||||
if (b > a) { part.emplace_back(a, b); on.push_back(dv[d]); }
|
||||
}
|
||||
} else {
|
||||
static std::atomic<unsigned> turn{0};
|
||||
part.emplace_back(0, N);
|
||||
on.push_back(dv[turn.fetch_add(1, std::memory_order_relaxed) % dv.size()]);
|
||||
}
|
||||
std::vector<int> st(part.size(), RAD_OK);
|
||||
std::vector<std::string> wy(part.size());
|
||||
if (part.size() == 1) {
|
||||
st[0] = run_rows(g, *f, w, codes, scales, 0, N, K, u, dynamic, on[0], &wy[0]);
|
||||
} else {
|
||||
std::vector<std::thread> th;
|
||||
for (size_t d = 0; d < part.size(); ++d)
|
||||
th.emplace_back([&, d] {
|
||||
st[d] = run_rows(g, *f, w, codes, scales, part[d].first, part[d].second, K, u,
|
||||
dynamic, on[d], &wy[d]);
|
||||
});
|
||||
for (std::thread& t : th) t.join();
|
||||
}
|
||||
for (size_t d = 0; d < part.size(); ++d)
|
||||
if (st[d] != RAD_OK) {
|
||||
*why = "card " + std::to_string(on[d]) + ": " + wy[d];
|
||||
return st[d];
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace lq */
|
||||
Reference in new issue
Block a user