okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
7.7 KiB133 linesraw
1// metal/src/engine/stream.h - the SSD-streaming expert arena for Macs whose memory cannot hold the model (MAC-PLAN
2// Phase 3, the small-Mac path; measured on the M4 Mac mini 32 GB, phaseA-tests/notes-mac-ssd.md).
3//
4//   * The dense weights (everything but the routed experts) are read once into one resident shared buffer; the
5//     GGUF is never wrapped as a whole (a 37.6 GB NoCopy buffer cannot be made resident in 32 GB).
6//   * The routed experts live in a resident arena of slots (one shared MTLBuffer), filled straight from the GGUF
7//     with F_NOCACHE preads: one SSD read per expert slice, no staging copy, no page cache.  smap (48 x 512 uint32:
8//     the slot's 16 KiB page in the arena, or ~0) is what the expert kernels read (moe.metal, function constant 20).
9//   * The decode window is one command buffer in 48 segments; after each layer's router the GPU signals a shared
10//     event and waits for the host (mtl_rt run_graph_seg).  The host's turn (at_layer): the window's routed experts
11//     of that layer are looked up, the missing ones read into LRU victims (several reads in flight), smap updated;
12//     then the experts the NEXT layer's router predicts from this layer's FFN input are read ahead on the I/O
13//     threads while the GPU computes.
14//   * The arena starts with the expert profile's top-ranked pairs (data/expert-profile.bin).
15// The numbers are exact: a slot holds the expert's GGUF bytes unchanged, so the answers are those of the resident
16// engine (the kernels read the same bytes at another address).
17#pragma once
18
19#include "gguf_lite.h"
20#include "mtl_rt.h"
21
22#include <functional>
23#include <atomic>
24#include <condition_variable>
25#include <cstdint>
26#include <deque>
27#include <mutex>
28#include <string>
29#include <thread>
30#include <vector>
31
32namespace strata::metal_engine {
33
34class ExpertStream {
35public:
36    ~ExpertStream();
37    // On when STRATA_METAL_STREAM=1, or (unset / auto) when the GGUF's experts do not fit in the GPU working set
38    // with room to spare.  =0: never (the whole GGUF wrapped, as on the M5 Max).
39    static bool wanted(const gguf::File& f, const mtl::Context& cx);
40    bool open(const gguf::File& f, std::string& err);
41    // pread `len` bytes at file offset `off` (F_NOCACHE)
42    bool read(void* dst, uint64_t len, uint64_t off) const;
43    // The dense tensors into one buffer; every tensor's offset in `f` is rewritten to its offset in `out`.
44    // Tensors named in `skip` are left out (their offset is set to 0: they must not be read any more).
45    bool load_dense(gguf::File& f, mtl::Context& cx, const std::vector<std::string>& skip, mtl::Buffer& out,
46                    std::string& err);
47    // The arena: `budget` bytes of slots, filled from the profile's ranking (or layer-interleaved if none).
48    // min_slots: each size class at least this many slots (576 with prompt chunks, else 64)
49    // recheck (optional): just before the arena is committed, the bytes it may have now (arena_shrink); when that is
50    // less than the arena laid out, nothing is allocated, shrink_to() says how much, and the caller tries again
51    bool make_arena(mtl::Context& cx, uint64_t budget, const std::string& profile, int min_slots, std::string& err,
52                    const std::function<uint64_t()>& recheck = {},
53                    const std::function<bool(uint64_t)>& grow = {});
54    uint64_t shrink_to() const { return shrink_to_; }
55    uint64_t arena_used_bytes() const { return arena_live_; }   // the arena's bytes in use (its retired slots left out)
56    bool ready() const { return !chunks_.empty(); }
57    // the arena's buffers (at most 4, each within the device's maxBufferLength): chunk(i) for i >= count is chunk 0
58    const mtl::Buffer& chunk(int i) const { return chunks_[(size_t) i < chunks_.size() ? (size_t) i : 0]; }
59    const mtl::Buffer& smap() const { return smap_; }
60    uint64_t up_in_slot(int l) const { return lay_[(size_t) l].gs; }
61    uint64_t down_in_slot(int l) const { return lay_[(size_t) l].gs + lay_[(size_t) l].us; }
62    // The host's turn at layer l: ids = the window's T x topk routed ids; pred = T x 512 router logits of layer l + 1
63    // computed from this layer's FFN input (nullptr: no read-ahead).
64    // pred2: layer l + 2's, from the same input (STRATA_METAL_PREFETCH2 = its top-k, 0 = off)
65    void at_layer(int l, int T, int topk, const int32_t* ids, const float* pred, const float* pred2 = nullptr);
66    int ahead2() const { return pre_k2_; }
67    // a prompt's scratch buffers inside the arena: region() places them (once), hold_region() empties and holds its
68    // slots while a prompt runs and gives them back after
69    uint8_t* region(uint64_t bytes);
70    void hold_region(bool hold);
71    void report(FILE* f) const;
72    void reset_stats();
73
74private:
75    uint64_t shrink_to_ = 0;
76    struct Lay { uint64_t g, gs, u, us, d, ds; int cls; };
77    struct Slot { int16_t layer = -1; int16_t e = -1; int prev = -1, next = -1; bool pre = false; int left = 0; uint64_t pin = 0; std::atomic<int> state{0}; };  // 0 idle, 1 queued, 2 reading
78    struct Cls { uint64_t pages = 0; int n = 0; int base = 0; int head = -1, tail = -1; };  // slot range [base, base+n)
79    struct Job { int slot; int layer, e, part; };   // part: slice * split_ + piece
80    void lru_unlink(int s);
81    void lru_front(int s);
82    void lru_back(int s);
83    int cls_of(int s) const;
84    int victim(int cls);
85    void read_part(int slot, int l, int e, int part);
86    void cancel_slot(int s);
87    void promote_slot(int s);
88    void io_main();
89    void ahead(int ln, int T, const float* pred, int K);
90    void submit(int slot, int l, int e, bool urgent);
91    void wait_slot(int s);
92    uint8_t* standalone_region(uint64_t bytes);   // the prompt's buffers as their own allocation, when no region of the arena's slots takes them
93
94    int fd_ = -1;
95    // <gguf>.experts (metal/tools/stream_experts.py): each expert's gate, up and down rows together, read with one
96    // request (cfd_ >= 0); else the GGUF's three slices.  STRATA_METAL_CONTIG=0: the GGUF always.
97    int cfd_ = -1;
98    std::vector<uint64_t> coff_;
99    std::vector<Lay> lay_;
100    std::vector<Cls> cls_;
101    std::vector<Slot> slots_;
102    std::vector<uint8_t> retired_;   // slots left unused when the stepped fill stopped at macOS's floor (never in an LRU)
103    std::vector<int32_t> where_;      // (l * 512 + e) -> slot, -1
104    std::vector<mtl::Buffer> chunks_;
105    std::vector<int> region_slots_;
106    uint8_t* region_ = nullptr;
107    uint64_t region_bytes_ = 0;
108    std::vector<uint32_t> code_;      // slot -> its smap value (chunk << 28 | page)
109    std::vector<uint8_t*> host_;      // slot -> its CPU address
110    mtl::Buffer smap_;
111    uint64_t arena_bytes_ = 0;
112    uint64_t arena_live_ = 0;
113    // the I/O threads
114    std::vector<std::thread> io_;
115    std::mutex mu_;
116    std::condition_variable cv_, done_cv_;
117    std::deque<Job> urgent_q_, pre_q_;
118    bool stop_ = false;
119    int outstanding_ = 0;
120    int nio_ = 6, pre_k_ = 10, pre_k2_ = 0, split_ = 2;
121    bool prefetch_ = true, fake_ = false, pre_mru_ = false;
122    int ne_ = 512;   // routed experts per layer of this model (512; 256 for the expert-pruned Coder), read from the GGUF at open(); stream.cpp's NE is the largest (array sizes, the 512-wide key / smap stride)
123    // stats
124    uint64_t stamp_ = 1;   // the handshake count: slots pinned with the current one are in use on the GPU
125    uint64_t p_lookups_ = 0, p_hits_ = 0, p_pre_ = 0, p_misses_ = 0, p_streamed_ = 0, p_chunks_ = 0;
126    double p_wait_ms_ = 0, p_host_ms_ = 0;
127    uint64_t lookups_ = 0, hits_ = 0, pre_hits_ = 0, late_ = 0, misses_ = 0, pre_issued_ = 0, pre_cancel_ = 0, windows_ = 0;
128    std::atomic<uint64_t> bytes_read_{0}, reads_{0};
129    double wait_ms_ = 0, host_ms_ = 0, fill_s_ = 0;
130    uint64_t fill_bytes_ = 0;
131};
132
133}  // namespace strata::metal_engine