From 8b3ec44b1db2b2c66b43f9bd90ceaf446dc3a2b6 Mon Sep 17 00:00:00 2001 From: hokar3361 <80492699+hokar3361@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:51:30 +0900 Subject: [PATCH] metal: wrap a model bigger than maxBufferLength as overlapping no-copy buffers (64 GB Macs keep IQ3_XXS resident); MoE kernels bound per layer --- metal/src/engine/prompt_chain.inc | 5 +-- metal/src/engine/window.cpp | 33 +++++++++++++++--- metal/src/mtl_rt.h | 9 ++++- metal/src/mtl_rt.mm | 57 ++++++++++++++++++++++++++++--- 4 files changed, 92 insertions(+), 12 deletions(-) diff --git a/metal/src/engine/prompt_chain.inc b/metal/src/engine/prompt_chain.inc index 573b460e..39efd5e6 100644 --- a/metal/src/engine/prompt_chain.inc +++ b/metal/src/engine/prompt_chain.inc @@ -288,6 +288,7 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& N, NFF}; ma.gu_stride = (uint64_t) ma.gu_row * NFF; ma.d_stride = (uint64_t) ma.d_row * N; + const size_t ebase = moe_rebase(ma.gate_off, ma.up_off, ma.down_off); const uint32_t ne = N; mtl::Dispatch g; g.p = P_(b.lib, "mm_gather"); @@ -305,7 +306,7 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& const std::string fn = "mm_gu2_" + std::to_string(eg.type) + gu2_tile(eg.type); gu.p = P_(b.lib, fn, mtl::Constants().i(5, 0), fn + "#p0"); } - gu.args = {mtl::Arg::B(W_), mtl::Arg::B(b.XS), mtl::Arg::B(b.HS), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)}; + gu.args = {mtl::Arg::B(W_, ebase), mtl::Arg::B(b.XS), mtl::Arg::B(b.HS), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)}; gu.tg[0] = b.k4 ? 32 * b.gu3[3] : 64; gu.indirect = &b.meta; gu.ind_off = 2 * 4; @@ -317,7 +318,7 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string& } else { dn.p = P_(b.lib, "mm_down2_" + std::to_string(ed.type) + dn2_tile(ed.type)); } - dn.args = {mtl::Arg::B(W_), mtl::Arg::B(b.HS), mtl::Arg::B(b.YE), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)}; + dn.args = {mtl::Arg::B(W_, ebase), mtl::Arg::B(b.HS), mtl::Arg::B(b.YE), mtl::Arg::B(b.tiles), mtl::Arg::V(ma)}; dn.tg[0] = b.k4 ? 32 * b.dn3[3] : 64; dn.indirect = &b.meta; dn.ind_off = 5 * 4; diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cpp index 9a6d1d32..c652a956 100644 --- a/metal/src/engine/window.cpp +++ b/metal/src/engine/window.cpp @@ -207,6 +207,14 @@ private: gguf::File f_; std::unique_ptr cx_; mtl::Buffer W_; + // a model wrapped in chunks (mtl::Context::wrap): the routed experts are bound at the layer's first expert tensor, + // their offsets made relative to it; returns that binding offset (0 when W_ is one buffer or the experts stream) + size_t moe_rebase(uint64_t& g, uint64_t& u, uint64_t& d) const { + if (stream_ || !W_.chunks) return 0; + const uint64_t b = std::min({g, u, d}); + g -= b; u -= b; d -= b; + return (size_t) b; + } int lib_ = -1, lgdn_ = -1, lqsa_ = -1, lsmp_ = -1, lple_ = -1; std::map pcache_; bool nb_ = false; @@ -431,7 +439,20 @@ bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionSta if (!st_->open(f_, err)) return false; } else { madvise(f_.map, f_.map_bytes, MADV_WILLNEED); - W_ = cx_->wrap(f_.map, f_.map_bytes); + // the chunks of a model bigger than one Metal buffer overlap by the largest range bound at one offset: a tensor, + // or a layer's routed experts (gate, up and down, bound together at the first of them: moe_rebase) + size_t span = 0; + for (const auto& kv : f_.tensors) span = std::max(span, kv.second.bytes); + for (int l = 0; l < 48; ++l) { + const std::string b = "blk." + std::to_string(l) + "."; + const gguf::Tensor *g = f_.find(b + "ffn_gate_exps.weight"), *u = f_.find(b + "ffn_up_exps.weight"), + *d = f_.find(b + "ffn_down_exps.weight"); + if (!g || !u || !d) continue; + const uint64_t lo = std::min({g->offset, u->offset, d->offset}); + const uint64_t hi = std::max({g->offset + g->bytes, u->offset + u->bytes, d->offset + d->bytes}); + span = std::max(span, hi - lo); + } + W_ = cx_->wrap(f_.map, f_.map_bytes, span); if (W_.handle == nullptr) { err = "metal window: cannot wrap " + shard1 + " as a Metal buffer"; return false; } } n_vocab_ = (int64_t) T("output.weight").shape[1]; @@ -793,6 +814,7 @@ void Window::layer(std::vector& ds, int l, int ntok, int64_t pos0 a.up_off = st_->up_in_slot(l); a.down_off = st_->down_in_slot(l); } + const size_t ebase = moe_rebase(a.gate_off, a.up_off, a.down_off); a.gu_row = (uint32_t) ref::row_bytes(tg_.type, N); a.d_row = (uint32_t) ref::row_bytes(td.type, NFF); a.gu_stride = (uint64_t) a.gu_row * NFF; @@ -851,7 +873,7 @@ void Window::layer(std::vector& ds, int l, int ntok, int64_t pos0 ac.b(23, ct); const std::string ak = std::string(stream_ ? "#arena" : "") + (ct ? "#ct" : ""); g.p = P(lib_, gun, ac, gun + ak); - g.args = {mtl::Arg::B(EW), mtl::Arg::B(XF_.b, XF_.plane_bytes() * xkind(tg_.type)), mtl::Arg::B(h_), mtl::Arg::B(plan_), + g.args = {mtl::Arg::B(EW, ebase), mtl::Arg::B(XF_.b, XF_.plane_bytes() * xkind(tg_.type)), mtl::Arg::B(h_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(XF_.b, XF_.plane_bytes() * 4)}; if (stream_) for (int c = -1; c < 3; ++c) @@ -865,7 +887,7 @@ void Window::layer(std::vector& ds, int l, int ntok, int64_t pos0 gemv(ds, T(b + "ffn_down_shexp.weight"), XH_, ysh_, N, ntok); mtl::Dispatch dd; dd.p = P(lib_, dnn, ac, dnn + ak); - dd.args = {mtl::Arg::B(EW), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(h_)}; + dd.args = {mtl::Arg::B(EW, ebase), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(h_)}; if (stream_) for (int c = -1; c < 3; ++c) dd.args.push_back(c < 0 ? mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4) : mtl::Arg::B(st_->chunk(c + 1))); @@ -2314,6 +2336,7 @@ bool Window::prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::stri ma.gu_stride = (uint64_t) ma.gu_row * NFF; ma.d_stride = (uint64_t) ma.d_row * N; if (stream_) { ma.gate_off = 0; ma.up_off = st_->up_in_slot(l); ma.down_off = st_->down_in_slot(l); } + const size_t ebase = moe_rebase(ma.gate_off, ma.up_off, ma.down_off); const uint32_t ne_ = N; { mtl::Dispatch g; @@ -2345,7 +2368,7 @@ bool Window::prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::stri gu.p = PP(p.lib, fn, c, fn + ak); gu.tg[0] = 64; } - gu.args = {mtl::Arg::B(EW), mtl::Arg::B(p.XS), mtl::Arg::B(p.HS), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)}; + gu.args = {mtl::Arg::B(EW, ebase), mtl::Arg::B(p.XS), mtl::Arg::B(p.HS), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)}; arena_args(gu); gu.indirect = &p.meta; gu.ind_off = 2 * 4; @@ -2365,7 +2388,7 @@ bool Window::prompt_chunk(const int32_t* tokens, int Tn, int64_t pos0, std::stri dn.p = PP(p.lib, fn, c, fn + ak); dn.tg[0] = 64; } - dn.args = {mtl::Arg::B(EW), mtl::Arg::B(p.HS), mtl::Arg::B(p.YE), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)}; + dn.args = {mtl::Arg::B(EW, ebase), mtl::Arg::B(p.HS), mtl::Arg::B(p.YE), mtl::Arg::B(p.tiles), mtl::Arg::V(ma)}; arena_args(dn); dn.indirect = &p.meta; dn.ind_off = 5 * 4; diff --git a/metal/src/mtl_rt.h b/metal/src/mtl_rt.h index e5d72592..6bd3bfac 100644 --- a/metal/src/mtl_rt.h +++ b/metal/src/mtl_rt.h @@ -9,15 +9,19 @@ #include #include #include +#include #include #include namespace mtl { struct Buffer { - void* handle = nullptr; // id (retained) + void* handle = nullptr; // id (retained); the first chunk of a chunked buffer void* ptr = nullptr; // CPU address (shared storage) size_t bytes = 0; + // a buffer longer than maxBufferLength: overlapping chunks every `stride` bytes (see Context::wrap) + std::shared_ptr> chunks; + size_t stride = 0; template T* as() const { return static_cast(ptr); } }; @@ -89,6 +93,9 @@ public: Buffer alloc(size_t bytes); // shared storage, zeroed Buffer wrap(void* page_aligned, size_t bytes); // no-copy wrap (page-aligned, size multiple of page) + // the same, also when bytes > maxBufferLength: then overlapping chunks, each holding any range of up to + // max_span bytes that starts in it (max_span = the largest tensor bound at one offset) + Buffer wrap(void* page_aligned, size_t bytes, size_t max_span); void free(Buffer& b); // Encodes `ds` into ONE compute encoder (serial or concurrent dispatch type) and ONE command buffer, `reps` diff --git a/metal/src/mtl_rt.mm b/metal/src/mtl_rt.mm index 4c6045b2..6b72f686 100644 --- a/metal/src/mtl_rt.mm +++ b/metal/src/mtl_rt.mm @@ -36,6 +36,13 @@ struct Context::Impl { }; static inline id B(const Buffer& b) { return (__bridge id)b.handle; } +// the MTLBuffer and offset that bind byte `off` of b (a chunked buffer: the chunk the offset selects) +static inline id BO(const Buffer& b, size_t off, size_t& o) { + if (!b.chunks) { o = off; return B(b); } + const size_t k = std::min(off / b.stride, b.chunks->size() - 1); + o = off - k * b.stride; + return (__bridge id)(*b.chunks)[k]; +} static inline id P(const Pipeline* p) { return (__bridge id)p->handle; } static std::string g_device_name = "unknown GPU"; @@ -183,6 +190,38 @@ Buffer Context::alloc(size_t bytes) { return r; } +Buffer Context::wrap(void* p, size_t bytes, size_t max_span) { + const size_t pg = 16384, maxlen = [impl_->dev maxBufferLength] / pg * pg; + if (bytes <= maxlen || std::getenv("STRATA_METAL_WRAP_SPLIT") && std::string(std::getenv("STRATA_METAL_WRAP_SPLIT")) == "0") + return wrap(p, bytes); + const size_t span = (max_span + pg - 1) / pg * pg; + if (span >= maxlen / 2) { + std::fprintf(stderr, "mtl: wrap %zu: a tensor of %zu bytes does not fit the chunks\n", bytes, max_span); + std::exit(4); + } + Buffer r; + r.chunks = std::make_shared>(); + r.stride = maxlen - span; + for (size_t base = 0; base < bytes; base += r.stride) { + const size_t len = std::min(maxlen, (bytes - base + pg - 1) / pg * pg); + id b = [impl_->dev newBufferWithBytesNoCopy:(uint8_t*) p + base length:len + options:MTLResourceStorageModeShared deallocator:nil]; + if (!b) { + std::fprintf(stderr, "mtl: wrap chunk %zu+%zu failed\n", base, len); + std::exit(4); + } + r.chunks->push_back((__bridge_retained void*)b); + if (base + len >= bytes) break; + } + allocated_ += bytes; + r.handle = (*r.chunks)[0]; + r.ptr = p; + r.bytes = bytes; + std::fprintf(stderr, "mtl: wrapped %.2f GB as %zu overlapping buffers (maxBufferLength %.2f GB, overlap %.2f GB)\n", + bytes / 1e9, r.chunks->size(), maxlen / 1e9, span / 1e9); + return r; +} + Buffer Context::wrap(void* p, size_t bytes) { id b = [impl_->dev newBufferWithBytesNoCopy:p length:bytes options:MTLResourceStorageModeShared deallocator:nil]; if (!b) { @@ -198,6 +237,11 @@ Buffer Context::wrap(void* p, size_t bytes) { } void Context::free(Buffer& b) { + if (b.chunks) { + for (void* h : *b.chunks) { id x = (__bridge_transfer id)h; x = nil; } + b = Buffer{}; + return; + } if (b.handle) { id x = (__bridge_transfer id)b.handle; x = nil; @@ -210,8 +254,11 @@ static void encode(id enc, const Dispatch& d) { [enc setComputePipelineState:P(d.p)]; for (size_t i = 0; i < d.args.size(); ++i) { const Arg& a = d.args[i]; - if (a.buf) - [enc setBuffer:B(*a.buf) offset:a.off atIndex:i]; + if (a.buf) { + size_t o; + id mb = BO(*a.buf, a.off, o); + [enc setBuffer:mb offset:o atIndex:i]; + } else [enc setBytes:a.bytes.data() length:a.bytes.size() atIndex:i]; } @@ -352,8 +399,10 @@ double Context::run_icb(const std::vector& ds, int reps, bool barrier_ std::fprintf(stderr, "mtl: run_icb needs buffer arguments only\n"); std::exit(5); } - [c setKernelBuffer:B(*d.args[a].buf) offset:d.args[a].off atIndex:a]; - [used addObject:B(*d.args[a].buf)]; + size_t o; + id mb = BO(*d.args[a].buf, d.args[a].off, o); + [c setKernelBuffer:mb offset:o atIndex:a]; + [used addObject:mb]; } if (d.tg_mem) [c setThreadgroupMemoryLength:(d.tg_mem + 15) / 16 * 16 atIndex:0]; [c concurrentDispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2])