okami.mom/strata

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

waveringanaread short prompts through every layer on the last GPU with the first stage's weights streamed and its state handed back (STRATA_PREFILL_SHORT_MAX/_MIN; STRATA_PREFILL_LM_NEXTFILES on the last stage)f8c748fdf

main
28.0 KiB607 linesraw
1// src/core/weights.cpp - the dense-weight loader.  See the header for the engine-vs-pack distinction.
2#include "strata/core/weights.hpp"
3#include <vector>
4#include <cmath>
5
6#include "strata/kernels/f16_bits.hpp"
7#include "strata/platform/memory.hpp"
8
9#include <cinttypes>
10#include <cuda_runtime.h>
11
12#include <chrono>
13#include <algorithm>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17
18#if defined(_WIN32)
19#include <io.h>
20#else
21#include <unistd.h>
22#endif
23
24namespace strata::core {
25namespace {
26
27constexpr uint64_t CHUNK = 8ull << 20;   // 8 MiB of SOURCE per staging round
28
29double now_ms() {
30    using namespace std::chrono;
31    return duration<double, std::milli>(steady_clock::now().time_since_epoch()).count();
32}
33
34struct IndexRow {
35    std::string name;
36    int file = 0;
37    WeightKind kind = WeightKind::Verbatim;
38    uint64_t src_off = 0, src_bytes = 0, dst_off = 0, dst_bytes = 0;
39    int64_t ne0 = 0, ne1 = 0;
40    int code_bits = 0, code_bias = 0, group_elems = 0, codebook = 0, has_offset = 0;
41    uint64_t codes_bytes = 0, scales_bytes = 0, offset_bytes = 0;
42    int scales_fp16 = 0;
43    int act_kind = 0;
44    bool raw16 = false;   ///< plan v0.3 P6: already 16-bit in the file (kinds 4/5)
45};
46
47/// How a segment's bytes must be transformed on the way from the pack to the arena.
48enum class Conv : int {
49    Copy = 0,      ///< the bytes are already the engine form
50    Bf16High = 1,  ///< f32 container holding a bf16 value: take the high 16 bits
51    ToF16 = 2,     ///< f32 container holding an f16 value: a real round-to-nearest-even conversion
52    WidenF16 = 3,  ///< fp16 bits to be held as f32: EXACT, and the reason this path exists at all
53};
54
55/// One contiguous run of a tensor's source span with a single destination range and one transform.
56///
57/// THE SEGMENT LIST IS WHY THIS LOADER CAN CHANGE WIDTHS PLANE BY PLANE.  A quantized tensor used to be one
58/// verbatim span, which is only correct when every plane is already in engine form - and for 90 of the 303
59/// quantized tensors the scale plane is fp16 in the pack and must be f32 in the arena.
60struct Seg {
61    uint64_t src_off = 0;   ///< relative to the row's src_off
62    uint64_t src_bytes = 0;
63    uint64_t dst_off = 0;   ///< relative to the row's dst_off
64    uint64_t dst_bytes = 0;
65    Conv conv = Conv::Copy;
66};
67
68const char* file_name(int id) {
69    switch (id) {
70        case 0: return "dense.bin";
71        case 1: return "embd.bin";
72        case 2: return "experts.bin";
73        case 3: return "extra.bin";   // plan v0.3 P6: a native pack's float tensors that the base pack quantized
74        default: return nullptr;
75    }
76}
77
78/// UTF-16 path for CreateFile-free portability: the loader uses `std::fopen`, which on Windows takes an ANSI
79/// path.  The pack lives beside the executable in practice, but a pack under a user directory with a
80/// non-ASCII name would silently fail to open, so the caller gets the errno rather than a null pointer.
81bool read_at(std::FILE* f, uint64_t off, void* dst, size_t n, std::string& err, const char* what) {
82#if defined(_WIN32)
83    if (_fseeki64(f, (long long) off, SEEK_SET) != 0) { err = std::string(what) + ": seek failed"; return false; }
84#else
85    if (fseeko(f, (off_t) off, SEEK_SET) != 0) { err = std::string(what) + ": seek failed"; return false; }
86#endif
87    if (std::fread(dst, 1, n, f) != n) { err = std::string(what) + ": short read"; return false; }
88    return true;
89}
90
91}  // namespace
92
93bool WeightTable::pool_bytes(const std::string& pack_dir, uint64_t& out, std::string& err,
94                             const std::set<std::string>* skip) {
95    const std::string path = pack_dir + "/index.txt";
96    std::FILE* f = std::fopen(path.c_str(), "rb");
97    if (!f) { err = "cannot open " + path; return false; }
98    char line[1024];
99    out = 0;
100    uint64_t pool = 0, compact = 0;
101    int align = 0;
102    while (std::fgets(line, sizeof line, f)) {
103        if (line[0] == '#') {
104            unsigned long long p = 0;
105            int a = 0, tensors = 0;
106            if (std::sscanf(line, "# align %d pool %llu tensors %d", &a, &p, &tensors) == 3) { pool = p; align = a; }
107            continue;
108        }
109        if (skip == nullptr) continue;
110        char name[256] = {0};
111        unsigned long long dst_bytes = 0, dummy = 0;
112        int i1 = 0, i2 = 0;
113        if (std::sscanf(line, "%255s %d %d %llu %llu %llu %llu", name, &i1, &i2, &dummy, &dummy, &dummy, &dst_bytes) != 7)
114            continue;
115        if (skip->count(name)) continue;
116        const uint64_t a = align > 0 ? (uint64_t) align : 256;
117        compact += (dst_bytes + a - 1) / a * a;
118    }
119    std::fclose(f);
120    if (pool == 0) { err = "no '# align ... pool ...' header in " + path; return false; }
121    out = skip ? compact : pool;
122    return true;
123}
124
125bool WeightTable::index_code_bits(const std::string& pack_dir, const std::string& name, int& code_bits,
126                                  std::string& err) {
127    const std::string path = pack_dir + "/index.txt";
128    std::FILE* f = std::fopen(path.c_str(), "rb");
129    if (!f) { err = "cannot open " + path; return false; }
130    char line[1024];
131    code_bits = -1;
132    while (std::fgets(line, sizeof line, f)) {
133        if (line[0] == '#') continue;
134        char row[256] = {0};
135        unsigned long long dummy = 0;
136        long long ne = 0;
137        int i1 = 0, i2 = 0, bits = 0;
138        // the first ten fields of the row `load` parses: name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits
139        if (std::sscanf(line, "%255s %d %d %llu %llu %llu %llu %lld %lld %d", row, &i1, &i2, &dummy, &dummy, &dummy,
140                        &dummy, &ne, &ne, &bits) != 10)
141            continue;
142        if (name == row) { code_bits = bits; break; }
143    }
144    std::fclose(f);
145    return true;
146}
147
148bool WeightTable::read_bf16_host(const std::string& name, std::vector<uint16_t>& out, std::string& err) const {
149    const auto it = table_.find(name);
150    if (it == table_.end()) { err = name + ": no such tensor"; return false; }
151    const WeightRef& r = it->second;
152    const char* fn = file_name(r.file_id);
153    if (fn == nullptr || r.kind != WeightKind::Bf16InF32) { err = name + ": not a bf16 row of a pack file"; return false; }
154    const uint64_t elems = (uint64_t) r.elements;
155    const bool raw16 = r.src_bytes == elems * 2;
156    if (!raw16 && r.src_bytes != elems * 4) { err = name + ": unexpected source size"; return false; }
157    std::FILE* f = std::fopen((pack_dir_ + "/" + fn).c_str(), "rb");
158    if (!f) { err = "cannot open " + pack_dir_ + "/" + fn; return false; }
159    out.resize((size_t) elems);
160    bool ok = true;
161    if (raw16) {
162        ok = read_at(f, r.src_off, out.data(), (size_t) (elems * 2), err, name.c_str());
163    } else {
164        std::vector<uint32_t> tmp((size_t) std::min<uint64_t>(elems, 1u << 22));
165        for (uint64_t done = 0; ok && done < elems;) {
166            const uint64_t n = std::min<uint64_t>(tmp.size(), elems - done);
167            ok = read_at(f, r.src_off + done * 4, tmp.data(), (size_t) (n * 4), err, name.c_str());
168            for (uint64_t i = 0; ok && i < n; ++i) out[(size_t) (done + i)] = (uint16_t) (tmp[(size_t) i] >> 16);
169            done += n;
170        }
171    }
172    std::fclose(f);
173    return ok;
174}
175
176bool WeightTable::load(const std::string& pack_dir, void* arena_base, uint64_t arena_bytes, std::string& err,
177                       const std::set<std::string>* skip) {
178    const std::string path = pack_dir + "/index.txt";
179    std::FILE* idx = std::fopen(path.c_str(), "rb");
180    if (!idx) { err = "cannot open " + path + " (run tools/pack_index.py)"; return false; }
181
182    uint64_t pool = 0;
183    int align = 0;
184    std::vector<IndexRow> rows;
185    char line[1024];
186    while (std::fgets(line, sizeof line, idx)) {
187        if (line[0] == '#') {
188            unsigned long long p = 0;
189            int a = 0, t = 0;
190            if (std::sscanf(line, "# align %d pool %llu tensors %d", &a, &p, &t) == 3) { pool = p; align = a; }
191            continue;
192        }
193        IndexRow r;
194        char name[256] = {0};
195        int kind = 0;
196        // The format is written by tools/pack_index.py and is space-separated with no quoting; a name with a
197        // space in it would break the parse, which is why the parser REFUSES rather than taking what it got.
198        const int n = std::sscanf(line,
199                                  "%255s %d %d %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNd64 " %" SCNd64 " %d %d %d %d %d %" SCNu64 " %" SCNu64 " %" SCNu64 " %d %d",
200                                  name, &r.file, &kind, &r.src_off, &r.src_bytes, &r.dst_off, &r.dst_bytes,
201                                  &r.ne0, &r.ne1, &r.code_bits, &r.code_bias, &r.group_elems, &r.codebook,
202                                  &r.has_offset, &r.codes_bytes, &r.scales_bytes, &r.offset_bytes,
203                                  &r.scales_fp16, &r.act_kind);
204        if (n != 19) {
205            // A malformed index line is a WRONG BYTE OFFSET waiting to happen, and a wrong offset decodes to
206            // a plausible weight.  Refuse loudly instead of loading the rows that happened to parse.
207            err = "index.txt: could not parse a row (" + std::to_string(n) + " of 19 fields)";
208            std::fclose(idx);
209            return false;
210        }
211        r.name = name;
212        // plan v0.3 P6: a standalone native pack (tools/iq_pack.py) stores 16-bit floats as they are in the GGUF:
213        // index kinds 4 (BF16) and 5 (F16) are copied and take the engine forms of kinds 1 and 3
214        if (kind == 4 || kind == 5) {
215            r.raw16 = true;
216            kind = kind == 4 ? (int) WeightKind::Bf16InF32 : (int) WeightKind::F16InF32;
217        }
218        r.kind = (WeightKind) kind;
219        rows.push_back(r);
220    }
221    std::fclose(idx);
222
223    if (pool == 0 || rows.empty()) { err = "index.txt has no header or no rows"; return false; }
224    // Plan v0.3 P1: a skip set compacts the arena.  Kept rows are re-placed in index order at the index's
225    // alignment; skipped rows keep their metadata and get no bytes.
226    std::vector<bool> skipped(rows.size(), false);
227    if (skip != nullptr) {
228        const uint64_t a = align > 0 ? (uint64_t) align : 256;
229        uint64_t at = 0;
230        for (size_t i = 0; i < rows.size(); ++i) {
231            if (skip->count(rows[i].name)) { skipped[i] = true; continue; }
232            rows[i].dst_off = at;
233            at += (rows[i].dst_bytes + a - 1) / a * a;
234        }
235        pool = at;
236    }
237    if (arena_bytes < pool) {
238        err = "arena is " + std::to_string(arena_bytes) + " B but the index needs " + std::to_string(pool);
239        return false;
240    }
241
242    // Two pinned staging buffers, both reused.  Pinned because a 5 GB pageable upload spends its time in the
243    // driver copying through a bounce buffer, and bounded by CHUNK rather than by the largest tensor.
244    //
245    // STAGE_OUT IS NOT OPTIONAL.  The first version of this loop converted the values straight into the
246    // destination pointer - which is DEVICE memory - from host code.  A host write to a device address is
247    // undefined behaviour, and on this driver it does not fault: it corrupts whatever the address maps to in
248    // the host's own space, which is nothing at all, so the tensor would have loaded as the UNCONVERTED pack
249    // bytes and every BF16 weight would have been read as 32-bit garbage.  Converted data goes to a host
250    // buffer and crosses the bus once.
251    //
252    // STAGE_OUT IS TWICE STAGE_IN because a conversion can now GROW: widening an fp16 scale plane to f32
253    // doubles it.  Sized at CHUNK it would have written 8 MiB past the end of a pinned allocation for every
254    // one of the 90 widened tensors - a heap corruption that would have been blamed on whatever ran next.
255    void* stage_in = nullptr;
256    void* stage_out = nullptr;
257    if (cudaHostAlloc(&stage_in, CHUNK, cudaHostAllocDefault) != cudaSuccess ||
258        cudaHostAlloc(&stage_out, CHUNK * 2, cudaHostAllocDefault) != cudaSuccess) {
259        err = "cudaHostAlloc for the staging buffers failed";
260        if (stage_in) cudaFreeHost(stage_in);
261        if (stage_out) cudaFreeHost(stage_out);
262        return false;
263    }
264
265    uint8_t* dst_base = (uint8_t*) arena_base;
266    std::FILE* cur = nullptr;
267    int cur_file = -1;
268    table_.clear();
269    report_ = LoadReport{};
270    pack_dir_ = pack_dir;
271
272    const double t_read0 = now_ms();
273    double upload_ms = 0;
274    for (size_t row_i = 0; row_i < rows.size(); ++row_i) {
275        const IndexRow& r = rows[row_i];
276        if (skipped[row_i]) {
277            WeightRef wr;
278            wr.data = nullptr;
279            wr.resident = false;
280            wr.bytes = r.dst_bytes;
281            wr.ne0 = r.ne0;
282            wr.ne1 = r.ne1;
283            wr.elements = r.ne0 * (r.ne1 > 0 ? r.ne1 : 1);
284            wr.kind = r.kind;
285            wr.code_bits = r.code_bits;
286            wr.code_bias = r.code_bias;
287            wr.group_elems = r.group_elems;
288            wr.codebook_iq4nl = r.codebook != 0;
289            wr.has_offset = r.has_offset != 0;
290            wr.codes_bytes = r.codes_bytes;
291            wr.scales_bytes = r.scales_bytes;
292            wr.offset_bytes = r.offset_bytes;
293            wr.src_off = r.src_off;
294            wr.src_bytes = r.src_bytes;
295            wr.file_id = r.file;
296            wr.scales_fp16 = r.scales_fp16 != 0;
297            wr.act_kind = r.act_kind;
298            table_[r.name] = wr;
299            ++report_.tensors;
300            continue;
301        }
302        if (r.code_bits != 0 && r.dst_bytes == 0) {
303            // plan v0.3 P6: a native pack's row that carries a shape only - the GGUF form must serve it
304            err = r.name + ": this pack holds the tensor only in its GGUF form (run with --native SHARD1)";
305            cudaFreeHost(stage_in); cudaFreeHost(stage_out);
306            return false;
307        }
308        if (r.file != cur_file) {
309            if (cur) std::fclose(cur);
310            const char* fn = file_name(r.file);
311            const std::string p = pack_dir + "/" + (fn ? fn : "?");
312            cur = std::fopen(p.c_str(), "rb");
313            if (!cur) { err = "cannot open " + p; cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; }
314            cur_file = r.file;
315#if !defined(_WIN32)
316            // ask for this file's remaining rows up front so their reads overlap
317            for (size_t j = row_i; j < rows.size(); ++j)
318                if (rows[j].file == r.file && !skipped[j])
319                    strata::platform::advise_willneed(fileno(cur), rows[j].src_off, rows[j].src_bytes);
320#endif
321        }
322
323        // ---- the segment list: what this tensor's bytes are, plane by plane, in both forms
324        Seg segs[3];
325        int n_segs = 0;
326        bool bad = false;
327        uint64_t sum_src = 0, sum_dst = 0;
328        if (r.codes_bytes != 0) {
329            // A quantized tensor: codes, then scales, then the optional offset plane, each contiguous in the
330            // source span in that order (pack_index.py verifies the contiguity and refuses otherwise).
331            segs[n_segs++] = Seg{0, r.codes_bytes, 0, r.codes_bytes, Conv::Copy};
332            if (r.scales_bytes) {
333                const uint64_t src_scale_bytes = r.scales_fp16 ? r.scales_bytes / 2 : r.scales_bytes;
334                if (r.scales_fp16 && (r.scales_bytes % 2 || src_scale_bytes * 2 != r.scales_bytes)) {
335                    err = r.name + ": an fp16 scale plane of an odd byte count";
336                    bad = true;
337                }
338                segs[n_segs++] = Seg{r.codes_bytes, src_scale_bytes, r.codes_bytes, r.scales_bytes,
339                                     r.scales_fp16 ? Conv::WidenF16 : Conv::Copy};
340            }
341            if (r.offset_bytes) {
342                const uint64_t after = r.codes_bytes + (r.scales_fp16 ? r.scales_bytes / 2 : r.scales_bytes);
343                segs[n_segs++] = Seg{after, r.offset_bytes, r.codes_bytes + r.scales_bytes, r.offset_bytes,
344                                     Conv::Copy};
345            }
346        } else {
347            // Everything else is one run whose transform is the row's kind.  The two promoted types shrink
348            // 4 B/elem to 2; the rest are already the engine form.
349            Conv c = Conv::Copy;
350            if (r.raw16) c = Conv::Copy;
351            else if (r.kind == WeightKind::Bf16InF32) c = Conv::Bf16High;
352            else if (r.kind == WeightKind::F16InF32) c = Conv::ToF16;
353            const uint64_t elems = (uint64_t) r.ne0 * (uint64_t) (r.ne1 > 0 ? r.ne1 : 1);
354            if (c != Conv::Copy && (r.src_bytes != elems * 4 || r.dst_bytes != elems * 2)) {
355                // A promoted type is 4 B/elem in and 2 B/elem out, and nothing else.  If those two numbers do
356                // not say so, the shape and the byte counts disagree and the element count this loop would
357                // use to walk the source is not the element count the pack wrote.
358                char buf[320];
359                std::snprintf(buf, sizeof buf,
360                              "%s: a promoted tensor of %llu elements is %llu B in and %llu B out, not %llu/%llu",
361                              r.name.c_str(), (unsigned long long) elems, (unsigned long long) r.src_bytes,
362                              (unsigned long long) r.dst_bytes, (unsigned long long) (elems * 4),
363                              (unsigned long long) (elems * 2));
364                err = buf;
365                bad = true;
366            }
367            segs[n_segs++] = Seg{0, r.src_bytes, 0, r.dst_bytes, c};
368        }
369        for (int i = 0; i < n_segs; ++i) { sum_src += segs[i].src_bytes; sum_dst += segs[i].dst_bytes; }
370        // The segment list is this loop's own idea of the layout, and it is the ONLY thing standing between a
371        // mis-sized plane and a wrong byte offset.  It is checked against both recorded totals, not trusted.
372        if (!bad && (sum_src != r.src_bytes || sum_dst != r.dst_bytes)) {
373            char buf[360];
374            std::snprintf(buf, sizeof buf,
375                          "%s: the segments cover %llu/%llu B but the index says %llu/%llu - the plane layout "
376                          "this loader built is not the one the index describes",
377                          r.name.c_str(), (unsigned long long) sum_src, (unsigned long long) sum_dst,
378                          (unsigned long long) r.src_bytes, (unsigned long long) r.dst_bytes);
379            err = buf;
380            bad = true;
381        }
382        if (bad) { cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; }
383
384        for (int si = 0; si < n_segs; ++si) {
385            const Seg& s = segs[si];
386            const bool widening = (s.conv == Conv::WidenF16);
387            if (widening && (s.src_bytes & 1ull)) {
388                err = r.name + ": an fp16 plane with an odd source byte count";
389                cudaFreeHost(stage_in); cudaFreeHost(stage_out);
390                return false;
391            }
392            uint64_t done = 0;
393            while (done < s.src_bytes) {
394                uint64_t n = std::min(CHUNK, s.src_bytes - done);
395                // WIDENING NEVER SPLITS AN ELEMENT.  CHUNK is even, so a full chunk cannot, but the tail of a
396                // plane whose length is odd would - and half an fp16 is a plausible-looking scale.
397                if (widening && (n & 1ull)) {
398                    if (n == 1) { err = r.name + ": an fp16 plane ending on a half element"; cudaFreeHost(stage_in); cudaFreeHost(stage_out); return false; }
399                    n -= 1;
400                }
401                if (!read_at(cur, r.src_off + s.src_off + done, stage_in, (size_t) n, err, r.name.c_str())) {
402                    cudaFreeHost(stage_in); cudaFreeHost(stage_out);
403                    return false;
404                }
405                const uint8_t* src = (const uint8_t*) stage_in;
406                const void* host_src = src;
407                uint64_t out_bytes = n;
408                uint64_t out_at = s.dst_off + done;
409
410                switch (s.conv) {
411                    case Conv::Copy:
412                        break;
413                    case Conv::Bf16High: {
414                        // THE HIGH 16 BITS ARE THE BF16 ENCODING, exactly - not a rounding.  A bf16 value is
415                        // the top half of its f32 image, and the pack promoted it without changing it, so
416                        // this is a copy with a stride.
417                        const uint64_t elems = n / 4;
418                        out_bytes = elems * 2;
419                        uint8_t* o = (uint8_t*) stage_out;
420                        for (uint64_t i = 0; i < elems; ++i) {
421                            uint32_t v;
422                            std::memcpy(&v, src + i * 4, 4);
423                            const uint16_t h = (uint16_t) (v >> 16);
424                            std::memcpy(o + i * 2, &h, 2);
425                        }
426                        host_src = stage_out;
427                        out_at = s.dst_off + done / 2;
428                        break;
429                    }
430                    case Conv::ToF16: {
431                        const uint64_t elems = n / 4;
432                        out_bytes = elems * 2;
433                        uint8_t* o = (uint8_t*) stage_out;
434                        for (uint64_t i = 0; i < elems; ++i) {
435                            float v;
436                            std::memcpy(&v, src + i * 4, 4);
437                            const uint16_t h = strata::kernels::f16_from_f32(v);
438                            std::memcpy(o + i * 2, &h, 2);
439                        }
440                        host_src = stage_out;
441                        out_at = s.dst_off + done / 2;
442                        break;
443                    }
444                    case Conv::WidenF16: {
445                        // fp16 bits -> f32.  EXACT: every fp16 value is an f32 value, including the
446                        // subnormals, so this cannot change a single weight - which is why the engine may do
447                        // it at all, and why doing it costs 10.88 MiB rather than a second kernel family.
448                        const uint64_t elems = n / 2;
449                        out_bytes = elems * 4;
450                        float* o = (float*) stage_out;
451                        for (uint64_t i = 0; i < elems; ++i) {
452                            uint16_t h;
453                            std::memcpy(&h, src + i * 2, 2);
454                            o[i] = strata::kernels::f32_from_f16(h);
455                        }
456                        host_src = stage_out;
457                        out_at = s.dst_off + done * 2;
458                        break;
459                    }
460                }
461
462                const double u0 = now_ms();
463                if (cudaMemcpy(dst_base + r.dst_off + out_at, host_src, out_bytes, cudaMemcpyHostToDevice) !=
464                    cudaSuccess) {
465                    err = "cudaMemcpy failed for " + r.name;
466                    cudaFreeHost(stage_in); cudaFreeHost(stage_out);
467                    return false;
468                }
469                upload_ms += now_ms() - u0;
470                done += n;
471            }
472        }
473
474        WeightRef wr;
475        wr.data = dst_base + r.dst_off;
476        wr.bytes = r.dst_bytes;
477        wr.ne0 = r.ne0;
478        wr.ne1 = r.ne1;
479        wr.elements = r.ne0 * (r.ne1 > 0 ? r.ne1 : 1);
480        wr.kind = r.kind;
481        wr.code_bits = r.code_bits;
482        wr.code_bias = r.code_bias;
483        wr.group_elems = r.group_elems;
484        wr.codebook_iq4nl = r.codebook != 0;
485        wr.has_offset = r.has_offset != 0;
486        wr.codes_bytes = r.codes_bytes;
487        wr.scales_bytes = r.scales_bytes;
488        wr.offset_bytes = r.offset_bytes;
489        wr.src_off = r.src_off;
490        wr.src_bytes = r.src_bytes;
491        wr.file_id = r.file;
492        wr.scales_fp16 = r.scales_fp16 != 0;
493        wr.act_kind = r.act_kind;
494        table_[r.name] = wr;
495
496        ++report_.tensors;
497        if ((r.kind == WeightKind::Bf16InF32 || r.kind == WeightKind::F16InF32) && !r.raw16) {
498            ++report_.re_rounded;
499            report_.bytes_saved += r.src_bytes - r.dst_bytes;
500        }
501    }
502    if (cur) std::fclose(cur);
503    cudaFreeHost(stage_in);
504    cudaFreeHost(stage_out);
505
506    report_.arena_bytes = pool;
507    report_.read_ms = now_ms() - t_read0 - upload_ms;
508    report_.upload_ms = upload_ms;
509    if (cudaDeviceSynchronize() != cudaSuccess) { err = "cudaDeviceSynchronize after the load failed"; return false; }
510    return true;
511}
512
513const WeightRef* WeightTable::find(const std::string& name) const {
514    const auto it = table_.find(name);
515    return it == table_.end() ? nullptr : &it->second;
516}
517
518WeightRef* WeightTable::find_mut(const std::string& name) {
519    const auto it = table_.find(name);
520    return it == table_.end() ? nullptr : &it->second;
521}
522
523void WeightTable::hc_q8_names(int64_t n_layers, std::set<std::string>& out) {
524    for (int64_t l = 0; l < n_layers; ++l)
525        for (const char* h : {"hc_attn_", "hc_ffn_"})
526            for (const char* m : {"down", "up"})
527                out.insert("blk." + std::to_string(l) + "." + h + m + ".weight");
528}
529
530bool WeightTable::load_hc_q8(const std::string& pack_dir, uint64_t& bytes, std::string& err) {
531    bytes = 0;
532    std::vector<WeightRef*> todo;
533    for (auto& [name, w] : table_) {
534        const bool hc = name.find(".hc_attn_down.") != std::string::npos || name.find(".hc_attn_up.") != std::string::npos ||
535                        name.find(".hc_ffn_down.") != std::string::npos || name.find(".hc_ffn_up.") != std::string::npos;
536        if (!hc || w.resident) continue;
537        // the pack holds BF16 either promoted to f32 (4 B/elem) or as it is in the GGUF (a native pack, 2 B/elem)
538        if (w.kind != WeightKind::Bf16InF32 || w.ne0 % 32 != 0 ||
539            (w.src_bytes != (uint64_t) w.elements * 4 && w.src_bytes != (uint64_t) w.elements * 2)) {
540            err = "STRATA_HC_REQ8: " + name + " is not a BF16 tensor of whole 32-value blocks";
541            return false;
542        }
543        todo.push_back(&w);
544    }
545    if (todo.empty()) return true;
546    auto al = [](uint64_t b) { return (b + 255) & ~(uint64_t) 255; };
547    uint64_t total = 0;
548    for (const WeightRef* w : todo) total += al((uint64_t) w->elements) + al((uint64_t) w->elements / 32 * 4);
549    uint8_t* dev = nullptr;
550    if (cudaMalloc((void**) &dev, total) != cudaSuccess) { err = "STRATA_HC_REQ8: cudaMalloc failed"; return false; }
551    std::vector<float> src;
552    std::vector<int8_t> q;
553    std::vector<float> sc;
554    uint64_t at = 0;
555    for (WeightRef* w : todo) {
556        const char* fn = file_name(w->file_id);
557        const std::string path = pack_dir + "/" + (fn ? fn : "?");
558        std::FILE* f = std::fopen(path.c_str(), "rb");
559        if (!f) { err = "STRATA_HC_REQ8: cannot open " + path; return false; }
560        src.resize((size_t) w->elements);
561        const bool raw16 = w->src_bytes == (uint64_t) w->elements * 2;
562#if defined(_WIN32)
563        bool ok = _fseeki64(f, (long long) w->src_off, SEEK_SET) == 0;
564#else
565        bool ok = fseeko(f, (off_t) w->src_off, SEEK_SET) == 0;   // 64-bit: a pack's dense file can pass 2 GiB
566#endif
567        if (ok && raw16) {
568            std::vector<uint16_t> h(src.size());
569            ok = std::fread(h.data(), 2, h.size(), f) == h.size();
570            for (size_t i = 0; ok && i < h.size(); ++i) {
571                const uint32_t b = (uint32_t) h[i] << 16;   // bf16 -> f32 is exact
572                std::memcpy(&src[i], &b, 4);
573            }
574        } else if (ok) {
575            ok = std::fread(src.data(), 4, src.size(), f) == src.size();
576        }
577        std::fclose(f);
578        if (!ok) { err = "STRATA_HC_REQ8: cannot read the source bytes"; return false; }
579        const size_t nb = src.size() / 32;
580        q.resize(src.size());
581        sc.resize(nb);
582        for (size_t b = 0; b < nb; ++b) {   // Q8_0's rule: d = amax / 127, q = round-to-nearest-even(x / d)
583            float amax = 0.f;
584            for (int j = 0; j < 32; ++j) amax = std::max(amax, std::fabs(src[b * 32 + j]));
585            const float d = amax / 127.f, id = d > 0.f ? 1.f / d : 0.f;
586            sc[b] = d;
587            for (int j = 0; j < 32; ++j) q[b * 32 + j] = (int8_t) std::nearbyint(src[b * 32 + j] * id);
588        }
589        uint8_t* codes = dev + at;
590        at += al(q.size());
591        float* scales = (float*) (dev + at);
592        at += al(sc.size() * 4);
593        if (cudaMemcpy(codes, q.data(), q.size(), cudaMemcpyHostToDevice) != cudaSuccess ||
594            cudaMemcpy(scales, sc.data(), sc.size() * 4, cudaMemcpyHostToDevice) != cudaSuccess) {
595            err = "STRATA_HC_REQ8: upload failed";
596            return false;
597        }
598        w->data = codes;
599        w->q8_scale = scales;
600        w->resident = true;
601        w->bytes = q.size() + sc.size() * 4;
602    }
603    bytes = total;
604    return true;
605}
606
607}  // namespace strata::core