okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-q4-geometry (fc1c4e429): the model shape is fixed at build time (-DSTRATA_GEOMETRY / -DSTRATA_GEOMETRY_FILE); the default Flash-Next build is unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 path-string offsets only, SYCL 22/22 checksums, Metal 10/10 tokens, CUDA 130/130 tokens); Qwen4 test shapes q4_lite/q4_mid/q4_big pass logits gate 2 on CUDA (Qwen4 prep)4dad59ab3

main
42.1 KiB822 linesraw
1// src/kernels/ngram.cpp - P2.S4: the PLE n-gram hash and the IQ4_NL table read.
2//
3// See include/strata/kernels/ngram.hpp for the semantics, the rival readings, and the note on MADV_RANDOM.
4#include "strata/kernels/ngram.hpp"
5#include "strata/artifact/gguf_reader.hpp"
6#include "strata/artifact/dequant.hpp"
7#include "strata/kernels/f16_bits.hpp"
8#include "strata/ngram/ple_reader.hpp"
9#include "strata/platform/memory.hpp"
10
11#include <cerrno>
12#include <cmath>
13#include <cstdio>
14#include <cstdlib>
15#include <cstring>
16#include <fstream>
17#include <limits>
18#if !defined(_WIN32)
19#include <sys/mman.h>
20#include <sys/resource.h>
21#endif
22#include <algorithm>
23#include <atomic>
24#include <mutex>
25#include <thread>
26#include <vector>
27#include <stdexcept>
28
29#if defined(_WIN32)
30// `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below.
31#define WIN32_LEAN_AND_MEAN
32#define NOMINMAX
33#include <windows.h>
34#endif
35
36namespace strata::kernels {
37
38namespace {
39/// The A/B arm.  Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`.
40bool g_ple_prefetch = true;
41}  // namespace
42
43void ple_prefetch_enable(bool on) { g_ple_prefetch = on; }
44bool ple_prefetch_enabled() { return g_ple_prefetch; }
45
46PleConsts ple_artifact_consts() {
47    // docs/gguf-dump-shard1.txt, verbatim.  Written once here rather than derived, because `head_offsets` is
48    // ALSO in the metadata as its own array - and deriving one from the other would hide a mismatch between
49    // them instead of surfacing it.  The parity test checks the two agree.
50    PleConsts c{};
51    c.mult[0] = 23703573157769ull;
52    c.mult[1] = 20109073645365ull;
53    c.mult[2] = 8052911324071ull;
54    const uint64_t vocab[PLE_N_HEADS] = {
55        20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077,
56        20000081, 20000093, 20000107, 20000147, 20000153, 20000159, 20000161, 20000171};
57    const uint64_t offset[PLE_N_HEADS] = {
58        0,        20000003, 40000026, 60000059, 80000106, 100000165, 120000228, 140000297,
59        160000374, 180000455, 200000548, 220000655, 240000802, 260000955, 280001114, 300001275};
60    for (int i = 0; i < PLE_N_HEADS; ++i) {
61        c.vocab[i] = vocab[i];
62        c.offset[i] = offset[i];
63    }
64    return c;
65}
66
67bool ple_consts_from_arrays(const std::vector<uint64_t>& mult, const std::vector<uint64_t>& vocab,
68                            const std::vector<uint64_t>& offset, uint64_t table_rows, PleConsts& out, std::string& err) {
69    if (mult.size() != (size_t) NGRAM_SIZE || vocab.size() != (size_t) PLE_N_HEADS || offset.size() != (size_t) PLE_N_HEADS) {
70        err = "the PLE metadata holds " + std::to_string(mult.size()) + " multipliers, " + std::to_string(vocab.size()) +
71              " head sizes and " + std::to_string(offset.size()) + " head offsets; the engine needs " +
72              std::to_string(NGRAM_SIZE) + ", " + std::to_string(PLE_N_HEADS) + " and " + std::to_string(PLE_N_HEADS);
73        return false;
74    }
75    PleConsts c{};
76    for (int i = 0; i < NGRAM_SIZE; ++i) c.mult[i] = mult[i];
77    for (int h = 0; h < PLE_N_HEADS; ++h) {
78        if (vocab[h] == 0) { err = "PLE head " + std::to_string(h) + " has a hash modulus of 0"; return false; }
79        if (table_rows != 0 && (offset[h] > table_rows || vocab[h] > table_rows - offset[h])) {
80            err = "PLE head " + std::to_string(h) + " (offset " + std::to_string(offset[h]) + ", " + std::to_string(vocab[h]) +
81                  " rows) reaches past the table's " + std::to_string(table_rows) + " rows";
82            return false;
83        }
84        c.vocab[h] = vocab[h];
85        c.offset[h] = offset[h];
86    }
87    out = c;
88    return true;
89}
90
91uint64_t ngram_mixed(const int64_t* ctx, const uint64_t* mult, int n) {
92    // The first term is an ASSIGNMENT and the rest are XORed into it, which is how the source writes it
93    // (`uint64_t mixed = ctx[0]*m[0]; for j=1.. mixed ^= ctx[j]*m[j];`).  Every product wraps mod 2^64,
94    // which is what the `(uint64_t)` casts in the source make explicit.
95    uint64_t mixed = (uint64_t) ctx[0] * mult[0];
96    for (int j = 1; j < n; ++j) mixed ^= (uint64_t) ctx[j] * mult[j];
97    return mixed;
98}
99
100void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const PleConsts& c, uint32_t* out) {
101    const int n_prev = NGRAM_SIZE - 1;
102    for (int i = 0; i < n_tokens; ++i) {
103        int64_t ctx[NGRAM_SIZE];
104        ctx[0] = tokens[i];
105        bool cut = false;
106        for (int s = 1; s < NGRAM_SIZE; ++s) {
107            // `prev` is OLDEST FIRST, so predecessor `s` positions back is entry (n_prev - s): s=1 reads the
108            // NEWEST.  Reading index (s-1) instead walks the window backwards, which still produces indices
109            // in range and so cannot be caught by a range check - only by an oracle.
110            const int32_t t = cut ? TOKEN_NULL : prev[i * n_prev + (n_prev - s)];
111            // The cut is evaluated BEFORE the value is stored, so the position whose predecessor was EOS is
112            // itself EOS.  Storing first and then cutting would leave position s holding the real token while
113            // position s+1 became EOS - one token of history too much.
114            cut = cut || t < 0 || t == PLE_EOS_TOKEN_ID;
115            ctx[s] = cut ? PLE_EOS_TOKEN_ID : t;
116        }
117        for (int n = 2; n <= NGRAM_SIZE; ++n) {
118            const uint64_t mixed = ngram_mixed(ctx, c.mult, n);
119            const int base = (n - 2) * HEADS_PER_NGRAM;
120            for (int g = 0; g < HEADS_PER_NGRAM; ++g) {
121                const int h = base + g;
122                out[i * PLE_N_HEADS + h] = (uint32_t) (mixed % c.vocab[h] + c.offset[h]);
123            }
124        }
125    }
126}
127
128namespace {
129const int8_t kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
130}
131
132int iq4nl_code(int code) { return kIq4Nl[code & 15]; }
133
134void iq4nl_dequant_row(const uint8_t* row, float* out160) {
135    for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) {
136        const uint8_t* blk = row + (size_t) b * 18;
137        uint16_t dbits;
138        std::memcpy(&dbits, blk, 2);
139        const float d = f32_from_f16(dbits);
140        const uint8_t* qs = blk + 2;
141        // SPLIT HALVES: qs[j] holds elements j and j+16, not 2j and 2j+1.
142        for (int j = 0; j < 16; ++j) {
143            out160[b * 32 + j] = d * (float) kIq4Nl[qs[j] & 0x0F];
144            out160[b * 32 + j + 16] = d * (float) kIq4Nl[qs[j] >> 4];
145        }
146    }
147}
148
149namespace {
150struct Fp8Table {
151    float v[256];
152    Fp8Table() {
153        for (int x = 0; x < 256; ++x) {
154            const int s = x >> 7, e = (x >> 3) & 15, m = x & 7;
155            float f;
156            if (e == 15 && m == 7) f = 0.0f;                     // NaN in e4m3fn; never in a real table, read as 0
157            else if (e == 0) f = std::ldexp((float) m / 8.0f, -6);
158            else f = std::ldexp(1.0f + (float) m / 8.0f, e - 7);
159            v[x] = s ? -f : f;
160        }
161    }
162};
163const Fp8Table kFp8;
164}  // namespace
165
166void fp8_e4m3_dequant_row(const uint8_t* row, float scale, float* out160) {
167    for (int j = 0; j < PLE_HEAD_DIM; ++j) out160[j] = kFp8.v[row[j]] * scale;
168}
169
170void bf16_dequant_row(const uint8_t* row, float* out160) {
171    // bfloat16 IS the top 16 bits of a float32, so widening is exact for every value, normal or not - no rounding,
172    // no clamp, no scale. Bytes are assembled little-endian explicitly rather than reinterpreted, so this is the
173    // same on a big-endian host.
174    for (int j = 0; j < PLE_HEAD_DIM; ++j) {
175        const uint32_t bits = (uint32_t) row[2 * j] | ((uint32_t) row[2 * j + 1] << 8);
176        const uint32_t wide = bits << 16;
177        float v;
178        std::memcpy(&v, &wide, sizeof v);
179        out160[j] = v;
180    }
181}
182
183// NVIDIA's FP4-Local table: a row of 160 values is 80 bytes of E2M1 codes (element 2i in the low nibble, 2i+1 in the
184// high one) followed by 10 E4M3 block scales (one per 16 values, sign bit always 0); one F32 scales the whole table.
185// value = e2m1(code) * e4m3(block scale) * table scale, exactly what vLLM's nvfp4 PLE lookup computes.
186void nvfp4_row_dequant(const uint8_t* row, float scale, float* out160) {
187    static const float kE2M1[8] = {0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f};
188    for (int j = 0; j < PLE_HEAD_DIM; ++j) {
189        const uint8_t byte = row[j >> 1];
190        const uint8_t code = (j & 1) ? (uint8_t) (byte >> 4) : (uint8_t) (byte & 15);
191        const float v = kE2M1[code & 7];
192        const float s = kFp8.v[row[PLE_HEAD_DIM / 2 + (j >> 4)]];
193        out160[j] = ((code & 8) ? -v : v) * s * scale;
194    }
195}
196
197// ---------------------------------------------------------------------------------------------------
198// THE FORMAT TABLE (see PleFormatInfo). One entry per table type; the block formats decode 5 blocks of 32.
199namespace {
200template <void (*Block)(const uint8_t*, float*), int BlockBytes>
201void dequant_blocks(const uint8_t* row, float /*scale*/, float* out160) {
202    for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) Block(row + (size_t) b * BlockBytes, out160 + b * 32);
203}
204void dequant_iq4_nl(const uint8_t* row, float, float* out160) { iq4nl_dequant_row(row, out160); }
205void dequant_fp8(const uint8_t* row, float scale, float* out160) { fp8_e4m3_dequant_row(row, scale, out160); }
206void dequant_bf16(const uint8_t* row, float, float* out160) { bf16_dequant_row(row, out160); }
207void dequant_nvfp4(const uint8_t* row, float scale, float* out160) { nvfp4_row_dequant(row, scale, out160); }
208
209const PleFormatInfo kPleFormats[] = {
210    {PleFormat::IQ4_NL, "IQ4_NL", "IQ4_NL", PLE_ROW_BYTES, false, dequant_iq4_nl},
211    {PleFormat::Q5_0, "Q5_0", "Q5_0", (PLE_HEAD_DIM / 32) * 22, false, dequant_blocks<strata::dequantize_q5_0, 22>},
212    {PleFormat::F8_E4M3, "F8_E4M3", "I8", PLE_ROW_BYTES_FP8, true, dequant_fp8},
213    // 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
214    {PleFormat::Q5_1, "Q5_1", "Q5_1", PLE_ROW_BYTES_Q5_1, false, dequant_blocks<strata::dequantize_q5_1, 24>},
215    {PleFormat::Q8_0, "Q8_0", "Q8_0", PLE_ROW_BYTES_Q8_0, false, dequant_blocks<strata::dequantize_q8_0, 34>},
216    // Q4_0 (plain llama-quantize Q4_0 files, #599): 90-byte rows like IQ4_NL (18-byte blocks), a linear 4-bit grid
217    {PleFormat::Q4_0, "Q4_0", "Q4_0", PLE_ROW_BYTES, false, dequant_blocks<strata::dequantize_q4_0, 18>},
218    // BF16 (#586): the checkpoint's own table at full precision, 320-byte rows; self-describing, so no scale and no
219    // metadata to trust (tools/ple_fp8_pack.py writes the FP8 form of the same table)
220    {PleFormat::BF16, "BF16", "BF16", PLE_ROW_BYTES_BF16, false, dequant_bf16},
221    // NVFP4 x16 (NVIDIA's Qwen3.8-Flash-Next-FP4-Local, tools/nvfp4_local_pack.py ple): 90-byte rows, I8 bytes marked
222    // strata.ple.format = nvfp4x16 with strata.ple.scale. The tensor is [90, rows]: ne0 is the row's byte count.
223    {PleFormat::NVFP4, "NVFP4", "I8", PLE_ROW_BYTES_NVFP4, true, dequant_nvfp4},
224};
225constexpr int kPleFormatCount = (int) (sizeof kPleFormats / sizeof kPleFormats[0]);
226}  // namespace
227
228const PleFormatInfo* ple_formats() { return kPleFormats; }
229int ple_format_count() { return kPleFormatCount; }
230const PleFormatInfo& ple_format_info(PleFormat f) { return kPleFormats[(int) f]; }
231const PleFormatInfo* ple_format_for_type(const char* gguf_type_name) {
232    for (const PleFormatInfo& f : kPleFormats)
233        if (std::strcmp(f.gguf_type, gguf_type_name) == 0) return &f;
234    return nullptr;
235}
236std::string ple_format_list() {
237    std::string out;
238    for (int i = 0; i < kPleFormatCount; ++i) {
239        const PleFormatInfo& f = kPleFormats[i];
240        if (i > 0) out += i + 1 == kPleFormatCount ? " or " : ", ";
241        out += std::strcmp(f.gguf_type, "I8") == 0 ? (f.id == PleFormat::NVFP4 ? "NVFP4 (I8)" : "FP8 (I8)") : f.name;
242    }
243    return out;
244}
245
246static_assert(PLE_ROW_BYTES_MAX >= PLE_ROW_BYTES && PLE_ROW_BYTES_MAX >= PLE_ROW_BYTES_FP8, "row buffers too small");
247
248struct PleTable::Impl {
249    GgufFile* file = nullptr;
250    const uint8_t* data = nullptr;
251    uint64_t n_rows = 0;
252    const PleFormatInfo* fmt = &ple_format_info(PleFormat::IQ4_NL);   // the table's format (#296: Q5_0 is one of them)
253    mutable uint64_t bytes_read = 0;
254    // Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes
255    // from an unbuffered SSD read into `raw`.
256    PleIo mode = PleIo::Mmap;
257    strata::ngram::PleReader reader;
258    strata::ngram::PleReader::Ticket ticket;
259    bool pending = false;
260    bool locked = false;
261    // the table is shared by the prompt path and the decode windows; they can use it at once (one on a worker thread)
262    std::recursive_mutex mu;
263    uint32_t rows[PLE_N_HEADS] = {};
264    uint8_t raw[PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {};
265    static constexpr size_t kMaxPrefetch = 16;
266    size_t n_prefetch = 0;
267    strata::ngram::PleReader::Ticket prefetch_tickets[kMaxPrefetch] = {};
268    uint32_t prefetch_keys[kMaxPrefetch][PLE_N_HEADS] = {};
269    uint8_t prefetch_raw[kMaxPrefetch][PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {};
270    float scale = 1.0f;               // the FP8 table's one scale
271    uint32_t rb = PLE_ROW_BYTES;      // bytes per row
272    void decode(const uint8_t* row, float* out160) const { fmt->dequant(row, scale, out160); }
273    // STRATA_PLE_CHECK=1 (a diagnostic for #3602, off by default): the file and the table's offset, to re-read a row whose decoded
274    // values are not plausible and compare the bytes the direct reader delivered with the file's own
275    std::string path;
276    uint64_t table_offset = 0;
277    mutable int check_reports = 0;
278    static bool check_on() {
279        static const bool on = [] { const char* v = std::getenv("STRATA_PLE_CHECK"); return v != nullptr && std::atoi(v) != 0; }();
280        return on;
281    }
282    /// One decoded row (`out160`, from `raw`): when a value is not finite or beyond 1e5 (a real PLE value is orders smaller; the
283    /// largest an IQ4_NL row can decode to is 8.3e6), say which row, where, and whether the delivered bytes are the file's.
284    void check_row(const char* where, uint32_t row, const uint8_t* raw, const float* out160) const {
285        if (check_reports >= 8 || row >= n_rows) return;
286        int bad = -1;
287        for (int j = 0; j < PLE_HEAD_DIM; ++j)
288            if (!std::isfinite(out160[j]) || std::fabs(out160[j]) > 1e5f) { bad = j; break; }
289        if (bad < 0) return;
290        ++check_reports;
291        const uint64_t at = table_offset + (uint64_t) row * rb;
292        std::vector<uint8_t> file(rb, 0);
293        bool read = false;
294        {
295            std::ifstream f(path, std::ios::binary);
296            if (f) {
297                f.seekg((std::streamoff) at);
298                f.read((char*) file.data(), (std::streamsize) rb);
299                read = (uint32_t) f.gcount() == rb;
300            }
301        }
302        std::fprintf(stderr, "strata ple check: %s: row %u (file offset %llu, page offset %llu): value %d of 160 decodes to %g", where,
303                     row, (unsigned long long) at, (unsigned long long) (at % 4096), bad, (double) out160[bad]);
304        if (!read) {
305            std::fprintf(stderr, "; the file could not be re-read\n");
306            return;
307        }
308        uint32_t first = rb;
309        for (uint32_t b = 0; b < rb; ++b)
310            if (raw[b] != file[b]) { first = b; break; }
311        if (first == rb) {
312            std::fprintf(stderr, "; the delivered bytes ARE the file's bytes (the table itself holds this value)\n");
313        } else {
314            std::fprintf(stderr, "; THE DELIVERED BYTES DIFFER FROM THE FILE from byte %u (delivered 0x%02x, file 0x%02x); first 8 delivered:", first,
315                         raw[first], file[first]);
316            for (int b = 0; b < 8 && (uint32_t) b < rb; ++b) std::fprintf(stderr, " %02x", raw[b]);
317            std::fprintf(stderr, "; first 8 of the file:");
318            for (int b = 0; b < 8 && (uint32_t) b < rb; ++b) std::fprintf(stderr, " %02x", file[b]);
319            std::fprintf(stderr, "\n");
320        }
321    }
322};
323
324PleTable::PleTable() : impl_(new Impl) {}
325PleTable::~PleTable() { close(); delete impl_; }
326
327bool PleTable::open(const std::string& gguf_path, std::string& err) {
328    return open(gguf_path, err, PleIoOptions{});
329}
330
331bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoOptions& io) {
332    close();
333    try {
334        impl_->file = new GgufFile(gguf_path);
335    } catch (const std::exception& e) {
336        err = e.what();
337        return false;
338    }
339    const TensorInfo* t = impl_->file->find("per_layer_token_embd.weight");
340    if (t == nullptr) {
341        err = "per_layer_token_embd.weight is not in " + gguf_path;
342        close();
343        return false;
344    }
345    // [160, 320001536]: ne0 = 160 is the FAST axis, so the ROW index is shape[1] and a row is contiguous. The NVFP4 table
346    // is I8 bytes with ne0 = 90 (the row's byte count), marked strata.ple.format = nvfp4x16.
347    const MetaValue* fmt_key = impl_->file->get("strata.ple.format");
348    const bool nvfp4x16 = std::strcmp(t->type_name(), "I8") == 0 && fmt_key != nullptr && fmt_key->s == "nvfp4x16";
349    const uint64_t want_ne0 = nvfp4x16 ? (uint64_t) PLE_ROW_BYTES_NVFP4 : (uint64_t) PLE_HEAD_DIM;
350    if (t->shape.size() != 2 || t->shape[0] != want_ne0) {
351        err = "per_layer_token_embd.weight has an unexpected shape";
352        close();
353        return false;
354    }
355    // The table's type is looked up in the format list (ple_formats()): IQ4_NL (ISTA-DASLab's shard 2, the original's
356    // own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as shipped: I8 bytes marked strata.ple.format =
357    // f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py)
358    const PleFormatInfo* fmt = nvfp4x16 ? &ple_format_info(PleFormat::NVFP4) : ple_format_for_type(t->type_name());
359    if (fmt == nullptr) {
360        err = std::string("per_layer_token_embd.weight is ") + t->type_name() + ", not " + ple_format_list();
361        close();
362        return false;
363    }
364    if (fmt->needs_scale) {
365        const MetaValue* f = impl_->file->get("strata.ple.format");
366        const MetaValue* s = impl_->file->get("strata.ple.scale");
367        const char* want = nvfp4x16 ? "nvfp4x16" : "f8_e4m3";
368        if (f == nullptr || f->s != want || s == nullptr || !(s->num() > 0.0)) {
369            err = std::string("per_layer_token_embd.weight is I8 without strata.ple.format = ") + want + " and a positive strata.ple.scale";
370            close();
371            return false;
372        }
373        impl_->scale = (float) s->num();
374    }
375    impl_->fmt = fmt;
376    impl_->rb = fmt->row_bytes;
377    // PleReader's row_bytes has been a runtime parameter since the FP8 table (160 B rows) needed it; Q5_0's
378    // 110 B rows go through the exact same generic path (ple_reader_test --selftest covers both 90 and 110 B
379    // rows: straddling, caching, in-flight tickets, keep-alive). This refusal was stale.
380    impl_->n_rows = t->shape[1];
381
382    // THE CHECK THAT MAKES THE OFFSET FALSIFIABLE.  The manifest's `shard2_tensor.offset` is 0, but that is
383    // the offset within the GGUF's DATA SECTION: the file's first 192 bytes are a header, and reading at 0
384    // would decode the header plus 192 bytes of shifted rows - still plausible IQ4_NL, and wrong for every
385    // row.  `GgufFile` parses the header, so `tensor_data` is already correct; this asserts the tensor
386    // exactly fills the file from there, which is what makes the whole arrangement checkable rather than
387    // assumed.  A wrong data offset would leave a different remainder.
388    // A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must
389    // then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly.
390    // The size arithmetic is checked before it is used (#865): a header that claims enough rows to wrap the 64-bit
391    // product, or a data section that starts past the end of the file, must be refused, not compared after wrapping.
392    if (impl_->n_rows > std::numeric_limits<uint64_t>::max() / impl_->rb ||
393        impl_->file->data_start() > impl_->file->file_size()) {
394        err = "PLE table size overflow or invalid data offset in " + gguf_path;
395        close();
396        return false;
397    }
398    const uint64_t need = impl_->n_rows * (uint64_t) impl_->rb;
399    const uint64_t have = impl_->file->file_size() - impl_->file->data_start();
400    const bool alone = impl_->file->tensors().size() == 1;
401    if (t->offset > have || need > have - t->offset || (alone && (t->offset != 0 || need != have))) {
402        char buf[256];
403        std::snprintf(buf, sizeof buf,
404                      "PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from "
405                      "data_start %llu",
406                      (unsigned long long) impl_->n_rows, (int) impl_->rb, (unsigned long long) need,
407                      (unsigned long long) t->offset, (unsigned long long) have,
408                      (unsigned long long) impl_->file->data_start());
409        err = buf;
410        if (alone && have > need)   // #657: extra bytes after the table: a damaged or wrong file, not a format question
411            err += "; the file is longer than its table - delete it and its .done mark and run setup again";
412        close();
413        return false;
414    }
415    impl_->data = impl_->file->tensor_data(*t);        // only a table that fits the file is mapped
416    if (io.mode == PleIo::Direct) {
417        // The parse above is the validated source of the offset; the mapping itself is not kept, so no page of
418        // the table can enter this process's working set or the file cache through it.
419        const uint64_t table_offset = impl_->file->data_start() + t->offset;
420        const uint64_t n_rows = impl_->n_rows;
421        impl_->path = gguf_path;
422        impl_->table_offset = table_offset;
423        delete impl_->file;
424        impl_->file = nullptr;
425        impl_->data = nullptr;
426        if (!impl_->reader.open(gguf_path, table_offset, n_rows, io.max_inflight, io.cache_rows, err, io.io_thread,
427                                impl_->rb)) {
428            close();
429            return false;
430        }
431        impl_->reader.set_keepalive(io.keepalive_ms, io.keepalive_window_s);
432        impl_->n_rows = n_rows;
433    }
434    if (io.mode == PleIo::Mmap && io.lock && impl_->data != nullptr) {
435#if defined(_WIN32)
436        // Windows has no mlock: the platform helper raises the process's minimum working set and
437        // VirtualLocks the mapped table instead (ordinary accounts hold the privilege). A failure
438        // falls back to touching the pages, i.e. plain mmap behaviour, with a warning - same as POSIX.
439        // A table that is more than half of the RAM leaves the rest of the process little (the locked pages cannot be
440        // paged out): say so, and go on (recommend, never force).
441        MEMORYSTATUSEX ms;
442        ms.dwLength = sizeof(ms);
443        if (GlobalMemoryStatusEx(&ms) && need > ms.ullTotalPhys / 2)
444            std::fprintf(stderr, "strata: warning: --ple-io ram locks %.1f GiB, more than half of this PC's %.1f GiB of RAM\n",
445                         (double) need / (1ull << 30), (double) ms.ullTotalPhys / (1ull << 30));
446        const strata::platform::LockResult lr =
447            strata::platform::lock_resident((void*) impl_->data, need);
448        if (lr.ok && lr.locked_bytes >= need) {
449            impl_->locked = true;
450        } else {
451            // a partial lock is not a lock: the unlocked rest would fault on the token path, so give it back
452            if (lr.locked_bytes > 0) strata::platform::unlock_resident((void*) impl_->data, lr.locked_bytes);
453            std::fprintf(stderr, "strata: PLE table lock failed (%s): touching its pages instead\n",
454                         lr.note.c_str());
455            volatile uint8_t sink = 0;
456            for (uint64_t off = 0; off < need; off += 4096) sink = sink + impl_->data[off];
457            (void) sink;
458        }
459#else
460        const uint64_t page = 4096;
461        const uintptr_t a0 = (uintptr_t) impl_->data & ~(uintptr_t) (page - 1);
462        const uintptr_t a1 = (uintptr_t) impl_->data + (uintptr_t) need;
463        madvise((void*) a0, a1 - a0, MADV_WILLNEED);
464        // Fault the table in with several threads first: mlock (and a single toucher) brings it in one page at a time
465        // 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
466        // and mlock only pins them.
467        {
468            constexpr uintptr_t kPiece = 64ull << 20;
469            const uintptr_t pieces = (a1 - a0 + kPiece - 1) / kPiece;
470            const unsigned threads = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
471            std::atomic<uintptr_t> next{0};
472            auto touch = [&] {
473                volatile uint8_t sink = 0;
474                for (uintptr_t i; (i = next.fetch_add(1)) < pieces;)
475                    for (uintptr_t p = a0 + i * kPiece, e = std::min(a1, p + kPiece); p < e; p += page)
476                        sink = sink + *(const volatile uint8_t*) p;
477                (void) sink;
478            };
479            std::vector<std::thread> pool;
480            for (unsigned t = 0; t < threads; ++t) pool.emplace_back(touch);
481            for (auto& t : pool) t.join();
482        }
483        // #4671: a systemd service without LimitMEMLOCK may lock 8 MiB (soft and hard), a login shell far more.  Raise the soft limit
484        // to what the hard limit allows first (no privilege needed); if the table still does not fit, say what to set.
485        struct rlimit rl {};
486        if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0 && rl.rlim_cur != RLIM_INFINITY && (uint64_t) rl.rlim_cur < a1 - a0 &&
487            rl.rlim_max > rl.rlim_cur) {
488            const rlim_t room = (rlim_t) (a1 - a0) + ((rlim_t) 1 << 30);
489            const rlim_t want = rl.rlim_max == RLIM_INFINITY ? room : std::min<rlim_t>(rl.rlim_max, room);
490            struct rlimit up = rl;
491            up.rlim_cur = want;
492            if (setrlimit(RLIMIT_MEMLOCK, &up) == 0)
493                std::fprintf(stderr, "strata: the memory this program may lock was %llu MiB; raised to %llu MiB for the PLE table\n",
494                             (unsigned long long) (rl.rlim_cur >> 20), (unsigned long long) (want >> 20));
495        }
496        if (mlock((const void*) a0, a1 - a0) == 0) {
497            impl_->locked = true;
498        } else {
499            const int why = errno;
500            struct rlimit now {};
501            if (getrlimit(RLIMIT_MEMLOCK, &now) == 0 && now.rlim_cur != RLIM_INFINITY && (uint64_t) now.rlim_cur < a1 - a0)
502                std::fprintf(stderr, "strata: the PLE table (%.1f GiB) was not locked in RAM: this program may lock only %.1f GiB "
503                                     "(RLIMIT_MEMLOCK). It still works, with the table's pages faulted in but reclaimable; the lock was measured "
504                                     "up to 6%% faster in decode (#4671). In a systemd service set LimitMEMLOCK=infinity, elsewhere run `ulimit -l unlimited`\n",
505                             (double) (a1 - a0) / (1ull << 30), (double) now.rlim_cur / (1ull << 30));
506            else
507                std::fprintf(stderr, "strata: PLE table mlock failed (%s; raise `ulimit -l`): its pages stay faulted in "
508                                     "but may be reclaimed\n", std::strerror(why));
509        }
510#endif
511    }
512    impl_->mode = io.mode;
513    return true;
514}
515
516void PleTable::wait_prefetches() {
517    std::lock_guard<std::recursive_mutex> lk(impl_->mu);
518    if (impl_->n_prefetch == 0) return;
519    std::string dummy;
520    for (size_t i = 0; i < impl_->n_prefetch; ++i) (void) impl_->reader.collect(impl_->prefetch_tickets[i], dummy);
521    impl_->n_prefetch = 0;
522}
523
524void PleTable::prefetch_rows(const uint32_t* rows16) {
525    std::lock_guard<std::recursive_mutex> lk(impl_->mu);
526    if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) {
527        for (size_t i = 0; i < impl_->n_prefetch; ++i)
528            if (std::memcmp(impl_->prefetch_keys[i], rows16, sizeof(uint32_t) * PLE_N_HEADS) == 0) return;
529        if (impl_->n_prefetch >= Impl::kMaxPrefetch) wait_prefetches();
530        const size_t slot = impl_->n_prefetch++;
531        std::memcpy(impl_->prefetch_keys[slot], rows16, sizeof(uint32_t) * PLE_N_HEADS);
532        impl_->prefetch_tickets[slot] = impl_->reader.issue(impl_->prefetch_keys[slot], PLE_N_HEADS, impl_->prefetch_raw[slot]);
533        return;
534    }
535#if defined(_WIN32)
536    if (impl_->data != nullptr && g_ple_prefetch) {
537        WIN32_MEMORY_RANGE_ENTRY ranges[PLE_N_HEADS];
538        ULONG_PTR n = 0;
539        for (int h = 0; h < PLE_N_HEADS; ++h) {
540            if (rows16[h] >= impl_->n_rows) continue;
541            ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb);
542            ranges[n].NumberOfBytes = impl_->rb;
543            ++n;
544        }
545        if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0);
546    }
547#endif
548}
549
550void PleTable::close() {
551    wait_prefetches();
552    impl_->reader.close();
553    impl_->pending = false;
554    impl_->locked = false;   // the unmap below releases the lock
555    impl_->mode = PleIo::Mmap;
556    delete impl_->file;
557    impl_->file = nullptr;
558    impl_->data = nullptr;
559    impl_->n_rows = 0;
560    impl_->rb = PLE_ROW_BYTES;
561    impl_->fmt = &ple_format_info(PleFormat::IQ4_NL);
562    impl_->scale = 1.0f;
563    impl_->bytes_read = 0;
564}
565
566bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); }
567bool PleTable::locked() const { return impl_->locked; }
568bool PleTable::unlock() {
569    std::lock_guard<std::recursive_mutex> lk(impl_->mu);
570    if (!impl_->locked || impl_->data == nullptr) return false;
571    strata::platform::unlock_resident((void*) impl_->data, impl_->n_rows * (uint64_t) impl_->rb);
572    impl_->locked = false;
573    return true;
574}
575const char* PleTable::format() const { return impl_->fmt->name; }
576PleIo PleTable::mode() const { return impl_->mode; }
577uint64_t PleTable::rows() const { return impl_->n_rows; }
578uint64_t PleTable::table_bytes() const { return impl_->n_rows * (uint64_t) impl_->rb; }
579uint64_t PleTable::bytes_read() const { return impl_->bytes_read; }
580
581void PleTable::read_row(uint32_t row, float* out160) const {
582    std::lock_guard<std::recursive_mutex> lk(impl_->mu);
583    if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) {
584        uint8_t raw[PLE_ROW_BYTES_MAX];
585        std::string err;
586        const auto t = impl_->reader.issue(&row, 1, raw);
587        if (!impl_->reader.collect(t, err)) {
588            std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float));
589            return;
590        }
591        impl_->decode(raw, out160);
592        if (Impl::check_on()) impl_->check_row("read_row", row, raw, out160);
593        impl_->bytes_read += impl_->rb;
594        return;
595    }
596    if (impl_->data == nullptr || row >= impl_->n_rows) {
597        std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float));
598        return;
599    }
600    impl_->decode(impl_->data + (size_t) row * impl_->rb, out160);
601    impl_->bytes_read += impl_->rb;
602}
603
604bool PleTable::issue(const uint32_t* rows16) {
605    std::lock_guard<std::recursive_mutex> lk(impl_->mu);
606    wait_prefetches();
607    std::memcpy(impl_->rows, rows16, sizeof impl_->rows);
608    if (impl_->mode == PleIo::Direct) {
609        if (impl_->pending) return false;              // one token in flight per table
610        impl_->ticket = impl_->reader.issue(impl_->rows, PLE_N_HEADS, impl_->raw);
611        impl_->pending = true;
612        return true;
613    }
614#if defined(_WIN32)
615    if (impl_->data != nullptr && g_ple_prefetch) {
616        WIN32_MEMORY_RANGE_ENTRY ranges[PLE_N_HEADS];
617        ULONG_PTR n = 0;
618        for (int h = 0; h < PLE_N_HEADS; ++h) {
619            if (rows16[h] >= impl_->n_rows) continue;
620            ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb);
621            ranges[n].NumberOfBytes = impl_->rb;
622            ++n;
623        }
624        if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0);
625    }
626#endif
627    impl_->pending = true;
628    return true;
629}
630
631bool PleTable::collect(float* out2560, std::string& err) {
632    std::lock_guard<std::recursive_mutex> lk(impl_->mu);
633    if (!impl_->pending) { err = "PleTable::collect without issue"; return false; }
634    impl_->pending = false;
635    if (impl_->mode == PleIo::Direct) {
636        if (!impl_->reader.collect(impl_->ticket, err)) return false;
637        for (int h = 0; h < PLE_N_HEADS; ++h)
638            impl_->decode(impl_->raw + (size_t) h * impl_->rb, out2560 + (size_t) h * PLE_HEAD_DIM);
639        if (Impl::check_on())
640            for (int h = 0; h < PLE_N_HEADS; ++h)
641                impl_->check_row("collect", impl_->rows[h], impl_->raw + (size_t) h * impl_->rb, out2560 + (size_t) h * PLE_HEAD_DIM);
642        impl_->bytes_read += (uint64_t) PLE_N_HEADS * impl_->rb;
643        return true;
644    }
645    for (int h = 0; h < PLE_N_HEADS; ++h) read_row(impl_->rows[h], out2560 + (size_t) h * PLE_HEAD_DIM);
646    return true;
647}
648
649bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, std::string& err) {
650    std::lock_guard<std::recursive_mutex> lk(impl_->mu);
651    if (impl_->pending) { err = "PleTable::gather_batch while a token is in flight"; return false; }
652    const size_t n = n_tokens * (size_t) PLE_N_HEADS;
653    if (impl_->mode == PleIo::Direct) {
654        // Fast path: match each requested token to any in-flight/completed prefetch slot, then collect directly
655        // without issuing a second PleReader ticket or copying through RowCache.
656        if (n_tokens <= Impl::kMaxPrefetch) {
657            size_t matched[Impl::kMaxPrefetch];
658            bool exact_match = true;
659            for (size_t t = 0; t < n_tokens; ++t) {
660                size_t i = 0;
661                while (i < impl_->n_prefetch &&
662                       std::memcmp(impl_->prefetch_keys[i], rows + t * PLE_N_HEADS,
663                                   sizeof(uint32_t) * PLE_N_HEADS) != 0) ++i;
664                if (i == impl_->n_prefetch) { exact_match = false; break; }
665                matched[t] = i;   // duplicate requests may share one immutable prefetch slot
666            }
667            if (exact_match) {
668                bool collect_ok = true;
669                for (size_t i = 0; i < impl_->n_prefetch; ++i) {
670                    std::string ignored;
671                    if (!impl_->reader.collect(impl_->prefetch_tickets[i], collect_ok ? err : ignored))
672                        collect_ok = false;   // retain the first error, but drain every output buffer
673                }
674                impl_->n_prefetch = 0;
675                if (!collect_ok) return false;
676                for (size_t t = 0; t < n_tokens; ++t) {
677                    for (int h = 0; h < PLE_N_HEADS; ++h) {
678                        impl_->decode(impl_->prefetch_raw[matched[t]] + (size_t) h * impl_->rb,
679                                      out + (t * PLE_N_HEADS + (size_t) h) * PLE_HEAD_DIM);
680                        if (Impl::check_on())
681                            impl_->check_row("gather_batch (prefetched)", rows[t * PLE_N_HEADS + (size_t) h],
682                                             impl_->prefetch_raw[matched[t]] + (size_t) h * impl_->rb,
683                                             out + (t * PLE_N_HEADS + (size_t) h) * PLE_HEAD_DIM);
684                    }
685                }
686                impl_->bytes_read += (uint64_t) n * impl_->rb;
687                return true;
688            }
689        }
690        wait_prefetches();
691        std::vector<uint8_t> raw(n * impl_->rb);
692        const auto ticket = impl_->reader.issue(rows, n, raw.data());
693        if (!impl_->reader.collect(ticket, err)) return false;
694        for (size_t i = 0; i < n; ++i) {
695            impl_->decode(raw.data() + i * impl_->rb, out + i * PLE_HEAD_DIM);
696            if (Impl::check_on()) impl_->check_row("gather_batch", rows[i], raw.data() + i * impl_->rb, out + i * PLE_HEAD_DIM);
697        }
698        impl_->bytes_read += (uint64_t) n * impl_->rb;
699        return true;
700    }
701    wait_prefetches();
702    // #1984 #1971: a mapped table that is not in the file cache served this loop as serial demand faults, one random
703    // 4 KiB page at a time (16 rows a token, 16 x the chunk's tokens for a prompt), and the first chunk of a prompt has
704    // only layer 0 to hide it behind: a cold 27 GB table at ~0.2-1 ms a fault is minutes with no progress mark, which
705    // is what the stall watchdog stops.  Ask the OS for the next window's pages in one go (PrefetchVirtualMemory /
706    // MADV_WILLNEED, a hint that cannot change a value: an unfetched page is faulted by the read) while this window is read.
707    constexpr size_t kWin = 4096;   // rows a window
708    auto hint = [&](size_t a, size_t b) {
709        if (impl_->data == nullptr || !g_ple_prefetch) return;
710#if defined(_WIN32)
711        WIN32_MEMORY_RANGE_ENTRY ranges[kWin];
712        ULONG_PTR k = 0;
713        for (size_t i = a; i < b; ++i) {
714            if (rows[i] >= impl_->n_rows) continue;
715            ranges[k].VirtualAddress = (PVOID) (impl_->data + (size_t) rows[i] * impl_->rb);
716            ranges[k].NumberOfBytes = impl_->rb;
717            ++k;
718        }
719        if (k > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), k, ranges, 0);
720#else
721        for (size_t i = a; i < b; ++i) {
722            if (rows[i] >= impl_->n_rows) continue;
723            const uintptr_t r0 = (uintptr_t) (impl_->data + (size_t) rows[i] * impl_->rb);
724            const uintptr_t p0 = r0 & ~(uintptr_t) 4095;
725            (void) madvise((void*) p0, (size_t) (r0 + impl_->rb - p0), MADV_WILLNEED);
726        }
727#endif
728    };
729    hint(0, std::min(n, kWin));
730    for (size_t w = 0; w < n; w += kWin) {
731        if (w + kWin < n) hint(w + kWin, std::min(n, w + 2 * kWin));
732        const size_t e = std::min(n, w + kWin);
733        for (size_t i = w; i < e; ++i) read_row(rows[i], out + i * PLE_HEAD_DIM);
734    }
735    return true;
736}
737
738bool PleTable::gather_raw_iq4nl(const uint32_t* rows, size_t n_tokens, uint8_t* out) const {
739    std::lock_guard<std::recursive_mutex> lk(impl_->mu);
740    if (impl_->data == nullptr || impl_->fmt->id != PleFormat::IQ4_NL || impl_->rb != PLE_ROW_BYTES) return false;
741    const size_t n = n_tokens * (size_t) PLE_N_HEADS;
742    for (size_t i = 0; i < n; ++i) {
743        uint8_t* o = out + i * PLE_ROW_BYTES;
744        if (rows[i] >= impl_->n_rows) {
745            // a row past the table reads as +0.0f (read_row): scale 0 and code 8 (value +1) in every nibble decode to +0.0f
746            // on the device, where all-zero bytes would decode to -0.0f (scale 0 times code 0's value -127)
747            for (int b = 0; b < PLE_HEAD_DIM / 32; ++b) {
748                uint8_t* blk = o + (size_t) b * 18;
749                std::memset(blk, 0, 2);
750                std::memset(blk + 2, 0x88, 16);
751            }
752        } else std::memcpy(o, impl_->data + (size_t) rows[i] * PLE_ROW_BYTES, PLE_ROW_BYTES);
753    }
754    impl_->bytes_read += (uint64_t) n * PLE_ROW_BYTES;
755    return true;
756}
757
758void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); }
759
760std::string PleTable::io_report() const {
761    if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {};
762    const strata::ngram::ReaderStats s = impl_->reader.snapshot();
763    char buf[400];
764    int n = std::snprintf(buf, sizeof buf,
765                  "ple io: %llu rows, %.1f%% row-cache hits, %llu SSD reads (%.1f MB), read p50 %.0f us p99 %.0f us, "
766                  "blocked %.3f ms total (submit %.3f ms), cache %llu/%llu rows",
767                  (unsigned long long) s.requests, s.requests ? 100.0 * (double) s.cache_hits / (double) s.requests : 0.0,
768                  (unsigned long long) s.reads, (double) s.bytes / 1e6, s.percentile(0.5), s.percentile(0.99),
769                  s.wait_us / 1000.0, s.submit_us / 1000.0, (unsigned long long) impl_->reader.cache_size(),
770                  (unsigned long long) impl_->reader.cache_capacity());
771    if (s.keepalive_reads > 0 && n > 0 && n < (int) sizeof buf)
772        std::snprintf(buf + n, sizeof buf - (size_t) n, ", SSD kept awake by %llu reads (slowest %.1f ms)",
773                      (unsigned long long) s.keepalive_reads, s.keepalive_us_max / 1000.0);
774    return buf;
775}
776
777void PleTable::gather(const uint32_t* rows16, float* out2560) const {
778    std::lock_guard<std::recursive_mutex> lk(impl_->mu);   // issue + collect as one
779    if (impl_->mode == PleIo::Direct) {
780        // `gather` stays const for its existing callers; the reader's state is the table's I/O state.
781        PleTable* self = const_cast<PleTable*>(this);
782        std::string err;
783        if (!self->issue(rows16) || !self->collect(out2560, err)) {
784            std::fprintf(stderr, "PleTable::gather: %s\n", err.empty() ? "a token is already in flight" : err.c_str());
785            std::memset(out2560, 0, (size_t) NG_N_EMBD * sizeof(float));
786        }
787        return;
788    }
789    // ================================ SIXTEEN SERIAL PAGE FAULTS, MEASURED ================================
790    //
791    // **THIS COST 2.10-2.61 ms PER TOKEN AND HAD NEVER BEEN IN THE PLAN'S BUDGET AT ALL.**  The round-309
792    // `token host phases` line put it second behind the layer loop among avoidable terms, and the arithmetic
793    // says why: the table is 320,001,536 rows of `PLE_ROW_BYTES` = 90 B in a 26.8 GB mapping, so the sixteen
794    // rows a token needs are 1,440 B - **0.5 MB/s**.  That is not bandwidth, it is latency: sixteen reads into
795    // sixteen different 4 KB pages scattered across 26.8 GB, taken ONE AT A TIME, and on this machine the PLE
796    // shard is 26.8 GB against 63 GB of RAM that the 31.6 GB expert arena is also competing for, so they are
797    // not in the OS cache.  Sixteen serial NVMe reads at ~150 us is 2.4 ms, which is the measurement.
798    //
799    // `PrefetchVirtualMemory` issues all sixteen in ONE call and lets them complete in parallel.  It is a hint
800    // and cannot change the answer - a range it does not fetch is simply faulted in by the read that follows -
801    // so the only risk is that it does nothing.
802#if defined(_WIN32)
803    if (impl_->data != nullptr && g_ple_prefetch) {
804        WIN32_MEMORY_RANGE_ENTRY ranges[PLE_N_HEADS];
805        ULONG_PTR n = 0;
806        for (int h = 0; h < PLE_N_HEADS; ++h) {
807            // Out-of-range rows are handled by `read_row` as zeros and have no address to prefetch.
808            if (rows16[h] >= impl_->n_rows) continue;
809            ranges[n].VirtualAddress = (PVOID) (impl_->data + (size_t) rows16[h] * impl_->rb);
810            ranges[n].NumberOfBytes = impl_->rb;
811            ++n;
812        }
813        if (n > 0) (void) PrefetchVirtualMemory(GetCurrentProcess(), n, ranges, 0);
814    }
815#endif
816    // HEAD-SLOWEST, which is what `ggml_get_rows` does and what the source's own comment says: head h's 160
817    // values occupy [h*160, (h+1)*160).  A head-fastest layout would put element (d, h) at d*16 + h and needs
818    // a real transpose - a reshape of the same flat buffer compares equal and would make the check vacuous.
819    for (int h = 0; h < PLE_N_HEADS; ++h) read_row(rows16[h], out2560 + (size_t) h * PLE_HEAD_DIM);
820}
821
822}  // namespace strata::kernels