Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Metal: gdn_step fits its launch size, every dispatch checks maxTotalThreadsPerThreadgroup, qsa_prompt compiles on macOS 26.3 (#2323)

Niko12215ce999455b30
diff --git a/metal/CMakeLists.txt b/metal/CMakeLists.txt
index 3516a9e58..d23a26fc8 100644
--- a/metal/CMakeLists.txt
+++ b/metal/CMakeLists.txt
@@ -107,7 +107,7 @@ file(GLOB STRATA_METAL_ENGINE_SOURCES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_D
add_library(strata_metal_host STATIC ${STRATA_METAL_HOST_SOURCES})
target_include_directories(strata_metal_host PUBLIC ${STRATA_ROOT}/include ${S}/core ${STRATA_ROOT}/third_party/ggml
${STRATA_GGML_DIR}/ggml/include ${STRATA_GGML_DIR}/ggml/src ${STRATA_GGML_DIR}/ggml/src/ggml-cpu)
-target_compile_definitions(strata_metal_host PUBLIC STRATA_NATIVE_EXPERTS=1 STRATA_VERSION="0.1.44-metal")
+target_compile_definitions(strata_metal_host PUBLIC STRATA_NATIVE_EXPERTS=1 STRATA_VERSION="0.1.44.1-metal")
target_compile_options(strata_metal_host PRIVATE -Wno-unused-parameter -Wno-deprecated-declarations)
target_link_libraries(strata_metal_host PUBLIC strata_gpu_metal ggml-cpu ggml-base)
diff --git a/metal/kernels/gdn.metal b/metal/kernels/gdn.metal
index c7954dfb2..516d89a47 100644
--- a/metal/kernels/gdn.metal
+++ b/metal/kernels/gdn.metal
@@ -27,7 +27,12 @@ struct GdnArgs {
// `plane` floats between planes) and the other planes and the per-16 sums are written too
};
+// The kernel is launched with IB * 128 threads (512 for gdn_step, 1024 for gdn_step8). Without the attribute the compiler
+// is free to use as many registers as the 128-row state needs and a pipeline can end up with
+// maxTotalThreadsPerThreadgroup below the launch size: an M2 Max gave 448 for the GDN_NTOK >= 2 specializations, and
+// Metal then skips the dispatch without an error (#2323). The attribute makes the compiler fit the launch size.
template <int IB>
+[[max_total_threads_per_threadgroup(IB * 128)]]
kernel void gdn_step_t(device float* state [[buffer(0)]], device float* hist [[buffer(1)]],
device const float* qkv [[buffer(2)]], device const float* alpha [[buffer(3)]],
device const float* beta [[buffer(4)]], device const float* z [[buffer(5)]],
diff --git a/metal/kernels/qsa_prompt.metal b/metal/kernels/qsa_prompt.metal
index 5b0b55d87..df7caf791 100644
--- a/metal/kernels/qsa_prompt.metal
+++ b/metal/kernels/qsa_prompt.metal
@@ -231,7 +231,11 @@ kernel void qsa_flash(device const half* qh [[buffer(0)]], device const char* kq
auto tPh = tP.template slice<32, 16>(0, 0);
auto acc = opO.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tPh)>,
__tensor_ops_detail::__remove_addrspace_t<decltype(rv)>, float>();
- auto tot = acc; // the running output; acc takes one chunk (fresh each chunk: on the M4 a run does not accumulate
+ // (a second destination tensor, not a copy of acc: the MetalPerformancePrimitives headers of macOS 26.3 cannot copy a
+ // cooperative tensor - "cannot initialize a parameter of type 'void *' with an rvalue of type 'const void *'", #2323;
+ // tot is zeroed right below, so the copy was only there for its type)
+ auto tot = opO.template get_destination_cooperative_tensor<__tensor_ops_detail::__remove_addrspace_t<decltype(tPh)>,
+ __tensor_ops_detail::__remove_addrspace_t<decltype(rv)>, float>(); // the running output; acc takes one chunk (fresh each chunk: on the M4 a run does not accumulate
// into elements rescaled in place)
for (uint16_t i = 0; i < acc.get_capacity(); ++i)
if (acc.is_valid_element(i)) tot[i] = 0.0f;
diff --git a/metal/src/engine/prompt_chain.inc b/metal/src/engine/prompt_chain.inc
index 97648094b..573b460eb 100644
--- a/metal/src/engine/prompt_chain.inc
+++ b/metal/src/engine/prompt_chain.inc
@@ -144,6 +144,7 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string&
d.args = std::move(a);
d.grid[0] = gx; d.grid[1] = gy; d.grid[2] = gz;
d.tg[0] = tg;
+ mtl::require_fit(d, "prompt-chain dispatch");
ds.push_back(std::move(d));
};
auto gemm = [&](const mtl::Buffer& A, const mtl::Buffer& B, const mtl::Buffer& Y, int M, int Nn, int K) {
diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cpp
index 5b064520b..9a6d1d325 100644
--- a/metal/src/engine/window.cpp
+++ b/metal/src/engine/window.cpp
@@ -171,6 +171,7 @@ private:
for (const auto& w : skip)
if (k.find(w) != std::string::npos) { d.indirect = nullptr; d.grid[0] = 0; break; }
}
+ mtl::require_fit(d, "engine dispatch (graph build)"); // a kernel Metal would skip silently: stop at the build, not at the first wrong answer
ds.push_back(std::move(d));
}
std::map<const mtl::Pipeline*, std::string> pkey_of_;
diff --git a/metal/src/gpu/runtime.cpp b/metal/src/gpu/runtime.cpp
index 3da2aed9e..edc311554 100644
--- a/metal/src/gpu/runtime.cpp
+++ b/metal/src/gpu/runtime.cpp
@@ -600,6 +600,27 @@ MTL::ComputePipelineState* pipeline(const char* source_name, const char* source,
Error dispatch(Stream st, MTL::ComputePipelineState* p, const void* args, size_t arg_bytes, Grid groups, Grid threads,
size_t tg_bytes) {
if (arg_bytes > 4096) return fail(kErrorInvalidValue); // setBytes limit
+ { // Metal skips a dispatch above the pipeline's maxTotalThreadsPerThreadgroup without any error (#2323): stop instead
+ const uint64_t want = (uint64_t) threads.x * threads.y * threads.z;
+ if (p && want > (uint64_t) p->maxTotalThreadsPerThreadgroup()) {
+ Runtime& r = rt();
+ std::string name = "?";
+ {
+ std::lock_guard<std::mutex> lk(r.mu);
+ for (const auto& kv : r.pipes)
+ if (kv.second == p) { name = kv.first; break; }
+ }
+ std::fprintf(stderr,
+ "strata metal: the kernel %s can run at most %lu threads per threadgroup on this GPU (%s), but the "
+ "launch asks for %lu.\nMetal skips such a dispatch without any error, so every answer would be "
+ "wrong; stopping here instead. Please report this (the GPU, macOS version and this line) at "
+ "https://github.com/Niko1221/Strata/issues . (#2323)\n",
+ name.c_str(), (unsigned long) p->maxTotalThreadsPerThreadgroup(),
+ r.dev->name()->utf8String(), (unsigned long) want);
+ std::fflush(stderr);
+ std::exit(6);
+ }
+ }
StreamImpl* s = S(st);
Op o;
o.kind = Op::Dispatch;
diff --git a/metal/src/mtl_rt.h b/metal/src/mtl_rt.h
index 60a493f8f..e5d72592a 100644
--- a/metal/src/mtl_rt.h
+++ b/metal/src/mtl_rt.h
@@ -26,6 +26,7 @@ struct Pipeline {
int max_threads = 0; // maxTotalThreadsPerThreadgroup
int simd_width = 0; // threadExecutionWidth
int static_tg_mem = 0; // staticThreadgroupMemoryLength
+ std::string name; // the function (+ its constants), for messages
};
// A function-constant value set (index -> int / bool / uint).
@@ -58,6 +59,16 @@ struct Dispatch {
bool barrier = true; // run_graph: a buffer memory barrier before this dispatch
};
+// A pipeline whose maxTotalThreadsPerThreadgroup is below the threadgroup size a dispatch asks for is NOT executed by
+// Metal and raises no error (0.1.44, #2323: gdn_step needs 512 threads, an M2 Max gave 448 for the GDN_NTOK >= 2
+// specializations - the layers silently kept their old outputs and every answer was garbage). So every dispatch is
+// checked: too few threads is fatal, with a message that names the kernel, the limit and the size needed.
+// STRATA_METAL_MAX_THREADS_CAP=N lowers every pipeline's reported limit to N (a test hook: it proves this check).
+void require_fit(const Pipeline& p, uint32_t threads, const char* where);
+inline void require_fit(const Dispatch& d, const char* where = "dispatch") {
+ require_fit(*d.p, d.tg[0] * d.tg[1] * d.tg[2], where);
+}
+
class Context {
public:
Context();
diff --git a/metal/src/mtl_rt.mm b/metal/src/mtl_rt.mm
index b85408925..4c6045b2f 100644
--- a/metal/src/mtl_rt.mm
+++ b/metal/src/mtl_rt.mm
@@ -37,6 +37,7 @@ struct Context::Impl {
static inline id<MTLBuffer> B(const Buffer& b) { return (__bridge id<MTLBuffer>)b.handle; }
static inline id<MTLComputePipelineState> P(const Pipeline* p) { return (__bridge id<MTLComputePipelineState>)p->handle; }
+static std::string g_device_name = "unknown GPU";
Context::Context() : impl_(new Impl) {
impl_->dev = MTLCreateSystemDefaultDevice();
@@ -88,7 +89,9 @@ int Context::compile(const std::vector<std::string>& files, const std::string& p
NSError* err = nil;
id<MTLLibrary> lib = [impl_->dev newLibraryWithSource:[NSString stringWithUTF8String:src.c_str()] options:o error:&err];
if (!lib) {
- std::fprintf(stderr, "mtl: compile failed:\n%s\n", [[err localizedDescription] UTF8String]);
+ std::fprintf(stderr, "mtl: compile failed (%s, macOS %s; %s):\n%s\n", [[impl_->dev name] UTF8String],
+ [[[NSProcessInfo processInfo] operatingSystemVersionString] UTF8String],
+ files.empty() ? "?" : files.back().c_str(), [[err localizedDescription] UTF8String]);
std::exit(3);
}
impl_->libs.push_back(lib);
@@ -136,11 +139,35 @@ Pipeline Context::pipeline(int lib, const std::string& fn, const Constants& c) {
Pipeline p;
p.handle = (__bridge_retained void*)ps;
p.max_threads = (int)ps.maxTotalThreadsPerThreadgroup;
+ if (const char* cap = std::getenv("STRATA_METAL_MAX_THREADS_CAP")) { // test hook, see require_fit
+ const int lim = std::atoi(cap);
+ if (lim > 0 && lim < p.max_threads) p.max_threads = lim;
+ }
p.simd_width = (int)ps.threadExecutionWidth;
p.static_tg_mem = (int)ps.staticThreadgroupMemoryLength;
+ p.name = fn;
+ if (!c.vals.empty()) {
+ p.name += "{";
+ for (size_t i = 0; i < c.vals.size(); ++i)
+ p.name += (i ? "," : "") + std::to_string(c.vals[i].index) + "=" + std::to_string((int)c.vals[i].v);
+ p.name += "}";
+ }
+ g_device_name = [[impl_->dev name] UTF8String];
return p;
}
+void require_fit(const Pipeline& p, uint32_t threads, const char* where) {
+ if (threads == 0 || (int64_t)threads <= (int64_t)p.max_threads) return;
+ std::fprintf(stderr,
+ "strata metal: the kernel %s can run at most %d threads per threadgroup on this GPU (%s), but the %s asks "
+ "for %u.\nMetal skips such a dispatch without any error, so every answer would be wrong; stopping here "
+ "instead. Please report this (the GPU, macOS version and this line) at "
+ "https://github.com/Niko1221/Strata/issues . (#2323)\n",
+ p.name.empty() ? "?" : p.name.c_str(), p.max_threads, g_device_name.c_str(), where, threads);
+ std::fflush(stderr);
+ std::exit(6);
+}
+
Buffer Context::alloc(size_t bytes) {
id<MTLBuffer> b = [impl_->dev newBufferWithLength:bytes options:MTLResourceStorageModeShared];
if (!b) {
@@ -179,6 +206,7 @@ void Context::free(Buffer& b) {
}
static void encode(id<MTLComputeCommandEncoder> enc, const Dispatch& d) {
+ require_fit(d, "dispatch");
[enc setComputePipelineState:P(d.p)];
for (size_t i = 0; i < d.args.size(); ++i) {
const Arg& a = d.args[i];
@@ -316,6 +344,7 @@ double Context::run_icb(const std::vector<Dispatch>& ds, int reps, bool barrier_
NSMutableSet* used = [NSMutableSet new];
for (size_t i = 0; i < ds.size(); ++i) {
const Dispatch& d = ds[i];
+ require_fit(d, "indirect-command dispatch");
id<MTLIndirectComputeCommand> c = [icb indirectComputeCommandAtIndex:i];
[c setComputePipelineState:P(d.p)];
for (size_t a = 0; a < d.args.size(); ++a) {
diff --git a/metal/tests/gdn_parity.cpp b/metal/tests/gdn_parity.cpp
index 0d8c1dea6..7288eb1d2 100644
--- a/metal/tests/gdn_parity.cpp
+++ b/metal/tests/gdn_parity.cpp
@@ -63,8 +63,20 @@ int main(int argc, char** argv) {
return d;
};
{
- mtl::Pipeline p1 = cx.pipeline(lib, "gdn_step", mtl::Constants().i(2, 1));
- std::printf("gdn_step pipeline: max %d threads per threadgroup (the kernel needs 512)\n", p1.max_threads);
+ // every specialization the engine launches (GDN_NTOK 1..8): an M2 Max gave 448 for ntok >= 2 (#2323)
+ const char* kn = std::getenv("GDN_IB8") ? "gdn_step8" : "gdn_step";
+ const int need = std::getenv("GDN_IB8") ? 1024 : 512;
+ int low = 0;
+ for (int nt = 1; nt <= 8; ++nt) {
+ mtl::Pipeline pn = cx.pipeline(lib, kn, mtl::Constants().i(2, nt));
+ std::printf("%s pipeline GDN_NTOK %d: max %d threads per threadgroup (the kernel needs %d)%s\n", kn, nt, pn.max_threads,
+ need, pn.max_threads < need ? " TOO FEW" : "");
+ low += pn.max_threads < need;
+ }
+ if (low) {
+ std::printf("gdn parity: %d specialization(s) cannot run with %d threads on this GPU: FAIL\n", low, need);
+ return 1;
+ }
}
if (bench) {
for (int nt : {1, 2, 3, 4}) {