okami.mom/strata

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

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

main
16.6 KiB308 linesraw
1#include "strata/core/native_head.hpp"
2#include "strata/core/spill_gate.hpp"
3#include "strata/core/run_manifest.hpp"
4#include "strata/artifact/gguf_reader.hpp"
5#include "strata/kernels/iq_kernels.hpp"
6#include "strata/kernels/native_mmvq.hpp"
7#include "strata/platform/memory.hpp"
8
9#include <cuda_runtime.h>
10#include <climits>
11#include <cstdio>
12#include <cstdlib>
13#include <cstring>
14#include <exception>
15
16namespace strata::core {
17
18NativeHead::~NativeHead() {
19    unload();
20}
21
22void NativeHead::unload() {
23    if (weights_) strata::kernels::native_q6_k_unpack(weights_);
24    if (weights_) strata::kernels::native_q8_0_sm60_release(weights_);
25    if (scratch_) cudaFree(scratch_);
26    if (host_) cudaFreeHost(host_);   // the mapped-host fallback (weights_ is its device alias)
27    else if (weights_) cudaFree(weights_);
28    scratch_ = nullptr;
29    weights_ = nullptr;
30    host_ = nullptr;
31}
32
33bool NativeHead::load(const std::vector<std::string>& shards, int64_t n_in, int64_t n_out, std::string& err) {
34    if (loaded()) { err = "native head is already loaded"; return false; }
35    if (n_in <= 0 || n_out <= 0 || n_in > INT_MAX || n_out > INT_MAX || n_in % 256) {
36        err = "native head requires positive int32 dimensions and whole 256-value rows";
37        return false;
38    }
39    try {
40        // The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2
41        // of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor).  GgufModel refuses a duplicate across shards.
42        const strata::GgufModel model(shards);
43        err = strata::check_engine_architecture(model.meta());
44        if (!err.empty()) return false;
45        size_t at = 0;
46        const strata::TensorInfo* tensor = model.find("output.weight", &at);
47        const strata::GgufFile& gguf = model.shard(at);
48        if (!tensor || !strata::kernels::native_mmvq_supported((int) tensor->type) || tensor->shape.size() != 2 ||
49            tensor->shape[0] != (uint64_t) n_in || tensor->shape[1] != (uint64_t) n_out) {
50            // opt-in head: unsupported (e.g. all-BF16 latent models) -> keep the canonical head (loaded() stays false)
51            std::fprintf(stderr, "strata generate: the native head is not loaded (output.weight unsupported/non-native); the canonical BF16 head stays\n");
52            return true;
53        }
54        const uint64_t bytes = strata::kernels::native_mmvq_weight_bytes((int) tensor->type, (int) n_in, (int) n_out);
55        const uint64_t payload = gguf.file_size() - gguf.data_start();
56        if (tensor->offset > payload || bytes > payload - tensor->offset) {
57            err = "native head: truncated output.weight payload";
58            return false;
59        }
60        void* weights = nullptr;
61        void* scratch = nullptr;
62        void* host = nullptr;
63        // SHORT OF VRAM: the head in mapped pinned host memory.  The head (about 0.4 GiB) is the one buffer a card that holds its sessions and weights but not this can
64        // spill whole; every logits row then reads it over PCIe (about 18 ms per row at 28 GB/s), so decode is slower, but the start works.  Taken only when the
65        // allocation in VRAM fails (or STRATA_HEAD_HOST=1 asks for it); the GEMV kernels read the same pointer either way.  Q5_K and the plain MMVQ types: the
66        // repacked Q6_K / SM60 layouts rewrite the weights in place and stay in VRAM.
67        const bool ask_host = std::getenv("STRATA_HEAD_HOST") != nullptr;
68        cudaError_t status = ask_host ? cudaErrorMemoryAllocation : cudaMalloc(&weights, bytes);
69        bool discrete = false;
70        { int d = 0; cudaDeviceProp pr{}; if (cudaGetDevice(&d) == cudaSuccess && cudaGetDeviceProperties(&pr, d) == cudaSuccess) discrete = strata::spill_allowed(strata::kSpillMetalBuild, pr.integrated != 0); else (void) cudaGetLastError(); }
71        if (status != cudaSuccess && discrete && std::getenv("STRATA_HEAD_HOST_OFF") == nullptr && !strata::kernels::native_q6_k_packed_enabled()) {
72            (void) cudaGetLastError();
73            void* hp = nullptr;
74            void* dp = nullptr;
75            if (cudaHostAlloc(&hp, bytes, cudaHostAllocMapped | cudaHostAllocPortable) == cudaSuccess && cudaHostGetDevicePointer(&dp, hp, 0) == cudaSuccess) {
76                std::memcpy(hp, gguf.tensor_data(*tensor), bytes);
77                host = hp;
78                weights = dp;
79                status = cudaSuccess;
80                std::fprintf(stderr, "strata generate: short of GPU memory: the output head (%llu MiB) stays in pinned host memory and is read over PCIe for every logits row: "
81                                     "decode is slower%s", (unsigned long long) (bytes >> 20), "\n");
82            } else {
83                if (hp) cudaFreeHost(hp);
84                (void) cudaGetLastError();
85            }
86        }
87        if (status == cudaSuccess)
88            status = cudaMalloc(&scratch, strata::kernels::native_q8_1_bytes((int) n_in, 1));
89        strata::platform::advise_willneed(gguf.tensor_data(*tensor), bytes);
90        if (status == cudaSuccess && host == nullptr)
91            status = cudaMemcpy(weights, gguf.tensor_data(*tensor), bytes, cudaMemcpyHostToDevice);
92        if (status != cudaSuccess) {
93            if (host) cudaFreeHost(host);
94            weights = host ? nullptr : weights;
95            if (scratch) cudaFree(scratch);
96            if (weights) cudaFree(weights);
97            err = std::string("native head upload: ") + cudaGetErrorString(status);
98            return false;
99        }
100        weights_ = weights;
101        host_ = host;
102        { int d = -1; if (cudaGetDevice(&d) == cudaSuccess) device_ = d; }
103        scratch_ = scratch;
104        bytes_ = bytes;
105        n_in_ = (int) n_in;
106        n_out_ = (int) n_out;
107        type_ = (int) tensor->type;
108        if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled())   // STRATA_Q6_PACKED=1
109            strata::kernels::native_q6_k_pack(weights_, n_in_, n_out_, "output head");
110        if (type_ == 8)   // STRATA_Q8_SM60=1 (a no-op otherwise); the MTP draft head reads the same matrix
111            strata::kernels::native_q8_0_sm60_pack(weights_, n_in_, n_out_, "output head");
112        if (strata::core::manifest::enabled()) {   // STRATA_MANIFEST: what the head holds and where
113            namespace mf = strata::core::manifest;
114            mf::instance().tensors("head", strata::ggml_type_name((uint32_t) type_), 1, bytes);
115            mf::instance().path("head", "output.weight", true,
116                                host_ != nullptr ? "held in mapped pinned host memory (short of VRAM or STRATA_HEAD_HOST)" : "held in VRAM",
117                                std::string("type ") + strata::ggml_type_name((uint32_t) type_) +
118                                    (type_ == 14 && strata::kernels::native_q6_k_packed_enabled() ? ", repacked (STRATA_Q6_PACKED)" : "") +
119                                    (type_ == 8 && std::getenv("STRATA_Q8_SM60") != nullptr ? ", repacked (STRATA_Q8_SM60)" : ""));
120        }
121        return true;
122    } catch (const std::exception& error) {
123        err = std::string("native head: ") + error.what();
124        return false;
125    }
126}
127
128bool NativeHead::to_host(std::string& err) {
129    if (weights_ == nullptr || host_ != nullptr || (type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) || (type_ == 8 && std::getenv("STRATA_Q8_SM60") != nullptr)) return false;   // (repacked in place: those stay in VRAM)
130    { int d = 0; cudaDeviceProp pr{}; if (cudaGetDevice(&d) != cudaSuccess || cudaGetDeviceProperties(&pr, d) != cudaSuccess || !strata::spill_allowed(strata::kSpillMetalBuild, pr.integrated != 0)) { (void) cudaGetLastError(); return false; } }   // (Q6_K / Q8_0 may be repacked in place: those stay)
131    void* hp = nullptr;
132    void* dp = nullptr;
133    if (cudaHostAlloc(&hp, bytes_, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) {
134        (void) cudaGetLastError();
135        err = "native head: no pinned host memory for the head";
136        return false;
137    }
138    if (cudaHostGetDevicePointer(&dp, hp, 0) != cudaSuccess || cudaMemcpy(hp, weights_, bytes_, cudaMemcpyDeviceToHost) != cudaSuccess) {
139        (void) cudaGetLastError();
140        cudaFreeHost(hp);
141        err = "native head: the head could not be moved to host memory";
142        return false;
143    }
144    cudaFree(weights_);
145    weights_ = dp;
146    host_ = hp;
147    return true;
148}
149
150bool NativeHead::run(const float* mixed, float* logits, void* stream, std::string& err) const {
151    if (!loaded() || !mixed || !logits || !stream) {
152        err = "native head requires loaded weights, device buffers and an explicit stream";
153        return false;
154    }
155    try {
156        if (type_ == 13) {
157            strata::kernels::native_q5_k_f32(weights_, mixed, scratch_, logits, n_in_, n_out_, 1, stream);
158        } else {
159            strata::kernels::native_quantize_q8_1(mixed, scratch_, n_in_, 1, stream);
160            strata::kernels::native_mmvq(type_, weights_, scratch_, logits, n_in_, n_out_, 1, stream);
161        }
162    } catch (const std::exception& error) {
163        err = std::string("native head launch: ") + error.what();
164        return false;
165    }
166    const cudaError_t status = cudaPeekAtLastError();
167    if (status != cudaSuccess) {
168        err = std::string("native head launch: ") + cudaGetErrorString(status);
169        return false;
170    }
171    return true;
172}
173
174// ================================ plan v0.3 P6: THE NATIVE EMBEDDING ================================
175
176namespace {
177const NativeEmbed* g_embed = nullptr;
178}
179void set_native_embed(const NativeEmbed* e) { g_embed = e; }
180const NativeEmbed* native_embed() { return g_embed; }
181
182NativeEmbed::~NativeEmbed() {
183    if (host_) cudaFreeHost(host_);
184    else if (dev_) cudaFree(const_cast<void*>(dev_));   // the VRAM fallback below
185}
186
187bool NativeEmbed::load(const std::vector<std::string>& shards, int64_t n_embd, int64_t n_vocab, std::string& err) {
188    try {
189        const strata::GgufModel model(shards);
190        // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked
191        const strata::MetaValue* arch = model.meta().get("general.architecture");
192        err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_engine_architecture(model.meta());
193        if (!err.empty()) { err = "native embedding: " + err; return false; }
194        size_t at = 0;
195        const strata::TensorInfo* t = model.find("token_embd.weight", &at);
196        const strata::GgufFile& gguf = model.shard(at);
197        if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab ||
198            !strata::kernels::embed_type_supported((int) t->type) || n_embd % 256) {
199            err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU "
200                  "dequantizer";
201            return false;
202        }
203        row_ = strata::kernels::iq_row_bytes((int) t->type, n_embd);
204        bytes_ = (uint64_t) row_ * (uint64_t) n_vocab;
205        // the table is copied out of the mapping below: a truncated shard must be an error, not a read past EOF
206        if (!model.in_bounds(*t, at) || strata::tensor_payload_bytes(*t) != bytes_) {
207            err = "native embedding: token_embd.weight's payload is truncated or not " + std::to_string(bytes_) +
208                  " B (" + gguf.path() + ")";
209            bytes_ = 0;
210            return false;
211        }
212        strata::platform::advise_willneed(gguf.tensor_data(*t), bytes_);   // copied out of the mapping below
213        // STRATA_EMBED_VRAM=1: the table in the current device's VRAM instead of mapped host memory. The same
214        // bytes, read by the same gather kernels through dev_ (bitwise the same rows); what changes is where a
215        // prompt's scattered row reads go: over a PCIe Gen2 x4 link they cost more than the table's size in VRAM
216        // is worth. Taken only with the table plus 512 MiB free; otherwise, or when the upload fails, the mapped
217        // placement below is used as before (and the fallback is said).
218        if (const char* ev = std::getenv("STRATA_EMBED_VRAM"); ev != nullptr && ev[0] == '1') {
219            size_t free_b = 0, total_b = 0;
220            const bool have_free = cudaMemGetInfo(&free_b, &total_b) == cudaSuccess;
221            void* d = nullptr;
222            if (have_free && (uint64_t) free_b > bytes_ + ((uint64_t) 512 << 20) &&
223                cudaMalloc(&d, bytes_) == cudaSuccess) {
224                if (cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) == cudaSuccess) {
225                    std::fprintf(stderr, "strata: native embedding: STRATA_EMBED_VRAM=1: %llu MiB placed in VRAM "
226                                         "(%llu MiB were free)\n",
227                                 (unsigned long long) (bytes_ >> 20), (unsigned long long) (free_b >> 20));
228                    dev_ = d;   // host_ stays null: the destructor frees dev_
229                    type_ = (int) t->type;
230                    n_embd_ = n_embd;
231                    n_vocab_ = n_vocab;
232                    return true;
233                }
234                (void) cudaFree(d);
235            }
236            (void) cudaGetLastError();
237            std::fprintf(stderr, "strata: native embedding: STRATA_EMBED_VRAM=1 not taken (%llu MiB free, the table "
238                                 "needs %llu MiB plus 512 MiB): kept in mapped host memory\n",
239                         (unsigned long long) (have_free ? free_b >> 20 : 0), (unsigned long long) (bytes_ >> 20));
240        }
241        cudaError_t host_err = cudaHostAlloc(&host_, bytes_, cudaHostAllocMapped | cudaHostAllocPortable);
242        if (host_err != cudaSuccess) {
243            // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts
244            // themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM
245            // instead: it costs its size there and reads faster than over PCIe.
246            cudaGetLastError();
247            host_ = nullptr;
248            void* d = nullptr;
249            if (cudaMalloc(&d, bytes_) != cudaSuccess ||
250                cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) {
251                if (d) cudaFree(d);
252                cudaGetLastError();
253                err = "native embedding: cannot pin " + std::to_string(bytes_ >> 20) + " MiB: " +
254                      cudaGetErrorString(host_err) + ", nor place it in VRAM";
255                return false;
256            }
257            std::fprintf(stderr, "strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n",
258                         (unsigned long long) (bytes_ >> 20));
259            dev_ = d;
260        } else {
261            std::memcpy(host_, gguf.tensor_data(*t), bytes_);
262            void* d = nullptr;
263#if defined(STRATA_USE_HIP)
264            // #325: the Windows HIP stack can refuse the device alias of a mapped allocation (and, when it gives
265            // one, it is the host address itself - unified addressing; kernels read it correctly there, a
266            // device-to-device copy into it does not land: tests/hip/mapped_alias). The table is only gathered from,
267            // so without an alias it goes into VRAM like the unpinnable case above, instead of failing the start.
268            if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess || d == nullptr) {
269                cudaGetLastError();
270                d = nullptr;
271                if (cudaMalloc(&d, bytes_) != cudaSuccess ||
272                    cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) {
273                    if (d) cudaFree(d);
274                    cudaGetLastError();
275                    err = "native embedding: no device alias for the mapped table, and no VRAM to copy it into";
276                    return false;
277                }
278                cudaFreeHost(host_);   // the destructor frees dev_ when host_ is null
279                host_ = nullptr;
280                std::fprintf(stderr, "strata: native embedding: no device alias for the mapped table, kept in VRAM\n");
281            }
282#else
283            if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess) {
284                err = "native embedding: no device alias for the mapped table";
285                return false;
286            }
287#endif
288            dev_ = d;
289        }
290        type_ = (int) t->type;
291        n_embd_ = n_embd;
292        n_vocab_ = n_vocab;
293        return true;
294    } catch (const std::exception& e) {
295        err = std::string("native embedding: ") + e.what();
296        return false;
297    }
298}
299
300void NativeEmbed::gather_dev(const int32_t* tokens, int64_t n_tok, float* out, void* stream) const {
301    strata::kernels::iq_embed_rows(type_, dev_, row_, tokens, n_tok, n_embd_, out, stream);
302}
303
304void NativeEmbed::gather_one(int64_t token, float* out, void* stream) const {
305    strata::kernels::iq_dequant_f32(type_, (const uint8_t*) dev_ + (size_t) token * row_, n_embd_, out, stream);
306}
307
308}  // namespace strata::core