metal: prompt-chain pair kernels for the Qwen4 .strata experts; converter option Q4S_DENSE=q8_0 (Compact and Balanced pass the drift gate with it)

This commit is contained in:
Niko1221 committed 2026-12-04 08:14:39 +01:00
1 parent 762a0e336d
commit c1c785bf89
4 files changed
+71 -21

No files matched your search

+10
View File
@@ -117,3 +117,13 @@ kernel void q4m_combine(device const float* ye [[buffer(0)]], device const float
const float gs = 1.0f / (1.0f + exp(-sg[t]));
bo[gid] = fma(gs, ysh[gid], s);
}
// y[t][d] = sum_k w[t][k] * ye[t * topk + k][d] (the routed experts' weighted sum of a prompt chunk; the shared expert is added by the caller); one thread per element
kernel void q4m_wsum(device const float* ye [[buffer(0)]], device const float* w [[buffer(1)]], device float* y [[buffer(2)]], constant SxArgs& a [[buffer(3)]],
uint gid [[thread_position_in_grid]]) {
const uint t = gid / a.n_embd, d = gid % a.n_embd;
if (int(t) >= a.n_tok) return;
float s = 0.0f;
for (int k = 0; k < a.topk; ++k) s += w[t * a.topk + k] * ye[((ulong)t * a.topk + k) * a.n_embd + d];
y[gid] = s;
}
+23
View File
@@ -435,6 +435,28 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string&
gemm(b.mixh, b.Wr, b.logits, nT, nexp_, N);
const uint32_t nt = (uint32_t) nT;
D(P_(b.lib, "route_topk"), {mtl::Arg::B(b.logits), mtl::Arg::B(b.ids), mtl::Arg::B(b.wts), mtl::Arg::V(nt), mtl::Arg::V((uint32_t) nexp_)}, (nT + 7) / 8, 1, 256);
if (sx_on_) {
// Qwen4 .strata routed experts for the chunk: pair kernels (q4m_moe.metal) on the router's ids / weights, the weighted sum into yr;
// the shared expert and moe_out below are the GGUF path's
if (sxp_rows_ < b.C) {
sxp_rows_ = b.C;
sxp_xr_ = cx_->alloc(4 * (size_t) b.C * N);
sxp_gu_ = cx_->alloc(4 * (size_t) b.C * TOPK * 2 * NFF);
sxp_act_ = cx_->alloc(4 * (size_t) b.C * TOPK * NFF);
sxp_ye_ = cx_->alloc(4 * (size_t) b.C * TOPK * N);
}
struct SxArgs { int32_t layer_base, topk, n_embd, n_ff, n_tok; } sa{l * nexp_, TOPK, N, NFF, nT};
const uint32_t npair = (uint32_t) nT * TOPK;
const int nn = N;
D(P_(lsx_, "q4m_fwht128"), {mtl::Arg::B(b.mixed), mtl::Arg::B(sxp_xr_), mtl::Arg::V(nn)}, (uint32_t) ((N / 128 + 3) / 4), (uint32_t) nT, 128);
D(P_(lsx_, "q4m_moe_gu"), {mtl::Arg::B(sx4_), mtl::Arg::B(sxd_), mtl::Arg::B(b.ids), mtl::Arg::B(sxp_xr_), mtl::Arg::B(sxp_gu_), mtl::Arg::V(sa)},
(uint32_t) ((2 * NFF + 3) / 4), npair, 128);
D(P_(lsx_, "q4m_moe_act"), {mtl::Arg::B(sx4_), mtl::Arg::B(sxd_), mtl::Arg::B(b.ids), mtl::Arg::B(sxp_gu_), mtl::Arg::B(sxp_act_), mtl::Arg::V(sa)},
npair, 1, (uint32_t) (32 * (NFF / 128)));
D(P_(lsx_, "q4m_moe_dn"), {mtl::Arg::B(sx4_), mtl::Arg::B(sxd_), mtl::Arg::B(b.ids), mtl::Arg::B(sxp_act_), mtl::Arg::B(sxp_ye_), mtl::Arg::V(sa)},
(uint32_t) ((N + 3) / 4), npair, 128);
D(P_(lsx_, "q4m_wsum"), {mtl::Arg::B(sxp_ye_), mtl::Arg::B(b.wts), mtl::Arg::B(b.yr), mtl::Arg::V(sa)}, (uint32_t) ((nT * N + 255) / 256), 1, 256);
} else {
const int nent = nT * TOPK, nblk = (nent + 1023) / 1024;
// this layer's tiles and the grid x each one is dispatched over, computed together (src/moe_tiles.h)
const MoeTile gu2 = gu2_tile(eg.type), dn2 = dn2_tile(ed.type);
@@ -497,6 +519,7 @@ bool Window::pc_chunk(const int64_t* tokens, int nT, int64_t pos0, std::string&
const uint32_t ca[4] = {(uint32_t) nT, N, TOPK, 0};
D(P_(b.lib, "mm_combine"), {mtl::Arg::B(b.YE), mtl::Arg::B(b.pos), mtl::Arg::B(b.sw), mtl::Arg::B(b.yr), mtl::Arg::V(ca)},
(nT * N + 255) / 256, 1, 256);
}
gemm(b.mixh, b.Wshg, b.gsh, nT, NFF, N);
gemm(b.mixh, b.Wshu, b.ush, nT, NFF, N);
const uint32_t nh = (uint32_t) nT * NFF;
+2 -1
View File
@@ -456,7 +456,8 @@ private:
// from the owner's file by q4m_moe.metal (per-expert S_K codes 1..8, FWHT-128 convention); sx_on_ replaces the window's expert dispatches
bool sx_on_ = false;
int lsx_ = -1;
mtl::Buffer sx4_, sxd_, sxr_, sgu_;
mtl::Buffer sx4_, sxd_, sxr_, sgu_, sxp_xr_, sxp_gu_, sxp_act_, sxp_ye_; // sxp_*: the prompt chunk's scratch
int sxp_rows_ = 0;
void* sx_map_ = nullptr;
size_t sx_len_ = 0;
bool sx_open(const std::string& path, std::string& err);
+36 -20
View File
@@ -12,6 +12,7 @@ sys.path.insert(0, sys.argv[1])
sys.path.insert(0, sys.argv[2])
import qwen4_strata_reader as q4s
import gguf
from gguf.quants import quantize
gguf.GGUFWriter.ggml_pad = staticmethod(lambda x, n: ((int(x) + n - 1) // n) * n) # numpy uint32 nbytes wrapped the offsets past 4 GiB
S = q4s.Strata(sys.argv[3])
@@ -57,6 +58,21 @@ def put_bf16(name, a):
n_t += 1
DENSE = os.environ.get("Q4S_DENSE", "bf16") # bf16 (default) or q8_0: the big matrices as GGML Q8_0 (half the bytes; the window's tuned Q8_0 kernels)
def put_mat(name, a):
global n_t
a = np.ascontiguousarray(a, dtype=np.float32)
if DENSE == "q8_0" and a.shape[-1] % 32 == 0:
q = np.ascontiguousarray(quantize(a, gguf.GGMLQuantizationType.Q8_0))
keep.append(q)
w.add_tensor(name, q, raw_dtype=gguf.GGMLQuantizationType.Q8_0)
n_t += 1
else:
put_bf16(name, a)
def put_f32(name, a):
global n_t
a = np.ascontiguousarray(a, dtype=np.float32)
@@ -83,23 +99,23 @@ for L in range(NL):
b = "blk.%d." % L
for hf, gg in (("attn_hyper_connection", "hc_attn"), ("mlp_hyper_connection", "hc_ffn")):
put_f32(b + gg + "_norm.weight", 1.0 + S.get(LM + p + hf + ".hc_norm.weight"))
put_bf16(b + gg + "_down.weight", dense(p + hf + ".input_mix_weight_down.weight"))
put_bf16(b + gg + "_up.weight", dense(p + hf + ".input_mix_weight_up.weight"))
put_bf16(b + gg + "_inject.weight", dense(p + hf + ".block_inject_weight.weight"))
put_mat(b + gg + "_down.weight", dense(p + hf + ".input_mix_weight_down.weight"))
put_mat(b + gg + "_up.weight", dense(p + hf + ".input_mix_weight_up.weight"))
put_mat(b + gg + "_inject.weight", dense(p + hf + ".block_inject_weight.weight"))
put_f32(b + "ffn_gate_inp.weight", S.get(LM + p + "mlp.gate.weight"))
put_f32(b + "ffn_gate_inp_shexp.weight", S.get(LM + p + "mlp.shared_expert_gate.weight").reshape(-1))
put_bf16(b + "ffn_gate_shexp.weight", dense(p + "mlp.shared_expert.gate_proj.weight"))
put_bf16(b + "ffn_up_shexp.weight", dense(p + "mlp.shared_expert.up_proj.weight"))
put_bf16(b + "ffn_down_shexp.weight", dense(p + "mlp.shared_expert.down_proj.weight"))
put_mat(b + "ffn_gate_shexp.weight", dense(p + "mlp.shared_expert.gate_proj.weight"))
put_mat(b + "ffn_up_shexp.weight", dense(p + "mlp.shared_expert.up_proj.weight"))
put_mat(b + "ffn_down_shexp.weight", dense(p + "mlp.shared_expert.down_proj.weight"))
if (L + 1) % 4 != 0: # GDN
q = p + "linear_attn."
qkv = dense(q + "in_proj_qkv.weight")
qkv = np.concatenate([qkv[:4096], qkv[4096:].reshape(32, 128, -1)[JP].reshape(4096, -1)], axis=0)
put_bf16(b + "attn_qkv.weight", qkv)
put_bf16(b + "attn_gate.weight", dense(q + "in_proj_z.weight").reshape(32, 128, -1)[JP].reshape(4096, -1))
put_bf16(b + "ssm_out.weight", dense(q + "out_proj.weight").reshape(2048, 32, 128)[:, JP, :].reshape(2048, 4096))
put_bf16(b + "ssm_alpha.weight", S.get(LM + q + "in_proj_a.weight")[JP])
put_bf16(b + "ssm_beta.weight", S.get(LM + q + "in_proj_b.weight")[JP])
put_mat(b + "attn_qkv.weight", qkv)
put_mat(b + "attn_gate.weight", dense(q + "in_proj_z.weight").reshape(32, 128, -1)[JP].reshape(4096, -1))
put_mat(b + "ssm_out.weight", dense(q + "out_proj.weight").reshape(2048, 32, 128)[:, JP, :].reshape(2048, 4096))
put_mat(b + "ssm_alpha.weight", S.get(LM + q + "in_proj_a.weight")[JP])
put_mat(b + "ssm_beta.weight", S.get(LM + q + "in_proj_b.weight")[JP])
put_f32(b + "ssm_a", (-np.exp(S.get(LM + q + "A_log")))[JP])
put_f32(b + "ssm_dt.bias", S.get(LM + q + "dt_bias")[JP])
cv = S.get(LM + q + "conv1d.weight").reshape(8192, 4)
@@ -108,15 +124,15 @@ for L in range(NL):
put_f32(b + "ssm_norm.weight", S.get(LM + q + "norm.weight"))
else:
a = p + "self_attn."
put_bf16(b + "attn_q.weight", dense(a + "q_proj.weight"))
put_bf16(b + "attn_k.weight", dense(a + "k_proj.weight"))
put_bf16(b + "attn_v.weight", dense(a + "v_proj.weight"))
put_bf16(b + "attn_output.weight", dense(a + "o_proj.weight"))
put_mat(b + "attn_q.weight", dense(a + "q_proj.weight"))
put_mat(b + "attn_k.weight", dense(a + "k_proj.weight"))
put_mat(b + "attn_v.weight", dense(a + "v_proj.weight"))
put_mat(b + "attn_output.weight", dense(a + "o_proj.weight"))
put_f32(b + "attn_q_norm.weight", 1.0 + S.get(LM + a + "q_norm.weight"))
put_f32(b + "attn_k_norm.weight", 1.0 + S.get(LM + a + "k_norm.weight"))
ix = dense(a + "indexer.index_qk_proj.weight")
put_bf16(b + "indexer.q_proj.weight", ix[:512])
put_bf16(b + "indexer.k_proj.weight", ix[512:])
put_mat(b + "indexer.q_proj.weight", ix[:512])
put_mat(b + "indexer.k_proj.weight", ix[512:])
put_f32(b + "indexer.q_norm.weight", 1.0 + S.get(LM + a + "indexer.q_layernorm.weight"))
put_f32(b + "indexer.k_norm.weight", 1.0 + S.get(LM + a + "indexer.k_layernorm.weight"))
if L == 1:
@@ -131,11 +147,11 @@ for L in range(NL):
print("layer %d done, %.0f s" % (L, time.time() - t0), flush=True)
m = LM + "hyper_connection_mixer."
put_f32("output_hc_norm.weight", 1.0 + S.get(m + "hc_norm.weight"))
put_bf16("output_hc_down.weight", unrot(S.get(m + "input_mix_weight_down.weight")))
put_bf16("output_hc_up.weight", unrot(S.get(m + "input_mix_weight_up.weight")))
put_mat("output_hc_down.weight", unrot(S.get(m + "input_mix_weight_down.weight")))
put_mat("output_hc_up.weight", unrot(S.get(m + "input_mix_weight_up.weight")))
put_bf16("token_embd.weight", unrot(S.get(LM + "embed_tokens.weight")))
print("embed done %.0f s" % (time.time() - t0), flush=True)
put_bf16("output.weight", unrot(S.get("lm_head.weight")))
put_mat("output.weight", unrot(S.get("lm_head.weight")))
print("head done %.0f s" % (time.time() - t0), flush=True)
w.write_header_to_file()
w.write_kv_data_to_file()