okami.mom/strata

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

Niko1221Merge f-sycl-prs e106b4c86 into the batch 16 candidate (SYCL pull requests 4185 and 3153)a8a51b280

main
13.5 KiB301 linesraw
1// src/core/gguf_expert_source.cpp - see the header. Plain C++, no device code.
2#include "strata/core/gguf_expert_source.hpp"
3#include "strata/kernels/cpu/expert_layout.hpp"
4#include "b60_layout_state.hpp"
5
6#include <algorithm>
7#include <atomic>
8#include <cstring>
9#include <utility>
10#include <fcntl.h>
11#include <unistd.h>
12#include <dpct/dpct.hpp>
13#include <sycl/sycl.hpp>
14#include <thread>
15#include <atomic>
16#include <algorithm>
17#include <utility>
18#include <stdexcept>
19
20namespace strata::core {
21
22namespace {
23constexpr size_t kRing = 512;   // blobs alive at once: the prompt path holds a layer's worth of streamed experts
24}
25
26GgufExpertSource::~GgufExpertSource() { close(); }
27
28void GgufExpertSource::close() {
29    for (uint8_t* c : mirror_chunks_) if (c) sycl::free(c, dpct::get_in_order_queue());
30    mirror_chunks_.clear();
31    mirror_bytes_ = 0; mirror_ptr_.clear(); layer_first_.clear();
32    for (int fd : fds_) if (fd >= 0) ::close(fd);
33    fds_.clear(); names_.clear(); layer_fd_.clear(); ring_.clear(); ring_key_.clear(); where_.clear();
34    ring_next_ = 0;
35}
36
37bool GgufExpertSource::open(const std::string& shard1, int64_t n_layers, int64_t n_expert, std::string& err) {
38    close();
39    const auto& lay = strata::kernels::cpu::expert_layout();
40    if (!lay.native || lay.gguf_off.size() < (size_t) (3 * n_layers)) {
41        err = "--stream-experts needs a native (IQ) pack whose native_experts.txt carries the GGUF tensor offsets";
42        return false;
43    }
44    for (int64_t l = 0; l < n_layers; ++l)
45        for (int r = 0; r < 3; ++r)
46            if (lay.gguf_off[(size_t) (3 * l + r)] == 0) {
47                err = "--stream-experts: layer " + std::to_string(l) + " has no GGUF offset for its experts";
48                return false;
49            }
50    shard_ = shard1;
51    const size_t cut = shard1.find_last_of("/\\");
52    dir_ = cut == std::string::npos ? std::string() : shard1.substr(0, cut + 1);
53    n_layers_ = n_layers;
54    n_expert_ = n_expert;
55    layer_fd_.assign((size_t) (3 * n_layers), -1);
56    for (int64_t l = 0; l < n_layers; ++l)
57        for (int r = 0; r < 3; ++r)
58            if (fd_of(l, r, err) < 0) { close(); return false; }
59    ring_.resize(kRing);
60    for (auto& b : ring_) b.resize((size_t) lay.max_blob);
61    ring_key_.assign(kRing, -1);
62    return true;
63}
64
65// The file of role `role` (0 gate, 1 up, 2 down) of `layer`. ExpertLayout::gguf_file is per layer AND role
66// (`3 * layer + role`) since upstream 0.1.31; indexing it by layer alone read a shard-2 layer from shard 1 (Swift 1.5,
67// whose layers 13-47 are in shard 2: garbage IQ1_M scales, NaN logits - 2026-10-01).
68int GgufExpertSource::fd_of(int64_t layer, int role, std::string& err) {
69    const size_t i = (size_t) (3 * layer + role);
70    if (layer_fd_[i] >= 0) return fds_[(size_t) layer_fd_[i]];
71    const auto& lay = strata::kernels::cpu::expert_layout();
72    std::string name = shard_;
73    if (lay.gguf_file.size() > i && !lay.gguf_file[i].empty()) name = dir_ + lay.gguf_file[i];
74    for (size_t k = 0; k < names_.size(); ++k)
75        if (names_[k] == name) { layer_fd_[i] = (int) k; return fds_[k]; }
76    const int fd = ::open(name.c_str(), O_RDONLY | O_CLOEXEC);
77    if (fd < 0) { err = "--stream-experts: cannot open " + name; return -1; }
78    names_.push_back(name);
79    fds_.push_back(fd);
80    layer_fd_[i] = (int) fds_.size() - 1;
81    return fd;
82}
83
84const uint8_t* GgufExpertSource::blob(int64_t layer, int64_t expert) {
85    if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_ || ring_.empty()) return nullptr;
86    if (!mirror_ptr_.empty()) {
87        const uint8_t* p = mirror_ptr_[(size_t) (layer * n_expert_ + expert)];
88        if (p != nullptr) return p;
89    }
90    const auto& lay = strata::kernels::cpu::expert_layout();
91    const auto& fm = lay.fmt[(size_t) layer];
92    const uint64_t blob = lay.bytes[(size_t) layer];
93    // the arena loader's gather, for one expert: [gate | up | down] from the three tensors
94    const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
95    const uint64_t at[3] = {0, fm.up_off, fm.down_off};
96    const int64_t key = ((int64_t) layer << 20) | expert;
97    size_t slot;
98    {
99        std::lock_guard<std::mutex> lk(mu_);
100        auto it = where_.find(key);
101        if (it != where_.end()) { ++reads_; return ring_[it->second].data(); }   // still resident
102        slot = ring_next_;
103        ring_next_ = (ring_next_ + 1) % ring_.size();
104        if (ring_key_[slot] >= 0) where_.erase(ring_key_[slot]);
105        ring_key_[slot] = key;
106        where_[key] = slot;
107    }
108    std::vector<uint8_t>& buf = ring_[slot];
109    for (int r = 0; r < 3; ++r) {
110        const int fd = fds_[(size_t) layer_fd_[(size_t) (3 * layer + r)]];
111        const uint64_t src = lay.gguf_off[(size_t) (3 * layer + r)] + per[r] * (uint64_t) expert;
112        uint64_t done = 0;
113        while (done < per[r]) {
114            const ssize_t n = ::pread(fd, buf.data() + at[r] + done, (size_t) (per[r] - done), (off_t) (src + done));
115            if (n <= 0) { std::lock_guard<std::mutex> lk(mu_); where_.erase(key); ring_key_[slot] = -1; return nullptr; }
116            done += (uint64_t) n;
117        }
118    }
119    ++reads_;
120    return buf.data();
121}
122
123int64_t GgufExpertSource::mirror(const std::vector<std::pair<int64_t, int64_t>>& pairs, uint64_t cap, int threads,
124                                 std::string& err) {
125    err.clear();
126    const auto& lay = strata::kernels::cpu::expert_layout();
127    std::vector<std::pair<int64_t, int64_t>> take;
128    uint64_t total = 0;
129    for (const auto& [l, e] : pairs) {
130        if (l < 0 || l >= n_layers_ || e < 0 || e >= n_expert_) continue;
131        const uint64_t b = (lay.bytes[(size_t) l] + 255) / 256 * 256;
132        if (b > cap - total) break;
133        take.push_back({l, e});
134        total += b;
135    }
136    if (take.empty()) return 0;
137    // Alchemist (Arc A-series) refuses a single USM host allocation past ~3 GiB (docs/INTEL.md, A750), so the mirror
138    // is built from chunks under that. Battlemage and the CUDA/HIP builds never hit the limit, but chunking is neutral
139    // for them. One chunk per (up to) 2 GiB of experts.
140    constexpr uint64_t kChunk = 2ull << 30;
141    std::vector<uint8_t*> chunks;
142    // Free every chunk unless the mirror is handed over to the object: covers an allocation failure, a failed read and
143    // any exception (a container allocation, a std::thread that cannot be created) on the way out.
144    struct ChunkCleanup {
145        std::vector<uint8_t*>& v;
146        bool armed = true;
147        ~ChunkCleanup() { if (armed) for (uint8_t* c : v) if (c) sycl::free(c, dpct::get_in_order_queue()); }
148    } cleanup{chunks};
149    std::vector<uint8_t*> ptrs(take.size(), nullptr);
150    uint64_t placed = 0;
151    uint8_t* cur = nullptr;
152    uint64_t cur_off = 0, cur_size = 0;
153    for (size_t j = 0; j < take.size(); ++j) {
154        const uint64_t b = (lay.bytes[(size_t) take[j].first] + 255) / 256 * 256;
155        if (cur == nullptr || cur_off + b > cur_size) {
156            // never smaller than one blob, so a single blob past kChunk still fits its chunk
157            const uint64_t want = std::max(b, std::min<uint64_t>(kChunk, total - placed));
158            uint8_t* nc = nullptr;
159            try {
160                nc = (uint8_t*) sycl::malloc_host((size_t) want, dpct::get_in_order_queue());
161            } catch (const sycl::exception& ex) {
162                err = std::string("mirror: ") + ex.what();
163            }
164            if (nc == nullptr) {
165                if (err.empty())
166                    err = "mirror: no pinned host memory for " + std::to_string(want >> 20) + " MiB";
167                return -1;
168            }
169            chunks.push_back(nc);
170            cur = nc; cur_off = 0; cur_size = want;
171        }
172        ptrs[j] = cur + cur_off;
173        cur_off += b;
174        placed += b;
175    }
176    std::atomic<size_t> next{0};
177    std::atomic<bool> bad{false};
178    std::vector<std::thread> ts;
179    try {
180        for (int i = 0; i < std::max(1, threads); ++i)
181            ts.emplace_back([&] {
182                for (size_t j; (j = next.fetch_add(1)) < take.size() && !bad.load();) {
183                    const auto [l, e] = take[j];
184                    if (!read_into(l, e, ptrs[j], (size_t) lay.bytes[(size_t) l])) bad.store(true);
185                }
186            });
187    } catch (...) {
188        for (auto& th : ts) if (th.joinable()) th.join();   // join before the cleanup frees, and before unwinding
189        throw;
190    }
191    for (auto& th : ts) th.join();
192    if (bad.load()) {
193        err = "mirror: reading an expert from the GGUF failed";
194        return -1;
195    }
196    for (uint8_t* c : mirror_chunks_) if (c) sycl::free(c, dpct::get_in_order_queue());
197    mirror_chunks_ = std::move(chunks);
198    cleanup.armed = false;                                  // the chunks now belong to the object
199    mirror_bytes_ = total;
200    mirror_ptr_.assign((size_t) (n_layers_ * n_expert_), nullptr);
201    layer_first_.assign((size_t) n_layers_, nullptr);
202    for (size_t j = 0; j < take.size(); ++j) {
203        const auto [l, e] = take[j];
204        mirror_ptr_[(size_t) (l * n_expert_ + e)] = ptrs[j];
205        if (layer_first_[(size_t) l] == nullptr) layer_first_[(size_t) l] = ptrs[j];
206    }
207    return (int64_t) take.size();
208}
209
210bool GgufExpertSource::pinned(int64_t layer, int64_t expert) const {
211    if (mirror_ptr_.empty() || layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_) return false;
212    return mirror_ptr_[(size_t) (layer * n_expert_ + expert)] != nullptr;
213}
214
215const uint8_t* GgufExpertSource::device_alias(int64_t layer, int64_t expert) const {
216    if (mirror_ptr_.empty() || layer < 0 || layer >= n_layers_) return nullptr;
217    if (expert >= 0 && expert < n_expert_) {
218        const uint8_t* p = mirror_ptr_[(size_t) (layer * n_expert_ + expert)];
219        if (p != nullptr) return p;
220    }
221    return layer_first_[(size_t) layer];
222}
223
224bool GgufExpertSource::read_into(int64_t layer, int64_t expert, uint8_t* dst, size_t bytes) const {
225    if (layer < 0 || layer >= n_layers_ || expert < 0 || expert >= n_expert_ || dst == nullptr) return false;
226    const auto& lay = strata::kernels::cpu::expert_layout();
227    const auto& fm = lay.fmt[(size_t) layer];
228    const uint64_t blob = lay.bytes[(size_t) layer];
229    if (bytes < blob) return false;
230    const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
231    const uint64_t at[3] = {0, fm.up_off, fm.down_off};
232    for (int r = 0; r < 3; ++r) {
233        const int fd = fds_[(size_t) layer_fd_[(size_t) (3 * layer + r)]];
234        const uint64_t src = lay.gguf_off[(size_t) (3 * layer + r)] + per[r] * (uint64_t) expert;
235        uint64_t done = 0;
236        while (done < per[r]) {
237            const ssize_t n = ::pread(fd, dst + at[r] + done, (size_t) (per[r] - done), (off_t) (src + done));
238            if (n <= 0) return false;
239            done += (uint64_t) n;
240        }
241    }
242    return true;
243}
244
245// Exchange existing host/device bytes without an additional expert blob.
246namespace {
247class MirrorCacheExchange;
248void exchange_mirror_bytes(uint8_t* device, uint8_t* mirror, size_t bytes, sycl::queue& q) {
249    if (!device || !mirror || !bytes || bytes % 16 ||
250        (reinterpret_cast<uintptr_t>(device) & 15) || (reinterpret_cast<uintptr_t>(mirror) & 15) ||
251        sycl::get_pointer_type(device, q.get_context()) != sycl::usm::alloc::device ||
252        sycl::get_pointer_type(mirror, q.get_context()) != sycl::usm::alloc::host)
253        throw std::invalid_argument("mirror cache exchange requires aligned device/host whole blobs");
254    const size_t vectors = bytes / 16;
255    auto* dp = reinterpret_cast<uint32_t*>(device);
256    auto* hp = reinterpret_cast<uint32_t*>(mirror);
257    q.parallel_for<MirrorCacheExchange>(
258        sycl::nd_range<1>((vectors + 255) / 256 * 256, 256),
259        [=](sycl::nd_item<1> item) [[sycl::reqd_sub_group_size(32)]] {
260            const size_t i = item.get_global_id(0);
261            if (i >= vectors) return;
262            sycl::uint4 old_device, old_host;
263            old_device.load(0, dp + 4 * i);
264            old_host.load(0, hp + 4 * i);
265            old_host.store(0, dp + 4 * i);
266            old_device.store(0, hp + 4 * i);
267        });
268    q.wait_and_throw();
269}
270}  // namespace
271
272bool GgufExpertSource::exchange_cached_expert(int64_t layer, int32_t incoming, int32_t outgoing,
273                                             void* device_slot, void* stream, std::string& err) {
274    if (layer < 0 || layer >= n_layers_ || incoming < 0 || outgoing < 0 ||
275        incoming >= n_expert_ || outgoing >= n_expert_ || incoming == outgoing ||
276        mirror_ptr_.empty() || !stream) {
277        err = "mirror cache exchange invalid identity"; return false;
278    }
279    const size_t in = (size_t)(layer * n_expert_ + incoming);
280    const size_t out = (size_t)(layer * n_expert_ + outgoing);
281    std::lock_guard<std::mutex> lock(mu_);
282    if (!mirror_ptr_[in] || mirror_ptr_[out]) {
283        err = "mirror cache exchange requires incoming mirror and unmirrored outgoing"; return false;
284    }
285    try {
286        auto* memory = const_cast<uint8_t*>(mirror_ptr_[in]);
287        const auto& layout = strata::kernels::cpu::expert_layout();
288        if (strata::kernels::b60_weights_packed()) {
289            const auto& f = layout.fmt.at((size_t)layer);
290            strata::kernels::b60_exchange_single_expert(static_cast<uint8_t*>(device_slot), memory,
291                f.gu_type, (size_t)f.up_off, (size_t)f.down_off, (size_t)layout.blob_bytes(layer), stream);
292        } else {
293            exchange_mirror_bytes(static_cast<uint8_t*>(device_slot), memory,
294                (size_t)layout.blob_bytes(layer), *static_cast<sycl::queue*>(stream));
295        }
296        mirror_ptr_[out] = memory;
297        mirror_ptr_[in] = nullptr;
298        return true;
299    } catch (const std::exception& e) { err = e.what(); return false; }
300}
301}  // namespace strata::core