okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-vision7c5e84612

main
13.4 KiB295 linesraw
1#define DPCT_PROFILING_ENABLED
2#include <sycl/sycl.hpp>
3#include <dpct/dpct.hpp>
4#include "strata/sycl_queue.hpp"
5#include "strata/core/native_head.hpp"
6#include "strata/artifact/gguf_reader.hpp"
7#include "strata/kernels/iq_kernels.hpp"
8#include "strata/kernels/native_mmvq.hpp"
9#include "strata/platform/memory.hpp"
10
11#include <climits>
12#include <cstdio>
13#include <cstring>
14#include <exception>
15
16namespace strata::core {
17
18NativeHead::~NativeHead() {
19    if (weights_) strata::kernels::native_q6_k_unpack(weights_);
20    if (scratch_) sycl::free(scratch_, dpct::get_in_order_queue());
21    if (weights_) sycl::free(weights_, dpct::get_in_order_queue());
22}
23
24bool NativeHead::load(const std::vector<std::string> &shards, int64_t n_in,
25                      int64_t n_out, std::string &err) try {
26    if (loaded()) { err = "native head is already loaded"; return false; }
27    if (n_in <= 0 || n_out <= 0 || n_in > INT_MAX || n_out > INT_MAX || n_in % 256) {
28        err = "native head requires positive int32 dimensions and whole 256-value rows";
29        return false;
30    }
31    try {
32        // The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2
33        // of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor).  GgufModel refuses a duplicate across shards.
34        const strata::GgufModel model(shards);
35        err = strata::check_engine_architecture(model.meta());
36        if (!err.empty()) return false;
37        size_t at = 0;
38        const strata::TensorInfo* tensor = model.find("output.weight", &at);
39        const strata::GgufFile& gguf = model.shard(at);
40        if (!tensor || !strata::kernels::native_mmvq_supported((int) tensor->type) || tensor->shape.size() != 2 ||
41            tensor->shape[0] != (uint64_t) n_in || tensor->shape[1] != (uint64_t) n_out) {
42            err = "native head: expected a natively supported output.weight with the canonical head dimensions";
43            return false;
44        }
45        const uint64_t bytes = strata::kernels::native_mmvq_weight_bytes((int) tensor->type, (int) n_in, (int) n_out);
46        const uint64_t payload = gguf.file_size() - gguf.data_start();
47        if (tensor->offset > payload || bytes > payload - tensor->offset) {
48            err = "native head: truncated output.weight payload";
49            return false;
50        }
51        void* weights = nullptr;
52        void* scratch = nullptr;
53        dpct::err0 status =
54            DPCT_CHECK_ERROR(weights = (void *)strata::malloc_device_guarded(
55                                 bytes, dpct::get_in_order_queue()));
56        if (status == 0)
57            status = DPCT_CHECK_ERROR(
58                scratch = (void *)strata::malloc_device_guarded(
59                    strata::kernels::native_q8_1_bytes((int)n_in, 1),
60                    dpct::get_in_order_queue()));
61        strata::platform::advise_willneed(gguf.tensor_data(*tensor), bytes);
62        if (status == 0)
63            status = DPCT_CHECK_ERROR(
64                dpct::get_in_order_queue()
65                    .memcpy(weights, gguf.tensor_data(*tensor), bytes)
66                    .wait());
67        /*
68        DPCT1000: Error handling if-stmt was detected but could not be
69        rewritten.
70        */
71        if (status != 0) {
72            if (scratch) sycl::free(scratch, dpct::get_in_order_queue());
73            if (weights) sycl::free(weights, dpct::get_in_order_queue());
74            /*
75            DPCT1009: SYCL reports errors using exceptions and does not use
76            error codes. Please replace the "get_error_string_dummy(...)" with a
77            real error-handling function.
78            */
79            /*
80            DPCT1001: The statement could not be removed.
81            */
82            err = std::string("native head upload: ") +
83                  dpct::get_error_string_dummy(status);
84            return false;
85        }
86        weights_ = weights;
87        scratch_ = scratch;
88        bytes_ = bytes;
89        n_in_ = (int) n_in;
90        n_out_ = (int) n_out;
91        type_ = (int) tensor->type;
92        if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled())   // STRATA_Q6_PACKED=1
93            strata::kernels::native_q6_k_pack(weights_, n_in_, n_out_, "output head");
94        if (type_ == 14 && !strata::kernels::native_q6_k_packed_enabled() && strata::kernels::native_q6_k_planar_enabled())   // STRATA_Q6_PLANAR: stored as planes (same bytes)
95            weights_ = strata::kernels::native_q6_k_planar_adopt(weights_, n_in_, n_out_, "output head");
96        return true;
97    } catch (const std::exception& error) {
98        err = std::string("native head: ") + error.what();
99        return false;
100    }
101}
102catch (sycl::exception const &exc) {
103  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
104            << ", line:" << __LINE__ << std::endl;
105  std::exit(1);
106}
107
108bool NativeHead::run(const float *mixed, float *logits, void *stream,
109                     std::string &err) const try {
110    if (!loaded() || !mixed || !logits || !stream) {
111        err = "native head requires loaded weights, device buffers and an explicit stream";
112        return false;
113    }
114    try {
115        if (type_ == 13) {
116            strata::kernels::native_q5_k_f32(weights_, mixed, scratch_, logits, n_in_, n_out_, 1, stream);
117        } else {
118            strata::kernels::native_quantize_q8_1(mixed, scratch_, n_in_, 1, stream);
119            strata::kernels::native_mmvq(type_, weights_, scratch_, logits, n_in_, n_out_, 1, stream);
120        }
121    } catch (const std::exception& error) {
122        err = std::string("native head launch: ") + error.what();
123        return false;
124    }
125    /*
126    DPCT1010: SYCL uses exceptions to report errors and does not use the
127    error codes. The cudaPeekAtLastError function call was replaced with 0. You
128    need to rewrite this code.
129    */
130    const dpct::err0 status = 0;
131    /*
132    DPCT1000: Error handling if-stmt was detected but could not be
133    rewritten.
134    */
135    if (status != 0) {
136        /*
137        DPCT1009: SYCL reports errors using exceptions and does not use
138        error codes. Please replace the "get_error_string_dummy(...)" with a
139        real error-handling function.
140        */
141        /*
142        DPCT1001: The statement could not be removed.
143        */
144        err = std::string("native head launch: ") +
145              dpct::get_error_string_dummy(status);
146        return false;
147    }
148    return true;
149}
150catch (sycl::exception const &exc) {
151  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
152            << ", line:" << __LINE__ << std::endl;
153  std::exit(1);
154}
155
156// ================================ plan v0.3 P6: THE NATIVE EMBEDDING ================================
157
158namespace {
159const NativeEmbed* g_embed = nullptr;
160}
161void set_native_embed(const NativeEmbed* e) { g_embed = e; }
162const NativeEmbed* native_embed() { return g_embed; }
163
164NativeEmbed::~NativeEmbed() {
165    if (host_) sycl::free(host_, dpct::get_in_order_queue());
166    else if (dev_)
167        sycl::free((void *) dev_, dpct::get_in_order_queue()); // the VRAM fallback below
168}
169
170bool NativeEmbed::load(const std::vector<std::string> &shards, int64_t n_embd,
171                       int64_t n_vocab, std::string &err) try {
172    try {
173        const strata::GgufModel model(shards);
174        // --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked
175        const strata::MetaValue* arch = model.meta().get("general.architecture");
176        err = arch != nullptr && arch->s == "strata-embd" ? std::string() : strata::check_engine_architecture(model.meta());
177        if (!err.empty()) { err = "native embedding: " + err; return false; }
178        size_t at = 0;
179        const strata::TensorInfo* t = model.find("token_embd.weight", &at);
180        const strata::GgufFile& gguf = model.shard(at);
181        if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) n_embd || t->shape[1] != (uint64_t) n_vocab ||
182            !strata::kernels::embed_type_supported((int) t->type) || n_embd % 256) {
183            err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU "
184                  "dequantizer";
185            return false;
186        }
187        row_ = strata::kernels::iq_row_bytes((int) t->type, n_embd);
188        bytes_ = (uint64_t) row_ * (uint64_t) n_vocab;
189        // the table is copied out of the mapping below: a truncated shard must be an error, not a read past EOF
190        if (!model.in_bounds(*t, at) || strata::tensor_payload_bytes(*t) != bytes_) {
191            err = "native embedding: token_embd.weight's payload is truncated or not " + std::to_string(bytes_) +
192                  " B (" + gguf.path() + ")";
193            bytes_ = 0;
194            return false;
195        }
196        strata::platform::advise_willneed(gguf.tensor_data(*t), bytes_);   // copied out of the mapping below
197        /*
198        DPCT1048: The original value cudaHostAllocMapped is not meaningful in
199        the migrated code and was removed or replaced with 0. You may need to
200        check the migrated code.
201        */
202        /*
203        DPCT1048: The original value cudaHostAllocPortable is not meaningful
204        in the migrated code and was removed or replaced with 0. You may need to
205        check the migrated code.
206        */
207        if (DPCT_CHECK_ERROR(host_ = (void *)sycl::malloc_host(
208                                 bytes_, dpct::get_in_order_queue())) != 0) {
209            // Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts
210            // themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM
211            // instead: it costs its size there and reads faster than over PCIe.
212            /*
213            DPCT1026: The call to cudaGetLastError was removed because this
214            functionality is redundant in SYCL.
215            */
216            host_ = nullptr;
217            void* d = nullptr;
218            if (DPCT_CHECK_ERROR(d = (void *)strata::malloc_device_guarded(
219                                     bytes_, dpct::get_in_order_queue())) !=
220                    0 ||
221                /*
222                DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
223                assuming in the original code the source host memory is pageable
224                memory. If the memory is not pageable, call wait() on event
225                return by memcpy API to ensure synchronization behavior.
226                */
227                DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(
228                    d, gguf.tensor_data(*t), bytes_).wait()) != 0) {
229                if (d) sycl::free(d, dpct::get_in_order_queue());
230                /*
231                DPCT1026: The call to cudaGetLastError was removed because
232                this functionality is redundant in SYCL.
233                */
234                err = "native embedding: cannot pin " +
235                      std::to_string(bytes_ >> 20) +
236                      " MiB, nor place it in VRAM";
237                return false;
238            }
239            std::fprintf(stderr, "strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n",
240                         (unsigned long long) (bytes_ >> 20));
241            dev_ = d;
242        } else {
243            std::memcpy(host_, gguf.tensor_data(*t), bytes_);
244            void* d = nullptr;
245#if defined(STRATA_USE_HIP)
246            // #325: the Windows HIP stack can refuse the device alias of a mapped allocation (and, when it gives
247            // one, it is the host address itself - unified addressing; kernels read it correctly there, a
248            // device-to-device copy into it does not land: tests/hip/mapped_alias). The table is only gathered from,
249            // so without an alias it goes into VRAM like the unpinnable case above, instead of failing the start.
250            if (cudaHostGetDevicePointer(&d, host_, 0) != cudaSuccess || d == nullptr) {
251                cudaGetLastError();
252                d = nullptr;
253                if (cudaMalloc(&d, bytes_) != cudaSuccess ||
254                    cudaMemcpy(d, gguf.tensor_data(*t), bytes_, cudaMemcpyHostToDevice) != cudaSuccess) {
255                    if (d) cudaFree(d);
256                    cudaGetLastError();
257                    err = "native embedding: no device alias for the mapped table, and no VRAM to copy it into";
258                    return false;
259                }
260                cudaFreeHost(host_);   // the destructor frees dev_ when host_ is null
261                host_ = nullptr;
262                std::fprintf(stderr, "strata: native embedding: no device alias for the mapped table, kept in VRAM\n");
263            }
264#else
265            if (DPCT_CHECK_ERROR(d = (void *)host_) != 0) {
266                err = "native embedding: no device alias for the mapped table";
267                return false;
268            }
269#endif
270            dev_ = d;
271        }
272        type_ = (int) t->type;
273        n_embd_ = n_embd;
274        n_vocab_ = n_vocab;
275        return true;
276    } catch (const std::exception& e) {
277        err = std::string("native embedding: ") + e.what();
278        return false;
279    }
280}
281catch (sycl::exception const &exc) {
282  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
283            << ", line:" << __LINE__ << std::endl;
284  std::exit(1);
285}
286
287void NativeEmbed::gather_dev(const int32_t* tokens, int64_t n_tok, float* out, void* stream) const {
288    strata::kernels::iq_embed_rows(type_, dev_, row_, tokens, n_tok, n_embd_, out, stream);
289}
290
291void NativeEmbed::gather_one(int64_t token, float* out, void* stream) const {
292    strata::kernels::iq_dequant_f32(type_, (const uint8_t*) dev_ + (size_t) token * row_, n_embd_, out, stream);
293}
294
295}  // namespace strata::core