okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
39.3 KiB694 linesraw
1#include "strata/core/native_dense.hpp"
2#include "strata/core/run_manifest.hpp"
3#include <cstdlib>
4#include "strata/core/weights.hpp"
5#include "strata/artifact/gguf_reader.hpp"
6#include "strata/kernels/fused_gr.hpp"
7#include "strata/kernels/gfx_arch.hpp"
8#include "strata/kernels/native_mmvq.hpp"
9#include "strata/platform/memory.hpp"
10
11#include <cuda_runtime.h>
12#include <algorithm>
13#include <climits>
14#include <cstdio>
15#include <cstdlib>
16#include <exception>
17#include <limits>
18#include <memory>
19#include <set>
20#include <cmath>
21#include <cstring>
22#include <map>
23#include <mutex>
24#include <thread>
25#include <vector>
26
27namespace strata::core {
28namespace {
29// `load` makes one cudaMalloc per projection matrix, and the driver backs each call with 2 MiB granules
30// (measured on the RTX 5060: 300 buffers of 6.73 MiB asked 2019 MiB and cost 2400).  So a stage's real
31// footprint is the granule-rounded sum, not the payload sum.  This rule - a granule for every matrix of a
32// MiB or more, the payload for the rest - prices the iq3_s pack's 300 matrices at 2255 MiB where they
33// really take 2238 (+0.8%).  It over-prices, which is the safe side.  (Pricing every matrix at a granule is
34// far worse, 2378 MiB: the driver packs the sub-MiB matrices into the slack of the rounded ones.)
35constexpr uint64_t kAllocGranule = 2ull << 20;
36constexpr uint64_t kSmallAlloc = 1ull << 20;
37uint64_t alloc_bytes(uint64_t bytes) {
38    return bytes < kSmallAlloc ? bytes : (bytes + kAllocGranule - 1) / kAllocGranule * kAllocGranule;
39}
40int g_layer_lb = -1, g_layer_le = -1;   // set_layer_range; -1: every layer
41bool in_range(const std::string& name) {
42    if (g_layer_lb < 0 || name.rfind("blk.", 0) != 0) return true;
43    const int l = std::atoi(name.c_str() + 4);
44    return l >= g_layer_lb && l < g_layer_le;
45}
46// S23 experiment (STRATA_HC_Q8=1): the hyper-connection projections' Q8_0 bytes for the verify read
47bool hc_q8_env() {
48    // STRATA_HC_Q8: 1 = on (the GGUF's own Q8_0 projections, or - a bf16 pack - a Q8_0 copy quantized at load); 0 = off;
49    // unset / auto = on for gfx12 (RDNA4: the R9700 decode +2.5 to +4%, KL 0.0003-0.0010 over its noise floor) unless
50    // STRATA_GFX12_DEFAULTS=0; also on for gfx1151 (Strix Halo, STRATA_HC_Q8=0 turns it off), off elsewhere
51    static const bool on = [] {
52        const char* v = std::getenv("STRATA_HC_Q8");
53        if (v != nullptr && v[0] == '1') return true;
54        if (v != nullptr && v[0] != '\0' && std::strcmp(v, "auto") != 0) return false;
55#if defined(STRATA_USE_HIP)
56        {   // Strix Halo (gfx1151): on by default (decode +9.5%, json/code/tool/chat/agent +7.9..+10.7%); the answers differ in
57            // near-tie tokens by about the size of the engine's own CPU-vs-GPU expert rounding (docs/AMD_HIP.md);
58            // STRATA_HC_Q8=0 keeps the bf16 read
59            int dev1151 = 0;
60            cudaDeviceProp p1151;
61            const bool g1151 = cudaGetDevice(&dev1151) == cudaSuccess && cudaGetDeviceProperties(&p1151, dev1151) == cudaSuccess &&
62                               strata::kernels::gfx_arch_is_gfx1151(p1151.gcnArchName);
63            (void) cudaGetLastError();
64            if (g1151) {
65                std::fprintf(stderr, "strata: Strix Halo (gfx1151): 8-bit hyper-connection weights are on (decode about 9%% faster, "
66                                     "answers can differ in near-tie tokens); STRATA_HC_Q8=0 keeps the bf16 read\n");
67                return true;
68            }
69        }
70        const char* d = std::getenv("STRATA_GFX12_DEFAULTS");
71        if (d != nullptr && d[0] == '0') return false;
72        int dev = 0;
73        cudaDeviceProp p;
74        const bool g12 = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
75                         strata::kernels::gfx_arch_is_gfx12(p.gcnArchName);
76        (void) cudaGetLastError();
77        if (g12) std::fprintf(stderr, "strata: gfx12 (RDNA4): the hyper-connection projections are read as Q8_0 (quantized at load, "
78                                      "decode faster, answers differ slightly); STRATA_HC_Q8=0 keeps the bf16 read\n");
79        return g12;
80#else
81        return false;
82#endif
83    }();
84    return on;
85}
86// STRATA_HC_Q8_ALL_STAGES=1: the Q8_0 hyper-connection rows of every layer are copied to every stage (the behaviour before #3559)
87bool hc_q8_stage_local() {
88    static const bool on = [] { const char* v = std::getenv("STRATA_HC_Q8_ALL_STAGES"); return !(v != nullptr && v[0] == '1'); }();
89    return on;
90}
91// STRATA_HC_Q8_INJECT=1: the F32 inject rows get a Q8_0 copy too (S25)
92bool hc_q8_inject_env() {
93    static const bool on = [] { const char* v = std::getenv("STRATA_HC_Q8_INJECT"); return v && v[0] == '1'; }();
94    return on;
95}
96bool hc_q8_name(const std::string& name) {
97    if (name == "output_hc_down.weight" || name == "output_hc_up.weight") return true;   // S25: the final mixer too
98    if (name.rfind("blk.", 0) != 0) return false;
99    static const char* suffixes[] = {".hc_attn_down.weight", ".hc_attn_up.weight", ".hc_attn_inject.weight",
100                                     ".hc_ffn_down.weight", ".hc_ffn_up.weight", ".hc_ffn_inject.weight"};
101    for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true;
102    return false;
103}
104// S25: the GGUF keeps the inject rows as F32 - quantized here to Q8_0 (ggml's reference rounding) so the Q8_0 read
105// covers every hc projection
106uint16_t half_bits(float f) {
107    uint32_t x;
108    std::memcpy(&x, &f, 4);
109    const uint32_t sign = (x >> 16) & 0x8000u;
110    int32_t e = (int32_t) ((x >> 23) & 0xff) - 127 + 15;
111    uint32_t m = x & 0x7fffffu;
112    if (e <= 0) {                                   // subnormal or zero
113        if (e < -10) return (uint16_t) sign;
114        m |= 0x800000u;
115        const uint32_t shift = (uint32_t) (14 - e);
116        uint32_t h = m >> shift;
117        const uint32_t rem = m & ((1u << shift) - 1), half = 1u << (shift - 1);
118        if (rem > half || (rem == half && (h & 1u))) ++h;
119        return (uint16_t) (sign | h);
120    }
121    if (e >= 31) return (uint16_t) (sign | 0x7c00u);
122    uint32_t h = ((uint32_t) e << 10) | (m >> 13);
123    const uint32_t rem = m & 0x1fffu;
124    if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h;
125    return (uint16_t) (sign | h);
126}
127std::vector<uint8_t> q8_0_of(const float* x, uint64_t n) {
128    std::vector<uint8_t> out((size_t) (n / 32 * 34));
129    for (uint64_t b = 0; b < n / 32; ++b) {
130        float amax = 0.0f;
131        for (int j = 0; j < 32; ++j) amax = (std::max)(amax, std::fabs(x[b * 32 + j]));
132        const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f;
133        uint8_t* o = out.data() + b * 34;
134        const uint16_t hb = half_bits(d);
135        std::memcpy(o, &hb, 2);
136        for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t) (int8_t) std::lround(x[b * 32 + j] * id);
137    }
138    return out;
139}
140// A bf16 matrix (the pack file's values) as Q8_0, ggml's reference rounding; the blocks are independent, so a few threads
141std::vector<uint8_t> q8_0_of_bf16(const uint16_t* x, uint64_t n) {
142    std::vector<uint8_t> out((size_t) (n / 32 * 34));
143    const uint64_t nb = n / 32;
144    auto work = [&](uint64_t b0, uint64_t b1) {
145        for (uint64_t b = b0; b < b1; ++b) {
146            float v[32], amax = 0.0f;
147            for (int j = 0; j < 32; ++j) {
148                const uint32_t u = (uint32_t) x[b * 32 + j] << 16;
149                std::memcpy(&v[j], &u, 4);
150                amax = (std::max)(amax, std::fabs(v[j]));
151            }
152            const float d = amax / 127.0f, id = d != 0.0f ? 1.0f / d : 0.0f;
153            uint8_t* o = out.data() + b * 34;
154            const uint16_t hb = half_bits(d);
155            std::memcpy(o, &hb, 2);
156            for (int j = 0; j < 32; ++j) o[2 + j] = (uint8_t) (int8_t) std::lround(v[j] * id);
157        }
158    };
159    const unsigned nt = (std::min)(8u, (std::max)(1u, std::thread::hardware_concurrency()));
160    std::vector<std::thread> pool;
161    for (unsigned i = 0; i < nt; ++i) pool.emplace_back(work, nb * i / nt, nb * (i + 1) / nt);
162    for (auto& th : pool) th.join();
163    return out;
164}
165bool eligible(const strata::TensorInfo& tensor, bool include_ple_key) {
166    const auto& name = tensor.name;
167    if (name.rfind("blk.", 0) != 0) return false;
168    // Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16
169    // fallback.
170    if (name == "blk.1.ple_key.weight")
171        return include_ple_key && (tensor.type == 42 || tensor.type == 18 || tensor.type == 23 || tensor.type == 8);
172    static const char* suffixes[] = {".attn_qkv.weight", ".attn_gate.weight", ".ssm_out.weight",
173        ".attn_q.weight", ".attn_k.weight", ".attn_v.weight", ".attn_output.weight",
174        ".ffn_gate_shexp.weight", ".ffn_up_shexp.weight", ".ffn_down_shexp.weight"};
175    for (const char* suffix : suffixes) if (name.ends_with(suffix)) return true;
176    return false;
177}
178// #4741: a native-eligible projection a pack keeps unquantized (BF16, GGUF type 30; Heretic v2 IQ4_NL has its layer-0 attn_gate so)
179// has no native kernel.  Its siblings are Q8_0, so it is served as Q8_0 made from the file's BF16 values (ggml's rounding), and
180// the dispatchers that need a native projection find one.  The pack's BF16 copy stays where it is.
181bool bf16_as_q8_0(const strata::TensorInfo& tensor, const WeightRef& ref) {
182    return tensor.type == 30 && tensor.name != "blk.1.ple_key.weight" && tensor.shape.size() == 2 &&
183           !ref.quantized() && ref.kind == WeightKind::Bf16InF32 &&
184           ref.ne0 > 0 && ref.ne0 <= INT_MAX && ref.ne1 > 0 && ref.ne1 <= INT_MAX && ref.ne0 % 32 == 0 &&
185           tensor.shape[0] == (uint64_t) ref.ne0 && tensor.shape[1] == (uint64_t) ref.ne1;
186}
187struct DeviceFree { void operator()(void* p) const { if (p) cudaFree(p); } };
188using DevicePtr = std::unique_ptr<void, DeviceFree>;
189struct Pending {
190    WeightRef* ref;
191    int type;
192    uint64_t bytes;
193    DevicePtr data;
194    DevicePtr packed;   // STRATA_Q8_PACKED=1 copy, or null
195};
196}
197
198bool NativeDense::served_names(const std::vector<std::string>& shards, bool include_ple_key,
199                               std::set<std::string>& out, std::string& err) {
200    try {
201        for (const auto& path : shards) {
202            strata::GgufFile gguf(path);
203            for (const auto& tensor : gguf.tensors())
204                if (eligible(tensor, include_ple_key) && strata::kernels::native_mmvq_supported(tensor.type) &&
205                    tensor.shape.size() == 2)
206                    out.insert(tensor.name);
207        }
208        return true;
209    } catch (const std::exception& error) {
210        err = std::string("native dense: ") + error.what();
211        return false;
212    }
213}
214
215void NativeDense::set_layer_range(int lb, int le) { g_layer_lb = lb; g_layer_le = le; }
216// The byte walk `load` does for the layers [lb, le), without the allocations: the same filters in the same order,
217// reading the GGUF headers and the canonical table only, so it needs no device.  A later stage's projections are not
218// on the card when the split search prices that stage, and `load` runs one cudaMalloc per matrix (#1238).  The two
219// have to stay in step.  A repeated name is skipped rather than refused (`load` refuses it).
220bool NativeDense::weight_bytes_for(const std::vector<std::string>& shards, WeightTable& table, bool include_ple_key,
221                                   int64_t lb, int64_t le, uint64_t& out, std::string& err) {
222    out = 0;
223    try {
224        std::set<std::string> seen, hc_seen;
225        uint64_t total = 0;
226        auto in_stage = [&](const std::string& name) {   // a blk.<l>. tensor of layers [lb, le); the rest belongs to every stage
227            if (name.rfind("blk.", 0) != 0) return true;
228            const long l = std::strtol(name.c_str() + 4, nullptr, 10);
229            return l >= lb && l < le;
230        };
231        for (const auto& path : shards) {
232            strata::GgufFile gguf(path);
233            for (const auto& tensor : gguf.tensors()) {
234                // STRATA_HC_Q8: `load` copies the GGUF's Q8_0 hyper-connection rows of its layers (and the final mixer's)
235                // to the card, one cudaMalloc each, and the pack's bf16 rows get a Q8_0 copy below: priced as `load` makes them
236                if (hc_q8_env() && hc_q8_name(tensor.name) && tensor.shape.size() == 2) {
237                    const bool f32_inject = hc_q8_inject_env() && tensor.type == 0 && tensor.name.ends_with("_inject.weight");
238                    if ((tensor.type == 8 || f32_inject) && (!hc_q8_stage_local() || in_stage(tensor.name)) &&
239                        hc_seen.insert(tensor.name).second) {
240                        const auto found = table.table_.find(tensor.name);
241                        if (found != table.table_.end() && found->second.ne0 % 32 == 0 &&
242                            tensor.shape[0] == (uint64_t) found->second.ne0 && tensor.shape[1] == (uint64_t) found->second.ne1)
243                            total += alloc_bytes((uint64_t) found->second.ne0 / 32 * 34 * (uint64_t) found->second.ne1);
244                    }
245                }
246                if (!eligible(tensor, include_ple_key)) continue;
247                if (tensor.name.rfind("blk.", 0) == 0 && tensor.name.find("ple") == std::string::npos) {   // `load` takes the PLE key on every stage
248                    const long l = std::strtol(tensor.name.c_str() + 4, nullptr, 10);
249                    if (l < lb || l >= le) continue;
250                }
251                if (!seen.insert(tensor.name).second) continue;
252                auto found = table.table_.find(tensor.name);
253                if (found == table.table_.end()) {
254                    err = "native dense: tensor absent from canonical table: " + tensor.name;
255                    return false;
256                }
257                const auto& ref = found->second;
258                if (bf16_as_q8_0(tensor, ref)) {   // #4741
259                    total += alloc_bytes((uint64_t) ref.ne0 / 32 * 34 * (uint64_t) ref.ne1);
260                    continue;
261                }
262                if (!strata::kernels::native_mmvq_supported(tensor.type)) continue;
263                if (tensor.name == "blk.1.ple_key.weight" && !ref.quantized()) continue;
264                if (!ref.quantized() || tensor.shape.size() != 2 ||
265                    ref.ne0 <= 0 || ref.ne0 > INT_MAX || ref.ne1 <= 0 || ref.ne1 > INT_MAX ||
266                    tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1) {
267                    err = "native dense: incompatible matrix " + tensor.name;
268                    return false;
269                }
270                total += alloc_bytes(strata::kernels::native_mmvq_weight_bytes(tensor.type, (int) ref.ne0, (int) ref.ne1));
271            }
272        }
273        if (hc_q8_env())   // a bf16 pack: `load` quantizes the layers' down / up projections that the GGUF does not carry as Q8_0
274            for (const auto& [name, ref] : table.table_) {
275                if (name.rfind("blk.", 0) != 0 || !in_stage(name) || !hc_q8_name(name) || hc_seen.count(name) ||
276                    !(name.ends_with("_down.weight") || name.ends_with("_up.weight")))
277                    continue;
278                if (ref.ne0 % 32 == 0 && ref.elements == ref.ne0 * ref.ne1) total += alloc_bytes((uint64_t) ref.elements / 32 * 34);
279            }
280        out = total;
281        return true;
282    } catch (const std::exception& error) {
283        err = std::string("native dense: ") + error.what();
284        return false;
285    }
286}
287bool NativeDense::keep_unquantized_ple_key(const std::string& pack_dir, std::set<std::string>& skip,
288                                           std::string& err) {
289    const std::string key = "blk.1.ple_key.weight";
290    if (!skip.count(key)) return true;
291    int code_bits = -1;
292    if (!WeightTable::index_code_bits(pack_dir, key, code_bits, err)) return false;
293    if (code_bits == 0) skip.erase(key);
294    return true;
295}
296
297// STRATA_HC_Q8 without a bf16 copy: the two dequantization scratches (one bf16 matrix each) of `hc_bf16_view`, per device,
298// allocated by `load` - never on first use, so a graph capture cannot meet the allocation
299static void* g_hc_scratch[64][2][2] = {};     // [device][class][slot]
300static cudaEvent_t g_hc_ev[64][2] = {};        // [device][slot]: the prompt path's last reader of the slot
301static bool g_hc_ev_set[64][2] = {};
302
303NativeDense::~NativeDense() {
304    release();
305}
306
307void NativeDense::release() {
308    // what the destructor always did first: no HC scratch pointer and no packed-Q8 registry key may outlive the memory
309    for (auto& dev : g_hc_scratch)
310        for (auto& cl : dev)
311            for (void*& b : cl)
312                if (b != nullptr && std::find(weights_.begin(), weights_.end(), b) != weights_.end()) b = nullptr;
313    for (const void* p : packed_keys_) strata::kernels::native_q8_0_packed_unregister(p);
314    if (scratch_) cudaFree(scratch_);
315    for (void* p : weights_) cudaFree(p);
316    scratch_ = nullptr;
317    weights_.clear();
318    packed_keys_.clear();
319    layer_bytes_.clear();
320    bytes_ = 0;
321}
322
323uint64_t NativeDense::bytes_in(int64_t lo, int64_t hi) const {
324    uint64_t n = 0;
325    for (int64_t l = std::max<int64_t>(lo, 0); l < hi && l < (int64_t) layer_bytes_.size(); ++l) n += layer_bytes_[(size_t) l];
326    return n;
327}
328
329bool NativeDense::load(const std::vector<std::string>& shards, WeightTable& table, std::string& err,
330                       bool include_ple_key, int64_t layer_lo, int64_t layer_hi) {
331    auto outside = [&](const std::string& name) {   // a blk.<l>. tensor of another stage's layers
332        if (layer_hi < 0 || name.rfind("blk.", 0) != 0) return false;
333        const long l = std::strtol(name.c_str() + 4, nullptr, 10);
334        return l < layer_lo || l >= layer_hi;
335    };
336    auto layer_of = [&](const std::string& name) -> int64_t {   // the layer of a blk.<l>. tensor, -1 otherwise
337        if (name.rfind("blk.", 0) != 0) return -1;
338        return std::strtoll(name.c_str() + 4, nullptr, 10);
339    };
340    if (scratch_ || !weights_.empty()) { err = "native dense: already loaded"; return false; }
341    if (shards.empty()) { err = "native dense: at least one GGUF shard is required"; return false; }
342    try {
343        std::vector<Pending> pending;
344        std::set<std::string> seen;
345        int max_in = 0;
346        uint64_t total = 0, hc_q8_bytes = 0, allocated = 0, hc_q8_skipped_bytes = 0, hc_q8_skipped = 0;
347        std::vector<uint64_t> per_layer;
348        uint64_t split_count = 0, split_tensors = 0;
349        std::set<uint64_t> split_numbers;
350        bool have_architecture = false;
351        for (const auto& path : shards) {
352            strata::GgufFile gguf(path);
353            const auto* count = gguf.get("split.count");
354            const auto* number = gguf.get("split.no");
355            const auto* tensors = gguf.get("split.tensors.count");
356            if (gguf.get("general.architecture") && (!number || number->u == 0)) {
357                // splitter may copy general.architecture into every shard (Huihui abliterated re-split)
358                err = strata::check_engine_architecture(gguf);
359                if (!err.empty()) return false;
360                have_architecture = true;
361                if (count && number && tensors && number->u == 0 && count->u > 1) {
362                    split_count = count->u;
363                    split_tensors = tensors->u;
364                }
365            } else if (!have_architecture || !split_count || !count || !number || !tensors ||
366                       count->u != split_count || number->u == 0 || number->u >= split_count ||
367                       tensors->u != split_tensors) {
368                err = "native dense: additional shard must match the architecture-validated first shard's split metadata";
369                return false;
370            }
371            if (number && !split_numbers.insert(number->u).second) {
372                err = "native dense: duplicate split shard number"; return false;
373            }
374            std::vector<uint64_t> offsets;
375            for (const auto& tensor : gguf.tensors()) offsets.push_back(tensor.offset);
376            std::sort(offsets.begin(), offsets.end());
377            if (std::adjacent_find(offsets.begin(), offsets.end()) != offsets.end()) {
378                err = "native dense: tensor payload offsets overlap"; return false;
379            }
380            // Validate every directory span, including tensors we do not upload:
381            // an ignored tensor must not overlap the native matrix that follows it.
382            const uint64_t payload = gguf.file_size() - gguf.data_start();
383            for (const auto& tensor : gguf.tensors()) {
384                int block_elements = 0, block_bytes = 0;
385                uint64_t elements = 1;
386                if (tensor.shape.empty() || !strata::block_geometry(tensor.type, block_elements, block_bytes) ||
387                    tensor.shape[0] % (uint64_t) block_elements != 0) {
388                    err = "native dense: invalid block geometry " + tensor.name; return false;
389                }
390                for (uint64_t dimension : tensor.shape) {
391                    if (!dimension || elements > (std::numeric_limits<uint64_t>::max)() / dimension) {
392                        err = "native dense: invalid tensor extent " + tensor.name; return false;
393                    }
394                    elements *= dimension;
395                }
396                const uint64_t blocks = elements / (uint64_t) block_elements;
397                if (blocks > (std::numeric_limits<uint64_t>::max)() / (uint64_t) block_bytes) {
398                    err = "native dense: tensor byte count overflow " + tensor.name; return false;
399                }
400                const uint64_t bytes = blocks * (uint64_t) block_bytes;
401                if (tensor.offset > payload || bytes > payload - tensor.offset) {
402                    err = "native dense: truncated payload " + tensor.name; return false;
403                }
404                const auto next = std::upper_bound(offsets.begin(), offsets.end(), tensor.offset);
405                if (next != offsets.end() && bytes > *next - tensor.offset) {
406                    err = "native dense: overlapping payload " + tensor.name; return false;
407                }
408                // the uploads below read these: ask for them now so the reads overlap
409                if (eligible(tensor, include_ple_key) && !outside(tensor.name) &&
410                    strata::kernels::native_mmvq_supported(tensor.type))
411                    strata::platform::advise_willneed(gguf.tensor_data(tensor), bytes);
412            }
413            for (const auto& tensor : gguf.tensors()) {
414                if (!eligible(tensor, include_ple_key) || outside(tensor.name)) continue;
415                if (!in_range(tensor.name) && tensor.name.find("ple") == std::string::npos) continue;
416                if (!seen.insert(tensor.name).second) {
417                    err = "native dense: duplicate tensor " + tensor.name; return false;
418                }
419                auto found = table.table_.find(tensor.name);
420                if (found == table.table_.end()) {
421                    err = "native dense: tensor absent from canonical table: " + tensor.name; return false;
422                }
423                auto& ref = found->second;
424                if (ref.native_data) { err = "native dense: override already attached"; return false; }
425                if (bf16_as_q8_0(tensor, ref)) {   // #4741: a BF16 projection of the pack, served as Q8_0
426                    const uint64_t n = (uint64_t) ref.ne0 * (uint64_t) ref.ne1;
427                    const std::vector<uint8_t> q8 = q8_0_of_bf16((const uint16_t*) gguf.tensor_data(tensor), n);
428                    void* allocation = nullptr;
429                    auto status = cudaMalloc(&allocation, q8.size());
430                    DevicePtr data(allocation);
431                    if (status == cudaSuccess) status = cudaMemcpy(data.get(), q8.data(), q8.size(), cudaMemcpyHostToDevice);
432                    if (status != cudaSuccess) {
433                        err = "native dense upload " + tensor.name + ": " + cudaGetErrorString(status); return false;
434                    }
435                    max_in = (std::max)(max_in, (int) ref.ne0);
436                    total += q8.size();
437                    allocated += alloc_bytes(q8.size());
438                    std::fprintf(stderr, "native dense: %s is BF16 in the file: served as Q8_0 like its siblings (#4741)\n",
439                                 tensor.name.c_str());
440                    pending.push_back(Pending{&ref, 8, (uint64_t) q8.size(), std::move(data), DevicePtr()});
441                    continue;
442                }
443                if (!strata::kernels::native_mmvq_supported(tensor.type)) continue;
444                // #326: the pack keeps an unquantized (--compat-bf16) key, which the PLE reads from the arena
445                if (tensor.name == "blk.1.ple_key.weight" && !ref.quantized()) continue;
446                if (!ref.quantized() || tensor.shape.size() != 2 ||
447                    ref.ne0 <= 0 || ref.ne0 > INT_MAX || ref.ne1 <= 0 || ref.ne1 > INT_MAX ||
448                    tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1) {
449                    err = "native dense: incompatible matrix " + tensor.name; return false;
450                }
451                const auto bytes = strata::kernels::native_mmvq_weight_bytes(
452                    tensor.type, (int) ref.ne0, (int) ref.ne1);
453                void* allocation = nullptr;
454                auto status = cudaMalloc(&allocation, bytes);
455                DevicePtr data(allocation);
456                if (status == cudaSuccess)
457                    status = cudaMemcpy(data.get(), gguf.tensor_data(tensor), bytes, cudaMemcpyHostToDevice);
458                if (status != cudaSuccess) {
459                    err = "native dense upload " + tensor.name + ": " + cudaGetErrorString(status); return false;
460                }
461                max_in = (std::max)(max_in, (int) ref.ne0);
462                total += bytes;
463                allocated += alloc_bytes(bytes);
464                {
465                    const int64_t layer = layer_of(tensor.name);
466                    if (layer >= 0) {
467                        if (per_layer.size() <= (size_t) layer) per_layer.resize((size_t) layer + 1, 0);
468                        per_layer[(size_t) layer] += bytes;
469                    }
470                }
471                // STRATA_Q8_PACKED=1: a second, packed copy of an eligible Q8_0 matrix for the decode MMVQ (the GGUF
472                // copy stays: the prompt path's GEMMs read it).
473                DevicePtr packed;
474                if (tensor.type == 8 && tensor.name != "blk.1.ple_key.weight" &&   // the PLE has its own kernel
475                    strata::kernels::native_q8_0_packed_enabled() &&
476                    strata::kernels::native_q8_0_packed_eligible((int) ref.ne0, (int) ref.ne1)) {
477                    std::vector<uint8_t> host(bytes);
478                    strata::kernels::native_q8_0_pack_host(gguf.tensor_data(tensor), host.data(), (int) ref.ne0,
479                                                           (int) ref.ne1);
480                    void* packed_allocation = nullptr;
481                    auto packed_status = cudaMalloc(&packed_allocation, bytes);
482                    packed.reset(packed_allocation);
483                    if (packed_status == cudaSuccess)
484                        packed_status = cudaMemcpy(packed.get(), host.data(), bytes, cudaMemcpyHostToDevice);
485                    if (packed_status != cudaSuccess) {
486                        err = "native dense packed upload " + tensor.name + ": " + cudaGetErrorString(packed_status);
487                        return false;
488                    }
489                }
490                if (strata::core::manifest::enabled()) {   // STRATA_MANIFEST: the dense formats as held, and the packed copies
491                    strata::core::manifest::instance().tensors("dense", strata::ggml_type_name((uint32_t) tensor.type), 1, bytes);
492                    if (packed) strata::core::manifest::instance().tensors("dense_packed_copy", "Q8_0", 1, bytes);
493                }
494                pending.push_back(Pending{&ref, (int) tensor.type, bytes, std::move(data), std::move(packed)});
495            }
496            if (strata::core::manifest::enabled()) {
497                const char* v = std::getenv("STRATA_HC_Q8");
498                strata::core::manifest::instance().path("dense", "hc_q8", hc_q8_env(),
499                    hc_q8_env() ? (v != nullptr && v[0] == '1' ? "STRATA_HC_Q8=1" : "architecture default (gfx12 / gfx1151 HIP)")
500                                : (v != nullptr && v[0] != '\0' && std::strcmp(v, "auto") != 0 ? "STRATA_HC_Q8 turned it off"
501                                                                                               : "off by default on this backend"));
502            }
503            if (hc_q8_env())
504                for (const auto& tensor : gguf.tensors()) {
505                    // S25: the F32 inject rows hold BF16-exact values: the read takes the pack's BF16 rows unless
506                    // STRATA_HC_Q8_INJECT=1 asks for a Q8_0 copy
507                    const bool f32_inject = hc_q8_inject_env() && tensor.type == 0 && tensor.name.ends_with("_inject.weight");
508                    if ((tensor.type != 8 && !f32_inject) || !hc_q8_name(tensor.name) || tensor.shape.size() != 2) continue;
509                    // a trimmed layer split: another stage's layers are never read here, so their rows are not copied (the upload
510                    // loop above and the bf16 pack path below already filter this way; PR #3559, havok2-htwo).
511                    // STRATA_HC_Q8_ALL_STAGES=1 copies them as before.
512                    if (hc_q8_stage_local() && (outside(tensor.name) || !in_range(tensor.name))) {
513                        hc_q8_skipped_bytes += (uint64_t) tensor.shape[0] / 32 * 34 * (uint64_t) tensor.shape[1];
514                        ++hc_q8_skipped;
515                        continue;
516                    }
517                    auto found = table.table_.find(tensor.name);
518                    if (found == table.table_.end() || found->second.hc_q8 != nullptr) continue;
519                    auto& ref = found->second;
520                    if (tensor.shape[0] != (uint64_t) ref.ne0 || tensor.shape[1] != (uint64_t) ref.ne1 || ref.ne0 % 32 != 0) {
521                        err = "native dense (STRATA_HC_Q8): incompatible matrix " + tensor.name; return false;
522                    }
523                    const uint64_t bytes = (uint64_t) ref.ne0 / 32 * 34 * (uint64_t) ref.ne1;
524                    void* p = nullptr;
525                    std::vector<uint8_t> q8;
526                    if (f32_inject) q8 = q8_0_of((const float*) gguf.tensor_data(tensor), (uint64_t) ref.ne0 * (uint64_t) ref.ne1);
527                    if (cudaMalloc(&p, bytes) != cudaSuccess ||
528                        cudaMemcpy(p, f32_inject ? (const void*) q8.data() : gguf.tensor_data(tensor), bytes,
529                                   cudaMemcpyHostToDevice) != cudaSuccess) {
530                        err = "native dense (STRATA_HC_Q8) upload " + tensor.name; return false;
531                    }
532                    ref.hc_q8 = p;
533                    weights_.push_back(p);
534                    hc_q8_bytes += bytes;
535                    allocated += alloc_bytes(bytes);
536                    strata::core::manifest::instance().tensors("dense_hc_q8_copy", f32_inject ? "F32->Q8_0" : "Q8_0", 1, bytes);
537                }
538        }
539        if (hc_q8_env()) {
540            // a bf16 pack stores no Q8_0 copy: quantize the layers' down / up projections. A row the arena kept
541            // (--keep-canonical, a layer split) is quantized on the GPU from the arena's bf16; a skipped row (the
542            // single-GPU default: add_hc_skip) from the pack file on the host, and has no bf16 copy at all. The
543            // inject rows stay bf16 (82 KB), the final mixer stays bf16 (it runs once a window).
544            uint64_t made = 0;
545            for (auto& [name, ref] : table.table_) {
546                if (ref.hc_q8 != nullptr || name.rfind("blk.", 0) != 0 || !in_range(name) ||
547                    !hc_q8_name(name) || !(name.ends_with("_down.weight") || name.ends_with("_up.weight"))) continue;
548                const bool skipped = ref.data == nullptr;
549                if (skipped && ref.resident) continue;
550                if (ref.ne0 % 32 != 0 || ref.elements != ref.ne0 * ref.ne1 || (!skipped && ref.bytes != (uint64_t) ref.elements * 2)) {
551                    err = "native dense (STRATA_HC_Q8): " + name + " is not a bf16 matrix"; return false;
552                }
553                const uint64_t nb = (uint64_t) ref.elements / 32, bytes = nb * 34;
554                void* p = nullptr;
555                if (cudaMalloc(&p, bytes) != cudaSuccess) { err = "native dense (STRATA_HC_Q8) alloc " + name; return false; }
556                weights_.push_back(p);
557                if (skipped) {
558                    std::vector<uint16_t> host;
559                    if (!table.read_bf16_host(name, host, err)) return false;
560                    const std::vector<uint8_t> q8 = q8_0_of_bf16(host.data(), (uint64_t) host.size());
561                    if (cudaMemcpy(p, q8.data(), bytes, cudaMemcpyHostToDevice) != cudaSuccess) {
562                        err = "native dense (STRATA_HC_Q8) upload " + name; return false;
563                    }
564                } else {
565                    strata::kernels::fused_gr_quantize_q8_0((const uint16_t*) ref.data, (uint8_t*) p, (int64_t) nb, nullptr);
566                }
567                ref.hc_q8 = p;
568                hc_q8_bytes += bytes;
569                allocated += alloc_bytes(bytes);
570                ++made;
571            }
572            if (made && (cudaGetLastError() != cudaSuccess || cudaDeviceSynchronize() != cudaSuccess)) {
573                err = "native dense (STRATA_HC_Q8): quantizing the projections failed"; return false;
574            }
575        }
576        if (hc_q8_env()) {   // the scratches of hc_bf16_view (rows without a bf16 copy), here and not on first use
577            uint64_t elems = 0;
578            for (const auto& [name, ref] : table.table_)
579                if (ref.hc_q8 != nullptr && ref.data == nullptr) elems = (std::max)(elems, (uint64_t) ref.elements);
580            int dev = 0;
581            if (elems != 0 && cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < 64 && g_hc_scratch[dev][0][0] == nullptr) {
582                for (int c = 0; c < 2; ++c)
583                    for (int i = 0; i < 2; ++i) {
584                        void* b = nullptr;
585                        if (cudaMalloc(&b, (size_t) elems * 2) != cudaSuccess) { err = "native dense (STRATA_HC_Q8): scratch alloc"; return false; }
586                        weights_.push_back(b);
587                        g_hc_scratch[dev][c][i] = b;
588                    }
589                for (int i = 0; i < 2; ++i)
590                    if (g_hc_ev[dev][i] == nullptr && cudaEventCreateWithFlags(&g_hc_ev[dev][i], cudaEventDisableTiming) != cudaSuccess) {
591                        err = "native dense (STRATA_HC_Q8): scratch event"; return false;
592                    }
593            }
594        }
595        // Edge0 latent / all-BF16 native shards: every projection is canonical-pack BF16 and the GEMMs read it
596        // from the arena ("BF16 weights as they are"); no native quantization to publish, and nothing left to do.
597        if (pending.empty()) return true;
598        void* allocation = nullptr;
599        const auto status = cudaMalloc(&allocation, strata::kernels::native_q8_1_bytes(max_in));
600        DevicePtr scratch(allocation);
601        if (status != cudaSuccess) { err = std::string("native dense scratch: ") + cudaGetErrorString(status); return false; }        // All checks and allocations finish before publishing any reference.
602        weights_.reserve(pending.size());
603        uint64_t packed_bytes = 0;
604        size_t packed_count = 0;
605        for (auto& item : pending) {
606            item.ref->native_data = item.data.get();
607            item.ref->native_type = item.type;
608            item.ref->native_q8_1 = scratch.get();
609            if (item.packed) {
610                strata::kernels::native_q8_0_packed_register(item.data.get(), item.packed.get(), (int) item.ref->ne0,
611                                                             (int) item.ref->ne1);
612                packed_keys_.push_back(item.data.get());
613                packed_bytes += item.bytes;
614                ++packed_count;
615                weights_.push_back(item.packed.release());
616            }
617            weights_.push_back(item.data.release());
618        }
619        if (packed_count)
620            std::fprintf(stderr, "native dense: STRATA_Q8_PACKED=1 packed %zu Q8_0 matrices for decode (+%.1f MiB)\n",
621                         packed_count, packed_bytes / 1048576.0);
622        scratch_ = scratch.release();
623        bytes_ = total + hc_q8_bytes;
624        layer_bytes_ = std::move(per_layer);
625        allocated_ = allocated;
626        if (hc_q8_skipped != 0 && strata::core::manifest::enabled())   // STRATA_MANIFEST: what the stage filter did not copy
627            strata::core::manifest::instance().tensors("dense_hc_q8_out_of_stage_not_copied", "Q8_0", hc_q8_skipped, hc_q8_skipped_bytes);
628        if (hc_q8_env())
629            std::fprintf(stderr, "strata: STRATA_HC_Q8=1: %.2f GiB of Q8_0 hyper-connection projections for the verify read\n",
630                         (double) hc_q8_bytes / 1073741824.0);
631        return true;
632    } catch (const std::exception& error) {
633        err = std::string("native dense: ") + error.what();
634        return false;
635    }
636}
637bool NativeDense::gguf_carries_q8_hc(const std::vector<std::string>& shards) {
638    try {
639        for (const auto& path : shards) {
640            const strata::GgufFile g(path);
641            for (const auto& tensor : g.tensors())
642                if (tensor.type == 8 && tensor.shape.size() == 2 && hc_q8_name(tensor.name) && !tensor.name.ends_with("_inject.weight")) return true;
643        }
644    } catch (const std::exception&) {}
645    return false;
646}
647
648bool NativeDense::apply_hc_q8_default(const std::vector<std::string>& shards) {
649    if (std::getenv("STRATA_HC_Q8") != nullptr || !gguf_carries_q8_hc(shards)) return false;
650#if defined(_WIN32)
651    _putenv_s("STRATA_HC_Q8", "1");
652#else
653    setenv("STRATA_HC_Q8", "1", 0);
654#endif
655    return true;
656}
657
658bool NativeDense::hc_q8_requested() { return hc_q8_env(); }
659
660bool NativeDense::add_hc_skip(const std::string& pack_dir, std::set<std::string>& skip) {
661    std::FILE* f = std::fopen((pack_dir + "/index.txt").c_str(), "rb");
662    if (!f) return false;
663    char line[1024], name[256];
664    while (std::fgets(line, sizeof line, f)) {
665        if (line[0] == '#' || std::sscanf(line, "%255s", name) != 1) continue;
666        const std::string n = name;
667        if (n.rfind("blk.", 0) == 0 && hc_q8_name(n) && (n.ends_with("_down.weight") || n.ends_with("_up.weight"))) skip.insert(n);
668    }
669    std::fclose(f);
670    return true;
671}
672
673const uint16_t* NativeDense::hc_bf16_view(const WeightRef& w, void* stream, int slot, int cls) {
674    if (w.data != nullptr) return (const uint16_t*) w.data;
675    if (w.hc_q8 == nullptr) return nullptr;
676    // the device's scratch (allocated at load, one pair per device): the prompt path and the single-token read run one
677    // after the other on a device, and each use is stream-ordered after the previous GEMM that read the slot
678    int dev = 0;
679    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64 || slot < 0 || slot > 1 || cls < 0 || cls > 1) return nullptr;
680    void* buf = g_hc_scratch[dev][cls][slot];
681    if (buf == nullptr) return nullptr;
682    // the prompt path: the scratch may still be read by a GEMM another stream enqueued (batch serving: several slots' prompts)
683    if (cls == 0 && g_hc_ev_set[dev][slot]) cudaStreamWaitEvent((cudaStream_t) stream, g_hc_ev[dev][slot], 0);
684    strata::kernels::fused_gr_dequant_q8_0((const uint8_t*) w.hc_q8, (uint16_t*) buf, w.elements / 32, stream);
685    return (const uint16_t*) buf;
686}
687
688void NativeDense::hc_bf16_release(void* stream, int slot, int cls) {
689    int dev = 0;
690    if (cls != 0 || slot < 0 || slot > 1 || cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64 || g_hc_ev[dev][slot] == nullptr) return;
691    cudaEventRecord(g_hc_ev[dev][slot], (cudaStream_t) stream);
692    g_hc_ev_set[dev][slot] = true;
693}
694} // namespace strata::core