okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
9.0 KiB152 linesraw
1// metal/src/mtl_rt.h - a thin C++ face over Metal for the standalone kernel programs (parity, benches).
2//
3// The implementation (mtl_rt.mm) is the only Objective-C++ file; every program and test is plain C++ against this
4// header.  Kernels are MSL source files compiled at run time (newLibraryWithSource): the Command Line Tools have no
5// offline `metal` compiler, and the runtime compiler is part of the OS.  ggml-common.h (MIT, third_party/ggml) is
6// prepended for the i-quant grids and block structs.
7#pragma once
8
9#include <cstddef>
10#include <cstdint>
11#include <cstring>
12#include <memory>
13#include <string>
14#include <vector>
15
16namespace mtl {
17
18struct Buffer {
19    void* handle = nullptr;   // id<MTLBuffer> (retained); the first chunk of a chunked buffer
20    void* ptr = nullptr;      // CPU address (shared storage)
21    size_t bytes = 0;
22    // a buffer longer than maxBufferLength: overlapping chunks every `stride` bytes (see Context::wrap)
23    std::shared_ptr<std::vector<void*>> chunks;
24    size_t stride = 0;
25    size_t bias = 0;          // bytes from the MTLBuffer's start to ptr (a view onto an allocation the runtime owns)
26    template <class T> T* as() const { return static_cast<T*>(ptr); }
27};
28
29struct Pipeline {
30    void* handle = nullptr;   // id<MTLComputePipelineState>
31    int max_threads = 0;      // maxTotalThreadsPerThreadgroup
32    int simd_width = 0;       // threadExecutionWidth
33    int static_tg_mem = 0;    // staticThreadgroupMemoryLength
34    std::string name;         // the function (+ its constants), for messages
35};
36
37// A function-constant value set (index -> int / bool / uint).
38struct Constants {
39    struct V { int index; int type; uint32_t v; };  // type 0 int, 1 bool, 2 uint, 3 short, 4 ushort
40    std::vector<V> vals;
41    Constants& i(int idx, int v) { vals.push_back({idx, 0, (uint32_t)v}); return *this; }
42    Constants& b(int idx, bool v) { vals.push_back({idx, 1, (uint32_t)v}); return *this; }
43    Constants& u(int idx, uint32_t v) { vals.push_back({idx, 2, v}); return *this; }
44};
45
46struct Arg {           // one argument of a dispatch: a buffer (+ offset) or inline bytes
47    const Buffer* buf = nullptr;
48    size_t off = 0;
49    std::vector<uint8_t> bytes;
50    static Arg B(const Buffer& b, size_t off = 0) { Arg a; a.buf = &b; a.off = off; return a; }
51    template <class T> static Arg V(const T& v) {
52        Arg a; a.bytes.resize(sizeof(T)); std::memcpy(a.bytes.data(), &v, sizeof(T)); return a;
53    }
54};
55
56struct Dispatch {
57    const Pipeline* p = nullptr;
58    std::vector<Arg> args;
59    uint32_t grid[3] = {1, 1, 1};     // threadgroups
60    uint32_t tg[3] = {32, 1, 1};      // threads per threadgroup
61    uint32_t tg_mem = 0;              // dynamic threadgroup memory at index 0 (bytes)
62    const Buffer* indirect = nullptr; // grid from a GPU buffer (3 x uint32 threadgroup counts) at ind_off
63    size_t ind_off = 0;
64    bool barrier = true;              // run_graph: a buffer memory barrier before this dispatch
65};
66
67// A pipeline whose maxTotalThreadsPerThreadgroup is below the threadgroup size a dispatch asks for is NOT executed by
68// Metal and raises no error (0.1.44, #2323: gdn_step needs 512 threads, an M2 Max gave 448 for the GDN_NTOK >= 2
69// specializations - the layers silently kept their old outputs and every answer was garbage).  So every dispatch is
70// checked: too few threads is fatal, with a message that names the kernel, the limit and the size needed.
71// STRATA_METAL_MAX_THREADS_CAP=N lowers every pipeline's reported limit to N (a test hook: it proves this check).
72void require_fit(const Pipeline& p, uint32_t threads, const char* where);
73inline void require_fit(const Dispatch& d, const char* where = "dispatch") {
74    require_fit(*d.p, d.tg[0] * d.tg[1] * d.tg[2], where);
75}
76
77class Context {
78public:
79    Context();
80    ~Context();
81    std::string device_name() const;
82    bool has_family_apple(int n) const;          // MTLGPUFamilyApple<n>
83    bool supports_metal4() const;
84    uint64_t recommended_working_set() const;
85    uint64_t max_buffer_length() const;
86    // Zero-copy weights: the GPU address of host memory [p, p + bytes) (file-backed pages of the model, RAM slots) through a
87    // no-copy buffer over the pages it spans, made resident.  0: not mappable (the cap on buffers is reached, or the pages are not
88    // ours).  The first dispatch that reads cold pages waits for them (the buffer is wired on use).
89    uint64_t zc_map(const void* p, size_t bytes);
90    Pipeline pipeline_uncached(int lib, const std::string& fn, const Constants& c);
91    size_t zc_count() const;
92    uint64_t allocated() const { return allocated_; }   // bytes of alloc() + wrap() buffers so far
93
94    // Compiles a library from MSL source files (paths), prepended by `prelude` (defines) and, if include_ggml,
95    // ggml-common.h with GGML_COMMON_DECL_METAL/IMPL_METAL.  Returns a library id (index); aborts with the
96    // compiler log on error.
97    // Safe math unless STRATA_METAL_MATH=fast (the argument is ignored; kept for callers).
98    int compile(const std::vector<std::string>& files, const std::string& prelude = "", bool fast_math = false);
99    // compile() that returns -1 (the compiler's message in *why) on a failure instead of ending the process
100    int compile_try(const std::vector<std::string>& files, const std::string& prelude, bool fast_math, std::string* why);
101    Pipeline pipeline(int lib, const std::string& fn, const Constants& c = {});
102
103    Buffer alloc(size_t bytes);                  // shared storage, zeroed
104    Buffer wrap(void* page_aligned, size_t bytes);  // no-copy wrap (page-aligned, size multiple of page)
105    // the same, also when bytes > maxBufferLength: then overlapping chunks, each holding any range of up to
106    // max_span bytes that starts in it (max_span = the largest tensor bound at one offset)
107    Buffer wrap(void* page_aligned, size_t bytes, size_t max_span);
108    void free(Buffer& b);
109
110    // Encodes `ds` into ONE compute encoder (serial or concurrent dispatch type) and ONE command buffer, `reps`
111    // times over; commits and waits.  Returns the GPU time (GPUEndTime - GPUStartTime) in seconds.
112    void* mark();                 // split_runs() that returns a token for the buffer just committed (nullptr: nothing was queued)
113    void wait_mark(void* token);  // block until that buffer has completed, then drop the token
114    void drop_mark(void* token);  // drop a token without waiting (an event recorded again, or destroyed, before it was waited on)
115    void split_runs();   // commit the batched dispatches as their own command buffer, without waiting
116    void flush_runs();   // commit and wait for the dispatches batched since the last flush
117    double run(const std::vector<Dispatch>& ds, int reps = 1, bool concurrent = false, bool barrier_between = false);
118    // A dependency graph in ONE concurrent encoder: a memory barrier only before dispatches with `barrier` set, so
119    // the dispatches between two barriers may overlap.  Returns the GPU time in seconds.
120    double run_graph(const std::vector<Dispatch>& ds, size_t count = (size_t) -1);   // count: only the first `count` dispatches (the step profile's prefixes)
121    // run_graph on a SECOND queue, committed without waiting: the GPU may overlap it with work on the main queue (the two must touch
122    // different buffers).  Returns a token; wait_async(token) blocks until it has completed (returns its GPU time in seconds).
123    void* run_graph_async(const std::vector<Dispatch>& ds);
124    double wait_async(void* token);
125    // run_graph in segments: the dispatches [cuts[s-1], cuts[s]) are one concurrent encoder; after segment s (for
126    // s < cuts.size()) the GPU signals a shared event and waits until the host has run at_cut(s) - the host's turn
127    // between two parts of one committed command buffer (the SSD-streaming handshake: the routing is read, the
128    // missing experts are put in place).  Returns the GPU time in seconds.
129    double run_graph_seg(const std::vector<Dispatch>& ds, const std::vector<int>& cuts, void (*at_cut)(void*, int),
130                         void* user);
131    // One command buffer per `run_cb` call, empty or not: measures commit+wait round trips.
132    double run_wall(const std::vector<Dispatch>& ds, int reps, double* gpu_seconds = nullptr);
133
134    // Indirect command buffer: the dispatches recorded once, executed `reps` times in one command buffer.
135    // Buffers are bound per command (setKernelBuffer); inline bytes are not allowed (use buffers).
136    double run_icb(const std::vector<Dispatch>& ds, int reps, bool barrier_between);
137    // Runs `ds` repeatedly for about `seconds` of wall time: lifts the GPU out of its idle clocks before a timing.
138    void warm(const std::vector<Dispatch>& ds, double seconds = 0.3);
139
140    std::string ggml_common_path;                // where strata-quant-common.h (formerly ggml-common.h) is read from
141    std::string kernel_dir;                      // where relative kernel paths resolve
142
143private:
144    struct Impl;
145    Impl* impl_;
146    uint64_t allocated_ = 0;
147};
148
149double now_s();                                  // monotonic wall clock (seconds)
150std::string read_file(const std::string& path);
151
152}  // namespace mtl