Merge branch 'f-140' into f-140-j

This commit is contained in:
Niko1221 committed 2026-10-05 13:24:21 +02:00
commit 0fff115dfd
52 files changed
+3698 -183

No files matched your search

+77 -5
View File
@@ -312,7 +312,7 @@ __device__ __forceinline__ float vec_dot_iq4_xs_q8_1(const void* __restrict__ vb
// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the
// Q5_1 min term is the one departure (below). Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0,
// gopinath87607), which agree with llama.cpp and with each other.
constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q8_0 = 2;
constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q4_1 = 2, VDR_Q4_0 = 2, VDR_Q8_0 = 2;
__device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int* __restrict__ v, const int* __restrict__ u,
const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m,
@@ -452,6 +452,46 @@ __device__ __forceinline__ float vec_dot_q5_0_q8_1(const void* __restrict__ vbq,
const float s8 = __high2float(bq8_1->ds);
return d5 * (sumi * d8 - (16.0f * VDR_Q5_0 / QI5_0) * s8);
}
// Q4_0 (plain llama-quantize Q4_0 files, e.g. bartowski's: gate/up and most down projections): the codes are centred
// (q - 8 as signed bytes) before the dot, the exact integer form ggml-cpu's q4_0 x q8_0 dot uses, rather than
// llama.cpp's CUDA chain (uncentred codes minus 8 x the q8_1 block's float sum `ds.y`). On a real Q4_0 expert
// (2560 x 640) the CUDA chain measured 1.4e-2 relative error against the float product, the centred form 5.3e-3;
// with the CUDA chain native_expert_parity failed its 3e-2 limit on two layers of a Q4_0 Flash-Next file. The
// centring is the same idea as the Q5_1 min term above: the offset is applied to the activations' own int8 codes.
__device__ __forceinline__ int q4_0_centred(const int v) {
const int b = v ^ 0x08080808; // per byte: 0..15 -> (q - 8) as a 4-bit two's complement value
return b | ((b & 0x08080808) * 0x1E); // sign-extend each nibble into its byte (0x08 * 0x1E = 0xF0)
}
__device__ __forceinline__ float vec_dot_q4_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
const int& kbx, const int& iqs) {
const block_q4_0* bq4 = (const block_q4_0*) vbq + kbx;
int sumi = 0;
#pragma unroll
for (int i = 0; i < VDR_Q4_0; ++i) {
const int v = get_int_b2(bq4->qs, iqs + i);
sumi = ggml_cuda_dp4a(q4_0_centred((v >> 0) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i), sumi);
sumi = ggml_cuda_dp4a(q4_0_centred((v >> 4) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i + QI4_0), sumi);
}
return __half2float(bq4->d) * __low2float(bq8_1->ds) * sumi;
}
// Q4_1 (llama-quantize puts it on a few down projections of its Q4_0 files): the Q5_1 chain above without the fifth
// bit, the same min-term choice (the activations' own int8 codes): sumi * (d4 * d8) + sumu * (m4 * d8).
__device__ __forceinline__ float vec_dot_q4_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
const int& kbx, const int& iqs) {
const block_q4_1* bq4_1 = (const block_q4_1*) vbq + kbx;
int sumi = 0, sumu = 0;
#pragma unroll
for (int i = 0; i < VDR_Q4_1; ++i) {
const int v = get_int_b4(bq4_1->qs, iqs + i);
const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI4_1);
sumi = ggml_cuda_dp4a((v >> 0) & 0x0F0F0F0F, u0, sumi);
sumi = ggml_cuda_dp4a((v >> 4) & 0x0F0F0F0F, u1, sumi);
sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
}
const float2 dm4 = __half22float2(bq4_1->dm);
const float d8 = __low2float(bq8_1->ds);
return sumi * (dm4.x * d8) + sumu * (dm4.y * d8);
}
__device__ __forceinline__ float vec_dot_q5_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
const int& kbx, const int& iqs) {
const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx;
@@ -517,6 +557,10 @@ template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1;
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<2> { static constexpr int qk = 32, ipb = QI4_0 / VDR_Q4_0, step = VDR_Q4_0;
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_0_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<3> { static constexpr int qk = 32, ipb = QI4_1 / VDR_Q4_1, step = VDR_Q4_1;
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_1_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, step = VDR_Q5_0;
__device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } };
template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0;
@@ -524,9 +568,9 @@ template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0,
// The formats of each role, one list each so a type cannot be in one switch and missing from another. Every
// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(8)
#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(8)
#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(8)
#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8)
#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8)
#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8)
__device__ __forceinline__ float warp_sum(float v) {
#pragma unroll
@@ -1608,6 +1652,30 @@ __device__ void dq_q5_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
}
}
template<typename dst_t>
__device__ void dq_q4_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
const block_q4_0* x = (const block_q4_0*) vx + ibs * (QK_K / QK4_0);
const int ib = tid % 8, il = tid / 8;
const float d = __half2float(x[ib].d);
dst_t* y = yy + 32 * ib;
for (int j = 0; j < 4; ++j) {
const int iqs = 4 * il + j; // llama.cpp's dequantize_q4_0 for value pairs iqs, iqs + 16
y[iqs] = cvt<dst_t>(((float) (x[ib].qs[iqs] & 0xf) - 8.0f) * d);
y[iqs + 16] = cvt<dst_t>(((float) (x[ib].qs[iqs] >> 4) - 8.0f) * d);
}
}
template<typename dst_t>
__device__ void dq_q4_1(const void* vx, int64_t ibs, dst_t* yy, int tid) {
const block_q4_1* x = (const block_q4_1*) vx + ibs * (QK_K / QK4_1);
const int ib = tid % 8, il = tid / 8;
const float2 dm = __half22float2(x[ib].dm);
dst_t* y = yy + 32 * ib;
for (int j = 0; j < 4; ++j) {
const int iqs = 4 * il + j; // llama.cpp's dequantize_q4_1 for value pairs iqs, iqs + 16
y[iqs] = cvt<dst_t>((float) (x[ib].qs[iqs] & 0xf) * dm.x + dm.y);
y[iqs + 16] = cvt<dst_t>((float) (x[ib].qs[iqs] >> 4) * dm.x + dm.y);
}
}
template<typename dst_t>
__device__ void dq_q5_1(const void* vx, int64_t ibs, dst_t* yy, int tid) {
const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1);
const int ib = tid % 8, il = tid / 8;
@@ -1658,6 +1726,8 @@ __device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs,
case 13: dq_q5_k(vx, ibs, y, tid); break;
case 7: dq_q5_1(vx, ibs, y, tid); break;
case 6: dq_q5_0(vx, ibs, y, tid); break;
case 2: dq_q4_0(vx, ibs, y, tid); break;
case 3: dq_q4_1(vx, ibs, y, tid); break;
case 8: dq_q8_0(vx, ibs, y, tid); break;
case 30: dq_bf16(vx, ibs, y, tid); break;
default: break;
@@ -1682,7 +1752,7 @@ __global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const v
// the types dq_dispatch dequantizes
bool is_iq(int t) {
return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||
t == 12 || t == 13 || t == 7 || t == 6 || t == 8;
t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8;
}
// values per block of the types the grouped expert kernels take (0 = none)
int gu_qk(int t) {
@@ -2456,6 +2526,8 @@ size_t iq_row_bytes(int t, int64_t n) noexcept {
case 13: return (size_t) (n / 256) * sizeof(block_q5_K);
case 7: return (size_t) (n / 32) * sizeof(block_q5_1);
case 6: return (size_t) (n / 32) * sizeof(block_q5_0);
case 2: return (size_t) (n / 32) * sizeof(block_q4_0);
case 3: return (size_t) (n / 32) * sizeof(block_q4_1);
case 8: return (size_t) (n / 32) * sizeof(block_q8_0);
case 30: return (size_t) n * 2; // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)
default: return 0;
+1
View File
@@ -25,6 +25,7 @@ bool cpu_block(int type, const uint8_t* b, float* out) {
switch (type) {
case 2: dequantize_q4_0(b, out); return true;
case 6: dequantize_q5_0(b, out); return true;
case 7: dequantize_q5_1(b, out); return true;
case 8: dequantize_q8_0(b, out); return true;
case 11: dequantize_q3_K(b, out); return true;
case 12: dequantize_q4_K(b, out); return true;
+112 -30
View File
@@ -11,9 +11,13 @@
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#if !defined(_WIN32)
#include <sys/mman.h>
#endif
#include <algorithm>
#include <atomic>
#include <thread>
#include <vector>
#include <stdexcept>
@@ -134,12 +138,71 @@ void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) {
for (int j = 0; j < PLE_HEAD_DIM; ++j) out160[j] = kFp8.v[row[j]] * scale;
}
void bf16_dequant_row(const uint8_t* row, float* out160) {
// bfloat16 IS the top 16 bits of a float32, so widening is exact for every value, normal or not - no rounding,
// no clamp, no scale. Bytes are assembled little-endian explicitly rather than reinterpreted, so this is the
// same on a big-endian host.
for (int j = 0; j < PLE_HEAD_DIM; ++j) {
const uint32_t bits = (uint32_t) row[2 * j] | ((uint32_t) row[2 * j + 1] << 8);
const uint32_t wide = bits << 16;
float v;
std::memcpy(&v, &wide, sizeof v);
out160[j] = v;
}
}
// ---------------------------------------------------------------------------------------------------
// THE FORMAT TABLE (see PleFormatInfo). One entry per table type; the block formats decode 5 blocks of 32.
namespace {
template <void (*Block)(const uint8_t*, float*), int BlockBytes>
void dequant_blocks(const uint8_t* row, float /*scale*/, float* out160) {
for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) Block(row + (size_t) b * BlockBytes, out160 + b * 32);
}
void dequant_iq4_nl(const uint8_t* row, float, float* out160) { iq4nl_dequant_row(row, out160); }
void dequant_fp8(const uint8_t* row, float scale, float* out160) { fp8_e4m3_dequant_row(row, scale, out160); }
void dequant_bf16(const uint8_t* row, float, float* out160) { bf16_dequant_row(row, out160); }
const PleFormatInfo kPleFormats[] = {
{PleFormat::IQ4_NL, "IQ4_NL", "IQ4_NL", PLE_ROW_BYTES, false, dequant_iq4_nl},
{PleFormat::Q5_0, "Q5_0", "Q5_0", (PLE_HEAD_DIM / 32) * 22, false, dequant_blocks<strata::dequantize_q5_0, 22>},
{PleFormat::F8_E4M3, "F8_E4M3", "I8", PLE_ROW_BYTES_FP8, true, dequant_fp8},
// Ordinary GGUFs ship the table in other types: Unsloth's UD-Q6_K_XL and Swift-1.5 Q4_K_L as Q8_0, a Q5_K_M finetune as Q5_1
{PleFormat::Q5_1, "Q5_1", "Q5_1", PLE_ROW_BYTES_Q5_1, false, dequant_blocks<strata::dequantize_q5_1, 24>},
{PleFormat::Q8_0, "Q8_0", "Q8_0", PLE_ROW_BYTES_Q8_0, false, dequant_blocks<strata::dequantize_q8_0, 34>},
// Q4_0 (plain llama-quantize Q4_0 files, #599): 90-byte rows like IQ4_NL (18-byte blocks), a linear 4-bit grid
{PleFormat::Q4_0, "Q4_0", "Q4_0", PLE_ROW_BYTES, false, dequant_blocks<strata::dequantize_q4_0, 18>},
// BF16 (#586): the checkpoint's own table at full precision, 320-byte rows; self-describing, so no scale and no
// metadata to trust (tools/ple_fp8_pack.py writes the FP8 form of the same table)
{PleFormat::BF16, "BF16", "BF16", PLE_ROW_BYTES_BF16, false, dequant_bf16},
};
constexpr int kPleFormatCount = (int) (sizeof kPleFormats / sizeof kPleFormats[0]);
} // namespace
const PleFormatInfo* ple_formats() { return kPleFormats; }
int ple_format_count() { return kPleFormatCount; }
const PleFormatInfo& ple_format_info(PleFormat f) { return kPleFormats[(int) f]; }
const PleFormatInfo* ple_format_for_type(const char* gguf_type_name) {
for (const PleFormatInfo& f : kPleFormats)
if (std::strcmp(f.gguf_type, gguf_type_name) == 0) return &f;
return nullptr;
}
std::string ple_format_list() {
std::string out;
for (int i = 0; i < kPleFormatCount; ++i) {
const PleFormatInfo& f = kPleFormats[i];
if (i > 0) out += i + 1 == kPleFormatCount ? " or " : ", ";
out += std::strcmp(f.gguf_type, "I8") == 0 ? "FP8 (I8)" : f.name;
}
return out;
}
static_assert(PLE_ROW_BYTES_MAX >= PLE_ROW_BYTES && PLE_ROW_BYTES_MAX >= PLE_ROW_BYTES_FP8, "row buffers too small");
struct PleTable::Impl {
GgufFile* file = nullptr;
const uint8_t* data = nullptr;
uint64_t n_rows = 0;
bool q5_0 = false; // #296: Q5_0 rows (110 B), the mapped reader only
const PleFormatInfo* fmt = &ple_format_info(PleFormat::IQ4_NL); // the table's format (#296: Q5_0 is one of them)
mutable uint64_t bytes_read = 0;
// Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes
// from an unbuffered SSD read into `raw`.
@@ -155,15 +218,9 @@ struct PleTable::Impl {
strata::ngram::PleReader::Ticket prefetch_tickets[kMaxPrefetch] = {};
uint32_t prefetch_keys[kMaxPrefetch][PLE_N_HEADS] = {};
uint8_t prefetch_raw[kMaxPrefetch][PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {};
bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL
float scale = 1.0f; // the FP8 table's one scale
uint32_t rb = PLE_ROW_BYTES; // bytes per row
void decode(const uint8_t* row, float* out160) const {
if (fp8) fp8_e4m3_dequant_row(row, scale, out160);
else if (q5_0)
for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) strata::dequantize_q5_0(row + (size_t) b * 22, out160 + b * 32);
else iq4nl_dequant_row(row, out160);
}
void decode(const uint8_t* row, float* out160) const { fmt->dequant(row, scale, out160); }
};
PleTable::PleTable() : impl_(new Impl) {}
@@ -193,12 +250,16 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
close();
return false;
}
// IQ4_NL (ISTA-DASLab's shard 2, the original's own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as
// shipped: I8 bytes marked strata.ple.format = f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py)
impl_->fp8 = false;
impl_->q5_0 = std::strcmp(t->type_name(), "Q5_0") == 0;
impl_->rb = impl_->q5_0 ? (PLE_HEAD_DIM / 32) * 22 : PLE_ROW_BYTES;
if (std::strcmp(t->type_name(), "I8") == 0) {
// The table's type is looked up in the format list (ple_formats()): IQ4_NL (ISTA-DASLab's shard 2, the original's
// own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as shipped: I8 bytes marked strata.ple.format =
// f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py)
const PleFormatInfo* fmt = ple_format_for_type(t->type_name());
if (fmt == nullptr) {
err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not " + ple_format_list();
close();
return false;
}
if (fmt->needs_scale) {
const MetaValue* f = impl_->file->get("strata.ple.format");
const MetaValue* s = impl_->file->get("strata.ple.scale");
if (f == nullptr || f->s != "f8_e4m3" || s == nullptr || !(s->num() > 0.0)) {
@@ -206,19 +267,14 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
close();
return false;
}
impl_->fp8 = true;
impl_->scale = (float) s->num();
impl_->rb = PLE_ROW_BYTES_FP8;
} else if (!impl_->q5_0 && std::strcmp(t->type_name(), "IQ4_NL") != 0) {
err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not IQ4_NL, Q5_0 or FP8 (I8)";
close();
return false;
}
impl_->fmt = fmt;
impl_->rb = fmt->row_bytes;
// PleReader's row_bytes has been a runtime parameter since the FP8 table (160 B rows) needed it; Q5_0's
// 110 B rows go through the exact same generic path (ple_reader_test --selftest covers both 90 and 110 B
// rows: straddling, caching, in-flight tickets, keep-alive). This refusal was stale.
impl_->n_rows = t->shape[1];
impl_->data = impl_->file->tensor_data(*t);
// THE CHECK THAT MAKES THE OFFSET FALSIFIABLE. The manifest's `shard2_tensor.offset` is 0, but that is
// the offset within the GGUF's DATA SECTION: the file's first 192 bytes are a header, and reading at 0
@@ -228,10 +284,18 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
// assumed. A wrong data offset would leave a different remainder.
// A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must
// then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly.
// The size arithmetic is checked before it is used (#865): a header that claims enough rows to wrap the 64-bit
// product, or a data section that starts past the end of the file, must be refused, not compared after wrapping.
if (impl_->n_rows > std::numeric_limits<uint64_t>::max() / impl_->rb ||
impl_->file->data_start() > impl_->file->file_size()) {
err = "PLE table size overflow or invalid data offset in " + gguf_path;
close();
return false;
}
const uint64_t need = impl_->n_rows * (uint64_t) impl_->rb;
const uint64_t have = impl_->file->file_size() - impl_->file->data_start();
const bool alone = impl_->file->tensors().size() == 1;
if (alone ? need != have : t->offset + need > have) {
if (t->offset > have || need > have - t->offset || (alone && (t->offset != 0 || need != have))) {
char buf[256];
std::snprintf(buf, sizeof buf,
"PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from "
@@ -243,6 +307,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
close();
return false;
}
impl_->data = impl_->file->tensor_data(*t); // only a table that fits the file is mapped
if (io.mode == PleIo::Direct) {
// The parse above is the validated source of the offset; the mapping itself is not kept, so no page of
// the table can enter this process's working set or the file cache through it.
@@ -265,14 +330,30 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO
const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1);
const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need;
madvise((void*) a0, a1 - a0, MADV_WILLNEED);
// Fault the table in with several threads first: mlock (and a single toucher) brings it in one page at a time
// from one thread, ~0.5 GB/s from a cold file - 106 s for a 54 GB Q8_0 table. The pages are then resident
// and mlock only pins them.
{
constexpr uintptr_t kPiece = 64ull << 20;
const uintptr_t pieces = (a1 - a0 + kPiece - 1) / kPiece;
const unsigned threads = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
std::atomic<uintptr_t> next{0};
auto touch = [&] {
volatile uint8_t sink = 0;
for (uintptr_t i; (i = next.fetch_add(1)) < pieces;)
for (uintptr_t p = a0 + i * kPiece, e = std::min(a1, p + kPiece); p < e; p += page)
sink = sink + *(const volatile uint8_t*) p;
(void) sink;
};
std::vector<std::thread> pool;
for (unsigned t = 0; t < threads; ++t) pool.emplace_back(touch);
for (auto& t : pool) t.join();
}
if (mlock((const void*) a0, a1 - a0) == 0) {
impl_->locked = true;
} else {
std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): touching its pages instead\n",
std::strerror(errno));
volatile uint8_t sink = 0;
for (uintptr_t p = a0; p < a1; p += page) sink = sink + *(const volatile uint8_t*) p;
(void) sink;
std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): its pages stay faulted in "
"but may be reclaimed\n", std::strerror(errno));
}
#endif
}
@@ -323,13 +404,14 @@ void PleTable::close() {
impl_->data = nullptr;
impl_->n_rows = 0;
impl_->rb = PLE_ROW_BYTES;
impl_->q5_0 = false;
impl_->fp8 = false;
impl_->fmt = &ple_format_info(PleFormat::IQ4_NL);
impl_->scale = 1.0f;
impl_->bytes_read = 0;
}
bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); }
bool PleTable::locked() const { return impl_->locked; }
const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; }
const char* PleTable::format() const { return impl_->fmt->name; }
PleIo PleTable::mode() const { return impl_->mode; }
uint64_t PleTable::rows() const { return impl_->n_rows; }
uint64_t PleTable::bytes_read() const { return impl_->bytes_read; }
+51 -24
View File
@@ -1,4 +1,5 @@
// Real-artifact Q5_0 PLE rows against ggml's reference dequantizer.
// Real-artifact Q5_0 / Q5_1 / Q8_0 PLE rows against ggml's reference dequantizer, through both readers (the mapped
// one and the direct SSD reader).
#define NOMINMAX
#include "strata/artifact/gguf_reader.hpp"
#include "strata/kernels/ngram.hpp"
@@ -10,33 +11,28 @@
#include <string>
#include <vector>
int main(int argc, char** argv) {
if (argc != 2) {
std::fprintf(stderr, "usage: ple_q5_parity <gguf-containing-ple>\n");
return 2;
}
strata::GgufFile gguf(argv[1]);
const auto* tensor = gguf.find("per_layer_token_embd.weight");
if (!tensor || tensor->type != 6 || tensor->shape.size() != 2 || tensor->shape[0] != 160) {
std::fprintf(stderr, "expected Q5_0 PLE [160, N]\n");
return 2;
}
namespace {
// Largest absolute difference between the table's rows and ggml's dequantization of the same bytes, single rows
// and one 16-row batch; -1 when the table cannot be opened or read.
double check(const char* path, strata::kernels::PleIo mode, const uint8_t* bytes, size_t row_bytes,
const ggml_type_traits* traits, std::string& format, size_t& n_rows) {
strata::kernels::PleIoOptions options;
options.mode = strata::kernels::PleIo::Mmap;
options.mode = mode;
strata::kernels::PleTable table;
std::string err;
if (!table.open(argv[1], err, options)) {
std::fprintf(stderr, "%s\n", err.c_str());
return 1;
if (!table.open(path, err, options)) {
std::fprintf(stderr, "open: %s\n", err.c_str());
return -1.0;
}
const auto* traits = ggml_get_type_traits(GGML_TYPE_Q5_0);
const uint8_t* bytes = gguf.tensor_data(*tensor);
format = table.format();
n_rows = (size_t) table.rows();
const uint32_t probes[] = {0, 1, 12345, 20000003, (uint32_t) (table.rows() - 1)};
double max_abs = 0.0;
for (uint32_t row : probes) {
float got[160], want[160];
table.read_row(row, got);
traits->to_float(bytes + (size_t) row * 110, want, 160);
traits->to_float(bytes + (size_t) row * row_bytes, want, 160);
for (int i = 0; i < 160; ++i)
max_abs = std::max(max_abs, (double) std::fabs(got[i] - want[i]));
}
@@ -45,15 +41,46 @@ int main(int argc, char** argv) {
float batch[16 * 160];
if (!table.issue(rows) || !table.collect(batch, err)) {
std::fprintf(stderr, "collect: %s\n", err.c_str());
return 1;
return -1.0;
}
for (int h = 0; h < 16; ++h) {
float want[160];
traits->to_float(bytes + (size_t) rows[h] * 110, want, 160);
traits->to_float(bytes + (size_t) rows[h] * row_bytes, want, 160);
for (int i = 0; i < 160; ++i)
max_abs = std::max(max_abs, (double) std::fabs(batch[h * 160 + i] - want[i]));
}
std::printf("Q5_0 PLE: %zu rows, max_abs %.3e %s\n", (size_t) table.rows(), max_abs,
max_abs <= 1e-6 ? "PASS" : "FAIL");
return max_abs <= 1e-6 ? 0 : 1;
return max_abs;
}
} // namespace
int main(int argc, char** argv) {
if (argc != 2) {
std::fprintf(stderr, "usage: ple_q5_parity <gguf-containing-ple>\n");
return 2;
}
strata::GgufFile gguf(argv[1]);
const auto* tensor = gguf.find("per_layer_token_embd.weight");
// Q5_0 (#296: OrcaRouter's Q4_K_S), Q5_1 (a Q5_K_M GGUF), Q8_0 (UD-Q6_K_XL, Swift-1.5 Q4_K_L): 5 blocks of
// 32 per row
if (!tensor || (tensor->type != GGML_TYPE_Q5_0 && tensor->type != GGML_TYPE_Q5_1 && tensor->type != GGML_TYPE_Q8_0) ||
tensor->shape.size() != 2 || tensor->shape[0] != 160) {
std::fprintf(stderr, "expected a Q5_0, Q5_1 or Q8_0 PLE [160, N]\n");
return 2;
}
const auto type = (ggml_type) tensor->type;
const size_t row_bytes = type == GGML_TYPE_Q5_0 ? 110 : type == GGML_TYPE_Q5_1 ? 120 : 170;
const auto* traits = ggml_get_type_traits(type);
const uint8_t* bytes = gguf.tensor_data(*tensor);
bool ok = true;
for (auto mode : {strata::kernels::PleIo::Mmap, strata::kernels::PleIo::Direct}) {
std::string format;
size_t n_rows = 0;
const double max_abs = check(argv[1], mode, bytes, row_bytes, traits, format, n_rows);
const bool pass = max_abs >= 0.0 && max_abs <= 1e-6;
std::printf("%s PLE, %s reader: %zu rows, max_abs %.3e %s\n", format.c_str(),
mode == strata::kernels::PleIo::Mmap ? "mapped" : "direct", n_rows, max_abs, pass ? "PASS" : "FAIL");
ok = ok && pass;
}
return ok ? 0 : 1;
}
+195
View File
@@ -75,6 +75,170 @@ bool check_rows(ng::PleReader& rd, const std::vector<uint32_t>& rows, uint32_t n
return true;
}
/// THE BF16 TABLE, and the claim it rests on. A bfloat16 is literally the top half of a float32, so widening
/// one is a shift: exact for every value, normal or not, with no rounding to hide behind. These patterns are
/// the ones a lossy path would break on - the subnormals and the NaN/inf encodings a saturating cast to FP8
/// would collapse - so a table that came back through the FP8 route would not reproduce all of them.
void bf16_widening_is_exact() {
const uint16_t bits[] = {0x0000, 0x8000, 0x3f80, 0xbf80, 0x7f7f, 0xff7f, // 0, -0, 1, -1, max, -max
0x0001, 0x8001, 0x007f, 0x7f80, 0xff80, // smallest subnormals, +-inf
0x7fc0, 0x7f81, 0x4049, 0xc249, 0x3c75}; // NaN, signalling NaN, 3.14, -3.14
for (uint16_t b : bits) {
uint8_t row[2 * k::PLE_HEAD_DIM];
std::memset(row, 0, sizeof row);
row[0] = (uint8_t) b; // little-endian: the low byte first
row[1] = (uint8_t) (b >> 8);
float out[k::PLE_HEAD_DIM];
k::bf16_dequant_row(row, out);
uint32_t want = (uint32_t) b << 16, got;
std::memcpy(&got, &out[0], sizeof got);
CHECK(got == want, "bf16 0x%04x widened to 0x%08x, not 0x%08x", b, got, want);
bool tail_zero = true; // one element under test must not have shifted the rest
for (int j = 1; j < k::PLE_HEAD_DIM; ++j) tail_zero = tail_zero && out[j] == 0.0f;
CHECK(tail_zero, "bf16 0x%04x: the rest of the row is not zero", b);
}
}
/// EVERY FORMAT OF THE TABLE, END TO END (table-driven: one entry in `k::ple_formats()` is one run here). A minimal
/// PLE-only GGUF holds `rows` rows of that format's row size, each filled with bytes that encode the row, and both I/O
/// modes must return exactly what the format's own dequantizer makes of those bytes - so the row width, the offset
/// and the type lookup all have to be right for every format, not only for IQ4_NL.
uint32_t gguf_type_id(const char* name) {
static const struct { const char* name; uint32_t id; } ids[] = {
{"IQ4_NL", 20}, {"Q4_0", 2}, {"Q4_1", 3}, {"Q5_0", 6}, {"Q5_1", 7}, {"Q8_0", 8}, {"BF16", 30}, {"F8_E4M3", 24}};
for (const auto& e : ids)
if (std::strcmp(e.name, name) == 0) return e.id;
return 0xFFFFFFFFu;
}
// `claimed_rows` is the row count the header states; `rows` rows are actually written (equal unless a test lies)
std::string write_format_table(const std::string& dir, const k::PleFormatInfo& f, uint32_t rows, uint64_t claimed_rows = 0) {
const std::string path = dir + "/ple_format_selftest.gguf";
std::ofstream out(path, std::ios::binary);
if (!out) { std::fprintf(stderr, "cannot write %s\n", path.c_str()); return {}; }
const auto le = [](auto value, int bytes) {
std::string s((size_t) bytes, '\0');
for (int i = 0; i < bytes; ++i) s[(size_t) i] = (char) ((value >> (8 * i)) & 0xff);
return s;
};
const auto str = [&](const char* s) { return le((uint64_t) std::strlen(s), 8) + std::string(s); };
const uint64_t n_kv = f.needs_scale ? 3 : 1;
std::string head = "GGUF" + le(3u, 4) + le(1ull, 8) + le(n_kv, 8);
head += str("general.architecture") + le(8u, 4) + str("strata-ple");
if (f.needs_scale) {
const float scale = 0.75f;
uint32_t sb;
std::memcpy(&sb, &scale, 4);
head += str("strata.ple.format") + le(8u, 4) + str("f8_e4m3");
head += str("strata.ple.scale") + le(6u, 4) + le(sb, 4); // 6 = FLOAT32
}
head += str("per_layer_token_embd.weight") + le(2u, 4);
head += le((uint64_t) k::PLE_HEAD_DIM, 8) + le(claimed_rows != 0 ? claimed_rows : (uint64_t) rows, 8);
head += le(gguf_type_id(f.name), 4) + le(0ull, 8);
while (head.size() % 32) head += '\0';
out.write(head.data(), (std::streamsize) head.size());
std::vector<uint8_t> r(f.row_bytes);
for (uint32_t i = 0; i < rows; ++i) {
expected_row(i, f.row_bytes, r.data());
out.write((const char*) r.data(), (std::streamsize) f.row_bytes);
}
out.close();
return out ? path : std::string();
}
void format_round_trip(const std::string& dir, const k::PleFormatInfo& f, uint32_t rows) {
CHECK(gguf_type_id(f.name) != 0xFFFFFFFFu, "%s: no GGUF type id in this test", f.name);
CHECK(f.row_bytes > 0 && f.row_bytes <= (uint32_t) k::PLE_ROW_BYTES_MAX, "%s: row_bytes %u out of range", f.name, f.row_bytes);
const std::string path = write_format_table(dir, f, rows);
if (path.empty()) { CHECK(false, "%s: no table was written", f.name); return; }
std::mt19937 rng(13);
std::vector<uint32_t> want(rows);
for (uint32_t i = 0; i < rows; ++i) want[i] = rng() % rows;
want[0] = 0;
want[1] = rows - 1;
for (k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) {
const char* name = mode == k::PleIo::Direct ? "direct" : "mmap";
k::PleTable t;
std::string err;
k::PleIoOptions io;
io.mode = mode;
io.max_inflight = 8;
io.cache_rows = 0;
CHECK(t.open(path, err, io), "%s: open in %s mode: %s", f.name, name, err.c_str());
if (g_fail) break;
CHECK(std::strcmp(t.format(), f.name) == 0, "%s: format() says \"%s\"", f.name, t.format());
CHECK(t.rows() == rows, "%s: rows %llu, not %u", f.name, (unsigned long long) t.rows(), rows);
std::vector<uint8_t> raw(f.row_bytes);
float got[k::PLE_HEAD_DIM], ref[k::PLE_HEAD_DIM];
for (uint32_t r : want) {
t.read_row(r, got);
expected_row(r, f.row_bytes, raw.data());
f.dequant(raw.data(), f.needs_scale ? 0.75f : 1.0f, ref);
if (std::memcmp(got, ref, sizeof got) != 0) {
CHECK(false, "%s: %s: row %u differs from the format's own dequantizer", f.name, name, r);
break;
}
}
// the 16-row path a token takes, one batch
float tok[16 * k::PLE_HEAD_DIM];
uint32_t rows16[16];
for (int h = 0; h < 16; ++h) rows16[h] = want[(size_t) h + 2];
t.gather(rows16, tok);
for (int h = 0; h < 16; ++h) {
expected_row(rows16[h], f.row_bytes, raw.data());
f.dequant(raw.data(), f.needs_scale ? 0.75f : 1.0f, ref);
CHECK(std::memcmp(tok + (size_t) h * k::PLE_HEAD_DIM, ref, sizeof ref) == 0, "%s: %s: gather head %d differs", f.name, name, h);
}
}
std::filesystem::remove(path);
}
/// A table whose header does not match the file is refused with a message, never read past its end (#865): one row
/// short, one row long (a single-tensor shard must be filled exactly), and a row count that wraps the 64-bit size.
void bad_sizes_are_refused(const std::string& dir) {
for (int i = 0; i < k::ple_format_count(); ++i) {
const k::PleFormatInfo& f = k::ple_formats()[i];
struct { const char* what; uint32_t rows; uint64_t claimed; } cases[] = {
{"claims one row more than the file holds", 500, 501},
{"claims one row less than the file holds", 500, 499},
{"claims a row count that wraps 2^64", 8, (uint64_t) 0x4000000000000000ull / 3 * 2},
};
for (const auto& c : cases) {
const std::string path = write_format_table(dir, f, c.rows, c.claimed);
if (path.empty()) { CHECK(false, "%s: no table was written", f.name); continue; }
for (k::PleIo mode : {k::PleIo::Direct, k::PleIo::Mmap}) {
k::PleTable t;
std::string err;
k::PleIoOptions io;
io.mode = mode;
io.cache_rows = 0;
CHECK(!t.open(path, err, io), "%s: a table that %s was accepted", f.name, c.what);
CHECK(!err.empty(), "%s: refused without a message (%s)", f.name, c.what);
CHECK(!t.is_open(), "%s: left open after refusing (%s)", f.name, c.what);
}
std::filesystem::remove(path);
}
}
}
void all_formats_round_trip(const std::string& dir) {
bf16_widening_is_exact(); // BF16's own claim: a shift, exact for every pattern
bad_sizes_are_refused(dir);
CHECK(k::ple_format_count() > 0, "no formats");
for (int i = 0; i < k::ple_format_count(); ++i) {
const k::PleFormatInfo& f = k::ple_formats()[i];
CHECK((int) f.id == i, "%s: the table is not in PleFormat order", f.name);
CHECK(k::ple_format_for_type(f.gguf_type) == &f, "%s: type lookup", f.name);
format_round_trip(dir, f, 2000);
}
CHECK(k::ple_format_for_type("Q6_K") == nullptr, "Q6_K must not be a PLE format");
if (g_fail == 0) {
std::printf("ple formats, both readers vs their dequantizers:");
for (int i = 0; i < k::ple_format_count(); ++i) std::printf(" %s", k::ple_formats()[i].name);
std::printf(": OK\n");
}
}
// row_bytes: ng::ROW_BYTES (90, IQ4_NL) is the production default; 110 (#296, OrcaRouter's Q5_0 PLE rows) is
// run too, through the exact same generic row_bytes path -- nothing here is IQ4_NL-specific, so a second row
// size run here is the correctness evidence for lifting ngram.cpp's "Q5_0 PLE requires --ple-io mmap" refusal.
@@ -272,9 +436,12 @@ int main(int argc, char** argv) {
bool direct_only = false;
bool sync_submit = false;
bool self = false;
std::string make_path, make_fmt, ram_path; // --make-table PATH FORMAT (uses --rows), --ram-time PATH
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
if (a == "--selftest") self = true;
else if (a == "--make-table" && i + 2 < argc) { make_path = argv[i + 1]; make_fmt = argv[i + 2]; i += 2; }
else if (a == "--ram-time" && i + 1 < argc) ram_path = argv[++i];
else if (a == "--dir" && i + 1 < argc) dir = argv[++i];
else if (a == "--gguf" && i + 1 < argc) gguf = argv[++i];
else if (a == "--rows" && i + 1 < argc) rows = std::atoi(argv[++i]);
@@ -288,10 +455,38 @@ int main(int argc, char** argv) {
if (self) {
// ng::ROW_BYTES (90, IQ4_NL, production default) and 110 (#296, OrcaRouter's Q5_0 PLE rows) through the
// same generic row_bytes path -- see the comment on selftest().
all_formats_round_trip(dir); // every format of k::ple_formats(), both readers, vs its dequantizer
if (g_fail != 0) return 1;
const int r90 = selftest(dir, ng::ROW_BYTES);
const int r110 = selftest(dir, 110);
return r90 != 0 ? r90 : r110;
}
if (!make_path.empty()) { // a big synthetic table, for timing --ple-io ram's fault-in
for (int i = 0; i < k::ple_format_count(); ++i) {
const k::PleFormatInfo& f = k::ple_formats()[i];
if (make_fmt != f.name) continue;
const std::string tmp = write_format_table(std::filesystem::path(make_path).parent_path().string(), f, (uint32_t) rows);
if (tmp.empty()) return 1;
std::filesystem::rename(tmp, make_path);
std::printf("wrote %s: %s, %d rows, %.2f GiB\n", make_path.c_str(), f.name, rows,
(double) rows * f.row_bytes / (1024.0 * 1024.0 * 1024.0));
return 0;
}
std::fprintf(stderr, "unknown format %s\n", make_fmt.c_str());
return 2;
}
if (!ram_path.empty()) { // open mapped and locked (--ple-io ram): the seconds it takes
k::PleTable t;
k::PleIoOptions io;
io.mode = k::PleIo::Mmap;
io.lock = true;
std::string err;
const double t0 = now_us();
const bool ok = t.open(ram_path, err, io);
std::printf("ram open: %s, format %s, locked %d, %.2f s\n", ok ? "ok" : err.c_str(), ok ? t.format() : "-", ok && t.locked(),
(now_us() - t0) / 1e6);
return ok ? 0 : 1;
}
if (!gguf.empty()) return real(gguf, rows, tokens, inflight, direct_first, direct_only, sync_submit);
std::fprintf(stderr, "nothing to do\n");
return 2;
+12 -4
View File
@@ -6388,6 +6388,11 @@ int main(int argc, char** argv) {
float req_min_p = 0.0f, req_penalty_repeat = 1.0f, req_penalty_freq = 0.0f, req_penalty_present = 0.0f;
int req_penalty_last_n = 0;
int req_cvec = 1; // cvec=0|1: a loaded control vector for this request (on when absent)
// ckpt=0: a one-shot call whose turn no later request extends. No checkpoint at its last turn boundary
// (so no split there) nor every --prompt-cache-every tokens, and its session is neither continued nor
// parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root
// when that reaches --prompt-cache-root. Absent = checkpointed as before.
int req_ckpt = 1;
// tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of
// the missed experts and the draft-probability floor, for this request only
double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p;
@@ -6404,6 +6409,7 @@ int main(int argc, char** argv) {
const std::string key = tok.substr(0, eq);
const float fv = std::strtof(tok.c_str() + eq + 1, nullptr);
if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1);
else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0;
else if (key == "temperature") req_temperature = fv;
else if (key == "top_p") req_top_p = fv;
else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1);
@@ -6792,7 +6798,7 @@ int main(int argc, char** argv) {
pp_from = read_from;
pp_reached = read_from;
pp_t0 = r0;
pp_next_check = reread_to > 0 ? INT64_MAX : resume + o.prompt_cache_every;
pp_next_check = reread_to > 0 || !req_ckpt ? INT64_MAX : resume + o.prompt_cache_every; // ckpt=0: none
{
std::lock_guard<std::mutex> lk(part_mu);
part_at.clear();
@@ -7119,9 +7125,11 @@ int main(int argc, char** argv) {
// which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it.
// (PR #65, code-martin.) Only for a system prompt of --prompt-cache-root tokens or more: a small one
// is cheaper to read again than the extra part costs (~0.3 s).
const int64_t last_turn = turn_at; // ckpt=0 drops the split there, the root is still looked for before it
if (!req_ckpt) turn_at = -1;
int64_t root_at = -1;
if (o.prompt_cache > 0 && o.turn_token >= 0 && o.prompt_cache_root > 0 && (read_from == 0 || resumed_from0))
for (int64_t i = 1; i < turn_at; ++i)
for (int64_t i = 1; i < last_turn; ++i)
if (ids[(size_t) i] == o.turn_token) {
if (i >= o.prompt_cache_root) root_at = i;
break;
@@ -7393,10 +7401,10 @@ int main(int argc, char** argv) {
// (the checkpoints taken while reading it are still good)
live.swap(consumed);
live_imgs = imgs_below(req_imgs, (int64_t) live.size());
live_ok = o.prompt_cache > 0;
live_ok = o.prompt_cache > 0 && req_ckpt; // ckpt=0: nothing to continue or park (#830)
}
static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr;
if (state_hash && live_ok) {
if (state_hash && !cancelled && o.prompt_cache > 0) { // every finished request, ckpt=0 too (parity gates)
// DEBUG: a fingerprint of every part of the session over the positions it holds ([0, L)), and
// separately of what lies past them in the last KV page (stale cells, fine unless something reads them)
if (cudaDeviceSynchronize() != cudaSuccess) {